aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndroid Build Coastguard Worker <android-build-coastguard-worker@google.com>2022-04-08 16:04:41 +0000
committerAndroid Build Coastguard Worker <android-build-coastguard-worker@google.com>2022-04-08 16:04:41 +0000
commitf3390973ee98a0bd29c9f59b85cd943a5ff1d27a (patch)
tree10c656a56ad93524671e1c710779c8a9b3731083
parent4bf0c3cf6210b58595cee76f13b1770ae097d805 (diff)
parent68a365af6dc8419d6fbd0dbb7a3d9e55dbf9b826 (diff)
downloadchre-aml_tz2_305400100.tar.gz
Change-Id: I33d6b0581fd6aeeb0abfc62bfcbcc9becc9c6a72
-rw-r--r--.gitignore2
-rw-r--r--Android.bp183
-rw-r--r--Android.mk22
-rw-r--r--Makefile13
-rw-r--r--TEST_MAPPING8
-rw-r--r--apps/apps.mk19
-rw-r--r--apps/ash_world/ash_world.cc199
-rw-r--r--apps/ash_world/ash_world.mk12
-rw-r--r--apps/audio_stress_test/Makefile4
-rw-r--r--apps/audio_world/Makefile4
-rw-r--r--apps/audio_world/audio_world.cc40
-rw-r--r--apps/debug_dump_world/debug_dump_world.cc4
-rw-r--r--apps/gnss_world/Makefile4
-rw-r--r--apps/gnss_world/gnss_world.cc37
-rw-r--r--apps/hello_world/hello_world.cc4
-rw-r--r--apps/host_awake_world/Makefile3
-rw-r--r--apps/host_awake_world/host_awake_world.cc4
-rw-r--r--apps/message_world/message_world.cc4
-rw-r--r--apps/power_test/common/idl/chre_power_test.fbs39
-rw-r--r--apps/power_test/common/idl/chre_power_test_generated.h300
-rw-r--r--apps/power_test/common/include/common.h2
-rw-r--r--apps/power_test/common/include/generated/chre_power_test_generated.h220
-rw-r--r--apps/power_test/common/include/request_manager.h17
-rw-r--r--apps/power_test/common/power_test.cc28
-rw-r--r--apps/power_test/common/power_test.mk16
-rw-r--r--apps/power_test/common/request_manager.cc55
-rw-r--r--apps/sensor_world/sensor_world.cc71
-rw-r--r--apps/spammer/spammer.cc6
-rw-r--r--apps/test/chqts/build/general_test/Makefile2
-rw-r--r--apps/test/chqts/build/general_test2/Makefile2
-rw-r--r--apps/test/chqts/build/general_test_sources.mk4
-rw-r--r--apps/test/chqts/build/shared_make.mk15
-rw-r--r--apps/test/chqts/src/Android.bp13
-rw-r--r--apps/test/chqts/src/busy_startup/busy_startup.cc4
-rw-r--r--apps/test/chqts/src/general_test/app.cc8
-rw-r--r--apps/test/chqts/src/general_test/basic_audio_test.cc153
-rw-r--r--apps/test/chqts/src/general_test/basic_gnss_test.cc102
-rw-r--r--apps/test/chqts/src/general_test/basic_gnss_test.h15
-rw-r--r--apps/test/chqts/src/general_test/basic_sensor_test_base.cc142
-rw-r--r--apps/test/chqts/src/general_test/basic_sensor_test_base.h19
-rw-r--r--apps/test/chqts/src/general_test/basic_sensor_tests.cc22
-rw-r--r--apps/test/chqts/src/general_test/basic_wifi_test.cc57
-rw-r--r--apps/test/chqts/src/general_test/logging_sanity_test.cc (renamed from apps/test/chqts/src/general_test/logging_consistency_test.cc)16
-rw-r--r--apps/test/chqts/src/general_test/logging_sanity_test.h (renamed from apps/test/chqts/src/general_test/logging_consistency_test.h)10
-rw-r--r--apps/test/chqts/src/general_test/send_event_stress_test.cc8
-rw-r--r--apps/test/chqts/src/general_test/send_event_stress_test.h2
-rw-r--r--apps/test/chqts/src/general_test/simple_heap_alloc_test.cc4
-rw-r--r--apps/test/chqts/src/general_test/test.h14
-rw-r--r--apps/test/chqts/src/general_test/test_names.h8
-rw-r--r--apps/test/chqts/src/general_test/version_sanity_test.cc (renamed from apps/test/chqts/src/general_test/version_consistency_test.cc)16
-rw-r--r--apps/test/chqts/src/general_test/version_sanity_test.h (renamed from apps/test/chqts/src/general_test/version_consistency_test.h)10
-rw-r--r--apps/test/chqts/src/shared/dumb_allocator.cc (renamed from apps/test/chqts/src/shared/chunk_allocator.cc)14
-rw-r--r--apps/test/chqts/src/shared/dumb_allocator.h (renamed from apps/test/chqts/src/shared/chunk_allocator.h)30
-rw-r--r--apps/test/chqts/src/shared/dumb_allocator_test.cc (renamed from apps/test/chqts/src/shared/chunk_allocator_test.cc)14
-rw-r--r--apps/test/chqts/src/shared/send_message.cc40
-rw-r--r--apps/test/common/chre_audio_concurrency_test/Makefile4
-rw-r--r--apps/test/common/chre_audio_concurrency_test/src/chre_audio_concurrency_test_manager.cc9
-rw-r--r--apps/test/common/chre_cross_validator_gnss/Makefile39
-rw-r--r--apps/test/common/chre_cross_validator_gnss/src/chre_cross_validator_gnss.cc31
-rw-r--r--apps/test/common/chre_cross_validator_sensor/inc/chre_cross_validator_sensor_manager.h44
-rw-r--r--apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc83
-rw-r--r--apps/test/common/chre_cross_validator_wifi/Makefile4
-rw-r--r--apps/test/common/chre_cross_validator_wifi/inc/chre_cross_validator_wifi_manager.h40
-rw-r--r--apps/test/common/chre_cross_validator_wifi/inc/wifi_scan_result.h20
-rw-r--r--apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc106
-rw-r--r--apps/test/common/chre_cross_validator_wifi/src/wifi_scan_result.cc25
-rw-r--r--apps/test/common/chre_settings_test/Makefile7
-rw-r--r--apps/test/common/chre_settings_test/inc/chre_settings_test_manager.h14
-rw-r--r--apps/test/common/chre_settings_test/src/chre_settings_test_manager.cc194
-rw-r--r--apps/test/common/chre_stress_test/Makefile59
-rw-r--r--apps/test/common/chre_stress_test/inc/chre_stress_test_manager.h212
-rw-r--r--apps/test/common/chre_stress_test/src/chre_stress_test.cc39
-rw-r--r--apps/test/common/chre_stress_test/src/chre_stress_test_manager.cc553
-rw-r--r--apps/test/common/permission_test/Makefile64
-rw-r--r--apps/test/common/permission_test/src/permission_test.cc161
-rw-r--r--apps/test/common/ping_test/Makefile56
-rw-r--r--apps/test/common/ping_test/src/ping_test.cc90
-rw-r--r--apps/test/common/proto/Android.bp45
-rw-r--r--apps/test/common/proto/chre_cross_validation_wifi.proto7
-rw-r--r--apps/test/common/proto/chre_settings_test.proto1
-rw-r--r--apps/test/common/proto/chre_stress_test.proto53
-rw-r--r--apps/test/common/proto/permission_test.proto20
-rw-r--r--apps/test/common/proto/ping_test.proto32
-rw-r--r--apps/test/common/shared/inc/send_message.h13
-rw-r--r--apps/test/common/shared/src/send_message.cc30
-rw-r--r--apps/test/pts/audio_enable_disable_test/Makefile4
-rw-r--r--apps/timer_world/timer_world.cc4
-rw-r--r--apps/unload_tester/unload_tester.cc10
-rw-r--r--apps/wifi_offload/Android.bp9
-rw-r--r--apps/wifi_world/Makefile4
-rw-r--r--apps/wifi_world/wifi_world.cc55
-rw-r--r--apps/wwan_world/Makefile4
-rw-r--r--apps/wwan_world/wwan_world.cc6
-rw-r--r--ash/ash.mk13
-rw-r--r--ash/include/ash_api/ash.h209
-rw-r--r--ash/platform/linux/ash.cc (renamed from platform/freertos/memory.cc)32
-rw-r--r--build/arch/x86.mk5
-rw-r--r--build/build_template.mk80
-rw-r--r--build/defs.mk6
-rw-r--r--build/nanoapp/app.mk37
-rw-r--r--build/nanopb.mk10
-rw-r--r--build/pw_unit_test.mk17
-rw-r--r--build/sys_support/qcom/chre.scons2
-rw-r--r--build/variant/google_hexagonv65_adsp-see-uimg.mk1
-rw-r--r--build/variant/google_hexagonv65_adsp-see.mk1
-rw-r--r--build/variant/google_hexagonv65_slpi-see-uimg.mk1
-rw-r--r--build/variant/google_hexagonv65_slpi-see.mk1
-rw-r--r--build/variant/google_hexagonv66_adsp-see-uimg.mk1
-rw-r--r--build/variant/google_hexagonv66_adsp-see.mk1
-rw-r--r--build/variant/google_hexagonv66_slpi-qsh.mk39
-rw-r--r--build/variant/google_hexagonv66_slpi-see-uimg.mk1
-rw-r--r--build/variant/google_hexagonv66_slpi-see.mk1
-rw-r--r--build/variant/google_x86_googletest.mk7
-rw-r--r--build/variant/google_x86_linux.mk1
-rw-r--r--chpp/Android.bp123
-rw-r--r--chpp/QUICKSTART.md72
-rw-r--r--chpp/README.md227
-rw-r--r--chpp/RELEASE_NOTES.md177
-rw-r--r--chpp/TEST_MAPPING12
-rw-r--r--chpp/api_parser/.gitignore1
-rw-r--r--chpp/api_parser/README.md160
-rw-r--r--chpp/api_parser/chre_api_annotations.json257
-rwxr-xr-xchpp/api_parser/chre_api_to_chpp.py1046
-rw-r--r--chpp/api_parser/parser_defines.h23
-rw-r--r--chpp/api_parser/requirements.txt2
-rw-r--r--chpp/app.c798
-rw-r--r--chpp/clients.c598
-rw-r--r--chpp/clients/discovery.c340
-rw-r--r--chpp/clients/gnss.c871
-rw-r--r--chpp/clients/loopback.c212
-rw-r--r--chpp/clients/timesync.c211
-rw-r--r--chpp/clients/wifi.c897
-rw-r--r--chpp/clients/wwan.c578
-rw-r--r--chpp/common/gnss_convert.c292
-rw-r--r--chpp/common/wifi_convert.c679
-rw-r--r--chpp/common/wifi_utils.c72
-rw-r--r--chpp/common/wwan_convert.c649
-rw-r--r--chpp/include/chpp/app.h507
-rw-r--r--chpp/include/chpp/clients.h389
-rw-r--r--chpp/include/chpp/clients/discovery.h93
-rw-r--r--chpp/include/chpp/clients/gnss.h68
-rw-r--r--chpp/include/chpp/clients/loopback.h94
-rw-r--r--chpp/include/chpp/clients/timesync.h131
-rw-r--r--chpp/include/chpp/clients/wifi.h68
-rw-r--r--chpp/include/chpp/clients/wwan.h68
-rw-r--r--chpp/include/chpp/common/common_types.h62
-rw-r--r--chpp/include/chpp/common/discovery.h53
-rw-r--r--chpp/include/chpp/common/gnss.h163
-rw-r--r--chpp/include/chpp/common/gnss_types.h184
-rw-r--r--chpp/include/chpp/common/standard_uuids.h59
-rw-r--r--chpp/include/chpp/common/timesync.h54
-rw-r--r--chpp/include/chpp/common/wifi.h131
-rw-r--r--chpp/include/chpp/common/wifi_types.h309
-rw-r--r--chpp/include/chpp/common/wifi_utils.h49
-rw-r--r--chpp/include/chpp/common/wwan.h73
-rw-r--r--chpp/include/chpp/common/wwan_types.h269
-rw-r--r--chpp/include/chpp/condition_variable.h94
-rw-r--r--chpp/include/chpp/crc.h47
-rw-r--r--chpp/include/chpp/link.h130
-rw-r--r--chpp/include/chpp/log.h86
-rw-r--r--chpp/include/chpp/macros.h111
-rw-r--r--chpp/include/chpp/memory.h7
-rw-r--r--chpp/include/chpp/mutex.h10
-rw-r--r--chpp/include/chpp/notifier.h108
-rw-r--r--chpp/include/chpp/pal_api.h44
-rw-r--r--chpp/include/chpp/services.h242
-rw-r--r--chpp/include/chpp/services/discovery.h49
-rw-r--r--chpp/include/chpp/services/gnss.h52
-rw-r--r--chpp/include/chpp/services/loopback.h53
-rw-r--r--chpp/include/chpp/services/nonhandle.h53
-rw-r--r--chpp/include/chpp/services/timesync.h49
-rw-r--r--chpp/include/chpp/services/wifi.h52
-rw-r--r--chpp/include/chpp/services/wwan.h52
-rw-r--r--chpp/include/chpp/time.h45
-rw-r--r--chpp/include/chpp/transport.h620
-rw-r--r--chpp/include/chpp/transport_signals.h43
-rw-r--r--chpp/platform/linux/include/chpp/platform/log.h44
-rw-r--r--chpp/platform/linux/include/chpp/platform/platform_condition_variable.h71
-rw-r--r--chpp/platform/linux/include/chpp/platform/platform_link.h72
-rw-r--r--chpp/platform/linux/include/chpp/platform/platform_log.h55
-rw-r--r--chpp/platform/linux/include/chpp/platform/platform_mutex.h4
-rw-r--r--chpp/platform/linux/include/chpp/platform/platform_notifier.h96
-rw-r--r--chpp/platform/linux/include/chpp/platform/platform_time.h41
-rw-r--r--chpp/platform/linux/include/chpp/platform/utils.h40
-rw-r--r--chpp/platform/linux/link.c126
-rw-r--r--chpp/platform/linux/memory.c87
-rw-r--r--chpp/platform/linux/notifier.c105
-rw-r--r--chpp/platform/linux/services/platform_gnss.c104
-rw-r--r--chpp/platform/linux/services/platform_wifi.c97
-rw-r--r--chpp/platform/linux/services/platform_wwan.c89
-rw-r--r--chpp/platform/pal_api.c86
-rw-r--r--chpp/platform/shared/crc.c39
-rw-r--r--chpp/services.c188
-rw-r--r--chpp/services/discovery.c99
-rw-r--r--chpp/services/gnss.c687
-rw-r--r--chpp/services/loopback.c56
-rw-r--r--chpp/services/nonhandle.c42
-rw-r--r--chpp/services/timesync.c84
-rw-r--r--chpp/services/wifi.c690
-rw-r--r--chpp/services/wwan.c432
-rw-r--r--chpp/test/app_test.cpp168
-rw-r--r--chpp/test/app_test_base.cpp117
-rw-r--r--chpp/test/app_test_base.h51
-rw-r--r--chpp/test/clients_test.cpp355
-rw-r--r--chpp/test/clients_test.h38
-rw-r--r--chpp/test/transport_test.cpp1093
-rw-r--r--chpp/test/transport_test.h20
-rw-r--r--chpp/test/wifi_convert_test.cpp550
-rw-r--r--chpp/test/wwan_convert_test.cpp394
-rw-r--r--chpp/tools/uuid_gen.py34
-rw-r--r--chpp/transport.c1674
-rw-r--r--chre_api/chre_api_version.mk2
-rw-r--r--chre_api/doc/Doxyfile2
-rw-r--r--chre_api/include/chre_api/chre.h1
-rw-r--r--chre_api/include/chre_api/chre/audio.h22
-rw-r--r--chre_api/include/chre_api/chre/common.h3
-rw-r--r--chre_api/include/chre_api/chre/event.h133
-rw-r--r--chre_api/include/chre_api/chre/gnss.h44
-rw-r--r--chre_api/include/chre_api/chre/nanoapp.h2
-rw-r--r--chre_api/include/chre_api/chre/re.h26
-rw-r--r--chre_api/include/chre_api/chre/sensor.h95
-rw-r--r--chre_api/include/chre_api/chre/sensor_types.h51
-rw-r--r--chre_api/include/chre_api/chre/toolchain.h26
-rw-r--r--chre_api/include/chre_api/chre/user_settings.h135
-rw-r--r--chre_api/include/chre_api/chre/version.h30
-rw-r--r--chre_api/include/chre_api/chre/wifi.h119
-rw-r--r--chre_api/include/chre_api/chre/wwan.h26
-rw-r--r--chre_api/legacy/v1_1/chre/wwan.h4
-rw-r--r--chre_api/legacy/v1_2/chre/wwan.h4
-rw-r--r--chre_api/legacy/v1_3/chre/wwan.h4
-rw-r--r--chre_api/legacy/v1_4/chre.h199
-rw-r--r--chre_api/legacy/v1_4/chre/audio.h407
-rw-r--r--chre_api/legacy/v1_4/chre/common.h174
-rw-r--r--chre_api/legacy/v1_4/chre/event.h587
-rw-r--r--chre_api/legacy/v1_4/chre/gnss.h562
-rw-r--r--chre_api/legacy/v1_4/chre/nanoapp.h93
-rw-r--r--chre_api/legacy/v1_4/chre/re.h437
-rw-r--r--chre_api/legacy/v1_4/chre/sensor.h1018
-rw-r--r--chre_api/legacy/v1_4/chre/sensor_types.h423
-rw-r--r--chre_api/legacy/v1_4/chre/toolchain.h40
-rw-r--r--chre_api/legacy/v1_4/chre/version.h210
-rw-r--r--chre_api/legacy/v1_4/chre/wifi.h913
-rw-r--r--chre_api/legacy/v1_4/chre/wwan.h569
-rw-r--r--core/audio_request_manager.cc91
-rw-r--r--core/core.mk19
-rw-r--r--core/debug_dump_manager.cc7
-rw-r--r--core/event.cc18
-rw-r--r--core/event_loop.cc111
-rw-r--r--core/event_loop_manager.cc2
-rw-r--r--core/gnss_manager.cc251
-rw-r--r--core/host_comms_manager.cc49
-rw-r--r--core/include/chre/core/audio_request_manager.h46
-rw-r--r--core/include/chre/core/audio_util.h72
-rw-r--r--core/include/chre/core/event.h92
-rw-r--r--core/include/chre/core/event_loop.h74
-rw-r--r--core/include/chre/core/event_loop_common.h15
-rw-r--r--core/include/chre/core/event_loop_manager.h103
-rw-r--r--core/include/chre/core/gnss_manager.h80
-rw-r--r--core/include/chre/core/host_comms_manager.h47
-rw-r--r--core/include/chre/core/nanoapp.h65
-rw-r--r--core/include/chre/core/sensor.h14
-rw-r--r--core/include/chre/core/sensor_request.h36
-rw-r--r--core/include/chre/core/sensor_request_manager.h54
-rw-r--r--core/include/chre/core/sensor_type.h3
-rw-r--r--core/include/chre/core/sensor_type_helpers.h8
-rw-r--r--core/include/chre/core/settings.h24
-rw-r--r--core/include/chre/core/timer_pool.h53
-rw-r--r--core/include/chre/core/wifi_request_manager.h2
-rw-r--r--core/init.cc9
-rw-r--r--core/log.cc (renamed from platform/shared/pw_tokenized_log.cc)5
-rw-r--r--core/nanoapp.cc97
-rw-r--r--core/sensor.cc3
-rw-r--r--core/sensor_request.cc14
-rw-r--r--core/sensor_request_manager.cc288
-rw-r--r--core/sensor_type_helpers.cc30
-rw-r--r--core/settings.cc89
-rw-r--r--core/tests/audio_request_manager_test.cc (renamed from core/tests/audio_util_test.cc)32
-rw-r--r--core/tests/memory_manager_test.cc36
-rw-r--r--core/tests/request_multiplexer_test.cc92
-rw-r--r--core/tests/sensor_request_test.cc46
-rw-r--r--core/tests/wifi_scan_request_test.cc4
-rw-r--r--core/timer_pool.cc64
-rw-r--r--core/wifi_request_manager.cc168
-rw-r--r--core/wwan_request_manager.cc7
-rw-r--r--doc/porting_guide.md2
-rw-r--r--external/flatbuffers/flatbuffers.mk2
-rw-r--r--external/flatbuffers/include/flatbuffers/flatbuffers.h110
-rw-r--r--external/kiss_fft/_kiss_fft_guts.h9
-rw-r--r--external/kiss_fft/kiss_fft.c14
-rw-r--r--external/kiss_fft/kiss_fftr.c24
-rw-r--r--host/common/audio_stress_test/audio_stress_test.cc8
-rw-r--r--host/common/daemon_base.cc256
-rw-r--r--host/common/fragmented_load_transaction.cc9
-rw-r--r--host/common/host_protocol_host.cc23
-rw-r--r--host/common/include/chre_host/daemon_base.h225
-rw-r--r--host/common/include/chre_host/fragmented_load_transaction.h20
-rw-r--r--host/common/include/chre_host/generated/host_messages_generated.h595
-rw-r--r--host/common/include/chre_host/host_protocol_host.h18
-rw-r--r--host/common/include/chre_host/log_message_parser_base.h109
-rw-r--r--host/common/include/chre_host/napp_header.h40
-rw-r--r--host/common/include/chre_host/socket_server.h5
-rw-r--r--host/common/include/chre_host/st_hal_lpma_handler.h167
-rw-r--r--host/common/include/chre_host/tokenized_log_message_parser.h113
-rw-r--r--host/common/log_message_parser_base.cc152
-rw-r--r--host/common/socket_client.cc25
-rw-r--r--host/common/st_hal_lpma_handler.cc210
-rw-r--r--host/common/test/chre_test_client.cc198
-rw-r--r--host/common/test/power_test/chre_power_test_client.cc298
-rw-r--r--host/hal_generic/V1_1/generic_context_hub_v1_1.cc46
-rw-r--r--host/hal_generic/V1_2/android.hardware.contexthub@1.2-generic.xml11
-rw-r--r--host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-generic.rc7
-rw-r--r--host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-small_fragments.rc7
-rw-r--r--host/hal_generic/V1_2/generic_context_hub_v1_2.cc102
-rw-r--r--host/hal_generic/V1_2/generic_context_hub_v1_2.h65
-rw-r--r--host/hal_generic/V1_2/service.cc42
-rw-r--r--host/hal_generic/common/context_hub_settings_util.cc91
-rw-r--r--host/hal_generic/common/context_hub_settings_util.h61
-rw-r--r--host/hal_generic/common/generic_context_hub_base.h66
-rw-r--r--host/hal_generic/common/permissions_util.cc52
-rw-r--r--host/hal_generic/common/permissions_util.h45
-rw-r--r--host/msm/daemon/chre_daemon.cc1067
-rw-r--r--host/msm/daemon/fastrpc_daemon.cc260
-rw-r--r--host/msm/daemon/fastrpc_daemon.h118
-rw-r--r--host/msm/daemon/main.cc29
-rw-r--r--java/test/audio_concurrency/Android.bp11
-rw-r--r--java/test/audio_concurrency/src/com/google/android/chre/test/audioconcurrency/ContextHubAudioConcurrencyTestExecutor.java9
-rw-r--r--java/test/chqts/Android.bp35
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubBadNanoAppsTestExecutor.java78
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubBusyStartupTestExecutor.java47
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubEstimatedHostTimeTestExecutor.java58
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubEventBetweenAppsTestExecutor.java121
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubGeneralTestExecutor.java370
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubGetTimeTestExecutor.java129
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubInfoByIdTestExecutor.java62
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubNanoAppInfoEventsTestExecutor.java107
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSendMessageToHostTestExecutor.java188
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSimpleGeneralTestExecutor.java38
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSimpleHeapAllocTestExecutor.java63
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubTestConstants.java365
-rw-r--r--java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubTrivialNanoAppsTestExecutor.java55
-rw-r--r--java/test/cross_validation/Android.bp11
-rw-r--r--java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorSensor.java4
-rw-r--r--java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorWifi.java50
-rw-r--r--java/test/permissions/Android.bp38
-rw-r--r--java/test/permissions/src/com/google/android/chre/test/permissions/ContextHubChrePermissionsTestExecutor.java136
-rw-r--r--java/test/permissions/src/com/google/android/chre/test/permissions/ContextHubFrameworkPermissionsTestExecutor.java185
-rw-r--r--java/test/settings/Android.bp11
-rw-r--r--java/test/settings/src/com/google/android/chre/test/setting/ContextHubMicDisableSettingsTestExecutor.java96
-rw-r--r--java/test/settings/src/com/google/android/chre/test/setting/ContextHubWifiSettingsTestExecutor.java7
-rw-r--r--java/test/settings/src/com/google/android/chre/test/setting/ContextHubWwanSettingsTestExecutor.java43
-rw-r--r--java/test/stress/Android.bp37
-rw-r--r--java/test/stress/src/com/google/android/chre/test/stress/ContextHubStressTestExecutor.java290
-rw-r--r--java/test/utils/Android.bp11
-rw-r--r--java/test/utils/src/com/google/android/utils/chre/ChreTestUtil.java181
-rw-r--r--pal/doc/Doxyfile2
-rw-r--r--pal/include/chre/pal/sensor.h4
-rw-r--r--pal/include/chre/pal/wifi.h12
-rw-r--r--pal/pal.mk7
-rw-r--r--pal/tests/include/gnss_pal_impl_test.h85
-rw-r--r--pal/tests/include/wifi_pal_impl_test.h98
-rw-r--r--pal/tests/src/gnss_pal_impl_test.cc324
-rw-r--r--pal/tests/src/wifi_pal_impl_test.cc256
-rw-r--r--pal/tests/version_test.cc (renamed from pal/tests/src/version_test.cc)4
-rw-r--r--pal/tests/wwan_test.cc (renamed from pal/tests/src/wwan_test.cc)0
-rw-r--r--pal/util/include/chre/pal/util/wifi_scan_cache.h208
-rw-r--r--pal/util/tests/wifi_scan_cache_test.cc365
-rw-r--r--pal/util/wifi_scan_cache.c330
-rw-r--r--platform/android/host_link.cc60
-rw-r--r--platform/android/platform_audio.cc15
-rw-r--r--platform/freertos/context.cc32
-rw-r--r--platform/freertos/include/chre/target_platform/atomic_base.h35
-rw-r--r--platform/freertos/include/chre/target_platform/atomic_base_impl.h84
-rw-r--r--platform/freertos/include/chre/target_platform/init.h52
-rw-r--r--platform/freertos/include/chre/target_platform/mutex_base.h52
-rw-r--r--platform/freertos/include/chre/target_platform/mutex_base_impl.h56
-rw-r--r--platform/freertos/include/chre/target_platform/platform_debug_dump_manager_base.h59
-rw-r--r--platform/freertos/include/chre/target_platform/platform_nanoapp_base.h177
-rw-r--r--platform/freertos/include/chre/target_platform/static_nanoapp_init.h64
-rw-r--r--platform/freertos/init.cc145
-rw-r--r--platform/freertos/memory_manager.cc39
-rw-r--r--platform/freertos/platform_debug_dump_manager.cc63
-rw-r--r--platform/freertos/platform_nanoapp.cc313
-rw-r--r--platform/include/chre/platform/assert.h53
-rw-r--r--platform/include/chre/platform/host_link.h19
-rw-r--r--platform/include/chre/platform/log.h38
-rw-r--r--platform/include/chre/platform/platform_debug_dump_manager.h9
-rw-r--r--platform/include/chre/platform/platform_gnss.h7
-rw-r--r--platform/include/chre/platform/platform_nanoapp.h16
-rw-r--r--platform/include/chre/platform/platform_sensor.h10
-rw-r--r--platform/include/chre/platform/platform_sensor_manager.h19
-rw-r--r--platform/include/chre/platform/static_nanoapp_init.h11
-rw-r--r--platform/include/chre/platform/system_timer.h6
-rw-r--r--platform/include/chre/platform/version.h31
-rw-r--r--platform/linux/assert.cc28
-rw-r--r--platform/linux/fatal_error.cc2
-rw-r--r--platform/linux/host_link.cc8
-rw-r--r--platform/linux/include/chre/target_platform/assert.h (renamed from platform/linux/include/chre/platform/linux/expect_assert.h)22
-rw-r--r--platform/linux/include/chre/target_platform/log.h30
-rw-r--r--platform/linux/include/chre/target_platform/platform_log_base.h (renamed from platform/linux/include/chre/platform/linux/platform_log.h)39
-rw-r--r--platform/linux/include/chre/target_platform/static_nanoapp_init.h12
-rw-r--r--platform/linux/init.cc2
-rw-r--r--platform/linux/memory_manager.cc4
-rw-r--r--platform/linux/pal_gnss.cc186
-rw-r--r--platform/linux/pal_wifi.cc133
-rw-r--r--platform/linux/pal_wwan.cc120
-rw-r--r--platform/linux/platform_audio.cc17
-rw-r--r--platform/linux/platform_debug_dump_manager.cc3
-rw-r--r--platform/linux/platform_log.cc12
-rw-r--r--platform/linux/platform_nanoapp.cc24
-rw-r--r--platform/linux/platform_sensor.cc8
-rw-r--r--platform/linux/power_control_manager.cc2
-rw-r--r--platform/platform.mk89
-rw-r--r--platform/shared/assert.cc27
-rw-r--r--platform/shared/chre_api_audio.cc11
-rw-r--r--platform/shared/chre_api_core.cc18
-rw-r--r--platform/shared/chre_api_gnss.cc54
-rw-r--r--platform/shared/chre_api_sensor.cc140
-rw-r--r--platform/shared/chre_api_user_settings.cc37
-rw-r--r--platform/shared/chre_api_wifi.cc24
-rw-r--r--platform/shared/chre_api_wwan.cc9
-rw-r--r--platform/shared/dlfcn.cc60
-rw-r--r--platform/shared/dram_vote_client.cc98
-rw-r--r--platform/shared/host_protocol_chre.cc122
-rw-r--r--platform/shared/host_protocol_common.cc6
-rw-r--r--platform/shared/idl/host_messages.fbs64
-rw-r--r--platform/shared/include/chre/platform/shared/authentication.h40
-rw-r--r--platform/shared/include/chre/platform/shared/dram_vote_client.h108
-rw-r--r--platform/shared/include/chre/platform/shared/generated/host_messages_generated.h337
-rw-r--r--platform/shared/include/chre/platform/shared/host_protocol_chre.h88
-rw-r--r--platform/shared/include/chre/platform/shared/host_protocol_common.h34
-rw-r--r--platform/shared/include/chre/platform/shared/libc/dlfcn.h69
-rw-r--r--platform/shared/include/chre/platform/shared/loader_util.h237
-rw-r--r--platform/shared/include/chre/platform/shared/log_buffer.h305
-rw-r--r--platform/shared/include/chre/platform/shared/log_buffer_manager.h142
-rw-r--r--platform/shared/include/chre/platform/shared/memory.h112
-rw-r--r--platform/shared/include/chre/platform/shared/memory_debug.h2
-rw-r--r--platform/shared/include/chre/platform/shared/nanoapp_dso_util.h7
-rw-r--r--platform/shared/include/chre/platform/shared/nanoapp_loader.h345
-rw-r--r--platform/shared/include/chre/platform/shared/nanoapp_support_lib_dso.h13
-rw-r--r--platform/shared/include/chre/platform/shared/platform_log.h54
-rw-r--r--platform/shared/include/chre/target_platform/platform_cache_management.h38
-rw-r--r--platform/shared/log_buffer.cc245
-rw-r--r--platform/shared/log_buffer_manager.cc161
-rw-r--r--platform/shared/memory_manager.cc3
-rw-r--r--platform/shared/nanoapp/nanoapp_dso_util.cc6
-rw-r--r--platform/shared/nanoapp/nanoapp_support_lib_dso.cc131
-rw-r--r--platform/shared/nanoapp_loader.cc931
-rw-r--r--platform/shared/platform_gnss.cc14
-rw-r--r--platform/shared/platform_sensor_manager.cc7
-rw-r--r--platform/shared/platform_wifi.cc10
-rw-r--r--platform/shared/version.cc37
-rw-r--r--platform/slpi/chre_api_re.cc15
-rw-r--r--platform/slpi/fatal_error.cc2
-rw-r--r--platform/slpi/host_link.cc330
-rw-r--r--platform/slpi/include/chre/platform/slpi/nanoapp_load_manager.h (renamed from platform/shared/include/chre/platform/shared/nanoapp_load_manager.h)12
-rw-r--r--platform/slpi/include/chre/platform/slpi/qsh/qsh_shim.h37
-rw-r--r--platform/slpi/include/chre/platform/slpi/see/island_vote_client.h2
-rw-r--r--platform/slpi/include/chre/platform/slpi/see/see_cal_helper.h16
-rw-r--r--platform/slpi/include/chre/target_platform/assert.h (renamed from std_overrides/include/assert.h)21
-rw-r--r--platform/slpi/include/chre/target_platform/condition_variable_base.h3
-rw-r--r--platform/slpi/include/chre/target_platform/condition_variable_impl.h18
-rw-r--r--platform/slpi/include/chre/target_platform/host_link_base.h23
-rw-r--r--platform/slpi/include/chre/target_platform/log.h84
-rw-r--r--platform/slpi/include/chre/target_platform/platform_nanoapp_base.h11
-rw-r--r--platform/slpi/include/chre/target_platform/platform_sensor_type_helpers_base.h22
-rw-r--r--platform/slpi/include/chre/target_platform/static_nanoapp_init.h4
-rw-r--r--platform/slpi/init.cc34
-rw-r--r--platform/slpi/log_buffer_manager.cc9
-rw-r--r--platform/slpi/memory.cc2
-rw-r--r--platform/slpi/nanoapp_load_manager.cc (renamed from platform/shared/nanoapp_load_manager.cc)11
-rw-r--r--platform/slpi/platform_audio.cc4
-rw-r--r--platform/slpi/platform_debug_dump_manager.cc3
-rw-r--r--platform/slpi/platform_nanoapp.cc149
-rw-r--r--platform/slpi/platform_sensor_type_helpers.cc34
-rw-r--r--platform/slpi/qsh/qsh_shim.cc139
-rw-r--r--platform/slpi/see/include/chre/target_platform/platform_sensor_base.h6
-rw-r--r--platform/slpi/see/include/chre/target_platform/platform_sensor_manager_base.h16
-rw-r--r--platform/slpi/see/platform_sensor.cc14
-rw-r--r--platform/slpi/see/platform_sensor_manager.cc432
-rw-r--r--platform/slpi/see/power_control_manager.cc13
-rw-r--r--platform/slpi/see/see_cal_helper.cc11
-rw-r--r--platform/slpi/see/see_helper.cc33
-rw-r--r--platform/tests/log_buffer_test.cc288
-rwxr-xr-xrun_pal_impl_tests.sh17
-rw-r--r--std_overrides/README.md18
-rw-r--r--std_overrides/std_overrides.mk12
-rw-r--r--std_overrides/stdlib_wrapper.cc80
-rw-r--r--test/README.md64
-rw-r--r--test/common/include/chre/test/common/macros.h27
-rw-r--r--test/common/include/chre/test/common/unit_test.h26
-rw-r--r--test/common/run_tests.cc83
-rw-r--r--test/test.mk42
-rw-r--r--util/container_support.cc12
-rw-r--r--util/include/chre/util/always_false.h46
-rw-r--r--util/include/chre/util/flatbuffers/helpers.h76
-rw-r--r--util/include/chre/util/log_common.h18
-rw-r--r--util/include/chre/util/macros.h30
-rw-r--r--util/include/chre/util/nanoapp/app_id.h2
-rw-r--r--util/include/chre/util/nanoapp/log.h31
-rw-r--r--util/include/chre/util/nanoapp/wifi.h10
-rw-r--r--util/include/chre/util/nested_data_ptr.h60
-rw-r--r--util/include/chre/util/system/debug_dump.h2
-rw-r--r--util/include/chre/util/system/napp_header_utils.h26
-rw-r--r--util/include/chre/util/system/napp_permissions.h45
-rw-r--r--util/include/chre/util/system/wifi_util.h52
-rw-r--r--util/include/chre/util/toolchain.h37
-rw-r--r--util/nanoapp/wifi.cc39
-rw-r--r--util/system/debug_dump.cc4
-rw-r--r--util/tests/array_queue_test.cc20
-rw-r--r--util/tests/debug_dump_test.cc9
-rw-r--r--util/tests/dynamic_vector_test.cc21
-rw-r--r--util/tests/priority_queue_test.cc22
-rw-r--r--variant/googletest/variant.mk1
-rw-r--r--variant/simulator/variant.mk4
514 files changed, 4813 insertions, 47863 deletions
diff --git a/.gitignore b/.gitignore
index c3548f59..1fcb1529 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1 @@
out
-.idea
-*.iml
diff --git a/Android.bp b/Android.bp
index ee5d1407..0ed5898a 100644
--- a/Android.bp
+++ b/Android.bp
@@ -14,36 +14,6 @@
* limitations under the License.
*/
-package {
- default_applicable_licenses: ["system_chre_license"],
-}
-
-// Added automatically by a large-scale-change that took the approach of
-// 'apply every license found to every target'. While this makes sure we respect
-// every license restriction, it may not be entirely correct.
-//
-// e.g. GPL in an MIT project might only apply to the contrib/ directory.
-//
-// Please consider splitting the single license below into multiple licenses,
-// taking care not to lose any license_kind information, and overriding the
-// default license using the 'licenses: [...]' property on targets as needed.
-//
-// For unused files, consider creating a 'fileGroup' with "//visibility:private"
-// to attach the license to, and including a comment whether the files may be
-// used in the current project.
-// See: http://go/android-license-faq
-license {
- name: "system_chre_license",
- visibility: [":__subpackages__"],
- license_kinds: [
- "SPDX-license-identifier-Apache-2.0",
- "SPDX-license-identifier-BSD",
- ],
- license_text: [
- "NOTICE",
- ],
-}
-
cc_library_static {
name: "chre_client",
vendor: true,
@@ -148,12 +118,10 @@ cc_library_shared {
relative_install_path: "hw",
srcs: [
"host/hal_generic/V1_0/generic_context_hub_v1_0.cc",
- "host/hal_generic/common/permissions_util.cc",
],
cflags: ["-Wall", "-Werror"],
header_libs: [
"android.hardware.contexthub@1.X-shared-impl",
- "android.hardware.contexthub@1.X-common-utils",
],
shared_libs: [
"libcutils",
@@ -161,8 +129,6 @@ cc_library_shared {
"libhidlbase",
"libutils",
"android.hardware.contexthub@1.0",
- "android.hardware.contexthub@1.1",
- "android.hardware.contexthub@1.2",
],
static_libs: ["chre_client"],
}
@@ -175,14 +141,11 @@ cc_binary {
srcs: [
"host/hal_generic/V1_1/generic_context_hub_v1_1.cc",
"host/hal_generic/V1_1/service.cc",
- "host/hal_generic/common/context_hub_settings_util.cc",
- "host/hal_generic/common/permissions_util.cc",
],
init_rc: ["host/hal_generic/V1_1/android.hardware.contexthub@1.1-service-generic.rc"],
cflags: ["-Wall", "-Werror"],
header_libs: [
"android.hardware.contexthub@1.X-shared-impl",
- "android.hardware.contexthub@1.X-common-utils",
],
shared_libs: [
"libcutils",
@@ -191,50 +154,17 @@ cc_binary {
"libutils",
"android.hardware.contexthub@1.0",
"android.hardware.contexthub@1.1",
- "android.hardware.contexthub@1.2",
],
static_libs: ["chre_client"],
vintf_fragments: ["host/hal_generic/V1_1/android.hardware.contexthub@1.1-generic.xml"],
}
-cc_binary {
- name: "android.hardware.contexthub@1.2-service.generic",
- defaults: ["hidl_defaults"],
- vendor: true,
- relative_install_path: "hw",
- srcs: [
- "host/hal_generic/V1_2/generic_context_hub_v1_2.cc",
- "host/hal_generic/V1_2/service.cc",
- "host/hal_generic/common/context_hub_settings_util.cc",
- "host/hal_generic/common/permissions_util.cc",
- ],
- init_rc: ["host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-generic.rc"],
- cflags: ["-Wall", "-Werror"],
- header_libs: [
- "android.hardware.contexthub@1.X-shared-impl",
- "android.hardware.contexthub@1.X-common-utils",
- ],
- shared_libs: [
- "libcutils",
- "liblog",
- "libhidlbase",
- "libutils",
- "android.hardware.contexthub@1.0",
- "android.hardware.contexthub@1.1",
- "android.hardware.contexthub@1.2",
- ],
- static_libs: ["chre_client"],
- vintf_fragments: ["host/hal_generic/V1_2/android.hardware.contexthub@1.2-generic.xml"],
-}
-
cc_library_headers {
name: "chre_api",
vendor: true,
export_include_dirs: [
"chre_api/include/chre_api",
- "chre_api/include",
- ],
- host_supported: true,
+ ]
}
cc_library_headers {
@@ -245,117 +175,6 @@ cc_library_headers {
],
}
-cc_library_headers {
- name: "chre_pal",
- vendor: true,
- export_include_dirs: [
- "pal/include",
- ],
- header_libs: [
- "chre_api",
- ],
- export_header_lib_headers: [
- "chre_api",
- ],
- host_supported: true,
-}
-
-cc_library_headers {
- name: "chre_test_common",
- vendor: true,
- export_include_dirs: [
- "test/common/include",
- ],
- host_supported: true,
-}
-
-cc_library_static {
- name: "chre_pal_linux",
- vendor: true,
- srcs: [
- "platform/shared/pal_system_api.cc",
- "platform/linux/assert.cc",
- "platform/linux/fatal_error.cc",
- "platform/linux/memory.cc",
- "platform/linux/pal_gnss.cc",
- "platform/linux/pal_wifi.cc",
- "platform/linux/pal_wwan.cc",
- "platform/linux/platform_log.cc",
- "platform/linux/system_time.cc",
- ],
- export_include_dirs: [
- "platform/shared/include",
- "platform/include",
- "platform/linux/include",
- "util/include",
- ],
- header_libs: [
- "chre_pal",
- ],
- cflags: [
- "-DCHRE_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_DEBUG",
- "-DCHRE_ASSERTIONS_ENABLED=true",
- "-DCHRE_FILENAME=__FILE__"
- ],
- host_supported: true,
-}
-
-cc_test_host {
- name: "chre_unit_tests",
- srcs: [
- "core/event_ref_queue.cc",
- "core/nanoapp.cc",
- "core/sensor_request.cc",
- "core/tests/**/*.cc",
- "core/wifi_scan_request.cc",
- "pal/tests/src/wwan_test.cc",
- "pal/tests/src/version_test.cc",
- "pal/util/tests/**/*.cc",
- "pal/util/wifi_scan_cache.c",
- "platform/linux/assert.cc",
- "platform/linux/fatal_error.cc",
- "platform/linux/platform_nanoapp.cc",
- "platform/linux/platform_log.cc",
- "platform/linux/memory.cc",
- "platform/linux/memory_manager.cc",
- "platform/linux/system_time.cc",
- "platform/shared/log_buffer.cc",
- "platform/shared/memory_manager.cc",
- "platform/shared/pal_system_api.cc",
- "platform/tests/**/*.cc",
- "util/buffer_base.cc",
- "util/dynamic_vector_base.cc",
- "util/nanoapp/wifi.cc",
- "util/system/debug_dump.cc",
- "util/tests/**/*.cc",
- ],
- local_include_dirs: [
- "chre_api/include",
- "chre_api/include/chre_api",
- "core/include",
- "pal/include",
- "pal/util/include",
- "platform/linux/include",
- "platform/shared/include",
- "platform/include",
- "util/include",
- ],
- test_suites: [
- // Needed to support running on TreeHugger
- "general-tests",
- ],
- cflags: [
- "-DCHRE_MESSAGE_TO_HOST_MAX_SIZE=4096",
- "-DCHRE_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_DEBUG",
- "-DCHRE_ASSERTIONS_ENABLED=true",
- "-DCHRE_FILENAME=__FILE__",
- "-DGTEST",
- ],
- static_libs: [
- "libgmock",
- ],
-}
-
subdirs = [
"apps/wifi_offload",
]
diff --git a/Android.mk b/Android.mk
index bfe725fc..fa3a9c39 100644
--- a/Android.mk
+++ b/Android.mk
@@ -29,9 +29,6 @@ include $(CLEAR_VARS)
# libadsprpc is converted as blueprint targets can't depend on targets exposed
# by makefiles
LOCAL_MODULE := chre
-LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-BSD
-LOCAL_LICENSE_CONDITIONS := notice
-LOCAL_NOTICE_FILE := $(LOCAL_PATH)/NOTICE
LOCAL_MODULE_OWNER := google
LOCAL_MODULE_TAGS := optional
LOCAL_VENDOR_MODULE := true
@@ -53,14 +50,10 @@ endif
CHRE_USE_TOKENIZED_LOGGING := false
LOCAL_SRC_FILES := \
- host/common/daemon_base.cc \
host/common/fragmented_load_transaction.cc \
host/common/host_protocol_host.cc \
- host/common/log_message_parser_base.cc \
host/common/socket_server.cc \
- host/common/st_hal_lpma_handler.cc \
- host/msm/daemon/fastrpc_daemon.cc \
- host/msm/daemon/main.cc \
+ host/msm/daemon/chre_daemon.cc \
host/msm/daemon/generated/chre_slpi_stub.c \
platform/shared/host_protocol_common.cc
@@ -72,9 +65,9 @@ LOCAL_C_INCLUDES := \
system/chre/platform/shared/include \
system/chre/platform/slpi/include \
system/chre/util/include \
- system/libbase/include \
+ system/core/base/include \
system/core/libcutils/include \
- system/logging/liblog/include \
+ system/core/liblog/include \
system/core/libutils/include \
LOCAL_SHARED_LIBRARIES := \
@@ -83,9 +76,7 @@ LOCAL_SHARED_LIBRARIES := \
libcutils \
liblog \
libhidlbase \
- libbase \
- android.hardware.soundtrigger@2.0 \
- libpower
+ libbase
# Enable tokenized logging
ifeq ($(CHRE_USE_TOKENIZED_LOGGING),true)
@@ -105,6 +96,11 @@ LOCAL_SRC_FILES += $(PIGWEED_TOKENIZER_DIR_RELPATH)/pw_tokenizer/decode.cc
LOCAL_SRC_FILES += $(PIGWEED_TOKENIZER_DIR_RELPATH)/pw_varint/varint.cc
endif
+ifeq ($(CHRE_DAEMON_LPMA_ENABLED),true)
+LOCAL_SHARED_LIBRARIES += android.hardware.soundtrigger@2.0
+LOCAL_SHARED_LIBRARIES += libpower
+endif
+
ifeq ($(CHRE_DAEMON_USE_SDSPRPC),true)
LOCAL_SHARED_LIBRARIES += libsdsprpc
else
diff --git a/Makefile b/Makefile
index d32355ab..494ab2ad 100644
--- a/Makefile
+++ b/Makefile
@@ -42,11 +42,6 @@ ifeq ($(CHRE_GNSS_SUPPORT_ENABLED), true)
COMMON_CFLAGS += -DCHRE_GNSS_SUPPORT_ENABLED
endif
-# Optional sensors support.
-ifeq ($(CHRE_SENSORS_SUPPORT_ENABLED), true)
-COMMON_CFLAGS += -DCHRE_SENSORS_SUPPORT_ENABLED
-endif
-
# Optional Wi-Fi support.
ifeq ($(CHRE_WIFI_SUPPORT_ENABLED), true)
COMMON_CFLAGS += -DCHRE_WIFI_SUPPORT_ENABLED
@@ -57,9 +52,6 @@ ifeq ($(CHRE_WWAN_SUPPORT_ENABLED), true)
COMMON_CFLAGS += -DCHRE_WWAN_SUPPORT_ENABLED
endif
-# Optional on-device unit tests support
-include $(CHRE_PREFIX)/test/test.mk
-
# Determine the CHRE_HOST_OS to resolve build discrepancies across Darwin and
# Linux.
CHRE_HOST_OS := $(shell uname)
@@ -89,6 +81,7 @@ include $(CHRE_PREFIX)/build/common.mk
# CHRE Implementation includes.
include $(CHRE_PREFIX)/apps/apps.mk
+include $(CHRE_PREFIX)/ash/ash.mk
include $(CHRE_PREFIX)/chre_api/chre_api.mk
include $(CHRE_PREFIX)/core/core.mk
include $(CHRE_PREFIX)/external/external.mk
@@ -99,9 +92,6 @@ include $(CHRE_PREFIX)/util/util.mk
# Supported Variants Includes. Not all CHRE variants are supported by this
# implementation of CHRE. Example: this CHRE implementation is never built for
# google_cm4_nanohub as Nanohub itself is a CHRE implementation.
-ifneq ($(CHRE_TARGET_EXTENSION),)
-include $(CHRE_TARGET_EXTENSION)
-endif
include $(CHRE_PREFIX)/build/variant/google_arm64_android.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv55_slpi-see.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv60_slpi.mk
@@ -115,6 +105,5 @@ include $(CHRE_PREFIX)/build/variant/google_hexagonv66_adsp-see.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv66_adsp-see-uimg.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv66_slpi-see.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv66_slpi-see-uimg.mk
-include $(CHRE_PREFIX)/build/variant/google_hexagonv66_slpi-qsh.mk
include $(CHRE_PREFIX)/build/variant/google_x86_linux.mk
include $(CHRE_PREFIX)/build/variant/google_x86_googletest.mk
diff --git a/TEST_MAPPING b/TEST_MAPPING
deleted file mode 100644
index ce5f3eb4..00000000
--- a/TEST_MAPPING
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "presubmit" : [
- {
- "name" : "chre_unit_tests",
- "host" : true
- }
- ]
-}
diff --git a/apps/apps.mk b/apps/apps.mk
index a76dc71d..ec6d060f 100644
--- a/apps/apps.mk
+++ b/apps/apps.mk
@@ -8,23 +8,10 @@ COMMON_CFLAGS += -Iapps/include
# App makefiles ################################################################
-ifeq ($(CHRE_AUDIO_SUPPORT_ENABLED), true)
+include apps/ash_world/ash_world.mk
include apps/audio_world/audio_world.mk
-endif
-
-ifeq ($(CHRE_GNSS_SUPPORT_ENABLED), true)
-include apps/gnss_world/gnss_world.mk
-endif
-
-ifeq ($(CHRE_WIFI_SUPPORT_ENABLED), true)
-include apps/wifi_world/wifi_world.mk
-endif
-
-ifeq ($(CHRE_WWAN_SUPPORT_ENABLED), true)
-include apps/wwan_world/wwan_world.mk
-endif
-
include apps/debug_dump_world/debug_dump_world.mk
+include apps/gnss_world/gnss_world.mk
include apps/hello_world/hello_world.mk
include apps/host_awake_world/host_awake_world.mk
include apps/message_world/message_world.mk
@@ -32,3 +19,5 @@ include apps/sensor_world/sensor_world.mk
include apps/spammer/spammer.mk
include apps/timer_world/timer_world.mk
include apps/unload_tester/unload_tester.mk
+include apps/wifi_world/wifi_world.mk
+include apps/wwan_world/wwan_world.mk
diff --git a/apps/ash_world/ash_world.cc b/apps/ash_world/ash_world.cc
new file mode 100644
index 00000000..304eefdb
--- /dev/null
+++ b/apps/ash_world/ash_world.cc
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * 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 <ash.h>
+#include <chre.h>
+#include <cinttypes>
+
+#include "chre/util/nanoapp/log.h"
+
+/**
+ * @file
+ * A nanoapp exclusively for testing, which saves locally defined ashCalParam
+ * of accel, gyro and mag to storage and lodas them back to check correctness.
+ * The loaded back asCalParam should be identical to the saved one, subject to
+ * storage quantization error.
+ * It's suggested that a copy of the original storage be made before running
+ * this test nanoapp so the original storage can be retained.
+ * Note that ASH functionality is not required for CHRE.
+ */
+
+#define LOG_TAG "[AshWorld]"
+
+#ifdef CHRE_NANOAPP_INTERNAL
+namespace chre {
+namespace {
+#endif // CHRE_NANOAPP_INTERNAL
+
+uint32_t gCyclicTimerHandle;
+uint32_t gCyclicTimerCount;
+
+struct ashCalParams accCalParams = {
+ .offset = {0.0, 1.0, 2.0},
+ .offsetTempCelsius = 3.0,
+ .tempSensitivity = {4.0, 5.0, 6.0},
+ .tempIntercept = {7.0, 8.0, 9.0},
+ .scaleFactor = {10.0, 11.0, 12.0},
+ .crossAxis = {13.0, 14.0, 15.0},
+ .offsetSource = 16,
+ .offsetTempCelsiusSource = 17,
+ .tempSensitivitySource = 18,
+ .tempInterceptSource = 19,
+ .scaleFactorSource = 20,
+ .crossAxisSource = 21,
+};
+
+struct ashCalParams gyrCalParams = {
+ .offset = {100.0, 101.0, 102.0},
+ .offsetTempCelsius = 103.0,
+ .tempSensitivity = {104.0, 105.0, 106.0},
+ .tempIntercept = {107.0, 108.0, 109.0},
+ .scaleFactor = {110.0, 111.0, 112.0},
+ .crossAxis = {113.0, 114.0, 115.0},
+ .offsetSource = 116,
+ .offsetTempCelsiusSource = 117,
+ .tempSensitivitySource = 118,
+ .tempInterceptSource = 119,
+ .scaleFactorSource = 120,
+ .crossAxisSource = 121,
+};
+
+struct ashCalParams magCalParams = {
+ .offset = {200.0, 201.0, 202.0},
+ .offsetTempCelsius = 203.0,
+ .tempSensitivity = {204.0, 205.0, 206.0},
+ .tempIntercept = {207.0, 208.0, 209.0},
+ .scaleFactor = {210.0, 211.0, 212.0},
+ .crossAxis = {213.0, 214.0, 215.0},
+ .offsetSource = 216,
+ .offsetTempCelsiusSource = 217,
+ .tempSensitivitySource = 218,
+ .tempInterceptSource = 219,
+ .scaleFactorSource = 220,
+ .crossAxisSource = 221,
+};
+
+struct ashCalInfo accCalInfo = {
+ .bias = {0.1f, -0.1f, 0.2f},
+ .compMatrix = {1.0f, 0.1f, -0.1f, 0.2f, -0.2f, 1.0f, 0.3f, -0.3f, 1.0f},
+ .accuracy = 1,
+};
+
+struct ashCalInfo gyrCalInfo = {
+ .bias = {0.2f, -0.2f, 0.1f},
+ .compMatrix = {1.0f, 0.2f, -0.2f, 0.4f, -0.4f, 1.0f, 0.6f, -0.6f, 1.0f},
+ .accuracy = 2,
+};
+
+struct ashCalInfo magCalInfo = {
+ .bias = {10, -10, 20},
+ .compMatrix = {1.0f, -0.1f, 0.1f, -0.2f, 0.2f, 1.0f, -0.3f, 0.3f, 1.0f},
+ .accuracy = 3,
+};
+
+bool nanoappStart() {
+ LOGI("App started on platform ID %" PRIx64, chreGetPlatformId());
+
+ gCyclicTimerHandle =
+ chreTimerSet(3000000000 /* duration: 3sec */,
+ &gCyclicTimerHandle /* data */, false /* oneShot */);
+ gCyclicTimerCount = 0;
+ return true;
+}
+
+void handleTimerEvent(const void *eventData) {
+ LOGI("Cyclic timer event received %" PRIu32, gCyclicTimerCount);
+ bool success = false;
+ uint64_t tic = 0, toc = 0;
+
+ uint8_t sensor = CHRE_SENSOR_TYPE_ACCELEROMETER;
+ struct ashCalParams *sensorCalParams = &accCalParams;
+ struct ashCalInfo *sensorCalInfo = &accCalInfo;
+ if ((gCyclicTimerCount / 3) == 1) {
+ sensor = CHRE_SENSOR_TYPE_GYROSCOPE;
+ sensorCalParams = &gyrCalParams;
+ sensorCalInfo = &gyrCalInfo;
+ } else if ((gCyclicTimerCount / 3) == 2) {
+ sensor = CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD;
+ sensorCalParams = &magCalParams;
+ sensorCalInfo = &magCalInfo;
+ }
+
+ if (gCyclicTimerCount >= 9) {
+ chreTimerCancel(gCyclicTimerHandle);
+ LOGI("Timer cancelled");
+ } else if (gCyclicTimerCount % 3 == 0) {
+ tic = chreGetTime();
+ success = ashSaveCalibrationParams(sensor, sensorCalParams);
+ toc = chreGetTime();
+ LOGI("*** save sensor %" PRIu8 ": %s, time %" PRIu64 " us", sensor,
+ success ? "success" : "failure", (toc - tic) / 1000);
+ } else if (gCyclicTimerCount % 3 == 1) {
+ struct ashCalParams p;
+ tic = chreGetTime();
+ success = ashLoadCalibrationParams(sensor, ASH_CAL_STORAGE_ASH, &p);
+ toc = chreGetTime();
+ LOGI("*** load sensor %" PRIu8 ": %s, time %" PRIu64 " us", sensor,
+ success ? "success" : "fail", (toc - tic) / 1000);
+
+ LOGI("offset %f %f %f", p.offset[0], p.offset[1], p.offset[2]);
+ LOGI("offsetTempCelsius %f", p.offsetTempCelsius);
+ LOGI("tempSensitivity %f %f %f", p.tempSensitivity[0], p.tempSensitivity[1],
+ p.tempSensitivity[2]);
+ LOGI("tempIntercept %f %f %f", p.tempIntercept[0], p.tempIntercept[1],
+ p.tempIntercept[2]);
+ LOGI("scaleFactor %f %f %f", p.scaleFactor[0], p.scaleFactor[1],
+ p.scaleFactor[2]);
+ LOGI("crossAxis %f %f %f", p.crossAxis[0], p.crossAxis[1], p.crossAxis[2]);
+ LOGI("%" PRIu8 " %" PRIu8 " %" PRIu8 " %" PRIu8 " %" PRIu8 " %" PRIu8,
+ p.offsetSource, p.offsetTempCelsiusSource, p.tempSensitivitySource,
+ p.tempInterceptSource, p.scaleFactorSource, p.crossAxisSource);
+ } else {
+ tic = chreGetTime();
+ success = ashSetCalibration(sensor, sensorCalInfo);
+ toc = chreGetTime();
+ LOGI("*** set sensor %" PRIu8 ": %s, time %" PRIu64 " us", sensor,
+ success ? "success" : "failure", (toc - tic) / 1000);
+ }
+
+ gCyclicTimerCount++;
+}
+
+void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
+ const void *eventData) {
+ switch (eventType) {
+ case CHRE_EVENT_TIMER:
+ handleTimerEvent(eventData);
+ break;
+ default:
+ LOGW("Unknown event received");
+ break;
+ }
+}
+
+void nanoappEnd() {
+ LOGI("Stopped");
+}
+
+#ifdef CHRE_NANOAPP_INTERNAL
+} // anonymous namespace
+} // namespace chre
+
+#include "chre/platform/static_nanoapp_init.h"
+#include "chre/util/nanoapp/app_id.h"
+
+CHRE_STATIC_NANOAPP_INIT(AshWorld, chre::kAshWorldAppId, 0);
+#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/ash_world/ash_world.mk b/apps/ash_world/ash_world.mk
new file mode 100644
index 00000000..99772d2e
--- /dev/null
+++ b/apps/ash_world/ash_world.mk
@@ -0,0 +1,12 @@
+#
+# ASH World Makefile
+#
+
+# Common Compiler Flags ########################################################
+
+# Include paths.
+COMMON_CFLAGS += -Iapps/ash_world/include
+
+# Common Source Files ##########################################################
+
+COMMON_SRCS += apps/ash_world/ash_world.cc
diff --git a/apps/audio_stress_test/Makefile b/apps/audio_stress_test/Makefile
index 7bdf99dd..74214789 100644
--- a/apps/audio_stress_test/Makefile
+++ b/apps/audio_stress_test/Makefile
@@ -32,10 +32,6 @@ COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_DEBUG
COMMON_SRCS += audio_stress_test.cc
COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/audio.cc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_AUDIO = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/audio_world/Makefile b/apps/audio_world/Makefile
index 67a9fb98..3fda54e3 100644
--- a/apps/audio_world/Makefile
+++ b/apps/audio_world/Makefile
@@ -40,10 +40,6 @@ COMMON_SRCS += $(CHRE_PREFIX)/external/kiss_fft/kiss_fft.c
COMMON_SRCS += $(CHRE_PREFIX)/external/kiss_fft/kiss_fftr.c
COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/audio.cc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_AUDIO = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/audio_world/audio_world.cc b/apps/audio_world/audio_world.cc
index 02d981c3..ed1c93f6 100644
--- a/apps/audio_world/audio_world.cc
+++ b/apps/audio_world/audio_world.cc
@@ -124,25 +124,6 @@ void handleAudioSamplingChangeEvent(
event->handle, event->status.suspended);
}
-void handleAudioSettingChangedNotification(
- const struct chreUserSettingChangedEvent *event) {
- // The following checks on event and setting are primarily meant for
- // debugging and/or bring-up. Production nanoapps should not need to worry
- // about these scenarios since CHRE guarantees that out-of-memory conditions
- // are caught during event allocation before they're posted, and the setting
- // is guaranteed to be a member of enum chreUserSettingState.
- if (event != nullptr) {
- if (event->setting != CHRE_USER_SETTING_MICROPHONE) {
- LOGE("Unexpected setting ID: %u", event->setting);
- } else {
- LOGI("Microphone settings notification: status change to %d",
- static_cast<int8_t>(event->settingState));
- }
- } else {
- LOGE("Null event data for settings changed event");
- }
-}
-
bool nanoappStart() {
LOGI("Started");
@@ -168,13 +149,6 @@ bool nanoappStart() {
}
initKissFft();
-
- int8_t settingState = chreUserSettingGetState(CHRE_USER_SETTING_MICROPHONE);
- LOGD("Microphone setting status: %d", settingState);
-
- chreUserSettingConfigureEvents(CHRE_USER_SETTING_MICROPHONE,
- true /* enable */);
-
return true;
}
@@ -189,12 +163,6 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
handleAudioSamplingChangeEvent(
static_cast<const struct chreAudioSourceStatusEvent *>(eventData));
break;
-
- case CHRE_EVENT_SETTING_CHANGED_MICROPHONE:
- handleAudioSettingChangedNotification(
- static_cast<const struct chreUserSettingChangedEvent *>(eventData));
- break;
-
default:
LOGW("Unknown event received");
break;
@@ -206,10 +174,6 @@ void nanoappEnd() {
chreAudioConfigureSource(gAudioHandle, false /* enable */,
0 /* bufferDuration */, 0 /* deliveryInterval */);
}
-
- chreUserSettingConfigureEvents(CHRE_USER_SETTING_MICROPHONE,
- false /* enable */);
-
LOGI("Stopped");
}
@@ -219,8 +183,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(AudioWorld, chre::kAudioWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_AUDIO);
+CHRE_STATIC_NANOAPP_INIT(AudioWorld, chre::kAudioWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/debug_dump_world/debug_dump_world.cc b/apps/debug_dump_world/debug_dump_world.cc
index 4f4b82b2..206665e4 100644
--- a/apps/debug_dump_world/debug_dump_world.cc
+++ b/apps/debug_dump_world/debug_dump_world.cc
@@ -81,8 +81,6 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(DebugDumpWorld, chre::kDebugDumpWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_NONE);
+CHRE_STATIC_NANOAPP_INIT(DebugDumpWorld, chre::kDebugDumpWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/gnss_world/Makefile b/apps/gnss_world/Makefile
index af43b7e7..cc4bc744 100644
--- a/apps/gnss_world/Makefile
+++ b/apps/gnss_world/Makefile
@@ -35,10 +35,6 @@ COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_DEBUG
COMMON_SRCS += gnss_world.cc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_GNSS = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/gnss_world/gnss_world.cc b/apps/gnss_world/gnss_world.cc
index 640595d6..756039c7 100644
--- a/apps/gnss_world/gnss_world.cc
+++ b/apps/gnss_world/gnss_world.cc
@@ -32,7 +32,7 @@ namespace {
constexpr bool kEnableLocationTest = true;
constexpr bool kEnableMeasurementTest = true;
-//! A fake/unused cookie to pass into the session async and timer request.
+//! A dummy cookie to pass into the session async and timer request.
const uint32_t kLocationSessionCookie = 0x1337;
const uint32_t kMeasurementSessionCookie = 0xdaad;
@@ -241,18 +241,31 @@ void handleGnssDataEvent(const chreGnssDataEvent *event) {
bool nanoappStart() {
LOGI("App started as instance %" PRIu32, chreGetInstanceId());
+ const char *gnssCapabilitiesStr;
uint32_t gnssCapabilities = chreGnssGetCapabilities();
-
- if ((gnssCapabilities & CHRE_GNSS_CAPABILITIES_LOCATION) != 0) {
- gLocationSupported = true;
- }
- if ((gnssCapabilities & CHRE_GNSS_CAPABILITIES_MEASUREMENTS) != 0) {
- gMeasurementSupported = true;
+ switch (gnssCapabilities) {
+ case CHRE_GNSS_CAPABILITIES_LOCATION | CHRE_GNSS_CAPABILITIES_MEASUREMENTS:
+ gnssCapabilitiesStr = "LOCATION | MEASUREMENTS";
+ gLocationSupported = true;
+ gMeasurementSupported = true;
+ break;
+ case CHRE_GNSS_CAPABILITIES_LOCATION:
+ gnssCapabilitiesStr = "LOCATION";
+ gLocationSupported = true;
+ break;
+ case CHRE_GNSS_CAPABILITIES_MEASUREMENTS:
+ gnssCapabilitiesStr = "MEASUREMENTS";
+ gMeasurementSupported = true;
+ break;
+ case CHRE_GNSS_CAPABILITIES_NONE:
+ gnssCapabilitiesStr = "NONE";
+ break;
+ default:
+ gnssCapabilitiesStr = "INVALID";
}
- // TODO: Add logic for
- // CHRE_GNSS_CAPABILITIES_GNSS_ENGINE_BASED_PASSIVE_LISTENER
- LOGI("Detected GNSS support as 0x%" PRIx32, gnssCapabilities);
+ LOGI("Detected GNSS support as: %s (%" PRIu32 ")", gnssCapabilitiesStr,
+ gnssCapabilities);
if (gLocationSupported && kEnableLocationTest) {
makeLocationRequest();
@@ -296,8 +309,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(GnssWorld, chre::kGnssWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_GNSS);
+CHRE_STATIC_NANOAPP_INIT(GnssWorld, chre::kGnssWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/hello_world/hello_world.cc b/apps/hello_world/hello_world.cc
index c7022238..1238e437 100644
--- a/apps/hello_world/hello_world.cc
+++ b/apps/hello_world/hello_world.cc
@@ -53,8 +53,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(HelloWorld, chre::kHelloWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_NONE);
+CHRE_STATIC_NANOAPP_INIT(HelloWorld, chre::kHelloWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/host_awake_world/Makefile b/apps/host_awake_world/Makefile
index fae2466e..5127efef 100644
--- a/apps/host_awake_world/Makefile
+++ b/apps/host_awake_world/Makefile
@@ -26,9 +26,6 @@ NANOAPP_NAME_STRING = \"Host\ Awake\ World\"
COMMON_CFLAGS += -I.
-# Defines
-COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_DEBUG
-
# Common Source Files ##########################################################
COMMON_SRCS += host_awake_world.cc
diff --git a/apps/host_awake_world/host_awake_world.cc b/apps/host_awake_world/host_awake_world.cc
index 00798c70..4238d1ad 100644
--- a/apps/host_awake_world/host_awake_world.cc
+++ b/apps/host_awake_world/host_awake_world.cc
@@ -84,8 +84,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(HostAwakeWorld, chre::kHostAwakeWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_NONE);
+CHRE_STATIC_NANOAPP_INIT(HostAwakeWorld, chre::kHostAwakeWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/message_world/message_world.cc b/apps/message_world/message_world.cc
index f844f1ae..49e1f185 100644
--- a/apps/message_world/message_world.cc
+++ b/apps/message_world/message_world.cc
@@ -84,8 +84,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(MessageWorld, chre::kMessageWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_NONE);
+CHRE_STATIC_NANOAPP_INIT(MessageWorld, chre::kMessageWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/power_test/common/idl/chre_power_test.fbs b/apps/power_test/common/idl/chre_power_test.fbs
index 5d0a324e..9276a74c 100644
--- a/apps/power_test/common/idl/chre_power_test.fbs
+++ b/apps/power_test/common/idl/chre_power_test.fbs
@@ -35,8 +35,6 @@ enum MessageType : uint {
BREAK_IT_TEST,
/// Should be used with NanoappResponseMessage
NANOAPP_RESPONSE,
- /// Should be used with GnssMeasurementMessage
- GNSS_MEASUREMENT_TEST,
}
/// Represents a message to ask the nanoapp to create a timer that wakes up at
@@ -46,40 +44,11 @@ table TimerMessage {
wakeup_interval_ns:ulong;
}
-/// All the various WiFi scan types that can be interacted with inside the
-/// nanoapp. The values used here map directly to values from the CHRE API.
-enum WifiScanType : ubyte {
- ACTIVE = 0,
- ACTIVE_PLUS_PASSIVE_DFS = 1,
- PASSIVE = 2,
- NO_PREFERENCE = 3,
-}
-
-/// All the various WiFi radio chain preferences that can be interacted with
-/// inside the nanoapp. The values used here map directly to values from the
-/// CHRE API.
-enum WifiRadioChain : ubyte {
- DEFAULT = 0,
- LOW_LATENCY = 1,
- LOW_POWER = 2,
- HIGH_ACCURACY = 3,
-}
-
-/// All the various WiFi channel sets that can be interacted with inside the
-/// nanoapp. The values used here map directly to values from the CHRE API.
-enum WifiChannelSet : ubyte {
- NON_DFS = 0,
- ALL = 1,
-}
-
/// Represents a message to ask the nanoapp to start or stop WiFi scanning and
/// the scan interval to use if scanning is being started
table WifiScanMessage {
enable:bool;
scan_interval_ns:ulong;
- scan_type:WifiScanType;
- radio_chain:WifiRadioChain;
- channel_set:WifiChannelSet;
}
/// Represents a message to ask the nanoapp to start or stop Gnss location
@@ -122,7 +91,6 @@ enum SensorType : ubyte {
LIGHT = 12,
PROXIMITY = 13,
STEP_DETECT = 23,
- STEP_COUNTER = 24,
UNCALIBRATED_ACCELEROMETER = 55,
ACCELEROMETER_TEMPERATURE = 56,
GYROSCOPE_TEMPERATURE = 57,
@@ -150,10 +118,3 @@ table BreakItMessage {
table NanoappResponseMessage {
success:bool;
}
-
-/// Represents a message to ask the nanoapp to start or stop Gnss measurement
-/// sampling at the requested interval
-table GnssMeasurementMessage {
- enable:bool;
- min_interval_millis:uint;
-} \ No newline at end of file
diff --git a/apps/power_test/common/idl/chre_power_test_generated.h b/apps/power_test/common/idl/chre_power_test_generated.h
index df1b812a..918bec1b 100644
--- a/apps/power_test/common/idl/chre_power_test_generated.h
+++ b/apps/power_test/common/idl/chre_power_test_generated.h
@@ -41,10 +41,6 @@ struct NanoappResponseMessage;
struct NanoappResponseMessageBuilder;
struct NanoappResponseMessageT;
-struct GnssMeasurementMessage;
-struct GnssMeasurementMessageBuilder;
-struct GnssMeasurementMessageT;
-
/// Indicates which of the following messages is being sent to / from the
/// nanoapp. Use uint as the base type to match the message type in
/// chreMessageFromHostData.
@@ -66,13 +62,11 @@ enum class MessageType : uint32_t {
BREAK_IT_TEST = 7,
/// Should be used with NanoappResponseMessage
NANOAPP_RESPONSE = 8,
- /// Should be used with GnssMeasurementMessage
- GNSS_MEASUREMENT_TEST = 9,
MIN = UNSPECIFIED,
- MAX = GNSS_MEASUREMENT_TEST
+ MAX = NANOAPP_RESPONSE
};
-inline const MessageType (&EnumValuesMessageType())[10] {
+inline const MessageType (&EnumValuesMessageType())[9] {
static const MessageType values[] = {
MessageType::UNSPECIFIED,
MessageType::TIMER_TEST,
@@ -82,14 +76,13 @@ inline const MessageType (&EnumValuesMessageType())[10] {
MessageType::AUDIO_REQUEST_TEST,
MessageType::SENSOR_REQUEST_TEST,
MessageType::BREAK_IT_TEST,
- MessageType::NANOAPP_RESPONSE,
- MessageType::GNSS_MEASUREMENT_TEST
+ MessageType::NANOAPP_RESPONSE
};
return values;
}
inline const char * const *EnumNamesMessageType() {
- static const char * const names[11] = {
+ static const char * const names[10] = {
"UNSPECIFIED",
"TIMER_TEST",
"WIFI_SCAN_TEST",
@@ -99,127 +92,17 @@ inline const char * const *EnumNamesMessageType() {
"SENSOR_REQUEST_TEST",
"BREAK_IT_TEST",
"NANOAPP_RESPONSE",
- "GNSS_MEASUREMENT_TEST",
nullptr
};
return names;
}
inline const char *EnumNameMessageType(MessageType e) {
- if (flatbuffers::IsOutRange(e, MessageType::UNSPECIFIED, MessageType::GNSS_MEASUREMENT_TEST)) return "";
+ if (flatbuffers::IsOutRange(e, MessageType::UNSPECIFIED, MessageType::NANOAPP_RESPONSE)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesMessageType()[index];
}
-/// All the various WiFi scan types that can be interacted with inside the
-/// nanoapp. The values used here map directly to values from the CHRE API.
-enum class WifiScanType : uint8_t {
- ACTIVE = 0,
- ACTIVE_PLUS_PASSIVE_DFS = 1,
- PASSIVE = 2,
- NO_PREFERENCE = 3,
- MIN = ACTIVE,
- MAX = NO_PREFERENCE
-};
-
-inline const WifiScanType (&EnumValuesWifiScanType())[4] {
- static const WifiScanType values[] = {
- WifiScanType::ACTIVE,
- WifiScanType::ACTIVE_PLUS_PASSIVE_DFS,
- WifiScanType::PASSIVE,
- WifiScanType::NO_PREFERENCE
- };
- return values;
-}
-
-inline const char * const *EnumNamesWifiScanType() {
- static const char * const names[5] = {
- "ACTIVE",
- "ACTIVE_PLUS_PASSIVE_DFS",
- "PASSIVE",
- "NO_PREFERENCE",
- nullptr
- };
- return names;
-}
-
-inline const char *EnumNameWifiScanType(WifiScanType e) {
- if (flatbuffers::IsOutRange(e, WifiScanType::ACTIVE, WifiScanType::NO_PREFERENCE)) return "";
- const size_t index = static_cast<size_t>(e);
- return EnumNamesWifiScanType()[index];
-}
-
-/// All the various WiFi radio chain preferences that can be interacted with
-/// inside the nanoapp. The values used here map directly to values from the
-/// CHRE API.
-enum class WifiRadioChain : uint8_t {
- DEFAULT = 0,
- LOW_LATENCY = 1,
- LOW_POWER = 2,
- HIGH_ACCURACY = 3,
- MIN = DEFAULT,
- MAX = HIGH_ACCURACY
-};
-
-inline const WifiRadioChain (&EnumValuesWifiRadioChain())[4] {
- static const WifiRadioChain values[] = {
- WifiRadioChain::DEFAULT,
- WifiRadioChain::LOW_LATENCY,
- WifiRadioChain::LOW_POWER,
- WifiRadioChain::HIGH_ACCURACY
- };
- return values;
-}
-
-inline const char * const *EnumNamesWifiRadioChain() {
- static const char * const names[5] = {
- "DEFAULT",
- "LOW_LATENCY",
- "LOW_POWER",
- "HIGH_ACCURACY",
- nullptr
- };
- return names;
-}
-
-inline const char *EnumNameWifiRadioChain(WifiRadioChain e) {
- if (flatbuffers::IsOutRange(e, WifiRadioChain::DEFAULT, WifiRadioChain::HIGH_ACCURACY)) return "";
- const size_t index = static_cast<size_t>(e);
- return EnumNamesWifiRadioChain()[index];
-}
-
-/// All the various WiFi channel sets that can be interacted with inside the
-/// nanoapp. The values used here map directly to values from the CHRE API.
-enum class WifiChannelSet : uint8_t {
- NON_DFS = 0,
- ALL = 1,
- MIN = NON_DFS,
- MAX = ALL
-};
-
-inline const WifiChannelSet (&EnumValuesWifiChannelSet())[2] {
- static const WifiChannelSet values[] = {
- WifiChannelSet::NON_DFS,
- WifiChannelSet::ALL
- };
- return values;
-}
-
-inline const char * const *EnumNamesWifiChannelSet() {
- static const char * const names[3] = {
- "NON_DFS",
- "ALL",
- nullptr
- };
- return names;
-}
-
-inline const char *EnumNameWifiChannelSet(WifiChannelSet e) {
- if (flatbuffers::IsOutRange(e, WifiChannelSet::NON_DFS, WifiChannelSet::ALL)) return "";
- const size_t index = static_cast<size_t>(e);
- return EnumNamesWifiChannelSet()[index];
-}
-
/// All the various sensors that can be interacted with inside the nanoapp.
/// The values used here map directly to values from the CHRE API
enum class SensorType : uint8_t {
@@ -235,7 +118,6 @@ enum class SensorType : uint8_t {
LIGHT = 12,
PROXIMITY = 13,
STEP_DETECT = 23,
- STEP_COUNTER = 24,
UNCALIBRATED_ACCELEROMETER = 55,
ACCELEROMETER_TEMPERATURE = 56,
GYROSCOPE_TEMPERATURE = 57,
@@ -244,7 +126,7 @@ enum class SensorType : uint8_t {
MAX = GEOMAGNETIC_FIELD_TEMPERATURE
};
-inline const SensorType (&EnumValuesSensorType())[17] {
+inline const SensorType (&EnumValuesSensorType())[16] {
static const SensorType values[] = {
SensorType::UNKNOWN,
SensorType::ACCELEROMETER,
@@ -258,7 +140,6 @@ inline const SensorType (&EnumValuesSensorType())[17] {
SensorType::LIGHT,
SensorType::PROXIMITY,
SensorType::STEP_DETECT,
- SensorType::STEP_COUNTER,
SensorType::UNCALIBRATED_ACCELEROMETER,
SensorType::ACCELEROMETER_TEMPERATURE,
SensorType::GYROSCOPE_TEMPERATURE,
@@ -293,7 +174,7 @@ inline const char * const *EnumNamesSensorType() {
"",
"",
"STEP_DETECT",
- "STEP_COUNTER",
+ "",
"",
"",
"",
@@ -419,15 +300,9 @@ struct WifiScanMessageT : public flatbuffers::NativeTable {
typedef WifiScanMessage TableType;
bool enable;
uint64_t scan_interval_ns;
- chre::power_test::WifiScanType scan_type;
- chre::power_test::WifiRadioChain radio_chain;
- chre::power_test::WifiChannelSet channel_set;
WifiScanMessageT()
: enable(false),
- scan_interval_ns(0),
- scan_type(chre::power_test::WifiScanType::ACTIVE),
- radio_chain(chre::power_test::WifiRadioChain::DEFAULT),
- channel_set(chre::power_test::WifiChannelSet::NON_DFS) {
+ scan_interval_ns(0) {
}
};
@@ -438,10 +313,7 @@ struct WifiScanMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef WifiScanMessageBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_ENABLE = 4,
- VT_SCAN_INTERVAL_NS = 6,
- VT_SCAN_TYPE = 8,
- VT_RADIO_CHAIN = 10,
- VT_CHANNEL_SET = 12
+ VT_SCAN_INTERVAL_NS = 6
};
bool enable() const {
return GetField<uint8_t>(VT_ENABLE, 0) != 0;
@@ -455,31 +327,10 @@ struct WifiScanMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
bool mutate_scan_interval_ns(uint64_t _scan_interval_ns) {
return SetField<uint64_t>(VT_SCAN_INTERVAL_NS, _scan_interval_ns, 0);
}
- chre::power_test::WifiScanType scan_type() const {
- return static_cast<chre::power_test::WifiScanType>(GetField<uint8_t>(VT_SCAN_TYPE, 0));
- }
- bool mutate_scan_type(chre::power_test::WifiScanType _scan_type) {
- return SetField<uint8_t>(VT_SCAN_TYPE, static_cast<uint8_t>(_scan_type), 0);
- }
- chre::power_test::WifiRadioChain radio_chain() const {
- return static_cast<chre::power_test::WifiRadioChain>(GetField<uint8_t>(VT_RADIO_CHAIN, 0));
- }
- bool mutate_radio_chain(chre::power_test::WifiRadioChain _radio_chain) {
- return SetField<uint8_t>(VT_RADIO_CHAIN, static_cast<uint8_t>(_radio_chain), 0);
- }
- chre::power_test::WifiChannelSet channel_set() const {
- return static_cast<chre::power_test::WifiChannelSet>(GetField<uint8_t>(VT_CHANNEL_SET, 0));
- }
- bool mutate_channel_set(chre::power_test::WifiChannelSet _channel_set) {
- return SetField<uint8_t>(VT_CHANNEL_SET, static_cast<uint8_t>(_channel_set), 0);
- }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint8_t>(verifier, VT_ENABLE) &&
VerifyField<uint64_t>(verifier, VT_SCAN_INTERVAL_NS) &&
- VerifyField<uint8_t>(verifier, VT_SCAN_TYPE) &&
- VerifyField<uint8_t>(verifier, VT_RADIO_CHAIN) &&
- VerifyField<uint8_t>(verifier, VT_CHANNEL_SET) &&
verifier.EndTable();
}
WifiScanMessageT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -497,15 +348,6 @@ struct WifiScanMessageBuilder {
void add_scan_interval_ns(uint64_t scan_interval_ns) {
fbb_.AddElement<uint64_t>(WifiScanMessage::VT_SCAN_INTERVAL_NS, scan_interval_ns, 0);
}
- void add_scan_type(chre::power_test::WifiScanType scan_type) {
- fbb_.AddElement<uint8_t>(WifiScanMessage::VT_SCAN_TYPE, static_cast<uint8_t>(scan_type), 0);
- }
- void add_radio_chain(chre::power_test::WifiRadioChain radio_chain) {
- fbb_.AddElement<uint8_t>(WifiScanMessage::VT_RADIO_CHAIN, static_cast<uint8_t>(radio_chain), 0);
- }
- void add_channel_set(chre::power_test::WifiChannelSet channel_set) {
- fbb_.AddElement<uint8_t>(WifiScanMessage::VT_CHANNEL_SET, static_cast<uint8_t>(channel_set), 0);
- }
explicit WifiScanMessageBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -521,15 +363,9 @@ struct WifiScanMessageBuilder {
inline flatbuffers::Offset<WifiScanMessage> CreateWifiScanMessage(
flatbuffers::FlatBufferBuilder &_fbb,
bool enable = false,
- uint64_t scan_interval_ns = 0,
- chre::power_test::WifiScanType scan_type = chre::power_test::WifiScanType::ACTIVE,
- chre::power_test::WifiRadioChain radio_chain = chre::power_test::WifiRadioChain::DEFAULT,
- chre::power_test::WifiChannelSet channel_set = chre::power_test::WifiChannelSet::NON_DFS) {
+ uint64_t scan_interval_ns = 0) {
WifiScanMessageBuilder builder_(_fbb);
builder_.add_scan_interval_ns(scan_interval_ns);
- builder_.add_channel_set(channel_set);
- builder_.add_radio_chain(radio_chain);
- builder_.add_scan_type(scan_type);
builder_.add_enable(enable);
return builder_.Finish();
}
@@ -1011,82 +847,6 @@ inline flatbuffers::Offset<NanoappResponseMessage> CreateNanoappResponseMessage(
flatbuffers::Offset<NanoappResponseMessage> CreateNanoappResponseMessage(flatbuffers::FlatBufferBuilder &_fbb, const NanoappResponseMessageT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-struct GnssMeasurementMessageT : public flatbuffers::NativeTable {
- typedef GnssMeasurementMessage TableType;
- bool enable;
- uint32_t min_interval_millis;
- GnssMeasurementMessageT()
- : enable(false),
- min_interval_millis(0) {
- }
-};
-
-/// Represents a message to ask the nanoapp to start or stop Gnss measurement
-/// sampling at the requested interval
-struct GnssMeasurementMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
- typedef GnssMeasurementMessageT NativeTableType;
- typedef GnssMeasurementMessageBuilder Builder;
- enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
- VT_ENABLE = 4,
- VT_MIN_INTERVAL_MILLIS = 6
- };
- bool enable() const {
- return GetField<uint8_t>(VT_ENABLE, 0) != 0;
- }
- bool mutate_enable(bool _enable) {
- return SetField<uint8_t>(VT_ENABLE, static_cast<uint8_t>(_enable), 0);
- }
- uint32_t min_interval_millis() const {
- return GetField<uint32_t>(VT_MIN_INTERVAL_MILLIS, 0);
- }
- bool mutate_min_interval_millis(uint32_t _min_interval_millis) {
- return SetField<uint32_t>(VT_MIN_INTERVAL_MILLIS, _min_interval_millis, 0);
- }
- bool Verify(flatbuffers::Verifier &verifier) const {
- return VerifyTableStart(verifier) &&
- VerifyField<uint8_t>(verifier, VT_ENABLE) &&
- VerifyField<uint32_t>(verifier, VT_MIN_INTERVAL_MILLIS) &&
- verifier.EndTable();
- }
- GnssMeasurementMessageT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
- void UnPackTo(GnssMeasurementMessageT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
- static flatbuffers::Offset<GnssMeasurementMessage> Pack(flatbuffers::FlatBufferBuilder &_fbb, const GnssMeasurementMessageT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-};
-
-struct GnssMeasurementMessageBuilder {
- typedef GnssMeasurementMessage Table;
- flatbuffers::FlatBufferBuilder &fbb_;
- flatbuffers::uoffset_t start_;
- void add_enable(bool enable) {
- fbb_.AddElement<uint8_t>(GnssMeasurementMessage::VT_ENABLE, static_cast<uint8_t>(enable), 0);
- }
- void add_min_interval_millis(uint32_t min_interval_millis) {
- fbb_.AddElement<uint32_t>(GnssMeasurementMessage::VT_MIN_INTERVAL_MILLIS, min_interval_millis, 0);
- }
- explicit GnssMeasurementMessageBuilder(flatbuffers::FlatBufferBuilder &_fbb)
- : fbb_(_fbb) {
- start_ = fbb_.StartTable();
- }
- GnssMeasurementMessageBuilder &operator=(const GnssMeasurementMessageBuilder &);
- flatbuffers::Offset<GnssMeasurementMessage> Finish() {
- const auto end = fbb_.EndTable(start_);
- auto o = flatbuffers::Offset<GnssMeasurementMessage>(end);
- return o;
- }
-};
-
-inline flatbuffers::Offset<GnssMeasurementMessage> CreateGnssMeasurementMessage(
- flatbuffers::FlatBufferBuilder &_fbb,
- bool enable = false,
- uint32_t min_interval_millis = 0) {
- GnssMeasurementMessageBuilder builder_(_fbb);
- builder_.add_min_interval_millis(min_interval_millis);
- builder_.add_enable(enable);
- return builder_.Finish();
-}
-
-flatbuffers::Offset<GnssMeasurementMessage> CreateGnssMeasurementMessage(flatbuffers::FlatBufferBuilder &_fbb, const GnssMeasurementMessageT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-
inline TimerMessageT *TimerMessage::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
std::unique_ptr<chre::power_test::TimerMessageT> _o = std::unique_ptr<chre::power_test::TimerMessageT>(new TimerMessageT());
UnPackTo(_o.get(), _resolver);
@@ -1127,9 +887,6 @@ inline void WifiScanMessage::UnPackTo(WifiScanMessageT *_o, const flatbuffers::r
(void)_resolver;
{ auto _e = enable(); _o->enable = _e; }
{ auto _e = scan_interval_ns(); _o->scan_interval_ns = _e; }
- { auto _e = scan_type(); _o->scan_type = _e; }
- { auto _e = radio_chain(); _o->radio_chain = _e; }
- { auto _e = channel_set(); _o->channel_set = _e; }
}
inline flatbuffers::Offset<WifiScanMessage> WifiScanMessage::Pack(flatbuffers::FlatBufferBuilder &_fbb, const WifiScanMessageT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -1142,16 +899,10 @@ inline flatbuffers::Offset<WifiScanMessage> CreateWifiScanMessage(flatbuffers::F
struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const WifiScanMessageT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
auto _enable = _o->enable;
auto _scan_interval_ns = _o->scan_interval_ns;
- auto _scan_type = _o->scan_type;
- auto _radio_chain = _o->radio_chain;
- auto _channel_set = _o->channel_set;
return chre::power_test::CreateWifiScanMessage(
_fbb,
_enable,
- _scan_interval_ns,
- _scan_type,
- _radio_chain,
- _channel_set);
+ _scan_interval_ns);
}
inline GnssLocationMessageT *GnssLocationMessage::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
@@ -1331,35 +1082,6 @@ inline flatbuffers::Offset<NanoappResponseMessage> CreateNanoappResponseMessage(
_success);
}
-inline GnssMeasurementMessageT *GnssMeasurementMessage::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- std::unique_ptr<chre::power_test::GnssMeasurementMessageT> _o = std::unique_ptr<chre::power_test::GnssMeasurementMessageT>(new GnssMeasurementMessageT());
- UnPackTo(_o.get(), _resolver);
- return _o.release();
-}
-
-inline void GnssMeasurementMessage::UnPackTo(GnssMeasurementMessageT *_o, const flatbuffers::resolver_function_t *_resolver) const {
- (void)_o;
- (void)_resolver;
- { auto _e = enable(); _o->enable = _e; }
- { auto _e = min_interval_millis(); _o->min_interval_millis = _e; }
-}
-
-inline flatbuffers::Offset<GnssMeasurementMessage> GnssMeasurementMessage::Pack(flatbuffers::FlatBufferBuilder &_fbb, const GnssMeasurementMessageT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
- return CreateGnssMeasurementMessage(_fbb, _o, _rehasher);
-}
-
-inline flatbuffers::Offset<GnssMeasurementMessage> CreateGnssMeasurementMessage(flatbuffers::FlatBufferBuilder &_fbb, const GnssMeasurementMessageT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
- (void)_rehasher;
- (void)_o;
- struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const GnssMeasurementMessageT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
- auto _enable = _o->enable;
- auto _min_interval_millis = _o->min_interval_millis;
- return chre::power_test::CreateGnssMeasurementMessage(
- _fbb,
- _enable,
- _min_interval_millis);
-}
-
} // namespace power_test
} // namespace chre
diff --git a/apps/power_test/common/include/common.h b/apps/power_test/common/include/common.h
index 5d1068fa..fc9ef980 100644
--- a/apps/power_test/common/include/common.h
+++ b/apps/power_test/common/include/common.h
@@ -27,4 +27,4 @@
#define LOG_TAG "[PowerTest]"
#endif // CHRE_TCM_BUILD
-#endif // CHRE_POWER_TEST_COMMON_H_
+#endif // CHRE_POWER_TEST_COMMON_H_ \ No newline at end of file
diff --git a/apps/power_test/common/include/generated/chre_power_test_generated.h b/apps/power_test/common/include/generated/chre_power_test_generated.h
index b843d206..70ef4582 100644
--- a/apps/power_test/common/include/generated/chre_power_test_generated.h
+++ b/apps/power_test/common/include/generated/chre_power_test_generated.h
@@ -33,9 +33,6 @@ struct BreakItMessageBuilder;
struct NanoappResponseMessage;
struct NanoappResponseMessageBuilder;
-struct GnssMeasurementMessage;
-struct GnssMeasurementMessageBuilder;
-
/// Indicates which of the following messages is being sent to / from the
/// nanoapp. Use uint as the base type to match the message type in
/// chreMessageFromHostData.
@@ -57,13 +54,11 @@ enum class MessageType : uint32_t {
BREAK_IT_TEST = 7,
/// Should be used with NanoappResponseMessage
NANOAPP_RESPONSE = 8,
- /// Should be used with GnssMeasurementMessage
- GNSS_MEASUREMENT_TEST = 9,
MIN = UNSPECIFIED,
- MAX = GNSS_MEASUREMENT_TEST
+ MAX = NANOAPP_RESPONSE
};
-inline const MessageType (&EnumValuesMessageType())[10] {
+inline const MessageType (&EnumValuesMessageType())[9] {
static const MessageType values[] = {
MessageType::UNSPECIFIED,
MessageType::TIMER_TEST,
@@ -73,14 +68,13 @@ inline const MessageType (&EnumValuesMessageType())[10] {
MessageType::AUDIO_REQUEST_TEST,
MessageType::SENSOR_REQUEST_TEST,
MessageType::BREAK_IT_TEST,
- MessageType::NANOAPP_RESPONSE,
- MessageType::GNSS_MEASUREMENT_TEST
+ MessageType::NANOAPP_RESPONSE
};
return values;
}
inline const char * const *EnumNamesMessageType() {
- static const char * const names[11] = {
+ static const char * const names[10] = {
"UNSPECIFIED",
"TIMER_TEST",
"WIFI_SCAN_TEST",
@@ -90,127 +84,17 @@ inline const char * const *EnumNamesMessageType() {
"SENSOR_REQUEST_TEST",
"BREAK_IT_TEST",
"NANOAPP_RESPONSE",
- "GNSS_MEASUREMENT_TEST",
nullptr
};
return names;
}
inline const char *EnumNameMessageType(MessageType e) {
- if (flatbuffers::IsOutRange(e, MessageType::UNSPECIFIED, MessageType::GNSS_MEASUREMENT_TEST)) return "";
+ if (flatbuffers::IsOutRange(e, MessageType::UNSPECIFIED, MessageType::NANOAPP_RESPONSE)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesMessageType()[index];
}
-/// All the various WiFi scan types that can be interacted with inside the
-/// nanoapp. The values used here map directly to values from the CHRE API.
-enum class WifiScanType : uint8_t {
- ACTIVE = 0,
- ACTIVE_PLUS_PASSIVE_DFS = 1,
- PASSIVE = 2,
- NO_PREFERENCE = 3,
- MIN = ACTIVE,
- MAX = NO_PREFERENCE
-};
-
-inline const WifiScanType (&EnumValuesWifiScanType())[4] {
- static const WifiScanType values[] = {
- WifiScanType::ACTIVE,
- WifiScanType::ACTIVE_PLUS_PASSIVE_DFS,
- WifiScanType::PASSIVE,
- WifiScanType::NO_PREFERENCE
- };
- return values;
-}
-
-inline const char * const *EnumNamesWifiScanType() {
- static const char * const names[5] = {
- "ACTIVE",
- "ACTIVE_PLUS_PASSIVE_DFS",
- "PASSIVE",
- "NO_PREFERENCE",
- nullptr
- };
- return names;
-}
-
-inline const char *EnumNameWifiScanType(WifiScanType e) {
- if (flatbuffers::IsOutRange(e, WifiScanType::ACTIVE, WifiScanType::NO_PREFERENCE)) return "";
- const size_t index = static_cast<size_t>(e);
- return EnumNamesWifiScanType()[index];
-}
-
-/// All the various WiFi radio chain preferences that can be interacted with
-/// inside the nanoapp. The values used here map directly to values from the
-/// CHRE API.
-enum class WifiRadioChain : uint8_t {
- DEFAULT = 0,
- LOW_LATENCY = 1,
- LOW_POWER = 2,
- HIGH_ACCURACY = 3,
- MIN = DEFAULT,
- MAX = HIGH_ACCURACY
-};
-
-inline const WifiRadioChain (&EnumValuesWifiRadioChain())[4] {
- static const WifiRadioChain values[] = {
- WifiRadioChain::DEFAULT,
- WifiRadioChain::LOW_LATENCY,
- WifiRadioChain::LOW_POWER,
- WifiRadioChain::HIGH_ACCURACY
- };
- return values;
-}
-
-inline const char * const *EnumNamesWifiRadioChain() {
- static const char * const names[5] = {
- "DEFAULT",
- "LOW_LATENCY",
- "LOW_POWER",
- "HIGH_ACCURACY",
- nullptr
- };
- return names;
-}
-
-inline const char *EnumNameWifiRadioChain(WifiRadioChain e) {
- if (flatbuffers::IsOutRange(e, WifiRadioChain::DEFAULT, WifiRadioChain::HIGH_ACCURACY)) return "";
- const size_t index = static_cast<size_t>(e);
- return EnumNamesWifiRadioChain()[index];
-}
-
-/// All the various WiFi channel sets that can be interacted with inside the
-/// nanoapp. The values used here map directly to values from the CHRE API.
-enum class WifiChannelSet : uint8_t {
- NON_DFS = 0,
- ALL = 1,
- MIN = NON_DFS,
- MAX = ALL
-};
-
-inline const WifiChannelSet (&EnumValuesWifiChannelSet())[2] {
- static const WifiChannelSet values[] = {
- WifiChannelSet::NON_DFS,
- WifiChannelSet::ALL
- };
- return values;
-}
-
-inline const char * const *EnumNamesWifiChannelSet() {
- static const char * const names[3] = {
- "NON_DFS",
- "ALL",
- nullptr
- };
- return names;
-}
-
-inline const char *EnumNameWifiChannelSet(WifiChannelSet e) {
- if (flatbuffers::IsOutRange(e, WifiChannelSet::NON_DFS, WifiChannelSet::ALL)) return "";
- const size_t index = static_cast<size_t>(e);
- return EnumNamesWifiChannelSet()[index];
-}
-
/// All the various sensors that can be interacted with inside the nanoapp.
/// The values used here map directly to values from the CHRE API
enum class SensorType : uint8_t {
@@ -226,7 +110,6 @@ enum class SensorType : uint8_t {
LIGHT = 12,
PROXIMITY = 13,
STEP_DETECT = 23,
- STEP_COUNTER = 24,
UNCALIBRATED_ACCELEROMETER = 55,
ACCELEROMETER_TEMPERATURE = 56,
GYROSCOPE_TEMPERATURE = 57,
@@ -235,7 +118,7 @@ enum class SensorType : uint8_t {
MAX = GEOMAGNETIC_FIELD_TEMPERATURE
};
-inline const SensorType (&EnumValuesSensorType())[17] {
+inline const SensorType (&EnumValuesSensorType())[16] {
static const SensorType values[] = {
SensorType::UNKNOWN,
SensorType::ACCELEROMETER,
@@ -249,7 +132,6 @@ inline const SensorType (&EnumValuesSensorType())[17] {
SensorType::LIGHT,
SensorType::PROXIMITY,
SensorType::STEP_DETECT,
- SensorType::STEP_COUNTER,
SensorType::UNCALIBRATED_ACCELEROMETER,
SensorType::ACCELEROMETER_TEMPERATURE,
SensorType::GYROSCOPE_TEMPERATURE,
@@ -284,7 +166,7 @@ inline const char * const *EnumNamesSensorType() {
"",
"",
"STEP_DETECT",
- "STEP_COUNTER",
+ "",
"",
"",
"",
@@ -390,10 +272,7 @@ struct WifiScanMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef WifiScanMessageBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_ENABLE = 4,
- VT_SCAN_INTERVAL_NS = 6,
- VT_SCAN_TYPE = 8,
- VT_RADIO_CHAIN = 10,
- VT_CHANNEL_SET = 12
+ VT_SCAN_INTERVAL_NS = 6
};
bool enable() const {
return GetField<uint8_t>(VT_ENABLE, 0) != 0;
@@ -401,22 +280,10 @@ struct WifiScanMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
uint64_t scan_interval_ns() const {
return GetField<uint64_t>(VT_SCAN_INTERVAL_NS, 0);
}
- chre::power_test::WifiScanType scan_type() const {
- return static_cast<chre::power_test::WifiScanType>(GetField<uint8_t>(VT_SCAN_TYPE, 0));
- }
- chre::power_test::WifiRadioChain radio_chain() const {
- return static_cast<chre::power_test::WifiRadioChain>(GetField<uint8_t>(VT_RADIO_CHAIN, 0));
- }
- chre::power_test::WifiChannelSet channel_set() const {
- return static_cast<chre::power_test::WifiChannelSet>(GetField<uint8_t>(VT_CHANNEL_SET, 0));
- }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint8_t>(verifier, VT_ENABLE) &&
VerifyField<uint64_t>(verifier, VT_SCAN_INTERVAL_NS) &&
- VerifyField<uint8_t>(verifier, VT_SCAN_TYPE) &&
- VerifyField<uint8_t>(verifier, VT_RADIO_CHAIN) &&
- VerifyField<uint8_t>(verifier, VT_CHANNEL_SET) &&
verifier.EndTable();
}
};
@@ -431,15 +298,6 @@ struct WifiScanMessageBuilder {
void add_scan_interval_ns(uint64_t scan_interval_ns) {
fbb_.AddElement<uint64_t>(WifiScanMessage::VT_SCAN_INTERVAL_NS, scan_interval_ns, 0);
}
- void add_scan_type(chre::power_test::WifiScanType scan_type) {
- fbb_.AddElement<uint8_t>(WifiScanMessage::VT_SCAN_TYPE, static_cast<uint8_t>(scan_type), 0);
- }
- void add_radio_chain(chre::power_test::WifiRadioChain radio_chain) {
- fbb_.AddElement<uint8_t>(WifiScanMessage::VT_RADIO_CHAIN, static_cast<uint8_t>(radio_chain), 0);
- }
- void add_channel_set(chre::power_test::WifiChannelSet channel_set) {
- fbb_.AddElement<uint8_t>(WifiScanMessage::VT_CHANNEL_SET, static_cast<uint8_t>(channel_set), 0);
- }
explicit WifiScanMessageBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -455,15 +313,9 @@ struct WifiScanMessageBuilder {
inline flatbuffers::Offset<WifiScanMessage> CreateWifiScanMessage(
flatbuffers::FlatBufferBuilder &_fbb,
bool enable = false,
- uint64_t scan_interval_ns = 0,
- chre::power_test::WifiScanType scan_type = chre::power_test::WifiScanType::ACTIVE,
- chre::power_test::WifiRadioChain radio_chain = chre::power_test::WifiRadioChain::DEFAULT,
- chre::power_test::WifiChannelSet channel_set = chre::power_test::WifiChannelSet::NON_DFS) {
+ uint64_t scan_interval_ns = 0) {
WifiScanMessageBuilder builder_(_fbb);
builder_.add_scan_interval_ns(scan_interval_ns);
- builder_.add_channel_set(channel_set);
- builder_.add_radio_chain(radio_chain);
- builder_.add_scan_type(scan_type);
builder_.add_enable(enable);
return builder_.Finish();
}
@@ -806,60 +658,6 @@ inline flatbuffers::Offset<NanoappResponseMessage> CreateNanoappResponseMessage(
return builder_.Finish();
}
-/// Represents a message to ask the nanoapp to start or stop Gnss measurement
-/// sampling at the requested interval
-struct GnssMeasurementMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
- typedef GnssMeasurementMessageBuilder Builder;
- enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
- VT_ENABLE = 4,
- VT_MIN_INTERVAL_MILLIS = 6
- };
- bool enable() const {
- return GetField<uint8_t>(VT_ENABLE, 0) != 0;
- }
- uint32_t min_interval_millis() const {
- return GetField<uint32_t>(VT_MIN_INTERVAL_MILLIS, 0);
- }
- bool Verify(flatbuffers::Verifier &verifier) const {
- return VerifyTableStart(verifier) &&
- VerifyField<uint8_t>(verifier, VT_ENABLE) &&
- VerifyField<uint32_t>(verifier, VT_MIN_INTERVAL_MILLIS) &&
- verifier.EndTable();
- }
-};
-
-struct GnssMeasurementMessageBuilder {
- typedef GnssMeasurementMessage Table;
- flatbuffers::FlatBufferBuilder &fbb_;
- flatbuffers::uoffset_t start_;
- void add_enable(bool enable) {
- fbb_.AddElement<uint8_t>(GnssMeasurementMessage::VT_ENABLE, static_cast<uint8_t>(enable), 0);
- }
- void add_min_interval_millis(uint32_t min_interval_millis) {
- fbb_.AddElement<uint32_t>(GnssMeasurementMessage::VT_MIN_INTERVAL_MILLIS, min_interval_millis, 0);
- }
- explicit GnssMeasurementMessageBuilder(flatbuffers::FlatBufferBuilder &_fbb)
- : fbb_(_fbb) {
- start_ = fbb_.StartTable();
- }
- GnssMeasurementMessageBuilder &operator=(const GnssMeasurementMessageBuilder &);
- flatbuffers::Offset<GnssMeasurementMessage> Finish() {
- const auto end = fbb_.EndTable(start_);
- auto o = flatbuffers::Offset<GnssMeasurementMessage>(end);
- return o;
- }
-};
-
-inline flatbuffers::Offset<GnssMeasurementMessage> CreateGnssMeasurementMessage(
- flatbuffers::FlatBufferBuilder &_fbb,
- bool enable = false,
- uint32_t min_interval_millis = 0) {
- GnssMeasurementMessageBuilder builder_(_fbb);
- builder_.add_min_interval_millis(min_interval_millis);
- builder_.add_enable(enable);
- return builder_.Finish();
-}
-
} // namespace power_test
} // namespace chre
diff --git a/apps/power_test/common/include/request_manager.h b/apps/power_test/common/include/request_manager.h
index 55ac3a13..e38e8e56 100644
--- a/apps/power_test/common/include/request_manager.h
+++ b/apps/power_test/common/include/request_manager.h
@@ -59,11 +59,6 @@ class RequestManager {
//! Holds the timer ID for each of the timer types.
uint32_t mTimerIds[TimerType::NUM_TYPES] = {CHRE_TIMER_INVALID};
- //! WiFi scan request parameters from host.
- uint8_t mWifiScanType = CHRE_WIFI_SCAN_TYPE_NO_PREFERENCE;
- uint8_t mWifiRadioChain = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT;
- uint8_t mWifiChannelSet = CHRE_WIFI_CHANNEL_SET_NON_DFS;
-
/**
* Enables or disables break-it mode. When enabled, requests WiFi / GNSS /
* Cell data at one second intervals, buffers audio at the fastest possible
@@ -113,16 +108,6 @@ class RequestManager {
uint32_t minTimeToNextFixMillis) const;
/**
- * Enables / disables GNSS measurement sampling.
- *
- * @param enable whether to enable GNSS measurement sampling
- * @param intervalMillis amount of time, in milliseconds, between each
- * GNSS measurement sample
- * @return whether the request was successful
- */
- bool requestGnssMeasurement(bool enable, uint32_t intervalMillis) const;
-
- /**
* Requests cell info. Should be invoked when a timer of TimerType::CELL
* fires.
*/
@@ -167,4 +152,4 @@ class RequestManager {
typedef chre::Singleton<chre::RequestManager> RequestManagerSingleton;
-#endif // CHRE_POWER_TEST_REQUEST_MANAGER_H_
+#endif // CHRE_POWER_TEST_REQUEST_MANAGER_H_ \ No newline at end of file
diff --git a/apps/power_test/common/power_test.cc b/apps/power_test/common/power_test.cc
index 419032c7..ef08ce41 100644
--- a/apps/power_test/common/power_test.cc
+++ b/apps/power_test/common/power_test.cc
@@ -17,7 +17,6 @@
#include <chre.h>
#include <cinttypes>
-#include "chre/util/flatbuffers/helpers.h"
#include "chre/util/nanoapp/callbacks.h"
#include "chre/util/unique_ptr.h"
#include "common.h"
@@ -30,6 +29,7 @@ namespace {
#endif // CHRE_NANOAPP_INTERNAL
using chre::power_test::MessageType;
+using flatbuffers::FlatBufferBuilder;
/**
* Responds to a host request indicating whether the request was successfully
@@ -39,16 +39,16 @@ using chre::power_test::MessageType;
* @param hostEndpoint the host endpoint that sent the request to the nanoapp
*/
void sendResponseMessageToHost(bool success, uint16_t hostEndpoint) {
- auto builder = chre::MakeUnique<chre::ChreFlatBufferBuilder>();
+ auto builder = chre::MakeUnique<FlatBufferBuilder>();
if (builder.isNull()) {
LOG_OOM();
} else {
builder->Finish(
chre::power_test::CreateNanoappResponseMessage(*builder, success));
- // TODO: Modify this logic to remove the buffer copy now that the latest
- // version of flatbuffers allows releasing the underlying buffer from the
- // builder.
+ // CHRE's version of flatbuffers doesn't allow releasing the underlying
+ // buffer from the builder so copy it into a new buffer to be sent to the
+ // host.
size_t bufferCopySize = builder->GetSize();
void *buffer = chreHeapAlloc(bufferCopySize);
if (buffer == nullptr) {
@@ -96,9 +96,7 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
case CHRE_EVENT_WIFI_SCAN_RESULT: {
const struct chreWifiScanEvent *event =
static_cast<const struct chreWifiScanEvent *>(eventData);
- LOGD("Wifi scan received with %" PRIu8 " results, scanType %" PRIu8
- ", radioChainPref %" PRIu8,
- event->resultCount, event->scanType, event->radioChainPref);
+ LOGD("Wifi scan received with %" PRIu8 " results", event->resultCount);
break;
}
case CHRE_EVENT_GNSS_ASYNC_RESULT: {
@@ -111,9 +109,6 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
case CHRE_EVENT_GNSS_LOCATION:
LOGD("GNSS location received");
break;
- case CHRE_EVENT_GNSS_DATA:
- LOGD("GNSS measurement received");
- break;
case CHRE_EVENT_WWAN_CELL_INFO_RESULT:
LOGD("Cell info received");
break;
@@ -142,7 +137,7 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
default:
// TODO: Make this log less as sensor events will spam the logcat if debug
// logging is enabled.
- LOGV("Received event type %" PRIu16, eventType);
+ LOGD("Received event type %" PRIu16, eventType);
}
}
@@ -157,13 +152,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-
-using chre::NanoappPermissions;
-CHRE_STATIC_NANOAPP_INIT(PowerTest, chre::kPowerTestAppId, 0,
- NanoappPermissions::CHRE_PERMS_AUDIO |
- NanoappPermissions::CHRE_PERMS_GNSS |
- NanoappPermissions::CHRE_PERMS_WIFI |
- NanoappPermissions::CHRE_PERMS_WWAN);
+CHRE_STATIC_NANOAPP_INIT(PowerTest, chre::kPowerTestAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/power_test/common/power_test.mk b/apps/power_test/common/power_test.mk
index a648f1f2..2955147a 100644
--- a/apps/power_test/common/power_test.mk
+++ b/apps/power_test/common/power_test.mk
@@ -16,7 +16,7 @@ endif
# Nanoapp Configuration ########################################################
-NANOAPP_VERSION = 0x00020000
+NANOAPP_VERSION = 0x00000001
# Common Compiler Flags ########################################################
@@ -26,11 +26,7 @@ COMMON_CFLAGS += -I$(CHRE_PREFIX)/external/flatbuffers/include
COMMON_CFLAGS += -I$(CHRE_PREFIX)/util/include
# Defines
-COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_DEBUG
-
-# Flatbuffers configuration
-include $(CHRE_PREFIX)/external/flatbuffers/flatbuffers.mk
-COMMON_CFLAGS += $(FLATBUFFERS_CFLAGS)
+COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
# Common Source Files ##########################################################
@@ -40,13 +36,7 @@ COMMON_SRCS += $(CHRE_PREFIX)/util/dynamic_vector_base.cc
COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/audio.cc
COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/callbacks.cc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_AUDIO = true
-CHRE_NANOAPP_USES_GNSS = true
-CHRE_NANOAPP_USES_WIFI = true
-CHRE_NANOAPP_USES_WWAN = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
+include $(CHRE_PREFIX)/external/external.mk \ No newline at end of file
diff --git a/apps/power_test/common/request_manager.cc b/apps/power_test/common/request_manager.cc
index 18124c9e..940576dd 100644
--- a/apps/power_test/common/request_manager.cc
+++ b/apps/power_test/common/request_manager.cc
@@ -35,7 +35,6 @@ constexpr uint8_t kAllSensorTypes[] = {
CHRE_SENSOR_TYPE_LIGHT,
CHRE_SENSOR_TYPE_PROXIMITY,
CHRE_SENSOR_TYPE_STEP_DETECT,
- CHRE_SENSOR_TYPE_STEP_COUNTER,
CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER,
CHRE_SENSOR_TYPE_ACCELEROMETER_TEMPERATURE,
CHRE_SENSOR_TYPE_GYROSCOPE_TEMPERATURE,
@@ -62,7 +61,6 @@ chreSensorConfigureMode getModeForSensorType(uint8_t sensorType) {
case CHRE_SENSOR_TYPE_LIGHT:
case CHRE_SENSOR_TYPE_PROXIMITY:
case CHRE_SENSOR_TYPE_STEP_DETECT:
- case CHRE_SENSOR_TYPE_STEP_COUNTER:
case CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER:
case CHRE_SENSOR_TYPE_ACCELEROMETER_TEMPERATURE:
case CHRE_SENSOR_TYPE_GYROSCOPE_TEMPERATURE:
@@ -113,7 +111,6 @@ using power_test::AudioRequestMessage;
using power_test::BreakItMessage;
using power_test::CellQueryMessage;
using power_test::GnssLocationMessage;
-using power_test::GnssMeasurementMessage;
using power_test::MessageType;
using power_test::NanoappResponseMessage;
using power_test::SensorRequestMessage;
@@ -124,21 +121,15 @@ bool RequestManager::requestTimer(bool enable, TimerType type,
Nanoseconds delay) {
bool success = false;
if (enable) {
- // Stop previous request if active.
- chreTimerCancel(mTimerIds[type]);
- mTimerIds[type] = CHRE_TIMER_INVALID;
-
- // Set a timer for the new request.
NestedDataPtr<TimerType> timerType(type);
- uint32_t timerId =
- chreTimerSet(delay.toRawNanoseconds(), timerType, false /* oneShot */);
+ uint32_t timerId = chreTimerSet(delay.toRawNanoseconds(), timerType.dataPtr,
+ false /* oneShot */);
if (timerId != CHRE_TIMER_INVALID) {
success = true;
- mTimerIds[type] = timerId;
}
+ mTimerIds[type] = timerId;
} else {
success = chreTimerCancel(mTimerIds[type]);
- mTimerIds[type] = CHRE_TIMER_INVALID;
}
LOGI("RequestTimer success %d, enable %d, type %d, delay %" PRIu64, success,
enable, type, delay.toRawNanoseconds());
@@ -146,14 +137,8 @@ bool RequestManager::requestTimer(bool enable, TimerType type,
}
void RequestManager::wifiTimerCallback() const {
- struct chreWifiScanParams params = {};
- params.scanType = mWifiScanType;
- params.radioChainPref = mWifiRadioChain;
- params.channelSet = mWifiChannelSet;
- bool success = chreWifiRequestScanAsync(&params, nullptr /*cookie*/);
- LOGI("Requested WiFi - success %d, scanType %" PRIu8 " radioChain %" PRIu8
- " channelSet %" PRIu8,
- success, params.scanType, params.radioChainPref, params.channelSet);
+ bool success = chreWifiRequestScanAsyncDefault(nullptr /* cookie */);
+ LOGI("Requested WiFi - success %d", success);
}
bool RequestManager::requestGnssLocation(
@@ -172,20 +157,6 @@ bool RequestManager::requestGnssLocation(
return success;
}
-bool RequestManager::requestGnssMeasurement(bool enable,
- uint32_t intervalMillis) const {
- bool success;
- if (enable) {
- success = chreGnssMeasurementSessionStartAsync(intervalMillis,
- nullptr /* cookie */);
- } else {
- success = chreGnssMeasurementSessionStopAsync(nullptr /* cookie */);
- }
- LOGI("RequestGnssMeasurement success %d, enable %d, intervalMillis %" PRIu32,
- success, enable, intervalMillis);
- return success;
-}
-
void RequestManager::cellTimerCallback() const {
bool success = chreWwanGetCellInfoAsync(nullptr /* cookie */);
LOGI("Requested Cell - success %d", success);
@@ -278,7 +249,8 @@ bool RequestManager::requestBreakIt(bool enable) {
void RequestManager::handleTimerEvent(const void *cookie) const {
if (cookie != nullptr) {
- NestedDataPtr<TimerType> timerType(const_cast<void *>(cookie));
+ NestedDataPtr<TimerType> timerType;
+ timerType.dataPtr = const_cast<void *>(cookie);
switch (timerType.data) {
case TimerType::WAKEUP:
LOGI("Received a wakeup timer event");
@@ -314,9 +286,6 @@ bool RequestManager::handleMessageFromHost(
case MessageType::WIFI_SCAN_TEST: {
const WifiScanMessage *msg;
if (verifyMessage<WifiScanMessage>(hostMessage, &msg)) {
- mWifiScanType = static_cast<uint8_t>(msg->scan_type());
- mWifiRadioChain = static_cast<uint8_t>(msg->radio_chain());
- mWifiChannelSet = static_cast<uint8_t>(msg->channel_set());
success = requestTimer(msg->enable(), TimerType::WIFI,
Nanoseconds(msg->scan_interval_ns()));
}
@@ -362,14 +331,6 @@ bool RequestManager::handleMessageFromHost(
}
break;
}
- case MessageType::GNSS_MEASUREMENT_TEST: {
- const GnssMeasurementMessage *msg;
- if (verifyMessage<GnssMeasurementMessage>(hostMessage, &msg)) {
- success =
- requestGnssMeasurement(msg->enable(), msg->min_interval_millis());
- }
- break;
- }
default:
LOGE("Received unknown host message %" PRIu32, hostMessage.messageType);
}
@@ -377,4 +338,4 @@ bool RequestManager::handleMessageFromHost(
return success;
}
-} // namespace chre
+} // namespace chre \ No newline at end of file
diff --git a/apps/sensor_world/sensor_world.cc b/apps/sensor_world/sensor_world.cc
index e10ae942..32e69d60 100644
--- a/apps/sensor_world/sensor_world.cc
+++ b/apps/sensor_world/sensor_world.cc
@@ -51,7 +51,6 @@ constexpr bool kEnableDefault = !kBreakIt;
struct SensorState {
const uint8_t type;
- const uint8_t sensorIndex;
uint32_t handle;
bool isInitialized;
bool enable;
@@ -63,7 +62,6 @@ struct SensorState {
SensorState sensors[] = {
{
.type = CHRE_SENSOR_TYPE_ACCELEROMETER,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -73,7 +71,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_INSTANT_MOTION_DETECT,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = false, // InstantMotion is triggered by Prox
@@ -83,7 +80,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_STATIONARY_DETECT,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = false, // StationaryDetect is triggered by Prox
@@ -93,7 +89,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_GYROSCOPE,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -103,7 +98,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -113,7 +107,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_PRESSURE,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -123,7 +116,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_LIGHT,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -133,7 +125,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_PROXIMITY,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -142,28 +133,7 @@ SensorState sensors[] = {
.info = {},
},
{
- .type = CHRE_SENSOR_TYPE_STEP_DETECT,
- .sensorIndex = 0,
- .handle = 0,
- .isInitialized = false,
- .enable = kEnableDefault,
- .interval = CHRE_SENSOR_INTERVAL_DEFAULT,
- .latency = CHRE_SENSOR_LATENCY_ASAP,
- .info = {},
- },
- {
- .type = CHRE_SENSOR_TYPE_STEP_COUNTER,
- .sensorIndex = 0,
- .handle = 0,
- .isInitialized = false,
- .enable = kEnableDefault,
- .interval = CHRE_SENSOR_INTERVAL_DEFAULT,
- .latency = CHRE_SENSOR_LATENCY_ASAP,
- .info = {},
- },
- {
.type = CHRE_SENSOR_TYPE_ACCELEROMETER_TEMPERATURE,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -173,7 +143,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_GYROSCOPE_TEMPERATURE,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -183,7 +152,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD_TEMPERATURE,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -193,7 +161,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -203,7 +170,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -213,7 +179,6 @@ SensorState sensors[] = {
},
{
.type = CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD,
- .sensorIndex = 0,
.handle = 0,
.isInitialized = false,
.enable = kEnableDefault,
@@ -309,8 +274,7 @@ bool nanoappStart() {
for (size_t i = 0; i < ARRAY_SIZE(sensors); i++) {
SensorState &sensor = sensors[i];
- sensor.isInitialized =
- chreSensorFind(sensor.type, sensor.sensorIndex, &sensor.handle);
+ sensor.isInitialized = chreSensorFindDefault(sensor.type, &sensor.handle);
LOGI("Sensor %zu initialized: %s with handle %" PRIu32, i,
sensor.isInitialized ? "true" : "false", sensor.handle);
@@ -370,7 +334,6 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
const auto *ev = static_cast<const chreSensorThreeAxisData *>(eventData);
const auto header = ev->header;
const auto *data = ev->readings;
- const auto accuracy = header.accuracy;
sampleTime = header.baseTimestamp;
float x = 0, y = 0, z = 0;
@@ -384,9 +347,9 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
y /= header.readingCount;
z /= header.readingCount;
- CLOGI("%s, %d samples: %f %f %f, accuracy: %u, t=%" PRIu64 " ms",
+ CLOGI("%s, %d samples: %f %f %f, t=%" PRIu64 " ms",
getSensorName(header.sensorHandle), header.readingCount, x, y, z,
- accuracy, header.baseTimestamp / kOneMillisecondInNanoseconds);
+ header.baseTimestamp / kOneMillisecondInNanoseconds);
if (eventType == CHRE_EVENT_SENSOR_UNCALIBRATED_GYROSCOPE_DATA) {
CLOGI("UncalGyro time: first %" PRIu64 " last %" PRIu64 " chre %" PRIu64
@@ -414,9 +377,8 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
}
v /= header.readingCount;
- CLOGI("%s, %d samples: %f, accuracy = %u, t=%" PRIu64 " ms",
+ CLOGI("%s, %d samples: %f, t=%" PRIu64 " ms",
getSensorName(header.sensorHandle), header.readingCount, v,
- header.accuracy,
header.baseTimestamp / kOneMillisecondInNanoseconds);
break;
}
@@ -427,9 +389,9 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
const auto reading = ev->readings[0];
sampleTime = header.baseTimestamp;
- CLOGI("%s, %d samples: isNear %d, invalid %d, accuracy: %u",
+ CLOGI("%s, %d samples: isNear %d, invalid %d",
getSensorName(header.sensorHandle), header.readingCount,
- reading.isNear, reading.invalid, header.accuracy);
+ reading.isNear, reading.invalid);
CLOGI("Prox time: sample %" PRIu64 " chre %" PRIu64 " delta %" PRId64
"ms",
@@ -461,23 +423,12 @@ void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
}
case CHRE_EVENT_SENSOR_INSTANT_MOTION_DETECT_DATA:
- case CHRE_EVENT_SENSOR_STATIONARY_DETECT_DATA:
- case CHRE_EVENT_SENSOR_STEP_DETECT_DATA: {
+ case CHRE_EVENT_SENSOR_STATIONARY_DETECT_DATA: {
const auto *ev = static_cast<const chreSensorOccurrenceData *>(eventData);
const auto header = ev->header;
- CLOGI("%s, %d samples, accuracy: %u", getSensorName(header.sensorHandle),
- header.readingCount, header.accuracy);
- break;
- }
-
- case CHRE_EVENT_SENSOR_STEP_COUNTER_DATA: {
- const auto *ev = static_cast<const chreSensorUint64Data *>(eventData);
- const auto header = ev->header;
- const uint64_t reading = ev->readings[header.readingCount - 1].value;
-
- CLOGI("%s, %" PRIu16 " samples: latest %" PRIu64,
- getSensorName(header.sensorHandle), header.readingCount, reading);
+ CLOGI("%s, %d samples", getSensorName(header.sensorHandle),
+ header.readingCount);
break;
}
@@ -516,8 +467,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(SensorWorld, chre::kSensorWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_NONE);
+CHRE_STATIC_NANOAPP_INIT(SensorWorld, chre::kSensorWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/spammer/spammer.cc b/apps/spammer/spammer.cc
index f7a570c3..611f765f 100644
--- a/apps/spammer/spammer.cc
+++ b/apps/spammer/spammer.cc
@@ -17,10 +17,9 @@
#include <cinttypes>
#include "chre/platform/assert.h"
+#include "chre/platform/log.h"
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/nanoapp/log.h"
-#include "chre/util/system/napp_permissions.h"
#include "chre_api/chre.h"
/**
@@ -120,5 +119,4 @@ void nanoappEnd() {
} // anonymous namespace
} // namespace chre
-CHRE_STATIC_NANOAPP_INIT(Spammer, chre::kSpammerAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_NONE);
+CHRE_STATIC_NANOAPP_INIT(Spammer, chre::kSpammerAppId, 0);
diff --git a/apps/test/chqts/build/general_test/Makefile b/apps/test/chqts/build/general_test/Makefile
index f3ce0480..255e2f8a 100644
--- a/apps/test/chqts/build/general_test/Makefile
+++ b/apps/test/chqts/build/general_test/Makefile
@@ -7,6 +7,4 @@ NANOAPP_ID := 0x476f6f6754000000
NANOAPP_VERSION := 0x00000000
NANOAPP_NAME_STRING := \"CHQTS\ General\ Test\"
-COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
-
include ../shared_make.mk
diff --git a/apps/test/chqts/build/general_test2/Makefile b/apps/test/chqts/build/general_test2/Makefile
index b69d821a..94a2f33c 100644
--- a/apps/test/chqts/build/general_test2/Makefile
+++ b/apps/test/chqts/build/general_test2/Makefile
@@ -8,6 +8,4 @@ NANOAPP_ID := 0x476f6f6754000001
NANOAPP_VERSION := 0x00000000
NANOAPP_NAME_STRING := \"CHQTS\ General\ Test\"
-COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
-
include ../shared_make.mk
diff --git a/apps/test/chqts/build/general_test_sources.mk b/apps/test/chqts/build/general_test_sources.mk
index b7ce9784..6f78afc9 100644
--- a/apps/test/chqts/build/general_test_sources.mk
+++ b/apps/test/chqts/build/general_test_sources.mk
@@ -24,7 +24,7 @@ GENERAL_TEST_SRC_FILES = \
heap_exhaustion_stability_test.cc \
hello_world_test.cc \
host_awake_suspend_test.cc \
- logging_consistency_test.cc \
+ logging_sanity_test.cc \
nanoapp_info.cc \
nanoapp_info_by_app_id_test.cc \
nanoapp_info_by_instance_id_test.cc \
@@ -40,7 +40,7 @@ GENERAL_TEST_SRC_FILES = \
timer_cancel_test.cc \
timer_set_test.cc \
timer_stress_test.cc \
- version_consistency_test.cc \
+ version_sanity_test.cc \
wifi_capabilities_test.cc \
wwan_capabilities_test.cc \
wwan_cell_info_test.cc
diff --git a/apps/test/chqts/build/shared_make.mk b/apps/test/chqts/build/shared_make.mk
index 661f05eb..f46ba27b 100644
--- a/apps/test/chqts/build/shared_make.mk
+++ b/apps/test/chqts/build/shared_make.mk
@@ -11,10 +11,13 @@ $(error Must set Android build environment first)
endif
NANOAPP_DIR_NAME ?= $(NANOAPP_NAME)
-NANOAPP_SRC_PATH = $(CHRE_PREFIX)/apps/test/chqts/src
+
+# This path is actually relative to one level deeper as this file
+# gets included from Makefile of each test subdirectory
+NANOAPP_SRC_PATH = ../../src
SHARED_LIB_FILES = abort.cc \
- chunk_allocator.cc \
+ dumb_allocator.cc \
nano_endian.cc \
nano_string.cc \
send_message.cc \
@@ -34,15 +37,7 @@ COMMON_CFLAGS += -DCHRE_NO_ENDIAN_H \
-D__BIG_ENDIAN=2
COMMON_CFLAGS += -I$(NANOAPP_SRC_PATH)
-COMMON_CFLAGS += -I$(CHRE_PREFIX)/util/include
OPT_LEVEL=2
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_AUDIO = true
-CHRE_NANOAPP_USES_GNSS = true
-CHRE_NANOAPP_USES_WIFI = true
-CHRE_NANOAPP_USES_WWAN = true
-
include ${ANDROID_BUILD_TOP}/system/chre/build/nanoapp/app.mk
diff --git a/apps/test/chqts/src/Android.bp b/apps/test/chqts/src/Android.bp
index a184584c..eca79902 100644
--- a/apps/test/chqts/src/Android.bp
+++ b/apps/test/chqts/src/Android.bp
@@ -18,26 +18,17 @@
// code here, it seems a long-term time saver to have Linux tests for
// what we can easily test.
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
cc_test_host {
name: "nanoapp_chqts_shared_tests",
srcs: [
// Files under test
- "shared/chunk_allocator.cc",
+ "shared/dumb_allocator.cc",
"shared/nano_endian.cc",
"shared/nano_string.cc",
// Testing source
- "shared/chunk_allocator_test.cc",
+ "shared/dumb_allocator_test.cc",
"shared/nano_endian_be_test.cc",
"shared/nano_endian_le_test.cc",
"shared/nano_endian_test.cc",
diff --git a/apps/test/chqts/src/busy_startup/busy_startup.cc b/apps/test/chqts/src/busy_startup/busy_startup.cc
index 2b80b79b..96623fe6 100644
--- a/apps/test/chqts/src/busy_startup/busy_startup.cc
+++ b/apps/test/chqts/src/busy_startup/busy_startup.cc
@@ -19,8 +19,8 @@
*
* This nanoapp is to confirm a number of CHRE methods can be invoked from
* within nanoappStart(). There are other tests which test each of these
- * CHRE methods more in depth. We're just doing a consistency check that
- * calling from nanoappStart() works at all.
+ * CHRE methods more in depth. We're just doing a sanity check that calling
+ * from nanoappStart() works at all.
*
* Specifically, we're testing:
* o chreHeapAlloc() and chreHeapFree()
diff --git a/apps/test/chqts/src/general_test/app.cc b/apps/test/chqts/src/general_test/app.cc
index 7881199a..b2599d59 100644
--- a/apps/test/chqts/src/general_test/app.cc
+++ b/apps/test/chqts/src/general_test/app.cc
@@ -33,7 +33,7 @@
#include <general_test/heap_exhaustion_stability_test.h>
#include <general_test/hello_world_test.h>
#include <general_test/host_awake_suspend_test.h>
-#include <general_test/logging_consistency_test.h>
+#include <general_test/logging_sanity_test.h>
#include <general_test/nanoapp_info_by_app_id_test.h>
#include <general_test/nanoapp_info_by_instance_id_test.h>
#include <general_test/nanoapp_info_events_test_observer.h>
@@ -48,7 +48,7 @@
#include <general_test/timer_cancel_test.h>
#include <general_test/timer_set_test.h>
#include <general_test/timer_stress_test.h>
-#include <general_test/version_consistency_test.h>
+#include <general_test/version_sanity_test.h>
#include <general_test/wifi_capabilities_test.h>
#include <general_test/wwan_capabilities_test.h>
#include <general_test/wwan_cell_info_test.h>
@@ -209,8 +209,8 @@ void App::createTest(const void *eventData) {
CASE(kBasicBarometer, BasicBarometerTest);
CASE(kBasicLightSensor, BasicLightSensorTest);
CASE(kBasicProximity, BasicProximityTest);
- CASE(kVersionConsistency, VersionConsistencyTest);
- CASE(kLoggingConsistency, LoggingConsistencyTest);
+ CASE(kVersionSanity, VersionSanityTest);
+ CASE(kLoggingSanity, LoggingSanityTest);
CASE(kSendMessageToHost, SendMessageToHostTest);
CASE(kTimerSet, TimerSetTest);
CASE(kTimerCancel, TimerCancelTest);
diff --git a/apps/test/chqts/src/general_test/basic_audio_test.cc b/apps/test/chqts/src/general_test/basic_audio_test.cc
index 3027a61f..e0f95df2 100644
--- a/apps/test/chqts/src/general_test/basic_audio_test.cc
+++ b/apps/test/chqts/src/general_test/basic_audio_test.cc
@@ -13,17 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-#include <cinttypes>
-
-#include "chre/util/nanoapp/log.h"
#include <general_test/basic_audio_test.h>
#include <shared/send_message.h>
#include <shared/time_util.h>
-#define LOG_TAG "[ChreBasicAudioTest]"
-
using nanoapp_testing::kOneSecondInNanoseconds;
using nanoapp_testing::sendFatalFailureToHost;
using nanoapp_testing::sendSuccessToHost;
@@ -61,11 +56,6 @@ constexpr uint64_t kMinBufferDuration =
//! not practical for always-on, low-power use-cases.
constexpr uint64_t kMaxBufferDuration = kOneSecondInNanoseconds * 120;
-//! While a variety of sample rates are supported, for the purposes of basic
-//! audio data validation, we buffer about 4 seconds worth of PCM audio data
-//! sampled at 16KHz.
-constexpr uint32_t kRequiredSampleRate = 16000;
-
/**
* @return true if the character is ASCII printable.
*/
@@ -129,6 +119,7 @@ bool validateAudioSource(uint32_t handle,
bool validateMinimumAudioSource(const struct chreAudioSource &source) {
// CHQTS requires a 16kHz, PCM-format, 2 second buffer.
+ constexpr uint32_t kRequiredSampleRate = 16000;
constexpr uint64_t kRequiredBufferDuration = 2 * kOneSecondInNanoseconds;
// Ensure that the minimum buffer size is less than or equal to the required
@@ -178,120 +169,6 @@ void validateAudioSources() {
}
}
-/**
- * Attempts to request audio data from the default microphone handle (0),
- * posts a failure if the data request failed
- */
-void requestAudioData() {
- constexpr uint32_t kAudioHandle = 0;
- struct chreAudioSource audioSource;
-
- if (!chreAudioGetSource(kAudioHandle, &audioSource)) {
- sendFatalFailureToHost("Failed to query source for handle 0");
- } else if (!chreAudioConfigureSource(kAudioHandle, true /* enable */,
- audioSource.minBufferDuration,
- audioSource.minBufferDuration)) {
- sendFatalFailureToHost("Failed to request audio data for handle 0");
- }
-}
-
-/**
- * Check if the audio samples are all zeros
- *
- * @return true on check passing
- */
-bool checkSamplesAllZeros(const int16_t *data, const size_t dataLen) {
- for (size_t i = 0; i < dataLen; ++i) {
- if (data[i] != 0) {
- return true;
- }
- }
- return false;
-}
-
-/**
- * Check if adjacent audio samples are unique
- *
- * @return true on check pass
- */
-bool checkSamplesAllSame(const int16_t *data, const size_t dataLen) {
- if (dataLen > 0) {
- const int16_t controlValue = data[0];
- for (size_t i = 1; i < dataLen; ++i) {
- if (data[i] != controlValue) {
- return true;
- }
- }
- }
- return false;
-}
-
-void handleAudioDataEvent(const chreAudioDataEvent *dataEvent) {
- constexpr uint32_t kAudioHandle = 0;
-
- // A count of the number of data events we've received - we stop
- // the test after receiving 2 data events.
- static uint8_t numDataEventsSoFar = 1;
-
- if (dataEvent == nullptr) {
- sendFatalFailureToHost("Null event data");
- } else if (dataEvent->samplesS16 == nullptr) {
- sendFatalFailureToHost("Null audio data frame");
- } else if (dataEvent->sampleCount == 0) {
- sendFatalFailureToHost("0 samples in audio data frame");
- } else {
- struct chreAudioSource audioSource;
- if (!chreAudioGetSource(kAudioHandle, &audioSource)) {
- sendFatalFailureToHost("Failed to get audio source for handle 0");
- } else {
- // Per the CHRE Audio API requirements, it is expected that we exactly
- // the number of samples that we ask for - we verify that here.
- const auto kNumSamplesExpected =
- static_cast<uint32_t>(audioSource.minBufferDuration *
- kRequiredSampleRate / kOneSecondInNanoseconds);
- if (dataEvent->sampleCount != kNumSamplesExpected) {
- LOGE("Unexpected num samples - Expected: %" PRIu32 ", Actual: %" PRIu32,
- kNumSamplesExpected, dataEvent->sampleCount);
- uint32_t sampleCountDifference =
- (kNumSamplesExpected > dataEvent->sampleCount)
- ? (kNumSamplesExpected - dataEvent->sampleCount)
- : (dataEvent->sampleCount - kNumSamplesExpected);
- sendFatalFailureToHost("Unexpected number of samples received",
- &sampleCountDifference);
- }
- }
- }
-
- if (numDataEventsSoFar == 2) {
- if (!chreAudioConfigureSource(kAudioHandle, false /* enable */,
- 0 /* bufferDuration */,
- 0 /* deliveryInterval */)) {
- sendFatalFailureToHost("Failed to disable audio source for handle 0");
- }
- } else {
- ++numDataEventsSoFar;
- }
-
- if (!checkSamplesAllZeros(dataEvent->samplesS16, dataEvent->sampleCount)) {
- sendFatalFailureToHost("All audio samples were zeros");
- } else if (!checkSamplesAllSame(dataEvent->samplesS16,
- dataEvent->sampleCount)) {
- sendFatalFailureToHost("All audio samples were identical");
- } else {
- sendSuccessToHost();
- }
-}
-
-bool isAudioSupported() {
- struct chreAudioSource source;
- constexpr uint32_t kRequiredAudioHandle = 0;
- // If the DUT supports CHRE audio, then audio handle 0 is required to be
- // valid. There is the risk that the chreAudioGetSource function might
- // legitimately fail however - we should replace this function when CHRE
- // audio capabilities in b/185155280 are implemented.
- // TODO (b/185155280): fix this query
- return chreAudioGetSource(kRequiredAudioHandle, &source);
-}
} // anonymous namespace
BasicAudioTest::BasicAudioTest()
@@ -303,16 +180,8 @@ void BasicAudioTest::setUp(uint32_t messageSize, const void * /* message */) {
&messageSize);
}
- if (!isAudioSupported()) {
- sendSuccessToHost();
-
- } else {
- validateAudioSources();
-
- mState = State::kExpectingAudioData;
-
- requestAudioData();
- }
+ validateAudioSources();
+ sendSuccessToHost();
}
void BasicAudioTest::handleEvent(uint32_t senderInstanceId, uint16_t eventType,
@@ -326,21 +195,7 @@ void BasicAudioTest::handleEvent(uint32_t senderInstanceId, uint16_t eventType,
if (mState == State::kPreStart) {
unexpectedEvent(eventType);
} else {
- switch (eventType) {
- case CHRE_EVENT_AUDIO_SAMPLING_CHANGE:
- /* This event is received, but not relevant to this test since we're
- * mostly interested in the audio data, so we ignore it. */
- break;
-
- case CHRE_EVENT_AUDIO_DATA:
- handleAudioDataEvent(
- static_cast<const chreAudioDataEvent *>(eventData));
- break;
-
- default:
- unexpectedEvent(eventType);
- break;
- }
+ // TODO: Handle audio data from sources, perform basic sanity checks on it.
}
mInMethod = false;
diff --git a/apps/test/chqts/src/general_test/basic_gnss_test.cc b/apps/test/chqts/src/general_test/basic_gnss_test.cc
index edad4d33..8f896d01 100644
--- a/apps/test/chqts/src/general_test/basic_gnss_test.cc
+++ b/apps/test/chqts/src/general_test/basic_gnss_test.cc
@@ -29,34 +29,17 @@ namespace general_test {
namespace {
-using nanoapp_testing::sendFatalFailureToHost;
-
void testLocationSessionAsync() {
if (!chreGnssLocationSessionStartAsync(1000 /* minIntervalMs */,
0 /* minTimeToNextFixMs */,
nullptr /* cookie */)) {
- sendFatalFailureToHost("Failed to start a location session");
+ nanoapp_testing::sendFatalFailureToHost(
+ "Failed to start a location session");
}
-}
-
-void testMeasurementSessionAsync() {
- if (!chreGnssMeasurementSessionStartAsync(1000 /* minIntervalMs */,
- nullptr /* cookie */)) {
- sendFatalFailureToHost("Failed to start a measurement session");
- }
-}
-
-bool testPassiveListener() {
- bool success = false;
- if (!chreGnssConfigurePassiveLocationListener(true /* enable */)) {
- sendFatalFailureToHost("Failed to enable passive location listener");
- } else if (!chreGnssConfigurePassiveLocationListener(false /* enable */)) {
- sendFatalFailureToHost("Failed to disable passive location listener");
- } else {
- success = true;
+ if (!chreGnssLocationSessionStopAsync(nullptr /* cookie */)) {
+ nanoapp_testing::sendFatalFailureToHost(
+ "Failed to stop a location session");
}
-
- return success;
}
} // anonymous namespace
@@ -65,82 +48,27 @@ BasicGnssTest::BasicGnssTest() : Test(CHRE_API_VERSION_1_1) {}
void BasicGnssTest::setUp(uint32_t messageSize, const void * /* message */) {
if (messageSize != 0) {
- sendFatalFailureToHost("Expected 0 byte message, got more bytes:",
- &messageSize);
+ nanoapp_testing::sendFatalFailureToHost(
+ "Expected 0 byte message, got more bytes:", &messageSize);
} else {
uint32_t capabilities = chreGnssGetCapabilities();
if (capabilities & CHRE_GNSS_CAPABILITIES_LOCATION) {
testLocationSessionAsync();
- } else {
- mTestSuccessMarker.markStageAndSuccessOnFinish(
- BASIC_GNSS_TEST_STAGE_LOCATION);
- }
-
- if (capabilities & CHRE_GNSS_CAPABILITIES_MEASUREMENTS) {
- testMeasurementSessionAsync();
- } else {
- mTestSuccessMarker.markStageAndSuccessOnFinish(
- BASIC_GNSS_TEST_STAGE_MEASUREMENT);
+ // TODO: Add tests for chreGnssMeasurementXxx and
+ // chreGnssConfigurePassiveLocationListener
}
- if (((mApiVersion < CHRE_API_VERSION_1_5) &&
- (capabilities &
- CHRE_GNSS_CAPABILITIES_GNSS_ENGINE_BASED_PASSIVE_LISTENER) == 0) ||
- testPassiveListener()) {
- mTestSuccessMarker.markStageAndSuccessOnFinish(
- BASIC_GNSS_TEST_STAGE_LISTENER);
- }
- }
-}
-
-void BasicGnssTest::handleGnssAsyncResult(const chreAsyncResult *result) {
- if (!result->success) {
- sendFatalFailureToHost("Received unsuccessful GNSS async result");
- }
-
- switch (result->requestType) {
- case CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_START: {
- if (!chreGnssLocationSessionStopAsync(nullptr /* cookie */)) {
- sendFatalFailureToHost("Failed to stop a location session");
- }
- break;
- }
- case CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_STOP: {
- mTestSuccessMarker.markStageAndSuccessOnFinish(
- BASIC_GNSS_TEST_STAGE_LOCATION);
- break;
- }
- case CHRE_GNSS_REQUEST_TYPE_MEASUREMENT_SESSION_START: {
- if (!chreGnssMeasurementSessionStopAsync(nullptr /* cookie */)) {
- sendFatalFailureToHost("Failed to stop a measurement session");
- }
- break;
- }
- case CHRE_GNSS_REQUEST_TYPE_MEASUREMENT_SESSION_STOP: {
- mTestSuccessMarker.markStageAndSuccessOnFinish(
- BASIC_GNSS_TEST_STAGE_MEASUREMENT);
- break;
- }
- default:
- sendFatalFailureToHost("Unexpected request type");
- break;
+ nanoapp_testing::sendSuccessToHost();
}
}
void BasicGnssTest::handleEvent(uint32_t /* senderInstanceId */,
- uint16_t eventType, const void *eventData) {
- switch (eventType) {
- case CHRE_EVENT_GNSS_ASYNC_RESULT:
- handleGnssAsyncResult(static_cast<const chreAsyncResult *>(eventData));
- break;
- case CHRE_EVENT_GNSS_LOCATION:
- case CHRE_EVENT_GNSS_DATA:
- // Do nothing
- break;
- default:
- unexpectedEvent(eventType);
- break;
+ uint16_t eventType,
+ const void * /* eventData */) {
+ if (eventType != CHRE_EVENT_GNSS_ASYNC_RESULT &&
+ eventType != CHRE_EVENT_GNSS_LOCATION) {
+ unexpectedEvent(eventType);
}
}
diff --git a/apps/test/chqts/src/general_test/basic_gnss_test.h b/apps/test/chqts/src/general_test/basic_gnss_test.h
index 15fe9faf..2218d4cf 100644
--- a/apps/test/chqts/src/general_test/basic_gnss_test.h
+++ b/apps/test/chqts/src/general_test/basic_gnss_test.h
@@ -20,8 +20,6 @@
#include <cstdint>
-#include <shared/test_success_marker.h>
-
#include <chre.h>
namespace general_test {
@@ -34,19 +32,6 @@ class BasicGnssTest : public Test {
void handleEvent(uint32_t senderInstanceId, uint16_t eventType,
const void *eventData) override;
void setUp(uint32_t messageSize, const void *message) override;
-
- private:
- enum BasicGnssTestStage {
- BASIC_GNSS_TEST_STAGE_LOCATION = 0,
- BASIC_GNSS_TEST_STAGE_MEASUREMENT,
- BASIC_GNSS_TEST_STAGE_LISTENER,
- BASIC_GNSS_TEST_STAGE_COUNT,
- };
-
- nanoapp_testing::TestSuccessMarker mTestSuccessMarker =
- nanoapp_testing::TestSuccessMarker(BASIC_GNSS_TEST_STAGE_COUNT);
-
- void handleGnssAsyncResult(const chreAsyncResult *result);
};
} // namespace general_test
diff --git a/apps/test/chqts/src/general_test/basic_sensor_test_base.cc b/apps/test/chqts/src/general_test/basic_sensor_test_base.cc
index 060316d6..9371a8f5 100644
--- a/apps/test/chqts/src/general_test/basic_sensor_test_base.cc
+++ b/apps/test/chqts/src/general_test/basic_sensor_test_base.cc
@@ -22,12 +22,8 @@
#include <shared/send_message.h>
#include <shared/time_util.h>
-#include "chre/util/nanoapp/log.h"
-
#include <chre.h>
-#define LOG_TAG "[BasicSensorTest]"
-
using nanoapp_testing::kOneMillisecondInNanoseconds;
using nanoapp_testing::kOneSecondInNanoseconds;
using nanoapp_testing::MessageType;
@@ -41,8 +37,8 @@ using nanoapp_testing::sendSuccessToHost;
* Our general test flow is as follows:
*
* Constructor: Send startEvent to self to start.
- * StartEvent: Get default sensor and perform various consistency checks.
- * Configure the sensor.
+ * StartEvent: Get default sensor and perform various sanity checks. Configure
+ * the sensor.
*
* At this point, it depends what kind of sensor we have for how we proceed
* with the test.
@@ -51,8 +47,8 @@ using nanoapp_testing::sendSuccessToHost;
* On-change: Wait for one data event from sensor. Then finishTest().
* Continuous: Wait for two data events from sensor. Then finishTest().
*
- * We also look for and perform basic consistency checking on sampling
- * status change events, as well as bias data reports.
+ * We also look for and perform basic sanity checking on sampling status
+ * change events, as well as bias data reports.
*/
namespace general_test {
@@ -69,13 +65,6 @@ uint64_t getEventDuration(const chreSensorThreeAxisData *event) {
return duration;
}
-
-bool isBiasEventType(uint16_t eventType) {
- return (eventType == CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO) ||
- (eventType == CHRE_EVENT_SENSOR_GYROSCOPE_BIAS_INFO) ||
- (eventType == CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_BIAS_INFO);
-}
-
} // anonymous namespace
BasicSensorTestBase::BasicSensorTestBase()
@@ -92,12 +81,6 @@ void BasicSensorTestBase::setUp(uint32_t messageSize,
sendFatalFailureToHost("Beginning message expects 0 additional bytes, got ",
&messageSize);
}
-
- sendStartTestMessage();
-}
-
-void BasicSensorTestBase::sendStartTestMessage() {
- mState = State::kPreStart;
// Most tests start running in the constructor. However, since this
// is a base class, and we invoke abstract methods when running our
// test, we don't start until after the class has been fully
@@ -179,28 +162,12 @@ void BasicSensorTestBase::checkPassiveConfigure() {
void BasicSensorTestBase::startTest() {
mState = State::kPreConfigure;
-
- bool found = false;
- if (mApiVersion >= CHRE_API_VERSION_1_5) {
- found =
- chreSensorFind(getSensorType(), mCurrentSensorIndex, &mSensorHandle);
- if (!found && chreSensorFind(getSensorType(), mCurrentSensorIndex + 1,
- &mSensorHandle)) {
- sendFatalFailureToHostUint8("Missing sensor index ", mCurrentSensorIndex);
- return;
- }
- } else {
- found = chreSensorFindDefault(getSensorType(), &mSensorHandle);
- }
-
- if (!found) {
+ if (!chreSensorFindDefault(getSensorType(), &mSensorHandle)) {
sendStringToHost(MessageType::kSkipped,
"No default sensor found for optional sensor.");
return;
}
- LOGI("Starting test for sensor index %" PRIu8, mCurrentSensorIndex);
-
chreSensorInfo info;
if (!chreGetSensorInfo(mSensorHandle, &info)) {
sendFatalFailureToHost("GetSensorInfo() call failed");
@@ -317,39 +284,19 @@ void BasicSensorTestBase::finishTest() {
}
}
}
-
- LOGI("Test passed for sensor index %" PRIu8, mCurrentSensorIndex);
-
- bool finished = true;
- if (mApiVersion >= CHRE_API_VERSION_1_5) {
- mCurrentSensorIndex++;
- uint32_t sensorHandle;
- if (chreSensorFind(getSensorType(), mCurrentSensorIndex, &sensorHandle)) {
- finished = false;
- mPrevSensorHandle = mSensorHandle;
- sendStartTestMessage();
- }
- }
-
- if (finished) {
- mState = State::kFinished;
- sendSuccessToHost();
- }
+ mState = State::kFinished;
+ sendSuccessToHost();
}
-void BasicSensorTestBase::verifyEventHeader(const chreSensorDataHeader *header,
- uint16_t eventType,
+void BasicSensorTestBase::sanityCheckHeader(const chreSensorDataHeader *header,
+ bool modifyTimestamps,
uint64_t eventDuration) {
if (header->sensorHandle != mSensorHandle) {
sendFatalFailureToHost("SensorDataHeader for wrong handle",
&header->sensorHandle);
}
- // Bias and on-change sensor events may have timestamps from before any of our
- // requests started since they aren't generated in response to requests. For
- // these types of events, only ensure the provided timestamp is less than the
- // current time.
- if (!isOnChangeSensor() && !isBiasEventType(eventType)) {
+ if (!isOnChangeSensor()) {
// An on-change sensor is supposed to send its current state, which
// could be timestamped in the past. Everything else should be
// getting recent data.
@@ -389,13 +336,10 @@ void BasicSensorTestBase::verifyEventHeader(const chreSensorDataHeader *header,
(header->baseTimestamp > mDoneTimestamp)) {
sendFatalFailureToHost("SensorDataHeader is from after DONE");
}
- *timeToUpdate = header->baseTimestamp;
- }
-
- if (header->baseTimestamp > chreGetTime()) {
- sendFatalFailureToHost("SensorDataHeader is in the future");
+ if (modifyTimestamps) {
+ *timeToUpdate = header->baseTimestamp;
+ }
}
-
if (header->readingCount == 0) {
sendFatalFailureToHost("SensorDataHeader has readingCount of 0");
}
@@ -431,57 +375,49 @@ void BasicSensorTestBase::handleBiasEvent(
if (expectedSensorType != getSensorType()) {
sendFatalFailureToHost("Unexpected bias event:", &eType);
}
- verifyEventHeader(&eventData->header, eventType, getEventDuration(eventData));
+ sanityCheckHeader(&eventData->header, false, getEventDuration(eventData));
- // TODO: consistency check the eventData. This check is out-of-scope for
+ // TODO: Sanity check the eventData. This check is out-of-scope for
// Android N testing.
}
void BasicSensorTestBase::handleSamplingChangeEvent(
const chreSensorSamplingStatusEvent *eventData) {
- if (mPrevSensorHandle.has_value() &&
- (mPrevSensorHandle.value() == eventData->sensorHandle)) {
- // We can get a "DONE" event from the previous sensor for multi-sensor
- // devices, so we ignore these events.
- return;
- }
-
if (eventData->sensorHandle != mSensorHandle) {
sendFatalFailureToHost("SamplingChangeEvent for wrong sensor handle:",
&eventData->sensorHandle);
}
+ if (mState == State::kFinished) {
+ // TODO: If we strictly define whether this event is or isn't
+ // generated upon being DONE with a sensor, then we can perform
+ // a strict check here. For now, we just let this go.
+ return;
+ }
+ // Passive sensor requests do not guarantee sensors will always be enabled.
+ // Bypass 'enabled' check for passive configurations.
+ if (!eventData->status.enabled) {
+ sendFatalFailureToHost("SamplingChangeEvent disabled the sensor.");
+ }
- // TODO: If we strictly define whether this event is or isn't
- // generated upon being DONE with a sensor, then we can perform
- // a strict check here. For now, we just let this go.
- if (mState != State::kFinished) {
- // Passive sensor requests do not guarantee sensors will always be enabled.
- // Bypass 'enabled' check for passive configurations.
- if (!eventData->status.enabled) {
- sendFatalFailureToHost("SamplingChangeEvent disabled the sensor.");
- }
-
- if ((mNewStatus.interval != eventData->status.interval) ||
- (mNewStatus.latency != eventData->status.latency)) {
- // This is from someone other than us. Let's note that so we know
- // our consistency checks are invalid.
- mExternalSamplingStatusChange = true;
- }
+ if ((mNewStatus.interval != eventData->status.interval) ||
+ (mNewStatus.latency != eventData->status.latency)) {
+ // This is from someone other than us. Let's note that so we know
+ // our sanity checks are invalid.
+ mExternalSamplingStatusChange = true;
}
}
-void BasicSensorTestBase::handleSensorDataEvent(uint16_t eventType,
- const void *eventData) {
+void BasicSensorTestBase::handleSensorDataEvent(const void *eventData) {
if ((mState == State::kPreStart) || (mState == State::kPreConfigure)) {
sendFatalFailureToHost("SensorDataEvent sent too early.");
}
// Note, if mState is kFinished, we could be getting batched data which
- // hadn't been delivered yet at the time we were DONE. We'll consistency
+ // hadn't been delivered yet at the time we were DONE. We'll sanity
// check it, even though in theory we're done testing.
uint64_t eventDuration =
getEventDuration(static_cast<const chreSensorThreeAxisData *>(eventData));
- verifyEventHeader(static_cast<const chreSensorDataHeader *>(eventData),
- eventType, eventDuration);
+ sanityCheckHeader(static_cast<const chreSensorDataHeader *>(eventData), true,
+ eventDuration);
// Send to the sensor itself for any additional checks of actual data.
confirmDataIsSane(eventData);
@@ -510,6 +446,9 @@ void BasicSensorTestBase::handleEvent(uint32_t senderInstanceId,
if ((eventType == kStartEvent) && (mState == State::kPreStart)) {
startTest();
}
+ } else if ((mState == State::kPreStart) || (mState == State::kPreConfigure)) {
+ unexpectedEvent(eventType);
+
} else if (senderInstanceId != CHRE_INSTANCE_ID) {
sendFatalFailureToHost("Unexpected senderInstanceId:", &senderInstanceId);
@@ -518,13 +457,14 @@ void BasicSensorTestBase::handleEvent(uint32_t senderInstanceId,
sendFatalFailureToHost("Got NULL eventData for event:", &eType);
} else if (eventType == dataEventType) {
- handleSensorDataEvent(eventType, eventData);
+ handleSensorDataEvent(eventData);
} else if (eventType == CHRE_EVENT_SENSOR_SAMPLING_CHANGE) {
handleSamplingChangeEvent(
static_cast<const chreSensorSamplingStatusEvent *>(eventData));
- } else if (isBiasEventType(eventType)) {
+ } else if ((eventType == CHRE_EVENT_SENSOR_GYROSCOPE_BIAS_INFO) ||
+ (eventType == CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_BIAS_INFO)) {
handleBiasEvent(eventType,
static_cast<const chreSensorThreeAxisData *>(eventData));
diff --git a/apps/test/chqts/src/general_test/basic_sensor_test_base.h b/apps/test/chqts/src/general_test/basic_sensor_test_base.h
index afdb9a89..5e69aa77 100644
--- a/apps/test/chqts/src/general_test/basic_sensor_test_base.h
+++ b/apps/test/chqts/src/general_test/basic_sensor_test_base.h
@@ -19,8 +19,6 @@
#include <general_test/test.h>
-#include "chre/util/optional.h"
-
#include <chre.h>
namespace general_test {
@@ -44,11 +42,6 @@ class BasicSensorTestBase : public Test {
void setUp(uint32_t messageSize, const void *message) override;
/**
- * Sends a message to itself to trigger startTest();
- */
- void sendStartTestMessage();
-
- /**
* Abstract method indicating which sensor type this is.
*
* @returns One of the CHRE_SENSOR_TYPE_* constants.
@@ -109,12 +102,6 @@ class BasicSensorTestBase : public Test {
bool mSupportsPassiveMode = true;
- // The current sensor index that we are testing for.
- uint8_t mCurrentSensorIndex = 0;
-
- // The sensor handle for the previous sensor tested.
- chre::Optional<uint32_t> mPrevSensorHandle;
-
void startTest();
void finishTest();
void checkPassiveConfigure();
@@ -122,9 +109,9 @@ class BasicSensorTestBase : public Test {
const chreSensorThreeAxisData *eventData);
void handleSamplingChangeEvent(
const chreSensorSamplingStatusEvent *eventData);
- void handleSensorDataEvent(uint16_t eventType, const void *eventData);
- void verifyEventHeader(const chreSensorDataHeader *header, uint16_t eventType,
- uint64_t eventDuration);
+ void handleSensorDataEvent(const void *eventData);
+ void sanityCheckHeader(const chreSensorDataHeader *header,
+ bool modifyTimestamps, uint64_t eventDuration);
};
} // namespace general_test
diff --git a/apps/test/chqts/src/general_test/basic_sensor_tests.cc b/apps/test/chqts/src/general_test/basic_sensor_tests.cc
index f9c9b8ef..3aff5bec 100644
--- a/apps/test/chqts/src/general_test/basic_sensor_tests.cc
+++ b/apps/test/chqts/src/general_test/basic_sensor_tests.cc
@@ -41,8 +41,8 @@ static void checkTimestampDelta(uint32_t delta, size_t index) {
}
}
-static void verifyThreeAxisData(const void *eventData, float extremeLow,
- float extremeHigh) {
+static void sanityCheckThreeAxisData(const void *eventData, float extremeLow,
+ float extremeHigh) {
auto data = static_cast<const chreSensorThreeAxisData *>(eventData);
for (size_t i = 0; i < data->header.readingCount; i++) {
checkTimestampDelta(data->readings[i].timestampDelta, i);
@@ -52,8 +52,8 @@ static void verifyThreeAxisData(const void *eventData, float extremeLow,
}
}
-static void verifyFloatData(const void *eventData, float extremeLow,
- float extremeHigh) {
+static void sanityCheckFloatData(const void *eventData, float extremeLow,
+ float extremeHigh) {
auto data = static_cast<const chreSensorFloatData *>(eventData);
for (size_t i = 0; i < data->header.readingCount; i++) {
checkTimestampDelta(data->readings[i].timestampDelta, i);
@@ -63,36 +63,36 @@ static void verifyFloatData(const void *eventData, float extremeLow,
void BasicAccelerometerTest::confirmDataIsSane(const void *eventData) {
constexpr float kExtreme = 70.5f; // Apollo 16 on reentry (7.19g)
- verifyThreeAxisData(eventData, -kExtreme, kExtreme);
+ sanityCheckThreeAxisData(eventData, -kExtreme, kExtreme);
}
void BasicInstantMotionDetectTest::confirmDataIsSane(const void *eventData) {
- // Nothing to check.
+ // Nothing to sanity check.
}
void BasicStationaryDetectTest::confirmDataIsSane(const void *eventData) {
- // Nothing to check.
+ // Nothing to sanity check.
}
void BasicGyroscopeTest::confirmDataIsSane(const void *eventData) {
constexpr float kExtreme = 9420.0f; // Zippe centrifuge
- verifyThreeAxisData(eventData, -kExtreme, kExtreme);
+ sanityCheckThreeAxisData(eventData, -kExtreme, kExtreme);
}
void BasicMagnetometerTest::confirmDataIsSane(const void *eventData) {
constexpr float kExtreme = 9400000.0f; // Strength of medical MRI
- verifyThreeAxisData(eventData, -kExtreme, kExtreme);
+ sanityCheckThreeAxisData(eventData, -kExtreme, kExtreme);
}
void BasicBarometerTest::confirmDataIsSane(const void *eventData) {
constexpr float kExtremeLow = 337.0f; // Mount Everest summit
constexpr float kExtremeHigh = 1067.0f; // Dead Sea
- verifyFloatData(eventData, kExtremeLow, kExtremeHigh);
+ sanityCheckFloatData(eventData, kExtremeLow, kExtremeHigh);
}
void BasicLightSensorTest::confirmDataIsSane(const void *eventData) {
constexpr float kExtreme = 300000.0f; // 3x the Sun
- verifyFloatData(eventData, 0.0f, kExtreme);
+ sanityCheckFloatData(eventData, 0.0f, kExtreme);
}
void BasicProximityTest::confirmDataIsSane(const void *eventData) {
diff --git a/apps/test/chqts/src/general_test/basic_wifi_test.cc b/apps/test/chqts/src/general_test/basic_wifi_test.cc
index af648c9c..57e52330 100644
--- a/apps/test/chqts/src/general_test/basic_wifi_test.cc
+++ b/apps/test/chqts/src/general_test/basic_wifi_test.cc
@@ -24,7 +24,6 @@
#include <shared/send_message.h>
#include <shared/time_util.h>
-#include "chre/util/nanoapp/log.h"
#include "chre/util/time.h"
#include "chre/util/unique_ptr.h"
@@ -32,8 +31,6 @@ using nanoapp_testing::sendFatalFailureToHost;
using nanoapp_testing::sendFatalFailureToHostUint8;
using nanoapp_testing::sendSuccessToHost;
-#define LOG_TAG "[BasicWifiTest]"
-
/*
* Test to check expected functionality of the CHRE WiFi APIs.
*
@@ -50,18 +47,18 @@ namespace general_test {
namespace {
-//! A fake/unused cookie to pass into the enable configure scan monitoring async
+//! A dummy cookie to pass into the enable configure scan monitoring async
//! request.
constexpr uint32_t kEnableScanMonitoringCookie = 0x1337;
-//! A fake/unused cookie to pass into the disable configure scan monitoring
-//! async request.
+//! A dummy cookie to pass into the disable configure scan monitoring async
+//! request.
constexpr uint32_t kDisableScanMonitoringCookie = 0x1338;
-//! A fake/unused cookie to pass into request ranging async.
+//! A dummy cookie to pass into request ranging async.
constexpr uint32_t kRequestRangingCookie = 0xefac;
-//! A fake/unused cookie to pass into request scan async.
+//! A dummy cookie to pass into request scan async.
constexpr uint32_t kOnDemandScanCookie = 0xcafe;
//! Starting frequency of band 2.4 GHz
@@ -101,18 +98,7 @@ void testConfigureScanMonitorAsync(bool enable, const void *cookie) {
* if API call fails.
*/
void testRequestScanAsync() {
- // Request a fresh scan to ensure the correct scan type is performed.
- constexpr struct chreWifiScanParams kParams = {
- /*.scanType=*/CHRE_WIFI_SCAN_TYPE_ACTIVE,
- /*.maxScanAgeMs=*/0, // 0 seconds
- /*.frequencyListLen=*/0,
- /*.frequencyList=*/NULL,
- /*.ssidListLen=*/0,
- /*.ssidList=*/NULL,
- /*.radioChainPref=*/CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT,
- /*.channelSet=*/CHRE_WIFI_CHANNEL_SET_NON_DFS};
-
- if (!chreWifiRequestScanAsync(&kParams, &kOnDemandScanCookie)) {
+ if (!chreWifiRequestScanAsyncDefault(&kOnDemandScanCookie)) {
sendFatalFailureToHost("Failed to request for on-demand WiFi scan.");
}
}
@@ -347,25 +333,20 @@ void BasicWifiTest::handleEvent(uint32_t /* senderInstanceId */,
sendFatalFailureToHost("WiFi scan event received when not requested");
}
const auto *result = static_cast<const chreWifiScanEvent *>(eventData);
-
- if (!isActiveWifiScanType(result)) {
- LOGW("Received unexpected scan type %" PRIu8, result->scanType);
- }
-
- // The first chreWifiScanResult is expected to come immediately,
- // but a long delay is possible if it's implemented incorrectly,
- // e.g. the async result comes right away (before the scan is actually
- // completed), then there's a long delay to the scan result.
- constexpr uint64_t maxDelayNs = 100 * chre::kOneMillisecondInNanoseconds;
- bool delayExceeded = (mStartTimestampNs != 0) &&
- (chreGetTime() - mStartTimestampNs > maxDelayNs);
- if (delayExceeded) {
- sendFatalFailureToHost(
- "Did not receive chreWifiScanResult within 100 milliseconds.");
+ if (isActiveWifiScanType(result)) {
+ // The first chreWifiScanResult is expected to come immediately,
+ // but a long delay is possible if it's implemented incorrectly,
+ // e.g. the async result comes right away (before the scan is actually
+ // completed), then there's a long delay to the scan result.
+ if (mStartTimestampNs != 0 &&
+ chreGetTime() - mStartTimestampNs >
+ 50 * chre::kOneMillisecondInNanoseconds) {
+ sendFatalFailureToHost(
+ "Did not receive chreWifiScanResult within 50 milliseconds.");
+ }
+ mStartTimestampNs = 0;
+ validateWifiScanEvent(result);
}
- // Do not reset mStartTimestampNs here, because it is used for the
- // subsequent RTT ranging timestamp validation.
- validateWifiScanEvent(result);
break;
}
case CHRE_EVENT_WIFI_RANGING_RESULT: {
diff --git a/apps/test/chqts/src/general_test/logging_consistency_test.cc b/apps/test/chqts/src/general_test/logging_sanity_test.cc
index 8fa9ba84..e2a02bf6 100644
--- a/apps/test/chqts/src/general_test/logging_consistency_test.cc
+++ b/apps/test/chqts/src/general_test/logging_sanity_test.cc
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include <general_test/logging_consistency_test.h>
+#include <general_test/logging_sanity_test.h>
#include <cstddef>
#include <limits>
@@ -30,14 +30,13 @@ using nanoapp_testing::sendSuccessToHost;
namespace general_test {
-LoggingConsistencyTest::LoggingConsistencyTest() : Test(CHRE_API_VERSION_1_0) {}
+LoggingSanityTest::LoggingSanityTest() : Test(CHRE_API_VERSION_1_0) {}
-void LoggingConsistencyTest::setUp(uint32_t messageSize,
- const void * /* message */) {
+void LoggingSanityTest::setUp(uint32_t messageSize,
+ const void * /* message */) {
if (messageSize != 0) {
sendFatalFailureToHost(
- "LoggingConsistency message expects 0 additional bytes, got ",
- &messageSize);
+ "LoggingSanity message expects 0 additional bytes, got ", &messageSize);
}
// Test each warning level.
@@ -122,9 +121,8 @@ void LoggingConsistencyTest::setUp(uint32_t messageSize,
sendSuccessToHost();
}
-void LoggingConsistencyTest::handleEvent(uint32_t senderInstanceId,
- uint16_t eventType,
- const void *eventData) {
+void LoggingSanityTest::handleEvent(uint32_t senderInstanceId,
+ uint16_t eventType, const void *eventData) {
unexpectedEvent(eventType);
}
diff --git a/apps/test/chqts/src/general_test/logging_consistency_test.h b/apps/test/chqts/src/general_test/logging_sanity_test.h
index 86893453..962822a4 100644
--- a/apps/test/chqts/src/general_test/logging_consistency_test.h
+++ b/apps/test/chqts/src/general_test/logging_sanity_test.h
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-#ifndef _GTS_NANOAPPS_GENERAL_TEST_LOGGING_CONSISTENCY_TEST_H_
-#define _GTS_NANOAPPS_GENERAL_TEST_LOGGING_CONSISTENCY_TEST_H_
+#ifndef _GTS_NANOAPPS_GENERAL_TEST_LOGGING_SANITY_TEST_H_
+#define _GTS_NANOAPPS_GENERAL_TEST_LOGGING_SANITY_TEST_H_
#include <general_test/test.h>
@@ -32,9 +32,9 @@ namespace general_test {
*
* Simple protocol.
*/
-class LoggingConsistencyTest : public Test {
+class LoggingSanityTest : public Test {
public:
- LoggingConsistencyTest();
+ LoggingSanityTest();
protected:
void handleEvent(uint32_t senderInstanceId, uint16_t eventType,
@@ -44,4 +44,4 @@ class LoggingConsistencyTest : public Test {
} // namespace general_test
-#endif // _GTS_NANOAPPS_GENERAL_TEST_LOGGING_CONSISTENCY_TEST_H_
+#endif // _GTS_NANOAPPS_GENERAL_TEST_LOGGING_SANITY_TEST_H_
diff --git a/apps/test/chqts/src/general_test/send_event_stress_test.cc b/apps/test/chqts/src/general_test/send_event_stress_test.cc
index 02e5321e..bda2ee2c 100644
--- a/apps/test/chqts/src/general_test/send_event_stress_test.cc
+++ b/apps/test/chqts/src/general_test/send_event_stress_test.cc
@@ -103,7 +103,7 @@ void SendEventStressTest::handleEvent(uint32_t senderInstanceId,
sendFatalFailureToHost("handleEvent got event from unexpected sender:",
&senderInstanceId);
}
- verifyEvent(eventType, eventData, 0);
+ sanityCheck(eventType, eventData, 0);
--sEventsLeft;
if (sEventsLeft < 0) {
@@ -113,7 +113,7 @@ void SendEventStressTest::handleEvent(uint32_t senderInstanceId,
sInMethod = false;
}
-void SendEventStressTest::verifyEvent(uint16_t eventType, const void *data,
+void SendEventStressTest::sanityCheck(uint16_t eventType, const void *data,
uint32_t num) {
if (eventType != kEventType) {
unexpectedEvent(eventType);
@@ -130,7 +130,7 @@ void SendEventStressTest::completeCallback(uint16_t eventType, void *data) {
// chreSendEvent(), after it failed. We only allow a
// single one of these calls.
sInitTime = false;
- verifyEvent(eventType, data, 1);
+ sanityCheck(eventType, data, 1);
sCompleteCallbacksLeft--;
return;
}
@@ -139,7 +139,7 @@ void SendEventStressTest::completeCallback(uint16_t eventType, void *data) {
sendFatalFailureToHost(
"completeCallback invoked while another nanoapp method is running");
}
- verifyEvent(eventType, data, 1);
+ sanityCheck(eventType, data, 1);
--sCompleteCallbacksLeft;
if (sCompleteCallbacksLeft == 0) {
diff --git a/apps/test/chqts/src/general_test/send_event_stress_test.h b/apps/test/chqts/src/general_test/send_event_stress_test.h
index f2e49a92..ec94304e 100644
--- a/apps/test/chqts/src/general_test/send_event_stress_test.h
+++ b/apps/test/chqts/src/general_test/send_event_stress_test.h
@@ -45,7 +45,7 @@ class SendEventStressTest : public Test {
static void completeCallback(uint16_t eventType, void *data);
- static void verifyEvent(uint16_t eventType, const void *data, uint32_t num);
+ static void sanityCheck(uint16_t eventType, const void *data, uint32_t num);
};
} // namespace general_test
diff --git a/apps/test/chqts/src/general_test/simple_heap_alloc_test.cc b/apps/test/chqts/src/general_test/simple_heap_alloc_test.cc
index 235657b6..aa6fcea9 100644
--- a/apps/test/chqts/src/general_test/simple_heap_alloc_test.cc
+++ b/apps/test/chqts/src/general_test/simple_heap_alloc_test.cc
@@ -39,8 +39,8 @@ namespace general_test {
// max alignment than what the toolchain claims.
// To support this, we allow for a compiler define set for building this
// test. For the most part, we need to just trust the CHRE implementation
-// that this number is correct. However, we perform a basic consistency
-// check on this in testMaxAlignment().
+// that this number is correct. However, we make a basic sanity check of
+// this in testMaxAlignment().
constexpr size_t kMaxAlignment =
#ifdef CHRE_CUSTOM_MAX_ALIGNMENT
diff --git a/apps/test/chqts/src/general_test/test.h b/apps/test/chqts/src/general_test/test.h
index ce021c66..4336fa0c 100644
--- a/apps/test/chqts/src/general_test/test.h
+++ b/apps/test/chqts/src/general_test/test.h
@@ -39,10 +39,9 @@ class Test {
protected:
/**
* Report a test-ending error due to an unexpectedEvent.
- * This method halts execution on an unexpected event,
- * and never returns.
*
* @param eventType The event type
+ * @returns Never. This method aborts execution.
*/
static void unexpectedEvent(uint16_t eventType);
@@ -80,14 +79,13 @@ class Test {
const chreAsyncRequest &request);
/**
- * Get the message data sent from the host, after performing consistency
- * checks.
+ * Get the message data sent from the host, after performing sanity checks.
*
- * The method centralizes a number of common consistency checks that tests
+ * The method centralizes a number of common sanity checks that tests
* will perform in taking the given CHRE event data and extracting out
* the raw data payload sent by the host. This method is still useful
* when no message data is expected from the host, as we'll still
- * perform the checks.
+ * perform the sanity checks.
*
* This method will end the test in failure if any of the following happen:
* o 'senderInstanceId' != CHRE_INSTANCE_ID
@@ -95,9 +93,6 @@ class Test {
* o 'eventData'->reservedMessageType != expectedMessageType
* o 'eventData'->messageSize != expectedMessageSize
*
- * On passing all consistency checks, the message data can be expected
- * to be in 'eventData->message'
- *
* @param senderInstanceId From handleEvent()
* @param eventType From handleEvent()
* @param eventData From handleEvent()
@@ -105,6 +100,7 @@ class Test {
* when 'eventData' is seen as a chreMessageFromHostData.
* @param expectedMessageSize The expected 'messageSize' field
* when 'eventData' is seen as a chreMessageFromHostData.
+ * @returns 'eventData'->message, assuming all the sanity checks pass.
*/
static const void *getMessageDataFromHostEvent(
uint32_t senderInstanceId, uint16_t eventType, const void *eventData,
diff --git a/apps/test/chqts/src/general_test/test_names.h b/apps/test/chqts/src/general_test/test_names.h
index 4f6d2283..d2538571 100644
--- a/apps/test/chqts/src/general_test/test_names.h
+++ b/apps/test/chqts/src/general_test/test_names.h
@@ -114,14 +114,14 @@ enum class TestNames : uint32_t {
kBasicProximity = 0x040F,
/**
- * Test: VersionConsistencyTest
+ * Test: VersionSanityTest
*/
- kVersionConsistency = 0x0410,
+ kVersionSanity = 0x0410,
/**
- * Test: LoggingConsistencyTest
+ * Test: LoggingSanityTest
*/
- kLoggingConsistency = 0x0411,
+ kLoggingSanity = 0x0411,
/**
* Test: SendMessageToHostTest
diff --git a/apps/test/chqts/src/general_test/version_consistency_test.cc b/apps/test/chqts/src/general_test/version_sanity_test.cc
index 652203c6..4584e5ac 100644
--- a/apps/test/chqts/src/general_test/version_consistency_test.cc
+++ b/apps/test/chqts/src/general_test/version_sanity_test.cc
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include <general_test/version_consistency_test.h>
+#include <general_test/version_sanity_test.h>
#include <cstddef>
@@ -27,14 +27,13 @@ using nanoapp_testing::sendSuccessToHost;
namespace general_test {
-VersionConsistencyTest::VersionConsistencyTest() : Test(CHRE_API_VERSION_1_0) {}
+VersionSanityTest::VersionSanityTest() : Test(CHRE_API_VERSION_1_0) {}
-void VersionConsistencyTest::setUp(uint32_t messageSize,
- const void * /* message */) {
+void VersionSanityTest::setUp(uint32_t messageSize,
+ const void * /* message */) {
if (messageSize != 0) {
sendFatalFailureToHost(
- "VersionConsistency message expects 0 additional bytes, got ",
- &messageSize);
+ "VersionSanity message expects 0 additional bytes, got ", &messageSize);
}
if (mApiVersion < CHRE_API_VERSION_1_0) {
@@ -73,9 +72,8 @@ void VersionConsistencyTest::setUp(uint32_t messageSize,
sendSuccessToHost();
}
-void VersionConsistencyTest::handleEvent(uint32_t senderInstanceId,
- uint16_t eventType,
- const void *eventData) {
+void VersionSanityTest::handleEvent(uint32_t senderInstanceId,
+ uint16_t eventType, const void *eventData) {
unexpectedEvent(eventType);
}
diff --git a/apps/test/chqts/src/general_test/version_consistency_test.h b/apps/test/chqts/src/general_test/version_sanity_test.h
index b20918a3..dd1b5219 100644
--- a/apps/test/chqts/src/general_test/version_consistency_test.h
+++ b/apps/test/chqts/src/general_test/version_sanity_test.h
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-#ifndef _GTS_NANOAPPS_GENERAL_TEST_VERSION_CONSISTENCY_TEST_H_
-#define _GTS_NANOAPPS_GENERAL_TEST_VERSION_CONSISTENCY_TEST_H_
+#ifndef _GTS_NANOAPPS_GENERAL_TEST_VERSION_SANITY_TEST_H_
+#define _GTS_NANOAPPS_GENERAL_TEST_VERSION_SANITY_TEST_H_
#include <general_test/test.h>
@@ -28,9 +28,9 @@ namespace general_test {
*
* (Note: TODO(b/30077401): This test will have a non-simple protocol.)
*/
-class VersionConsistencyTest : public Test {
+class VersionSanityTest : public Test {
public:
- VersionConsistencyTest();
+ VersionSanityTest();
protected:
void handleEvent(uint32_t senderInstanceId, uint16_t eventType,
@@ -40,4 +40,4 @@ class VersionConsistencyTest : public Test {
} // namespace general_test
-#endif // _GTS_NANOAPPS_GENERAL_TEST_VERSION_CONSISTENCY_TEST_H_
+#endif // _GTS_NANOAPPS_GENERAL_TEST_VERSION_SANITY_TEST_H_
diff --git a/apps/test/chqts/src/shared/chunk_allocator.cc b/apps/test/chqts/src/shared/dumb_allocator.cc
index bb2697c4..091d83a7 100644
--- a/apps/test/chqts/src/shared/chunk_allocator.cc
+++ b/apps/test/chqts/src/shared/dumb_allocator.cc
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-#include <shared/chunk_allocator.h>
+#include <shared/dumb_allocator.h>
#include <shared/nano_string.h>
namespace nanoapp_testing {
-ChunkAllocatorBase::ChunkAllocatorBase(size_t allocSize, size_t slotCount,
- uint8_t *rawMemory)
+DumbAllocatorBase::DumbAllocatorBase(size_t allocSize, size_t slotCount,
+ uint8_t *rawMemory)
: mAllocSize(allocSize),
mSlotCount(slotCount),
mRawMemory(rawMemory),
@@ -33,7 +33,7 @@ ChunkAllocatorBase::ChunkAllocatorBase(size_t allocSize, size_t slotCount,
memset(mRawMemory, 0xCD, mSlotCount * mAllocSize);
}
-void *ChunkAllocatorBase::alloc(size_t bytes) {
+void *DumbAllocatorBase::alloc(size_t bytes) {
if (bytes > mAllocSize) {
// Oversized for our allocator.
return nullptr;
@@ -53,7 +53,7 @@ void *ChunkAllocatorBase::alloc(size_t bytes) {
return mRawMemory + (slot * mAllocSize);
}
-bool ChunkAllocatorBase::free(void *pointer) {
+bool DumbAllocatorBase::free(void *pointer) {
size_t slot;
if (!getSlot(pointer, &slot)) {
return false;
@@ -62,12 +62,12 @@ bool ChunkAllocatorBase::free(void *pointer) {
return true;
}
-bool ChunkAllocatorBase::contains(const void *pointer) const {
+bool DumbAllocatorBase::contains(const void *pointer) const {
size_t slot;
return getSlot(pointer, &slot);
}
-bool ChunkAllocatorBase::getSlot(const void *pointer, size_t *slot) const {
+bool DumbAllocatorBase::getSlot(const void *pointer, size_t *slot) const {
const uint8_t *ptr = static_cast<const uint8_t *>(pointer);
if (ptr < mRawMemory) {
// Out of range.
diff --git a/apps/test/chqts/src/shared/chunk_allocator.h b/apps/test/chqts/src/shared/dumb_allocator.h
index 94b96a51..a64f8f00 100644
--- a/apps/test/chqts/src/shared/chunk_allocator.h
+++ b/apps/test/chqts/src/shared/dumb_allocator.h
@@ -14,21 +14,21 @@
* limitations under the License.
*/
-#ifndef _GTS_NANOAPPS_SHARED_CHUNK_ALLOCATOR_H_
-#define _GTS_NANOAPPS_SHARED_CHUNK_ALLOCATOR_H_
+#ifndef _GTS_NANOAPPS_SHARED_DUMB_ALLOCATOR_H_
+#define _GTS_NANOAPPS_SHARED_DUMB_ALLOCATOR_H_
#include <cstddef>
#include <cstdint>
namespace nanoapp_testing {
-// Implementation Note: We chose the pattern of having ChunkAllocatorBase to
-// reduce the code duplication from multiple instances of ChunkAllocator with
+// Implementation Note: We chose the pattern of having DumbAllocatorBase to
+// reduce the code duplication from multiple instances of DumbAllocator with
// different template parameters.
-// See ChunkAllocator below for usage and API documentation.
-class ChunkAllocatorBase {
+// See DumbAllocator below for usage and API documentation.
+class DumbAllocatorBase {
protected:
- ChunkAllocatorBase(size_t allocSize, size_t slotCount, uint8_t *rawMemory);
+ DumbAllocatorBase(size_t allocSize, size_t slotCount, uint8_t *rawMemory);
void *alloc(size_t bytes);
bool free(void *ptr);
@@ -50,7 +50,7 @@ class ChunkAllocatorBase {
};
/**
- * This chunk allocator is designed to allow us to easily get chunks of
+ * This dumb allocator is designed to allow us to easily get chunks of
* memory without needing to go through heap allocation. The idea is to
* reduce our dependency on CHRE for some aspects of our tests.
*
@@ -61,10 +61,10 @@ class ChunkAllocatorBase {
* each, and costs (kSlotCount * kAllocSize) bytes of underlying storage.
*/
template <size_t kAllocSize, size_t kSlotCount>
-class ChunkAllocator : ChunkAllocatorBase {
+class DumbAllocator : DumbAllocatorBase {
public:
- ChunkAllocator()
- : ChunkAllocatorBase(kAllocSize, kSlotCount, mRawMemoryArray) {}
+ DumbAllocator()
+ : DumbAllocatorBase(kAllocSize, kSlotCount, mRawMemoryArray) {}
/**
* If "bytes" <= kAllocSize, and there are less than kSlotCount allocations,
@@ -73,7 +73,7 @@ class ChunkAllocator : ChunkAllocatorBase {
* Reminder this is non-reentrant.
*/
void *alloc(size_t bytes) {
- return ChunkAllocatorBase::alloc(bytes);
+ return DumbAllocatorBase::alloc(bytes);
}
/**
@@ -83,7 +83,7 @@ class ChunkAllocator : ChunkAllocatorBase {
* Reminder this is non-reentrant.
*/
bool free(void *ptr) {
- return ChunkAllocatorBase::free(ptr);
+ return DumbAllocatorBase::free(ptr);
}
/**
@@ -91,7 +91,7 @@ class ChunkAllocator : ChunkAllocatorBase {
* return true. Otherwise, do nothing and return false.
*/
bool contains(const void *ptr) const {
- return ChunkAllocatorBase::contains(ptr);
+ return DumbAllocatorBase::contains(ptr);
}
private:
@@ -102,4 +102,4 @@ class ChunkAllocator : ChunkAllocatorBase {
} // namespace nanoapp_testing
-#endif // _GTS_NANOAPPS_SHARED_CHUNK_ALLOCATOR_H_
+#endif // _GTS_NANOAPPS_SHARED_DUMB_ALLOCATOR_H_
diff --git a/apps/test/chqts/src/shared/chunk_allocator_test.cc b/apps/test/chqts/src/shared/dumb_allocator_test.cc
index fa803e88..2f540f5e 100644
--- a/apps/test/chqts/src/shared/chunk_allocator_test.cc
+++ b/apps/test/chqts/src/shared/dumb_allocator_test.cc
@@ -14,28 +14,28 @@
* limitations under the License.
*/
-#include <shared/chunk_allocator.h>
+#include <shared/dumb_allocator.h>
#include <gtest/gtest.h>
static constexpr size_t kAllocSize = 128;
static constexpr size_t kSlotCount = 5;
-typedef nanoapp_testing::ChunkAllocator<kAllocSize, kSlotCount> DA;
+typedef nanoapp_testing::DumbAllocator<kAllocSize, kSlotCount> DA;
static void ExpectGoodAlloc(const DA &da, const void *ptr) {
EXPECT_NE(nullptr, ptr);
EXPECT_TRUE(da.contains(ptr));
}
-TEST(ChunkAllocatorTests, SimpleAlloc) {
+TEST(DumbAllocatorTests, SimpleAlloc) {
DA da;
void *ptr = da.alloc(kAllocSize);
ExpectGoodAlloc(da, ptr);
EXPECT_TRUE(da.free(ptr));
}
-TEST(ChunkAllocatorTests, AllocsAfterFree) {
+TEST(DumbAllocatorTests, AllocsAfterFree) {
DA da;
void *ptrs[kSlotCount];
for (size_t i = 0; i < kSlotCount; i++) {
@@ -61,7 +61,7 @@ TEST(ChunkAllocatorTests, AllocsAfterFree) {
}
}
-TEST(ChunkAllocatorTests, ContainsIsFalseForBadPtrs) {
+TEST(DumbAllocatorTests, ContainsIsFalseForBadPtrs) {
DA da;
uint8_t *ptr = static_cast<uint8_t *>(da.alloc(kAllocSize));
ASSERT_NE(nullptr, ptr);
@@ -70,13 +70,13 @@ TEST(ChunkAllocatorTests, ContainsIsFalseForBadPtrs) {
EXPECT_FALSE(da.contains(nullptr));
}
-TEST(ChunkAllocatorTests, FailLargeAllocations) {
+TEST(DumbAllocatorTests, FailLargeAllocations) {
DA da;
EXPECT_EQ(nullptr, da.alloc(kAllocSize + 1));
EXPECT_EQ(nullptr, da.alloc(kAllocSize * 2));
}
-TEST(ChunkAllocatorTests, SucceedSmallAllocations) {
+TEST(DumbAllocatorTests, SucceedSmallAllocations) {
DA da;
ExpectGoodAlloc(da, da.alloc(kAllocSize - 1));
ExpectGoodAlloc(da, da.alloc(1));
diff --git a/apps/test/chqts/src/shared/send_message.cc b/apps/test/chqts/src/shared/send_message.cc
index 56ec3b73..f4641780 100644
--- a/apps/test/chqts/src/shared/send_message.cc
+++ b/apps/test/chqts/src/shared/send_message.cc
@@ -19,7 +19,7 @@
#include <inttypes.h>
#include <shared/abort.h>
-#include <shared/chunk_allocator.h>
+#include <shared/dumb_allocator.h>
#include <shared/nano_endian.h>
#include <shared/nano_string.h>
@@ -29,27 +29,27 @@ namespace nanoapp_testing {
constexpr size_t kAllocSize = 128;
-static ChunkAllocator<kAllocSize, 4> gChunkAlloc;
+static DumbAllocator<kAllocSize, 4> gDumbAlloc;
-static void freeChunkAllocMessage(void *message, size_t messageSize) {
+static void freeDumbAllocMessage(void *message, size_t messageSize) {
if (messageSize > kAllocSize) {
uint32_t localSize = uint32_t(messageSize);
- sendFatalFailureToHost("freeChunkAllocMessage given oversized message:",
+ sendFatalFailureToHost("freeDumbAllocMessage given oversized message:",
&localSize);
}
- if (!gChunkAlloc.free(message)) {
+ if (!gDumbAlloc.free(message)) {
uint32_t localPtr =
reinterpret_cast<size_t>(message) & UINT32_C(0xFFFFFFFF);
- sendFatalFailureToHost("freeChunkAllocMessage given bad pointer:",
+ sendFatalFailureToHost("freeDumbAllocMessage given bad pointer:",
&localPtr);
}
}
static void freeHeapMessage(void *message, size_t /* messageSize */) {
- if (gChunkAlloc.contains(message)) {
+ if (gDumbAlloc.contains(message)) {
uint32_t localPtr =
reinterpret_cast<size_t>(message) & UINT32_C(0xFFFFFFFF);
- sendFatalFailureToHost("freeHeapMessage given ChunkAlloc pointer:",
+ sendFatalFailureToHost("freeHeapMessage given DumbAlloc pointer:",
&localPtr);
}
chreHeapFree(message);
@@ -74,17 +74,17 @@ static bool needToPrependMessageType() {
return true;
}
-static void *getMessageMemory(size_t *size, bool *ChunkAlloc) {
+static void *getMessageMemory(size_t *size, bool *dumbAlloc) {
if (needToPrependMessageType()) {
*size += sizeof(uint32_t);
}
- void *ret = gChunkAlloc.alloc(*size);
+ void *ret = gDumbAlloc.alloc(*size);
if (ret != nullptr) {
- *ChunkAlloc = true;
+ *dumbAlloc = true;
} else {
// Not expected, but possible if the CHRE is lagging in freeing
// these messages, or if we're sending a huge message.
- *ChunkAlloc = false;
+ *dumbAlloc = false;
ret = chreHeapAlloc(static_cast<uint32_t>(*size));
if (ret == nullptr) {
fatalError();
@@ -107,14 +107,14 @@ static void *prependMessageType(MessageType messageType, void *memory) {
}
static void internalSendMessage(MessageType messageType, void *data,
- size_t dataSize, bool ChunkAlloc) {
+ size_t dataSize, bool dumbAlloc) {
// Note that if the CHRE implementation occasionally drops a message
// here, then tests will become flaky. For now, we consider that to
// be a flaky CHRE implementation which should fail testing.
if (!chreSendMessageToHostEndpoint(
data, dataSize, static_cast<uint32_t>(messageType),
CHRE_HOST_ENDPOINT_BROADCAST,
- ChunkAlloc ? freeChunkAllocMessage : freeHeapMessage)) {
+ dumbAlloc ? freeDumbAllocMessage : freeHeapMessage)) {
fatalError();
}
}
@@ -124,12 +124,12 @@ void sendMessageToHost(MessageType messageType, const void *data,
if ((dataSize == 0) && (data != nullptr)) {
sendInternalFailureToHost("Bad sendMessageToHost args");
}
- bool ChunkAlloc = true;
+ bool dumbAlloc = true;
size_t fullMessageSize = dataSize;
- void *myMessageBase = getMessageMemory(&fullMessageSize, &ChunkAlloc);
+ void *myMessageBase = getMessageMemory(&fullMessageSize, &dumbAlloc);
void *ptr = prependMessageType(messageType, myMessageBase);
memcpy(ptr, data, dataSize);
- internalSendMessage(messageType, myMessageBase, fullMessageSize, ChunkAlloc);
+ internalSendMessage(messageType, myMessageBase, fullMessageSize, dumbAlloc);
}
void sendStringToHost(MessageType messageType, const char *message,
@@ -137,7 +137,7 @@ void sendStringToHost(MessageType messageType, const char *message,
if (message == nullptr) {
sendInternalFailureToHost("sendStringToHost 'message' is NULL");
}
- bool ChunkAlloc = true;
+ bool dumbAlloc = true;
const size_t messageStrlen = strlen(message);
size_t myMessageLen = messageStrlen;
if (value != nullptr) {
@@ -148,7 +148,7 @@ void sendStringToHost(MessageType messageType, const char *message,
size_t fullMessageLen = myMessageLen;
char *fullMessage =
- static_cast<char *>(getMessageMemory(&fullMessageLen, &ChunkAlloc));
+ static_cast<char *>(getMessageMemory(&fullMessageLen, &dumbAlloc));
char *ptr = static_cast<char *>(prependMessageType(messageType, fullMessage));
memcpy(ptr, message, messageStrlen);
ptr += messageStrlen;
@@ -159,7 +159,7 @@ void sendStringToHost(MessageType messageType, const char *message,
// Add the terminator.
fullMessage[fullMessageLen - 1] = '\0';
- internalSendMessage(messageType, fullMessage, fullMessageLen, ChunkAlloc);
+ internalSendMessage(messageType, fullMessage, fullMessageLen, dumbAlloc);
}
// Before we abort the nanoapp, we also put this message in the chreLog().
diff --git a/apps/test/common/chre_audio_concurrency_test/Makefile b/apps/test/common/chre_audio_concurrency_test/Makefile
index d7f3c2fc..a158b561 100644
--- a/apps/test/common/chre_audio_concurrency_test/Makefile
+++ b/apps/test/common/chre_audio_concurrency_test/Makefile
@@ -49,10 +49,6 @@ COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
COMMON_CFLAGS += -I$(NANOAPP_PATH)/inc
COMMON_CFLAGS += -I$(TEST_SHARED_PATH)/inc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_AUDIO = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/test/common/chre_audio_concurrency_test/src/chre_audio_concurrency_test_manager.cc b/apps/test/common/chre_audio_concurrency_test/src/chre_audio_concurrency_test_manager.cc
index 0000ed99..20cf736c 100644
--- a/apps/test/common/chre_audio_concurrency_test/src/chre_audio_concurrency_test_manager.cc
+++ b/apps/test/common/chre_audio_concurrency_test/src/chre_audio_concurrency_test_manager.cc
@@ -99,8 +99,7 @@ bool Manager::handleTestCommandMessage(uint16_t hostEndpointId, TestStep step) {
if (success) {
mTestSession = TestSession(hostEndpointId, step);
- LOGI("Starting test step %" PRIu8,
- static_cast<uint8_t>(mTestSession->step));
+ LOGI("Starting test step %" PRIu8, mTestSession->step);
}
}
@@ -159,8 +158,7 @@ void Manager::handleDataFromChre(uint16_t eventType, const void *eventData) {
void Manager::handleTimer() {
if (mTimerHandle != CHRE_TIMER_INVALID && mTestSession.has_value()) {
- LOGE("Timed out during test: step %" PRIu8,
- static_cast<uint8_t>(mTestSession->step));
+ LOGE("Timed out during test: step %" PRIu8, mTestSession->step);
sendTestResultToHost(mTestSession->hostEndpointId, kTestResultMessageType,
false /* success */);
mTestSession.reset();
@@ -238,8 +236,7 @@ void Manager::handleAudioDataEvent(const chreAudioDataEvent *data) {
}
default:
- LOGE("Unexpected test step %" PRIu8,
- static_cast<uint8_t>(mTestSession->step));
+ LOGE("Unexpected test step %" PRIu8, mTestSession->step);
break;
}
}
diff --git a/apps/test/common/chre_cross_validator_gnss/Makefile b/apps/test/common/chre_cross_validator_gnss/Makefile
deleted file mode 100644
index f3e92584..00000000
--- a/apps/test/common/chre_cross_validator_gnss/Makefile
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# CHRE GNSS Cross Validator Test Nanoapp Makefile
-#
-# Environment Checks ###########################################################
-ifeq ($(CHRE_PREFIX),)
- ifneq ($(ANDROID_BUILD_TOP),)
- CHRE_PREFIX = $(ANDROID_BUILD_TOP)/system/chre
- else
- $(error "You must run 'lunch' to setup ANDROID_BUILD_TOP, or explicitly \
- define the CHRE_PREFIX environment variable to point to the CHRE root \
- directory.")
- endif
-endif
-
-# Nanoapp Configuration ########################################################
-
-NANOAPP_NAME = chre_cross_validator_gnss
-NANOAPP_ID = 0x476f6f6754000006
-NANOAPP_NAME_STRING = \"CHRE\ Cross\ Validator\ GNSS\"
-NANOAPP_VERSION = 0x00000001
-
-NANOAPP_PATH = $(CHRE_PREFIX)/apps/test/common/chre_cross_validator_gnss
-
-# Source Code ##################################################################
-
-COMMON_SRCS += $(NANOAPP_PATH)/src/chre_cross_validator_gnss.cc
-
-# Compiler Flags ###############################################################
-
-# Defines
-COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
-
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_GNSS = true
-
-# Makefile Includes ############################################################
-
-include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/test/common/chre_cross_validator_gnss/src/chre_cross_validator_gnss.cc b/apps/test/common/chre_cross_validator_gnss/src/chre_cross_validator_gnss.cc
deleted file mode 100644
index 99aa371f..00000000
--- a/apps/test/common/chre_cross_validator_gnss/src/chre_cross_validator_gnss.cc
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 <chre.h>
-#include <cinttypes>
-
-namespace chre {
-
-extern "C" void nanoappHandleEvent(uint32_t senderInstanceId,
- uint16_t eventType, const void *eventData) {}
-
-extern "C" bool nanoappStart(void) {
- return true;
-}
-
-extern "C" void nanoappEnd(void) {}
-
-} // namespace chre
diff --git a/apps/test/common/chre_cross_validator_sensor/inc/chre_cross_validator_sensor_manager.h b/apps/test/common/chre_cross_validator_sensor/inc/chre_cross_validator_sensor_manager.h
index 47d05f55..2b871623 100644
--- a/apps/test/common/chre_cross_validator_sensor/inc/chre_cross_validator_sensor_manager.h
+++ b/apps/test/common/chre_cross_validator_sensor/inc/chre_cross_validator_sensor_manager.h
@@ -161,18 +161,6 @@ class Manager {
void *const *arg);
/**
- * Encodes the datapoints into a SensorData message.
- *
- * @param stream The stream to write to.
- * @param field The field to write to.
- * @param arg The data passed in order to write to the stream.
- * @return true if successful.
- */
- static bool encodeStepCounterSensorDatapoints(pb_ostream_t *stream,
- const pb_field_t *field,
- void *const *arg);
-
- /**
* Encodes a single float value into values list of SensorDatapoint object.
*
* @param stream The stream to write to.
@@ -199,19 +187,6 @@ class Manager {
void *const *arg);
/**
- * Encodes a single step counter value into the values list of SensorDatapoint
- * object, converting the uint64 value property into a float in the process.
- *
- * @param stream The stream to write to.
- * @param field The field to write to (unused).
- * @param arg The data passed in order to write to the stream.
- * @return true if successful.
- */
- static bool encodeStepCounterSensorDatapointValue(pb_ostream_t *stream,
- const pb_field_t *field,
- void *const *arg);
-
- /**
* Handle a start sensor message.
*
* @param startSensorCommand The StartSensorCommand proto message received.
@@ -287,16 +262,6 @@ class Manager {
const chreSensorByteData *proximityDataFromChre);
/**
- * @param stepCounterDataFromChre Proximity sensor data from CHRE.
- * @param sensorType The sensor type that sent the uint64 data.
- *
- * @return The Data proto message that is ready to be sent to host with float
- * data.
- */
- chre_cross_validation_sensor_Data makeSensorStepCounterData(
- const chreSensorUint64Data *stepCounterDataFromChre);
-
- /**
* Handle sensor three axis data from CHRE.
*
* @param threeAxisDataFromChre The data from CHRE to parse.
@@ -323,15 +288,6 @@ class Manager {
/**
* Send data to be validated to the host.
- * Handle step counter sensor data from CHRE.
- *
- * @param stepCounterDataFromChre The data to parse.
- */
- void handleStepCounterData(
- const chreSensorUint64Data *stepCounterDataFromChre);
-
- /**
- * Encode and send data to be validated to host.
*
* @param data The data to send.
*/
diff --git a/apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc b/apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc
index 2d0c3b78..02fa2635 100644
--- a/apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc
+++ b/apps/test/common/chre_cross_validator_sensor/src/chre_cross_validator_sensor_manager.cc
@@ -94,10 +94,6 @@ void Manager::handleEvent(uint32_t senderInstanceId, uint16_t eventType,
case CHRE_EVENT_SENSOR_PROXIMITY_DATA:
handleProximityData(static_cast<const chreSensorByteData *>(eventData));
break;
- case CHRE_EVENT_SENSOR_STEP_COUNTER_DATA:
- handleStepCounterData(
- static_cast<const chreSensorUint64Data *>(eventData));
- break;
default:
LOGE("Got unknown event type from senderInstanceId %" PRIu32
" and with eventType %" PRIu16,
@@ -171,27 +167,6 @@ bool Manager::encodeProximitySensorDatapointValue(pb_ostream_t *stream,
return true;
}
-bool Manager::encodeStepCounterSensorDatapointValue(pb_ostream_t *stream,
- const pb_field_t *field,
- void *const *arg) {
- const auto *sensorUint64DataSample =
- static_cast<const chreSensorUint64Data::chreSensorUint64SampleData *>(
- *arg);
- if (!pb_encode_tag_for_field(
- stream,
- &chre_cross_validation_sensor_SensorDatapoint_fields
- [chre_cross_validation_sensor_SensorDatapoint_values_tag - 1])) {
- return false;
- }
- // This value is casted to a float for the Java sensors framework so do it
- // here to make it easier to encode into the existing proto message.
- float stepValue = float(sensorUint64DataSample->value);
- if (!pb_encode_fixed32(stream, &stepValue)) {
- return false;
- }
- return true;
-}
-
bool Manager::encodeThreeAxisSensorDatapoints(pb_ostream_t *stream,
const pb_field_t * /*field*/,
void *const *arg) {
@@ -275,34 +250,6 @@ bool Manager::encodeProximitySensorDatapoints(pb_ostream_t *stream,
return true;
}
-bool Manager::encodeStepCounterSensorDatapoints(pb_ostream_t *stream,
- const pb_field_t *field,
- void *const *arg) {
- const auto *sensorStepCounterData =
- static_cast<const chreSensorUint64Data *>(*arg);
- uint64_t currentTimestamp = sensorStepCounterData->header.baseTimestamp +
- chreGetEstimatedHostTimeOffset();
- for (size_t i = 0; i < sensorStepCounterData->header.readingCount; i++) {
- const chreSensorUint64Data::chreSensorUint64SampleData &sampleData =
- sensorStepCounterData->readings[i];
- currentTimestamp += sampleData.timestampDelta;
- if (!pb_encode_tag_for_field(
- stream,
- &chre_cross_validation_sensor_SensorData_fields
- [chre_cross_validation_sensor_SensorData_datapoints_tag - 1])) {
- return false;
- }
- chre_cross_validation_sensor_SensorDatapoint datapoint = makeDatapoint(
- encodeStepCounterSensorDatapointValue, &sampleData, currentTimestamp);
- if (!pb_encode_submessage(
- stream, chre_cross_validation_sensor_SensorDatapoint_fields,
- &datapoint)) {
- return false;
- }
- }
- return true;
-}
-
bool Manager::handleStartSensorMessage(
const chre_cross_validation_sensor_StartSensorCommand &startSensorCommand) {
bool success = false;
@@ -493,26 +440,6 @@ chre_cross_validation_sensor_Data Manager::makeSensorProximityData(
return newData;
}
-chre_cross_validation_sensor_Data Manager::makeSensorStepCounterData(
- const chreSensorUint64Data *stepCounterDataFromChre) {
- chre_cross_validation_sensor_SensorData newStepCounterData = {
- .has_chreSensorType = true,
- .chreSensorType = CHRE_SENSOR_TYPE_STEP_COUNTER,
- .has_accuracy = true,
- .accuracy = stepCounterDataFromChre->header.accuracy,
- .datapoints = {
- .funcs = {.encode = encodeStepCounterSensorDatapoints},
- .arg = const_cast<chreSensorUint64Data *>(stepCounterDataFromChre)}};
- chre_cross_validation_sensor_Data newData = {
- .which_data = chre_cross_validation_sensor_Data_sensorData_tag,
- .data =
- {
- .sensorData = newStepCounterData,
- },
- };
- return newData;
-}
-
void Manager::handleSensorThreeAxisData(
const chreSensorThreeAxisData *threeAxisDataFromChre, uint8_t sensorType) {
if (processSensorData(threeAxisDataFromChre->header, sensorType)) {
@@ -541,16 +468,6 @@ void Manager::handleProximityData(
}
}
-void Manager::handleStepCounterData(
- const chreSensorUint64Data *stepCounterDataFromChre) {
- if (processSensorData(stepCounterDataFromChre->header,
- CHRE_SENSOR_TYPE_STEP_COUNTER)) {
- chre_cross_validation_sensor_Data newData =
- makeSensorStepCounterData(stepCounterDataFromChre);
- sendDataToHost(newData);
- }
-}
-
void Manager::sendDataToHost(const chre_cross_validation_sensor_Data &data) {
sendMessageToHost(
mCrossValidatorState->hostEndpoint,
diff --git a/apps/test/common/chre_cross_validator_wifi/Makefile b/apps/test/common/chre_cross_validator_wifi/Makefile
index 12e68870..0ad79071 100644
--- a/apps/test/common/chre_cross_validator_wifi/Makefile
+++ b/apps/test/common/chre_cross_validator_wifi/Makefile
@@ -46,10 +46,6 @@ COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
# Includes
COMMON_CFLAGS += -I$(NANOAPP_PATH)/inc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_WIFI = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/test/common/chre_cross_validator_wifi/inc/chre_cross_validator_wifi_manager.h b/apps/test/common/chre_cross_validator_wifi/inc/chre_cross_validator_wifi_manager.h
index 313d1f5f..0ca0a7ed 100644
--- a/apps/test/common/chre_cross_validator_wifi/inc/chre_cross_validator_wifi_manager.h
+++ b/apps/test/common/chre_cross_validator_wifi/inc/chre_cross_validator_wifi_manager.h
@@ -81,22 +81,6 @@ class Manager {
bool mChreDataCollectionDone = false;
/**
- * This is the fraction of the number of results in the greater set of
- * scan results between the AP and CHRE that the lesser set can differ by.
- * Increasing this value will increase the relative amount that AP and CHRE
- * results sizes can differ by.
- *
- * Ex: AP_results_size = 8
- * CHRE_results_size = 7
- * kMaxDiffNumResultsFraction = 0.25
- *
- * CHRE_results_size is valid because it is >= 8 - 8 * 0.25 = 6
- */
- // TODO(b/185026344): Perfect this number. Consider using an abolute
- // difference instead of a percentage difference also.
- static constexpr float kMaxDiffNumResultsFraction = 0.25f;
-
- /**
* Handle a message from the host.
* @param senderInstanceId The instance id of the sender.
* @param data The message from the host's data.
@@ -159,30 +143,6 @@ class Manager {
void compareAndSendResultToHost();
/**
- * Verify the wifi scan results are matching between AP and CHRE.
- *
- * @param testResultOut Pointer to the test result proto message which will be
- * sent back to host, whose bool and message depends on
- * the checks inside this method.
- */
- void verifyScanResults(chre_test_common_TestResult *testResultOut);
-
- /**
- * Get the scan result that has the same bssid as the scan result passed.
- *
- * @param results The array of scan results to search through.
- * @param resultsSize The number of valid scan result objects in the array
- * passed.
- * @param queryResult The result to search with.
- * @param resultIndexOut The pointer where the scan result index will be
- * copied to if the result was found.
- * @return true if the scan result was found.
- */
- bool getMatchingScanResult(WifiScanResult *results, uint8_t resultsSize,
- const WifiScanResult &queryResult,
- uint8_t *resultIndexOut);
-
- /**
* Setup WiFi scan monitoring from CHRE apis.
*
* @return true if chreWifiConfigureScanMonitorAsync() returns true
diff --git a/apps/test/common/chre_cross_validator_wifi/inc/wifi_scan_result.h b/apps/test/common/chre_cross_validator_wifi/inc/wifi_scan_result.h
index a7d64f1a..6bba0a3e 100644
--- a/apps/test/common/chre_cross_validator_wifi/inc/wifi_scan_result.h
+++ b/apps/test/common/chre_cross_validator_wifi/inc/wifi_scan_result.h
@@ -44,11 +44,7 @@ class WifiScanResult {
*/
WifiScanResult(const chreWifiScanResult &chreScanResult);
- static bool areEqual(const WifiScanResult &result1,
- const WifiScanResult &result2);
-
- static bool bssidsAreEqual(const WifiScanResult &result1,
- const WifiScanResult &result2);
+ static bool areEqual(WifiScanResult result1, WifiScanResult result2);
uint8_t getResultIndex() const {
return mResultIndex;
@@ -63,14 +59,6 @@ class WifiScanResult {
return mResultIndex >= mTotalNumResults - 1;
}
- bool getSeen() const {
- return mSeen;
- }
-
- void didSee() {
- mSeen = true;
- }
-
private:
char mSsid[CHRE_WIFI_SSID_MAX_LEN];
uint8_t mBssid[CHRE_WIFI_BSSID_LEN];
@@ -78,12 +66,10 @@ class WifiScanResult {
uint8_t mTotalNumResults = 0;
uint8_t mResultIndex = 0;
- //! If true then, a scan result with this bssid has been seen before in the
- //! other set of scan results.
- bool mSeen = false;
-
static bool decodeString(pb_istream_t *stream, const pb_field_t * /*field*/,
void **arg);
+
+ static bool byteArraysAreEqual(uint8_t *arr1, uint8_t *arr2, uint8_t len);
};
#endif // WIFI_SCAN_RESULT_H_
diff --git a/apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc b/apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc
index 3689192b..c23efedd 100644
--- a/apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc
+++ b/apps/test/common/chre_cross_validator_wifi/src/chre_cross_validator_wifi_manager.cc
@@ -16,7 +16,6 @@
#include "chre_cross_validator_wifi_manager.h"
#include <stdio.h>
-#include <algorithm>
#include <cinttypes>
#include <cstring>
@@ -163,78 +162,36 @@ void Manager::handleWifiScanResult(const chreWifiScanEvent *event) {
}
void Manager::compareAndSendResultToHost() {
+ constexpr uint16_t kMaxSizeErrMsg = 1000;
+ char *errMsg = static_cast<char *>(chreHeapAlloc(kMaxSizeErrMsg));
chre_test_common_TestResult testResult;
- // TODO(b/185188753): Log info about all scan results so that it is easier
- // to figure out which AP or CHRE scan results are missing or corrupted.
- if (mApScanResultsSize != mChreScanResultsSize) {
- testResult = makeTestResultProtoMessage(
- false, "There is a different number of AP and CHRE scan results.");
- LOGE("AP and CHRE wifi scan result counts differ, AP = %" PRIu8
- ", CHRE = %" PRIu8,
- mApScanResultsSize, mChreScanResultsSize);
+ if (errMsg == nullptr) {
+ LOG_OOM();
} else {
- verifyScanResults(&testResult);
- }
- encodeAndSendMessageToHost(
- static_cast<const void *>(&testResult),
- chre_test_common_TestResult_fields,
- chre_cross_validation_wifi_MessageType_STEP_RESULT);
-}
-
-void Manager::verifyScanResults(chre_test_common_TestResult *testResultOut) {
- bool allResultsValid = true;
- for (uint8_t i = 0; i < mChreScanResultsSize; i++) {
- const WifiScanResult &chreScanResult = mChreScanResults[i];
- uint8_t apScanResultIndex;
- bool didFind = getMatchingScanResult(mApScanResults, mApScanResultsSize,
- chreScanResult, &apScanResultIndex);
- // TODO(b/185188753): Log info about each result iterated through here and
- // do not just break at the first error.
- if (didFind) {
- WifiScanResult &apScanResult = mApScanResults[apScanResultIndex];
- if (apScanResult.getSeen()) {
- *testResultOut = makeTestResultProtoMessage(
- false, "Saw a CHRE scan result with a duplicate BSSID.");
- allResultsValid = false;
- break;
- }
- if (!WifiScanResult::areEqual(chreScanResult, apScanResult)) {
- *testResultOut =
- makeTestResultProtoMessage(false,
- "Fields differ between an AP and "
- "CHRE scan result with same Bssid.");
- allResultsValid = false;
- break;
- }
- apScanResult.didSee();
+ memset(errMsg, 0, kMaxSizeErrMsg);
+ // Logging all info about the scan results for debug purposes
+ if (mApScanResultsSize != mChreScanResultsSize) {
+ testResult = makeTestResultProtoMessage(
+ false, "There is a different number of AP and CHRE scan results.");
+ LOGE("AP and CHRE wifi scan result counts differ, AP = %" PRIu8
+ ", CHRE = %" PRIu8,
+ mApScanResultsSize, mChreScanResultsSize);
} else {
- // Error CHRE BSSID does not match any AP
- *testResultOut = makeTestResultProtoMessage(
- false,
- "Could not find an AP scan result with the same Bssid as a CHRE "
- "result");
- allResultsValid = false;
- break;
- }
- }
- if (allResultsValid) {
- *testResultOut = makeTestResultProtoMessage(true);
- }
-}
-
-bool Manager::getMatchingScanResult(WifiScanResult *results,
- uint8_t resultsSize,
- const WifiScanResult &queryResult,
- uint8_t *resultIndexOut) {
- for (uint8_t i = 0; i < resultsSize; i++) {
- if (WifiScanResult::bssidsAreEqual(results[i], queryResult)) {
- // Mark this scan result as already seen so that the next time it is used
- // as a match the test will fail because of duplicate scan results.
- *resultIndexOut = i;
- return true;
+ for (uint8_t i = 0; i < mApScanResultsSize; i++) {
+ if (!WifiScanResult::areEqual(mApScanResults[i], mChreScanResults[i])) {
+ testResult = makeTestResultProtoMessage(
+ false, "One of the AP and CHRE scan results are not equal.");
+ LOGE("The AP and CHRE scan results are not equal on index %" PRIu8,
+ i);
+ }
+ }
}
+ encodeAndSendMessageToHost(
+ static_cast<const void *>(&testResult),
+ chre_test_common_TestResult_fields,
+ chre_cross_validation_wifi_MessageType_STEP_RESULT);
+ chreHeapFree(errMsg);
}
- return false;
}
bool Manager::encodeErrorMessage(pb_ostream_t *stream,
@@ -299,36 +256,29 @@ void Manager::encodeAndSendMessageToHost(const void *message,
void Manager::handleWifiAsyncResult(const chreAsyncResult *result) {
chre_test_common_TestResult testResult;
- bool sendMessage = false;
if (result->requestType == CHRE_WIFI_REQUEST_TYPE_CONFIGURE_SCAN_MONITOR) {
if (mStep != chre_cross_validation_wifi_Step_SETUP) {
testResult = makeTestResultProtoMessage(
false, "Received scan monitor result event when step is not SETUP");
- sendMessage = true;
} else {
if (result->success) {
LOGD("Wifi scan monitoring setup successfully");
testResult = makeTestResultProtoMessage(true);
- sendMessage = true;
} else {
LOGE("Wifi scan monitoring setup failed async w/ error code %" PRIu8
".",
result->errorCode);
testResult = makeTestResultProtoMessage(
false, "Wifi scan monitoring setup failed async.");
- sendMessage = true;
}
}
} else {
testResult = makeTestResultProtoMessage(
false, "Unknown chre async result type received");
- sendMessage = true;
- }
- if (sendMessage) {
- encodeAndSendMessageToHost(
- static_cast<void *>(&testResult), chre_test_common_TestResult_fields,
- chre_cross_validation_wifi_MessageType_STEP_RESULT);
}
+ encodeAndSendMessageToHost(
+ static_cast<void *>(&testResult), chre_test_common_TestResult_fields,
+ chre_cross_validation_wifi_MessageType_STEP_RESULT);
}
} // namespace cross_validator_wifi
diff --git a/apps/test/common/chre_cross_validator_wifi/src/wifi_scan_result.cc b/apps/test/common/chre_cross_validator_wifi/src/wifi_scan_result.cc
index dfdb61d2..46a74e8a 100644
--- a/apps/test/common/chre_cross_validator_wifi/src/wifi_scan_result.cc
+++ b/apps/test/common/chre_cross_validator_wifi/src/wifi_scan_result.cc
@@ -39,25 +39,22 @@ WifiScanResult::WifiScanResult(pb_istream_t *apWifiScanResultStream) {
}
mTotalNumResults = wifiScanResultProto.totalNumResults;
mResultIndex = wifiScanResultProto.resultIndex;
+ LOGI("AP scan result mSsid = %s", mSsid);
}
WifiScanResult::WifiScanResult(const chreWifiScanResult &chreScanResult) {
+ LOGI("CHRE scan result mSsid = %s", chreScanResult.ssid);
memset(mSsid, 0, CHRE_WIFI_SSID_MAX_LEN);
memcpy(mSsid, chreScanResult.ssid, chreScanResult.ssidLen);
memcpy(mBssid, chreScanResult.bssid, CHRE_WIFI_BSSID_LEN);
}
-bool WifiScanResult::areEqual(const WifiScanResult &result1,
- const WifiScanResult &result2) {
- // TODO(b/184653034): Compare all fields that are shared between AP and CHRE
- // scan result.
+bool WifiScanResult::areEqual(WifiScanResult result1, WifiScanResult result2) {
+ // TODO(srok): Compare all fields that are shared between AP and CHRE scan
+ // result.
return strcmp(result1.mSsid, result2.mSsid) == 0 &&
- bssidsAreEqual(result1, result2);
-}
-
-bool WifiScanResult::bssidsAreEqual(const WifiScanResult &result1,
- const WifiScanResult &result2) {
- return memcmp(result1.mBssid, result2.mBssid, CHRE_WIFI_BSSID_LEN) == 0;
+ byteArraysAreEqual(result1.mBssid, result2.mBssid,
+ CHRE_WIFI_BSSID_LEN);
}
bool WifiScanResult::decodeString(pb_istream_t *stream,
@@ -65,3 +62,11 @@ bool WifiScanResult::decodeString(pb_istream_t *stream,
pb_byte_t *strPtr = reinterpret_cast<pb_byte_t *>(*arg);
return pb_read(stream, strPtr, stream->bytes_left);
}
+
+bool WifiScanResult::byteArraysAreEqual(uint8_t *arr1, uint8_t *arr2,
+ uint8_t len) {
+ for (uint8_t i = 0; i < len; i++) {
+ if (arr1[i] != arr2[i]) return false;
+ }
+ return true;
+}
diff --git a/apps/test/common/chre_settings_test/Makefile b/apps/test/common/chre_settings_test/Makefile
index 07a94b6b..3a95042e 100644
--- a/apps/test/common/chre_settings_test/Makefile
+++ b/apps/test/common/chre_settings_test/Makefile
@@ -46,13 +46,6 @@ COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
# Includes
COMMON_CFLAGS += -I$(NANOAPP_PATH)/inc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_GNSS = true
-CHRE_NANOAPP_USES_WIFI = true
-CHRE_NANOAPP_USES_WWAN = true
-CHRE_NANOAPP_USES_AUDIO = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/test/common/chre_settings_test/inc/chre_settings_test_manager.h b/apps/test/common/chre_settings_test/inc/chre_settings_test_manager.h
index f8395811..2c25c8d8 100644
--- a/apps/test/common/chre_settings_test/inc/chre_settings_test_manager.h
+++ b/apps/test/common/chre_settings_test/inc/chre_settings_test_manager.h
@@ -40,7 +40,6 @@ class Manager {
GNSS_LOCATION,
GNSS_MEASUREMENT,
WWAN_CELL_INFO,
- AUDIO,
};
enum class FeatureState : uint8_t {
@@ -145,19 +144,6 @@ class Manager {
void handleWifiScanResult(const chreWifiScanEvent *result);
/**
- * @param event CHRE Audio Source Status Event
- */
- void handleAudioSourceStatusEvent(
- const struct chreAudioSourceStatusEvent *event);
-
- /**
- * @param event CHRE Audio Data Event
- */
- void handleAudioDataEvent(const struct chreAudioDataEvent *event);
-
- void handleTimeout();
-
- /**
* End the current test session and sends result to host.
*
* @param hostEndpointId The host to send the result to.
diff --git a/apps/test/common/chre_settings_test/src/chre_settings_test_manager.cc b/apps/test/common/chre_settings_test/src/chre_settings_test_manager.cc
index 371482ea..5bfbc156 100644
--- a/apps/test/common/chre_settings_test/src/chre_settings_test_manager.cc
+++ b/apps/test/common/chre_settings_test/src/chre_settings_test_manager.cc
@@ -21,7 +21,6 @@
#include "chre/util/nanoapp/callbacks.h"
#include "chre/util/nanoapp/log.h"
-#include "chre/util/time.h"
#include "chre_settings_test.nanopb.h"
#include "chre_settings_test_util.h"
@@ -39,13 +38,6 @@ constexpr uint32_t kGnssLocationCookie = 0x3456;
constexpr uint32_t kGnssMeasurementCookie = 0x4567;
constexpr uint32_t kWwanCellInfoCookie = 0x5678;
-// Flag to verify if an audio data event was received after a valid sampling
-// change event (i.e., we only got the data event after a source-enabled-and-
-// not-suspended event).
-bool gGotSourceEnabledEvent = false;
-
-uint32_t gTimerHandle = CHRE_TIMER_INVALID;
-
bool getFeature(const chre_settings_test_TestCommand &command,
Manager::Feature *feature) {
bool success = true;
@@ -65,9 +57,6 @@ bool getFeature(const chre_settings_test_TestCommand &command,
case chre_settings_test_TestCommand_Feature_WWAN_CELL_INFO:
*feature = Manager::Feature::WWAN_CELL_INFO;
break;
- case chre_settings_test_TestCommand_Feature_AUDIO:
- *feature = Manager::Feature::AUDIO;
- break;
default:
LOGE("Unknown feature %d", command.feature);
success = false;
@@ -169,13 +158,8 @@ bool Manager::isFeatureSupported(Feature feature) {
((capabilities & CHRE_WWAN_GET_CELL_INFO) != 0);
break;
}
- case Feature::AUDIO: {
- struct chreAudioSource source;
- supported = chreAudioGetSource(0 /* handle */, &source);
- break;
- }
default:
- LOGE("Unknown feature %" PRIu8, static_cast<uint8_t>(feature));
+ LOGE("Unknown feature %" PRIu8, feature);
}
return supported;
@@ -206,9 +190,6 @@ void Manager::handleMessageFromHost(uint32_t senderInstanceId,
if (getFeature(testCommand, &feature) &&
getFeatureState(testCommand, &state) &&
getTestStep(testCommand, &step)) {
- LOGD("starting test: feature: %u, state %u, step %u",
- static_cast<uint8_t>(feature), static_cast<uint8_t>(state),
- static_cast<uint8_t>(step));
handleStartTestMessage(hostData->hostEndpoint, feature, state, step);
success = true;
}
@@ -224,15 +205,12 @@ void Manager::handleStartTestMessage(uint16_t hostEndpointId, Feature feature,
FeatureState state, TestStep step) {
// If the test/feature is not supported, treat as success and skip the test.
if (!isTestSupported() || !isFeatureSupported(feature)) {
- LOGW("Skipping test - TestSupported: %u, FeatureSupported: %u",
- isTestSupported(), isFeatureSupported(feature));
sendTestResult(hostEndpointId, true /* success */);
} else {
bool success = false;
if (step == TestStep::SETUP) {
if (feature != Feature::WIFI_RTT) {
- LOGE("Unexpected feature %" PRIu8 " for test step",
- static_cast<uint8_t>(feature));
+ LOGE("Unexpected feature %" PRIu8 " for test step", feature);
} else {
success = chreWifiRequestScanAsyncDefault(&kWifiScanningCookie);
}
@@ -253,37 +231,23 @@ void Manager::handleDataFromChre(uint16_t eventType, const void *eventData) {
// The validation for the correct data w.r.t. the current test session
// will be done in the methods called from here.
switch (eventType) {
- case CHRE_EVENT_AUDIO_DATA:
- handleAudioDataEvent(
- static_cast<const struct chreAudioDataEvent *>(eventData));
- break;
-
- case CHRE_EVENT_AUDIO_SAMPLING_CHANGE:
- handleAudioSourceStatusEvent(
- static_cast<const struct chreAudioSourceStatusEvent *>(eventData));
- break;
-
- case CHRE_EVENT_TIMER:
- handleTimeout();
- break;
-
- case CHRE_EVENT_WIFI_ASYNC_RESULT:
+ case CHRE_EVENT_WIFI_ASYNC_RESULT: {
handleWifiAsyncResult(static_cast<const chreAsyncResult *>(eventData));
break;
-
- case CHRE_EVENT_WIFI_SCAN_RESULT:
+ }
+ case CHRE_EVENT_WIFI_SCAN_RESULT: {
handleWifiScanResult(static_cast<const chreWifiScanEvent *>(eventData));
break;
-
- case CHRE_EVENT_GNSS_ASYNC_RESULT:
+ }
+ case CHRE_EVENT_GNSS_ASYNC_RESULT: {
handleGnssAsyncResult(static_cast<const chreAsyncResult *>(eventData));
break;
-
- case CHRE_EVENT_WWAN_CELL_INFO_RESULT:
+ }
+ case CHRE_EVENT_WWAN_CELL_INFO_RESULT: {
handleWwanCellInfoResult(
static_cast<const chreWwanCellInfoResult *>(eventData));
break;
-
+ }
default:
LOGE("Unknown event type %" PRIu16, eventType);
}
@@ -293,10 +257,10 @@ void Manager::handleDataFromChre(uint16_t eventType, const void *eventData) {
bool Manager::startTestForFeature(Feature feature) {
bool success = true;
switch (feature) {
- case Feature::WIFI_SCANNING:
+ case Feature::WIFI_SCANNING: {
success = chreWifiRequestScanAsyncDefault(&kWifiScanningCookie);
break;
-
+ }
case Feature::WIFI_RTT: {
if (!mCachedRangingTarget.has_value()) {
LOGE("No cached WiFi RTT ranging target");
@@ -307,42 +271,30 @@ bool Manager::startTestForFeature(Feature feature) {
}
break;
}
-
- case Feature::GNSS_LOCATION:
+ case Feature::GNSS_LOCATION: {
success = chreGnssLocationSessionStartAsync(1000 /* minIntervalMs */,
0 /* minTimeToNextFixMs */,
&kGnssLocationCookie);
break;
-
- case Feature::GNSS_MEASUREMENT:
+ }
+ case Feature::GNSS_MEASUREMENT: {
success = chreGnssMeasurementSessionStartAsync(1000 /* minIntervalMs */,
&kGnssMeasurementCookie);
break;
-
- case Feature::WWAN_CELL_INFO:
+ }
+ case Feature::WWAN_CELL_INFO: {
success = chreWwanGetCellInfoAsync(&kWwanCellInfoCookie);
break;
-
- case Feature::AUDIO: {
- struct chreAudioSource source;
- if ((success = chreAudioGetSource(0 /* handle */, &source))) {
- success = chreAudioConfigureSource(0 /* handle */, true /* enable */,
- source.minBufferDuration,
- source.minBufferDuration);
- }
- break;
}
-
default:
- LOGE("Unknown feature %" PRIu8, static_cast<uint8_t>(feature));
+ LOGE("Unknown feature %" PRIu8, feature);
return false;
}
if (!success) {
- LOGE("Failed to make request for test feature %" PRIu8,
- static_cast<uint8_t>(feature));
+ LOGE("Failed to make request for test feature %" PRIu8, feature);
} else {
- LOGI("Starting test for feature %" PRIu8, static_cast<uint8_t>(feature));
+ LOGI("Starting test for feature %" PRIu8, feature);
}
return success;
@@ -354,14 +306,14 @@ bool Manager::validateAsyncResult(const chreAsyncResult *result,
if (result->cookie != expectedCookie) {
LOGE("Unexpected cookie on async result");
} else {
- bool featureEnabled = (mTestSession->featureState == FeatureState::ENABLED);
- bool disabledErrorCode =
- (result->errorCode == CHRE_ERROR_FUNCTION_DISABLED);
-
- if (featureEnabled && disabledErrorCode) {
- LOGE("Got disabled error code when feature is enabled");
- } else if (!featureEnabled && !disabledErrorCode) {
- LOGE("Got non-disabled error code when feature is disabled");
+ chreError expectedErrorCode =
+ (mTestSession->featureState == FeatureState::ENABLED)
+ ? CHRE_ERROR_NONE
+ : CHRE_ERROR_FUNCTION_DISABLED;
+
+ if (result->errorCode != expectedErrorCode) {
+ LOGE("Unexpected async result: error code %" PRIu8 " expect %" PRIu8,
+ result->errorCode, expectedErrorCode);
} else {
success = true;
}
@@ -382,7 +334,7 @@ void Manager::handleWifiAsyncResult(const chreAsyncResult *result) {
}
if (mTestSession->feature != Feature::WIFI_SCANNING) {
LOGE("Unexpected WiFi scan async result: test feature %" PRIu8,
- static_cast<uint8_t>(mTestSession->feature));
+ mTestSession->feature);
} else {
success = validateAsyncResult(
result, static_cast<const void *>(&kWifiScanningCookie));
@@ -392,7 +344,7 @@ void Manager::handleWifiAsyncResult(const chreAsyncResult *result) {
case CHRE_WIFI_REQUEST_TYPE_RANGING: {
if (mTestSession->feature != Feature::WIFI_RTT) {
LOGE("Unexpected WiFi ranging async result: test feature %" PRIu8,
- static_cast<uint8_t>(mTestSession->feature));
+ mTestSession->feature);
} else {
success = validateAsyncResult(
result, static_cast<const void *>(&kWifiRttCookie));
@@ -442,7 +394,7 @@ void Manager::handleGnssAsyncResult(const chreAsyncResult *result) {
case CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_START: {
if (mTestSession->feature != Feature::GNSS_LOCATION) {
LOGE("Unexpected GNSS location async result: test feature %" PRIu8,
- static_cast<uint8_t>(mTestSession->feature));
+ mTestSession->feature);
} else {
success = validateAsyncResult(
result, static_cast<const void *>(&kGnssLocationCookie));
@@ -453,7 +405,7 @@ void Manager::handleGnssAsyncResult(const chreAsyncResult *result) {
case CHRE_GNSS_REQUEST_TYPE_MEASUREMENT_SESSION_START: {
if (mTestSession->feature != Feature::GNSS_MEASUREMENT) {
LOGE("Unexpected GNSS measurement async result: test feature %" PRIu8,
- static_cast<uint8_t>(mTestSession->feature));
+ mTestSession->feature);
} else {
success = validateAsyncResult(
result, static_cast<const void *>(&kGnssMeasurementCookie));
@@ -474,7 +426,7 @@ void Manager::handleWwanCellInfoResult(const chreWwanCellInfoResult *result) {
// CHRE API requirements.
if (mTestSession->feature != Feature::WWAN_CELL_INFO) {
LOGE("Unexpected WWAN cell info result: test feature %" PRIu8,
- static_cast<uint8_t>(mTestSession->feature));
+ mTestSession->feature);
} else if (result->cookie != &kWwanCellInfoCookie) {
LOGE("Unexpected cookie on WWAN cell info result");
} else if (result->errorCode != CHRE_ERROR_NONE) {
@@ -490,86 +442,6 @@ void Manager::handleWwanCellInfoResult(const chreWwanCellInfoResult *result) {
sendTestResult(mTestSession->hostEndpointId, success);
}
-// The MicDisabled Settings test works as follows:
-// * The contents of the Source Status Event are parsed, and there are 4
-// possible scenarios for the flow of our test:
-//
-// - Mic Access was disabled, source was suspended
-// -- Since CHRE guarantees that we'll receive audio data events spaced at
-// the source's minBufferDuration apart (plus a small delay/latency),
-// we set a timer for (minBufferDuration + 1) seconds to verify that no
-// data event was received. We pass the test on a timeout.
-//
-// - Mic Access was disabled, source wasn't suspended
-// -- We fail the test
-//
-// - Mic Access was enabled, source was suspended
-// -- We fail the test
-//
-// - Mic Access was enabled, source wasn't suspended
-// -- We set a flag 'GotSourceEnabledEvent'. The audio data event checks this
-// flag, and reports success/failure appropriately.
-
-void Manager::handleAudioSourceStatusEvent(
- const struct chreAudioSourceStatusEvent *event) {
- bool success = false;
- if (mTestSession.has_value()) {
- if (mTestSession->featureState == FeatureState::ENABLED) {
- if (event->status.suspended) {
- struct chreAudioSource source;
- if (chreAudioGetSource(0 /* handle */, &source)) {
- const uint64_t duration =
- source.minBufferDuration + kOneSecondInNanoseconds;
- gTimerHandle =
- chreTimerSet(duration, nullptr /* cookie */, true /* oneShot */);
-
- if (gTimerHandle == CHRE_TIMER_INVALID) {
- LOGE("Failed to set timer");
- } else {
- success = true;
- }
- } else {
- LOGE("Failed to query audio source");
- }
- } else {
- LOGE("Source wasn't suspended when Mic Access was disabled");
- }
- } else {
- gGotSourceEnabledEvent = true;
- success = true;
- }
-
- if (!success) {
- sendTestResult(mTestSession->hostEndpointId, success);
- }
- }
-}
-
-void Manager::handleAudioDataEvent(const struct chreAudioDataEvent *event) {
- bool success = false;
- if (mTestSession.has_value()) {
- if (mTestSession->featureState == FeatureState::ENABLED) {
- if (gTimerHandle != CHRE_TIMER_INVALID) {
- chreTimerCancel(gTimerHandle);
- gTimerHandle = CHRE_TIMER_INVALID;
- }
- } else if (gGotSourceEnabledEvent) {
- success = true;
- }
- chreAudioConfigureSource(0 /* handle */, false /* enable */,
- 0 /* minBufferDuration */,
- 0 /* maxbufferDuration */);
- sendTestResult(mTestSession->hostEndpointId, success);
- }
-}
-
-void Manager::handleTimeout() {
- gTimerHandle = CHRE_TIMER_INVALID;
- chreAudioConfigureSource(0 /*handle*/, false /*enable*/,
- 0 /*minBufferDuration*/, 0 /*maxBufferDuration*/);
- sendTestResult(mTestSession->hostEndpointId, true /*success*/);
-}
-
void Manager::sendTestResult(uint16_t hostEndpointId, bool success) {
sendTestResultToHost(hostEndpointId, success);
mTestSession.reset();
diff --git a/apps/test/common/chre_stress_test/Makefile b/apps/test/common/chre_stress_test/Makefile
deleted file mode 100644
index cc9ef761..00000000
--- a/apps/test/common/chre_stress_test/Makefile
+++ /dev/null
@@ -1,59 +0,0 @@
-#
-# CHRE Stress Test Nanoapp Makefile
-#
-# Environment Checks ###########################################################
-ifeq ($(CHRE_PREFIX),)
- ifneq ($(ANDROID_BUILD_TOP),)
- CHRE_PREFIX = $(ANDROID_BUILD_TOP)/system/chre
- else
- $(error "You must run 'lunch' to setup ANDROID_BUILD_TOP, or explicitly \
- define the CHRE_PREFIX environment variable to point to the CHRE root \
- directory.")
- endif
-endif
-
-# Nanoapp Configuration ########################################################
-
-NANOAPP_NAME = chre_stress_test
-NANOAPP_ID = 0x476f6f675400000a
-NANOAPP_NAME_STRING = \"CHRE\ Stress\ Test\"
-NANOAPP_VERSION = 0x00000003
-
-NANOAPP_PATH = $(CHRE_PREFIX)/apps/test/common/chre_stress_test
-TEST_SHARED_PATH = $(CHRE_PREFIX)/apps/test/common/shared
-
-# Protobuf Sources #############################################################
-
-NANOPB_EXTENSION = nanopb
-
-NANOPB_SRCS += $(NANOAPP_PATH)/../proto/chre_test_common.proto
-NANOPB_SRCS += $(NANOAPP_PATH)/../proto/chre_stress_test.proto
-NANOPB_PROTO_PATH = $(NANOAPP_PATH)/../proto
-NANOPB_INCLUDES = $(NANOPB_PROTO_PATH)
-NANOPB_FLAGS += --proto_path=$(NANOPB_PROTO_PATH)
-
-# Source Code ##################################################################
-
-COMMON_SRCS += $(NANOAPP_PATH)/src/chre_stress_test.cc
-COMMON_SRCS += $(NANOAPP_PATH)/src/chre_stress_test_manager.cc
-COMMON_SRCS += $(TEST_SHARED_PATH)/src/send_message.cc
-COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/callbacks.cc
-
-# Compiler Flags ###############################################################
-
-# Defines
-COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
-
-# Includes
-COMMON_CFLAGS += -I$(NANOAPP_PATH)/inc
-COMMON_CFLAGS += -I$(TEST_SHARED_PATH)/inc
-
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_WIFI = true
-CHRE_NANOAPP_USES_GNSS = true
-CHRE_NANOAPP_USES_WWAN = true
-
-# Makefile Includes ############################################################
-
-include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/test/common/chre_stress_test/inc/chre_stress_test_manager.h b/apps/test/common/chre_stress_test/inc/chre_stress_test_manager.h
deleted file mode 100644
index b6c8f914..00000000
--- a/apps/test/common/chre_stress_test/inc/chre_stress_test_manager.h
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 CHRE_STRESS_TEST_MANAGER_H_
-#define CHRE_STRESS_TEST_MANAGER_H_
-
-#include "chre_stress_test.nanopb.h"
-
-#include <chre.h>
-#include <cinttypes>
-
-#include "chre/util/optional.h"
-#include "chre/util/singleton.h"
-#include "chre/util/time.h"
-
-namespace chre {
-
-namespace stress_test {
-
-/**
- * A class to manage a CHRE stress test session.
- */
-class Manager {
- public:
- /**
- * Handles an event from CHRE. Semantics are the same as nanoappHandleEvent.
- */
- void handleEvent(uint32_t senderInstanceId, uint16_t eventType,
- const void *eventData);
-
- private:
- struct AsyncRequest {
- AsyncRequest(const void *cookie_) {
- cookie = cookie_;
- }
-
- uint64_t requestTimeNs = chreGetTime();
- const void *cookie;
- };
-
- /**
- * Handles a message from the host.
- *
- * @param senderInstanceId The sender instance ID of this message.
- * @param hostData The data from the host.
- */
- void handleMessageFromHost(uint32_t senderInstanceId,
- const chreMessageFromHostData *hostData);
- /**
- * Processes data from CHRE.
- *
- * @param eventType The event type as defined by CHRE.
- * @param eventData A pointer to the data.
- */
- void handleDataFromChre(uint16_t eventType, const void *eventData);
-
- /**
- * @param handle A pointer to the timer handle.
- */
- void handleTimerEvent(const uint32_t *handle);
-
- /**
- * Validates a timestamp of an event where the timestamp is expected
- * to be monotonically increasing.
- *
- * @param timestamp The timestamp.
- * @param pastTimestamp The previous timestamp.
- */
- void checkTimestamp(uint64_t timestamp, uint64_t pastTimestamp);
-
- /**
- * Handles a start command from the host.
- *
- * @param start true to start the test, stop otherwise.
- */
- void handleWifiStartCommand(bool start);
- void handleGnssLocationStartCommand(bool start);
- void handleGnssMeasurementStartCommand(bool start);
- void handleWwanStartCommand(bool start);
- void handleWifiScanMonitoringCommand(bool start);
-
- /**
- * @param result The WiFi async result from CHRE.
- */
- void handleWifiAsyncResult(const chreAsyncResult *result);
-
- /**
- * @param result The WiFi scan event from CHRE.
- */
- void handleWifiScanEvent(const chreWifiScanEvent *event);
-
- /**
- * Sets up a WiFi scan request after some time.
- */
- void requestDelayedWifiScan();
- void handleDelayedWifiTimer();
-
- /**
- * Sends the failure to the host.
- *
- * @param errorMessage The error message string.
- */
- void sendFailure(const char *errorMessage);
-
- /**
- * Sets/cancels a timer and asserts success.
- *
- * @param delayNs The delay of the timer in nanoseconds.
- * @param oneShot true if the timer request is one-shot.
- * @param timerHandle A non-null pointer to where the timer handle is stored.
- */
- void setTimer(uint64_t delayNs, bool oneShot, uint32_t *timerHandle);
- void cancelTimer(uint32_t *timerHandle);
-
- /**
- * Makes the next GNSS request.
- */
- void makeGnssLocationRequest();
- void makeGnssMeasurementRequest();
-
- /**
- * @param result The GNSS async result from CHRE.
- */
- void handleGnssAsyncResult(const chreAsyncResult *result);
-
- /**
- * @param result The result to validate.
- * @param request The async request associated with this result.
- * @param asyncTimerHandle The async timer handle for this request.
- */
- void validateGnssAsyncResult(const chreAsyncResult *result,
- Optional<AsyncRequest> &request,
- uint32_t *asyncTimerHandle);
-
- /**
- * @param event The GNSS event from CHRE.
- */
- void handleGnssLocationEvent(const chreGnssLocationEvent *event);
- void handleGnssDataEvent(const chreGnssDataEvent *event);
-
- /**
- * Makes the next cell info request.
- */
- void makeWwanCellInfoRequest();
-
- /**
- * @param event The cell info event from CHRE.
- */
- void handleCellInfoResult(const chreWwanCellInfoResult *event);
-
- //! The host endpoint of the current test host.
- Optional<uint16_t> mHostEndpoint;
-
- //! The timer handle for performing requests.
- uint32_t mWifiScanTimerHandle = CHRE_TIMER_INVALID;
- uint32_t mWifiScanAsyncTimerHandle = CHRE_TIMER_INVALID;
- uint32_t mGnssLocationTimerHandle = CHRE_TIMER_INVALID;
- uint32_t mGnssLocationAsyncTimerHandle = CHRE_TIMER_INVALID;
- uint32_t mGnssMeasurementTimerHandle = CHRE_TIMER_INVALID;
- uint32_t mGnssMeasurementAsyncTimerHandle = CHRE_TIMER_INVALID;
- uint32_t mWwanTimerHandle = CHRE_TIMER_INVALID;
- uint32_t mWifiScanMonitorAsyncTimerHandle = CHRE_TIMER_INVALID;
-
- //! true if the test has been started for the feature.
- bool mWifiTestStarted = false;
- bool mGnssLocationTestStarted = false;
- bool mGnssMeasurementTestStarted = false;
- bool mWwanTestStarted = false;
-
- //! true if scan monitor is enabled for the nanoapp.
- bool mWifiScanMonitorEnabled = false;
-
- //! The cookie to use for requests.
- const uint32_t kOnDemandWifiScanCookie = 0xface;
- const uint32_t kGnssLocationCookie = 0xbeef;
- const uint32_t kGnssMeasurementCookie = 0xbead;
- const uint32_t kWwanCellInfoCookie = 0x1337;
-
- //! The pending requests.
- Optional<AsyncRequest> mWifiScanAsyncRequest;
- Optional<AsyncRequest> mGnssLocationAsyncRequest;
- Optional<AsyncRequest> mGnssMeasurementAsyncRequest;
- Optional<AsyncRequest> mWwanCellInfoAsyncRequest;
-
- //! The previous timestamp of events.
- uint64_t mPrevGnssLocationEventTimestampMs = 0;
- uint64_t mPrevGnssMeasurementEventTimestampNs = 0;
- uint64_t mPrevWifiScanEventTimestampNs = 0;
- uint64_t mPrevWwanCellInfoEventTimestampNs = 0;
-};
-
-// The stress test manager singleton.
-typedef chre::Singleton<Manager> ManagerSingleton;
-
-} // namespace stress_test
-
-} // namespace chre
-
-#endif // CHRE_STRESS_TEST_MANAGER_H_
diff --git a/apps/test/common/chre_stress_test/src/chre_stress_test.cc b/apps/test/common/chre_stress_test/src/chre_stress_test.cc
deleted file mode 100644
index c52122e3..00000000
--- a/apps/test/common/chre_stress_test/src/chre_stress_test.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 <chre.h>
-#include <cinttypes>
-
-#include "chre_stress_test_manager.h"
-
-namespace chre {
-
-extern "C" void nanoappHandleEvent(uint32_t senderInstanceId,
- uint16_t eventType, const void *eventData) {
- stress_test::ManagerSingleton::get()->handleEvent(senderInstanceId, eventType,
- eventData);
-}
-
-extern "C" bool nanoappStart(void) {
- stress_test::ManagerSingleton::init();
- return true;
-}
-
-extern "C" void nanoappEnd(void) {
- stress_test::ManagerSingleton::deinit();
-}
-
-} // namespace chre
diff --git a/apps/test/common/chre_stress_test/src/chre_stress_test_manager.cc b/apps/test/common/chre_stress_test/src/chre_stress_test_manager.cc
deleted file mode 100644
index 9c4cee9c..00000000
--- a/apps/test/common/chre_stress_test/src/chre_stress_test_manager.cc
+++ /dev/null
@@ -1,553 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 "chre_stress_test_manager.h"
-
-#include <pb_decode.h>
-
-#include "chre/util/macros.h"
-#include "chre/util/nanoapp/callbacks.h"
-#include "chre/util/nanoapp/log.h"
-#include "chre_stress_test.nanopb.h"
-#include "send_message.h"
-
-#define LOG_TAG "[ChreStressTest]"
-
-namespace chre {
-
-namespace stress_test {
-
-namespace {
-
-constexpr chre::Nanoseconds kWifiScanInterval = chre::Seconds(5);
-
-bool isRequestTypeForLocation(uint8_t requestType) {
- return (requestType == CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_START) ||
- (requestType == CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_STOP);
-}
-
-bool isRequestTypeForMeasurement(uint8_t requestType) {
- return (requestType == CHRE_GNSS_REQUEST_TYPE_MEASUREMENT_SESSION_START) ||
- (requestType == CHRE_GNSS_REQUEST_TYPE_MEASUREMENT_SESSION_STOP);
-}
-
-} // anonymous namespace
-
-void Manager::handleEvent(uint32_t senderInstanceId, uint16_t eventType,
- const void *eventData) {
- if (eventType == CHRE_EVENT_MESSAGE_FROM_HOST) {
- handleMessageFromHost(
- senderInstanceId,
- static_cast<const chreMessageFromHostData *>(eventData));
- } else if (senderInstanceId == CHRE_INSTANCE_ID) {
- handleDataFromChre(eventType, eventData);
- } else {
- LOGW("Got unknown event type from senderInstanceId %" PRIu32
- " and with eventType %" PRIu16,
- senderInstanceId, eventType);
- }
-}
-
-void Manager::handleMessageFromHost(uint32_t senderInstanceId,
- const chreMessageFromHostData *hostData) {
- bool success = false;
- uint32_t messageType = hostData->messageType;
- if (senderInstanceId != CHRE_INSTANCE_ID) {
- LOGE("Incorrect sender instance id: %" PRIu32, senderInstanceId);
- } else if (messageType == chre_stress_test_MessageType_TEST_HOST_RESTARTED) {
- // Do nothing and only update the host endpoint
- mHostEndpoint = hostData->hostEndpoint;
- success = true;
- } else if (messageType != chre_stress_test_MessageType_TEST_COMMAND) {
- LOGE("Invalid message type %" PRIu32, messageType);
- } else if (mHostEndpoint.has_value() &&
- hostData->hostEndpoint != mHostEndpoint.value()) {
- LOGE("Invalid host endpoint %" PRIu16 " expected %" PRIu16,
- hostData->hostEndpoint, mHostEndpoint.value());
- } else {
- pb_istream_t istream = pb_istream_from_buffer(
- static_cast<const pb_byte_t *>(hostData->message),
- hostData->messageSize);
- chre_stress_test_TestCommand testCommand =
- chre_stress_test_TestCommand_init_default;
-
- if (!pb_decode(&istream, chre_stress_test_TestCommand_fields,
- &testCommand)) {
- LOGE("Failed to decode start command error %s", PB_GET_ERROR(&istream));
- } else {
- LOGI("Got message from host: feature %d start %d", testCommand.feature,
- testCommand.start);
-
- success = true;
- switch (testCommand.feature) {
- case chre_stress_test_TestCommand_Feature_WIFI_ON_DEMAND_SCAN: {
- handleWifiStartCommand(testCommand.start);
- break;
- }
- case chre_stress_test_TestCommand_Feature_GNSS_LOCATION: {
- handleGnssLocationStartCommand(testCommand.start);
- break;
- }
- case chre_stress_test_TestCommand_Feature_GNSS_MEASUREMENT: {
- handleGnssMeasurementStartCommand(testCommand.start);
- break;
- }
- case chre_stress_test_TestCommand_Feature_WWAN: {
- handleWwanStartCommand(testCommand.start);
- break;
- }
- case chre_stress_test_TestCommand_Feature_WIFI_SCAN_MONITOR: {
- handleWifiScanMonitoringCommand(testCommand.start);
- break;
- }
- default: {
- LOGE("Unknown feature %d", testCommand.feature);
- success = false;
- break;
- }
- }
- }
-
- mHostEndpoint = hostData->hostEndpoint;
- }
-
- if (!success) {
- test_shared::sendTestResultWithMsgToHost(
- hostData->hostEndpoint,
- chre_stress_test_MessageType_TEST_RESULT /* messageType */, success,
- nullptr /* errMessage */);
- }
-}
-
-void Manager::handleDataFromChre(uint16_t eventType, const void *eventData) {
- switch (eventType) {
- case CHRE_EVENT_TIMER:
- handleTimerEvent(static_cast<const uint32_t *>(eventData));
- break;
-
- case CHRE_EVENT_WIFI_ASYNC_RESULT:
- handleWifiAsyncResult(static_cast<const chreAsyncResult *>(eventData));
- break;
-
- case CHRE_EVENT_WIFI_SCAN_RESULT:
- handleWifiScanEvent(static_cast<const chreWifiScanEvent *>(eventData));
- break;
-
- case CHRE_EVENT_GNSS_ASYNC_RESULT:
- handleGnssAsyncResult(static_cast<const chreAsyncResult *>(eventData));
- break;
-
- case CHRE_EVENT_GNSS_LOCATION:
- handleGnssLocationEvent(
- static_cast<const chreGnssLocationEvent *>(eventData));
- break;
-
- case CHRE_EVENT_GNSS_DATA:
- handleGnssDataEvent(static_cast<const chreGnssDataEvent *>(eventData));
- break;
-
- case CHRE_EVENT_WWAN_CELL_INFO_RESULT:
- handleCellInfoResult(
- static_cast<const chreWwanCellInfoResult *>(eventData));
- break;
-
- default:
- LOGW("Unknown event type %" PRIu16, eventType);
- break;
- }
-}
-
-void Manager::handleTimerEvent(const uint32_t *handle) {
- if (*handle == mWifiScanTimerHandle) {
- handleDelayedWifiTimer();
- } else if (*handle == mWifiScanAsyncTimerHandle) {
- sendFailure("WiFi scan request timed out");
- } else if (*handle == mGnssLocationTimerHandle) {
- makeGnssLocationRequest();
- } else if (*handle == mGnssMeasurementTimerHandle) {
- makeGnssMeasurementRequest();
- } else if (*handle == mGnssLocationAsyncTimerHandle &&
- mGnssLocationAsyncRequest.has_value()) {
- sendFailure("GNSS location async result timed out");
- } else if (*handle == mGnssMeasurementAsyncTimerHandle &&
- mGnssMeasurementAsyncRequest.has_value()) {
- sendFailure("GNSS measurement async result timed out");
- } else if (*handle == mWwanTimerHandle) {
- makeWwanCellInfoRequest();
- } else if (*handle == mWifiScanMonitorAsyncTimerHandle) {
- sendFailure("WiFi scan monitor request timed out");
- } else {
- sendFailure("Unknown timer handle");
- }
-}
-
-void Manager::handleDelayedWifiTimer() {
- // NOTE: We set the maxScanAgeMs to something smaller than the WiFi
- // scan periodicity to ensure new scans are generated.
- static const struct chreWifiScanParams params = {
- /*.scanType=*/CHRE_WIFI_SCAN_TYPE_NO_PREFERENCE,
- /*.maxScanAgeMs=*/2000, // 2 seconds
- /*.frequencyListLen=*/0,
- /*.frequencyList=*/NULL,
- /*.ssidListLen=*/0,
- /*.ssidList=*/NULL,
- /*.radioChainPref=*/CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT,
- /*.channelSet=*/CHRE_WIFI_CHANNEL_SET_NON_DFS};
-
- bool success = chreWifiRequestScanAsync(&params, &kOnDemandWifiScanCookie);
- LOGI("Requested on demand wifi success ? %d", success);
- if (!success) {
- sendFailure("Failed to make WiFi scan request");
- } else {
- mWifiScanAsyncRequest = AsyncRequest(&kOnDemandWifiScanCookie);
- setTimer(CHRE_WIFI_SCAN_RESULT_TIMEOUT_NS, true /* oneShot */,
- &mWifiScanAsyncTimerHandle);
- }
-}
-
-void Manager::handleWifiAsyncResult(const chreAsyncResult *result) {
- if (result->requestType == CHRE_WIFI_REQUEST_TYPE_REQUEST_SCAN) {
- if (result->success) {
- LOGI("On-demand scan success");
- } else {
- LOGW("On-demand scan failed: code %" PRIu8, result->errorCode);
- }
-
- if (!mWifiScanAsyncRequest.has_value()) {
- sendFailure("Received WiFi async result with no pending request");
- } else if (result->cookie != mWifiScanAsyncRequest->cookie) {
- sendFailure("On-demand scan cookie mismatch");
- }
-
- cancelTimer(&mWifiScanAsyncTimerHandle);
- mWifiScanAsyncRequest.reset();
- requestDelayedWifiScan();
- } else if (result->requestType ==
- CHRE_WIFI_REQUEST_TYPE_CONFIGURE_SCAN_MONITOR) {
- if (!result->success) {
- LOGE("Scan monitor async failure: code %" PRIu8, result->errorCode);
- sendFailure("Scan monitor async failed");
- }
-
- cancelTimer(&mWifiScanMonitorAsyncTimerHandle);
- mWifiScanMonitorEnabled = (result->cookie != nullptr);
- } else {
- sendFailure("Unknown WiFi async result type");
- }
-}
-
-void Manager::handleGnssAsyncResult(const chreAsyncResult *result) {
- if (isRequestTypeForLocation(result->requestType)) {
- validateGnssAsyncResult(result, mGnssLocationAsyncRequest,
- &mGnssLocationAsyncTimerHandle);
- } else if (isRequestTypeForMeasurement(result->requestType)) {
- validateGnssAsyncResult(result, mGnssMeasurementAsyncRequest,
- &mGnssMeasurementAsyncTimerHandle);
- } else {
- sendFailure("Unknown GNSS async result type");
- }
-}
-
-void Manager::validateGnssAsyncResult(const chreAsyncResult *result,
- Optional<AsyncRequest> &request,
- uint32_t *asyncTimerHandle) {
- if (!request.has_value()) {
- sendFailure("Received GNSS async result with no pending request");
- } else if (!result->success) {
- sendFailure("Async GNSS failure");
- } else if (result->cookie != request->cookie) {
- sendFailure("GNSS async cookie mismatch");
- }
-
- cancelTimer(asyncTimerHandle);
- request.reset();
-}
-
-void Manager::checkTimestamp(uint64_t timestamp, uint64_t pastTimestamp) {
- if (timestamp < pastTimestamp) {
- sendFailure("Timestamp was too old");
- } else if (timestamp == pastTimestamp) {
- sendFailure("Timestamp was duplicate");
- }
-}
-
-void Manager::handleGnssLocationEvent(const chreGnssLocationEvent *event) {
- LOGI("Received GNSS location event at %" PRIu64 " ms", event->timestamp);
-
- checkTimestamp(event->timestamp, mPrevGnssLocationEventTimestampMs);
- mPrevGnssLocationEventTimestampMs = event->timestamp;
-}
-
-void Manager::handleGnssDataEvent(const chreGnssDataEvent *event) {
- static uint32_t sPrevDiscontCount = 0;
- LOGI("Received GNSS measurement event at %" PRIu64 " ns count %" PRIu32
- " flags 0x%" PRIx16,
- event->clock.time_ns, event->clock.hw_clock_discontinuity_count,
- event->clock.flags);
-
- if (sPrevDiscontCount == event->clock.hw_clock_discontinuity_count) {
- checkTimestamp(event->clock.time_ns, mPrevGnssMeasurementEventTimestampNs);
- }
-
- sPrevDiscontCount = event->clock.hw_clock_discontinuity_count;
- mPrevGnssMeasurementEventTimestampNs = event->clock.time_ns;
-}
-
-void Manager::handleWifiScanEvent(const chreWifiScanEvent *event) {
- LOGI("Received Wifi scan event of type %" PRIu8 " with %" PRIu8
- " results at %" PRIu64 " ns",
- event->scanType, event->resultCount, event->referenceTime);
-
- if (event->eventIndex == 0) {
- checkTimestamp(event->referenceTime, mPrevWifiScanEventTimestampNs);
- mPrevWifiScanEventTimestampNs = event->referenceTime;
- }
-
- if (mWifiScanMonitorEnabled) {
- chreSendMessageToHostEndpoint(
- nullptr, 0,
- chre_stress_test_MessageType_TEST_WIFI_SCAN_MONITOR_TRIGGERED,
- mHostEndpoint.value(), nullptr /* freeCallback */);
- }
-}
-
-void Manager::handleCellInfoResult(const chreWwanCellInfoResult *event) {
- LOGI("Received %" PRIu8 " cell info results", event->cellInfoCount);
-
- mWwanCellInfoAsyncRequest.reset();
- if (event->errorCode != CHRE_ERROR_NONE) {
- LOGE("Cell info request failed with error code %" PRIu8, event->errorCode);
- sendFailure("Cell info request failed");
- } else if (event->cellInfoCount > 0) {
- uint64_t maxTimestamp = 0;
- for (uint8_t i = 0; i < event->cellInfoCount; i++) {
- maxTimestamp = MAX(maxTimestamp, event->cells[i].timeStamp);
- checkTimestamp(event->cells[i].timeStamp,
- mPrevWwanCellInfoEventTimestampNs);
- }
-
- mPrevWwanCellInfoEventTimestampNs = maxTimestamp;
- }
-}
-
-void Manager::handleWifiStartCommand(bool start) {
- mWifiTestStarted = start;
- if (start) {
- requestDelayedWifiScan();
- } else {
- cancelTimer(&mWifiScanTimerHandle);
- }
-}
-
-void Manager::handleGnssLocationStartCommand(bool start) {
- constexpr uint64_t kTimerDelayNs = Seconds(60).toRawNanoseconds();
-
- if (chreGnssGetCapabilities() & CHRE_GNSS_CAPABILITIES_LOCATION) {
- mGnssLocationTestStarted = start;
- makeGnssLocationRequest();
-
- if (start) {
- setTimer(kTimerDelayNs, false /* oneShot */, &mGnssLocationTimerHandle);
- } else {
- cancelTimer(&mGnssLocationTimerHandle);
- }
- } else {
- sendFailure("Platform has no location capability");
- }
-}
-
-void Manager::handleGnssMeasurementStartCommand(bool start) {
- constexpr uint64_t kTimerDelayNs = Seconds(60).toRawNanoseconds();
-
- if (chreGnssGetCapabilities() & CHRE_GNSS_CAPABILITIES_MEASUREMENTS) {
- mGnssMeasurementTestStarted = start;
- makeGnssMeasurementRequest();
-
- if (start) {
- setTimer(kTimerDelayNs, false /* oneShot */,
- &mGnssMeasurementTimerHandle);
- } else {
- cancelTimer(&mGnssMeasurementTimerHandle);
- }
- } else {
- sendFailure("Platform has no GNSS measurement capability");
- }
-}
-
-void Manager::handleWwanStartCommand(bool start) {
- constexpr uint64_t kTimerDelayNs = CHRE_ASYNC_RESULT_TIMEOUT_NS;
-
- if (chreWwanGetCapabilities() & CHRE_WWAN_GET_CELL_INFO) {
- mWwanTestStarted = start;
- makeWwanCellInfoRequest();
-
- if (start) {
- setTimer(kTimerDelayNs, false /* oneShot */, &mWwanTimerHandle);
- } else {
- cancelTimer(&mWwanTimerHandle);
- }
- } else {
- sendFailure("Platform has no WWAN cell info capability");
- }
-}
-
-void Manager::handleWifiScanMonitoringCommand(bool start) {
- if (chreWifiGetCapabilities() & CHRE_WIFI_CAPABILITIES_SCAN_MONITORING) {
- const uint32_t kWifiScanMonitorEnabledCookie = 0x1234;
- bool success = chreWifiConfigureScanMonitorAsync(
- start, start ? &kWifiScanMonitorEnabledCookie : nullptr);
- LOGI("Scan monitor enable %d request success ? %d", start, success);
-
- if (!success) {
- sendFailure("Scan monitor request failed");
- } else {
- setTimer(CHRE_ASYNC_RESULT_TIMEOUT_NS, true /* oneShot */,
- &mWifiScanMonitorAsyncTimerHandle);
- }
- } else {
- sendFailure("Platform has no WiFi scan monitoring capability");
- }
-}
-
-void Manager::setTimer(uint64_t delayNs, bool oneShot, uint32_t *timerHandle) {
- *timerHandle = chreTimerSet(delayNs, timerHandle, oneShot);
- if (*timerHandle == CHRE_TIMER_INVALID) {
- sendFailure("Failed to set timer");
- }
-}
-
-void Manager::cancelTimer(uint32_t *timerHandle) {
- if (*timerHandle != CHRE_TIMER_INVALID) {
- if (!chreTimerCancel(*timerHandle)) {
- // We don't treat this as a test failure, because the CHRE API does not
- // guarantee this method succeeds (e.g. if the timer is one-shot and just
- // fired).
- LOGW("Failed to cancel timer");
- }
- *timerHandle = CHRE_TIMER_INVALID;
- }
-}
-
-void Manager::makeGnssLocationRequest() {
- // The list of location intervals to iterate; wraps around.
- static const uint32_t kMinIntervalMsList[] = {1000, 0};
- static size_t sIntervalIndex = 0;
-
- uint32_t minIntervalMs = 0;
- if (mGnssLocationTestStarted) {
- minIntervalMs = kMinIntervalMsList[sIntervalIndex];
- sIntervalIndex = (sIntervalIndex + 1) % ARRAY_SIZE(kMinIntervalMsList);
- } else {
- sIntervalIndex = 0;
- }
-
- bool success = false;
- if (minIntervalMs > 0) {
- success = chreGnssLocationSessionStartAsync(
- minIntervalMs, 0 /* minTimeToNextFixMs */, &kGnssLocationCookie);
- } else {
- success = chreGnssLocationSessionStopAsync(&kGnssLocationCookie);
- }
-
- LOGI("Configure GNSS location interval %" PRIu32 " ms success ? %d",
- minIntervalMs, success);
-
- if (!success) {
- sendFailure("Failed to make location request");
- } else {
- mGnssLocationAsyncRequest = AsyncRequest(&kGnssLocationCookie);
- setTimer(CHRE_GNSS_ASYNC_RESULT_TIMEOUT_NS, true /* oneShot */,
- &mGnssLocationAsyncTimerHandle);
- }
-}
-
-void Manager::makeGnssMeasurementRequest() {
- // The list of measurement intervals to iterate; wraps around.
- static const uint32_t kMinIntervalMsList[] = {1000, 0};
- static size_t sIntervalIndex = 0;
-
- uint32_t minIntervalMs = 0;
- if (mGnssMeasurementTestStarted) {
- minIntervalMs = kMinIntervalMsList[sIntervalIndex];
- sIntervalIndex = (sIntervalIndex + 1) % ARRAY_SIZE(kMinIntervalMsList);
- } else {
- sIntervalIndex = 0;
- }
-
- bool success = false;
- if (minIntervalMs > 0) {
- success = chreGnssMeasurementSessionStartAsync(minIntervalMs,
- &kGnssMeasurementCookie);
- } else {
- success = chreGnssMeasurementSessionStopAsync(&kGnssMeasurementCookie);
- // Reset the previous timestamp, since the GNSS internal clock may reset.
- mPrevGnssMeasurementEventTimestampNs = 0;
- }
-
- LOGI("Configure GNSS measurement interval %" PRIu32 " ms success ? %d",
- minIntervalMs, success);
-
- if (!success) {
- sendFailure("Failed to make measurement request");
- } else {
- mGnssMeasurementAsyncRequest = AsyncRequest(&kGnssMeasurementCookie);
- setTimer(CHRE_GNSS_ASYNC_RESULT_TIMEOUT_NS, true /* oneShot */,
- &mGnssMeasurementAsyncTimerHandle);
- }
-}
-
-void Manager::requestDelayedWifiScan() {
- if (mWifiTestStarted) {
- if (chreWifiGetCapabilities() & CHRE_WIFI_CAPABILITIES_ON_DEMAND_SCAN) {
- setTimer(kWifiScanInterval.toRawNanoseconds(), true /* oneShot */,
- &mWifiScanTimerHandle);
- } else {
- sendFailure("Platform has no on-demand scan capability");
- }
- }
-}
-
-void Manager::makeWwanCellInfoRequest() {
- if (mWwanTestStarted) {
- if (mWwanCellInfoAsyncRequest.has_value()) {
- if (chreGetTime() > mWwanCellInfoAsyncRequest->requestTimeNs +
- CHRE_ASYNC_RESULT_TIMEOUT_NS) {
- sendFailure("Prev cell info request did not complete in time");
- }
- } else {
- bool success = chreWwanGetCellInfoAsync(&kWwanCellInfoCookie);
-
- LOGI("Cell info request success ? %d", success);
-
- if (!success) {
- sendFailure("Failed to make cell info request");
- } else {
- mWwanCellInfoAsyncRequest = AsyncRequest(&kWwanCellInfoCookie);
- }
- }
- }
-}
-
-void Manager::sendFailure(const char *errorMessage) {
- test_shared::sendTestResultWithMsgToHost(
- mHostEndpoint.value(),
- chre_stress_test_MessageType_TEST_RESULT /* messageType */,
- false /* success */, errorMessage);
-}
-
-} // namespace stress_test
-
-} // namespace chre
diff --git a/apps/test/common/permission_test/Makefile b/apps/test/common/permission_test/Makefile
deleted file mode 100644
index 4736ac45..00000000
--- a/apps/test/common/permission_test/Makefile
+++ /dev/null
@@ -1,64 +0,0 @@
-#
-# Permission Test Nanoapp Makefile
-#
-# Environment Checks ###########################################################
-ifeq ($(CHRE_PREFIX),)
- ifneq ($(ANDROID_BUILD_TOP),)
- CHRE_PREFIX = $(ANDROID_BUILD_TOP)/system/chre
- else
- $(error "You must run 'lunch' to setup ANDROID_BUILD_TOP, or explicitly \
- define the CHRE_PREFIX environment variable to point to the CHRE root \
- directory.")
- endif
-endif
-
-# Nanoapp Configuration ########################################################
-
-NANOAPP_NAME = permission_test
-NANOAPP_ID = 0x476f6f6754000009
-NANOAPP_NAME_STRING = \"Permission\ Test\"
-NANOAPP_VERSION = 0x00000001
-
-NANOAPP_PATH = $(CHRE_PREFIX)/apps/test/common/permission_test
-TEST_SHARED_PATH = $(CHRE_PREFIX)/apps/test/common/shared
-
-# Protobuf Sources #############################################################
-
-NANOPB_EXTENSION = nanopb
-
-NANOPB_SRCS += $(NANOAPP_PATH)/../proto/chre_test_common.proto
-NANOPB_SRCS += $(NANOAPP_PATH)/../proto/permission_test.proto
-NANOPB_PROTO_PATH = $(NANOAPP_PATH)/../proto
-NANOPB_INCLUDES = $(NANOPB_PROTO_PATH)
-NANOPB_FLAGS += --proto_path=$(NANOPB_PROTO_PATH)
-
-# Source Code ##################################################################
-
-COMMON_SRCS += $(NANOAPP_PATH)/src/permission_test.cc
-COMMON_SRCS += $(TEST_SHARED_PATH)/src/send_message.cc
-COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/callbacks.cc
-
-# Compiler Flags ###############################################################
-
-# Defines
-COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
-
-# Includes
-COMMON_CFLAGS += -I$(TEST_SHARED_PATH)/inc
-
-# DO NOT USE. This macro is only meant to be used in this test nanoapp and
-# should never be used in production nanoapps. Please use the
-# CHRE_NANOAPP_USES_X macros there instead to ensure the right permissions are
-# declared.
-COMMON_CFLAGS += -DCHRE_TEST_NANOAPP_PERMS=0
-
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_AUDIO = true
-CHRE_NANOAPP_USES_GNSS = true
-CHRE_NANOAPP_USES_WIFI = true
-CHRE_NANOAPP_USES_WWAN = true
-
-# Makefile Includes ############################################################
-
-include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/test/common/permission_test/src/permission_test.cc b/apps/test/common/permission_test/src/permission_test.cc
deleted file mode 100644
index 63510af8..00000000
--- a/apps/test/common/permission_test/src/permission_test.cc
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 <chre.h>
-
-#include <pb_decode.h>
-#include <cinttypes>
-
-#include "chre/util/nanoapp/log.h"
-#include "chre/util/time.h"
-#include "permission_test.nanopb.h"
-#include "send_message.h"
-
-#define LOG_TAG "[PermissionTest]"
-
-/**
- * This nanoapp is compiled with the ability to refer to permission gated APIs
- * but doesn't actually declare permissions to use them. Its purpose is to
- * validate the permission gated APIs always return false for any of its
- * requests to ensure CHRE implementations are validating nanoapp permissions
- * prior to accepting a nanoapp request.
- */
-
-namespace chre {
-namespace {
-
-constexpr Nanoseconds kGnssMinInterval = Seconds(1);
-
-void checkAudioApis(uint32_t hostEndpointId) {
- struct chreAudioSource audioSource;
- for (uint32_t i = 0; chreAudioGetSource(i, &audioSource); i++) {
- if (chreAudioConfigureSource(i, true /* enable */,
- audioSource.minBufferDuration,
- audioSource.minBufferDuration)) {
- test_shared::sendTestResultWithMsgToHost(
- hostEndpointId, permission_test_MessageType_TEST_RESULT,
- false /* success */, "Configured audio without audio permission");
- }
-
- // TODO(b/174590023): Check chreAudioGetStatus once it's supported by our
- // CHRE versions.
- }
-}
-
-void checkGnssApis(uint32_t hostEndpointId) {
- if (chreGnssLocationSessionStartAsync(kGnssMinInterval.toRawNanoseconds(),
- kGnssMinInterval.toRawNanoseconds(),
- nullptr /* cookie */)) {
- test_shared::sendTestResultWithMsgToHost(
- hostEndpointId, permission_test_MessageType_TEST_RESULT,
- false /* success */,
- "Requested GNSS location without the GNSS permission");
- }
-
- if (chreGnssMeasurementSessionStartAsync(kGnssMinInterval.toRawNanoseconds(),
- nullptr /* cookie */)) {
- test_shared::sendTestResultWithMsgToHost(
- hostEndpointId, permission_test_MessageType_TEST_RESULT,
- false /* success */,
- "Requested GNSS measurements without the GNSS permission");
- }
-
- if (chreGnssConfigurePassiveLocationListener(true /* enable */)) {
- test_shared::sendTestResultWithMsgToHost(
- hostEndpointId, permission_test_MessageType_TEST_RESULT,
- false /* success */,
- "Requested GNSS passive locations without the GNSS permission");
- }
-}
-
-void checkWifiApis(uint32_t hostEndpointId) {
- if (chreWifiConfigureScanMonitorAsync(true /* enable */,
- nullptr /* cookie */)) {
- test_shared::sendTestResultWithMsgToHost(
- hostEndpointId, permission_test_MessageType_TEST_RESULT,
- false /* success */,
- "Requested WiFi scan monitor without WiFi permission");
- }
-
- if (chreWifiRequestScanAsyncDefault(nullptr /* cookie */)) {
- test_shared::sendTestResultWithMsgToHost(
- hostEndpointId, permission_test_MessageType_TEST_RESULT,
- false /* success */, "Requested WiFi scan without WiFi permission");
- }
-
- // RTT ranging not included in WiFi test because it requires a valid AP to
- // request which can't be obtained due to invalid permissions.
-}
-
-void checkWwanApis(uint32_t hostEndpointId) {
- if (chreWwanGetCellInfoAsync(nullptr /* cookie */)) {
- test_shared::sendTestResultWithMsgToHost(
- hostEndpointId, permission_test_MessageType_TEST_RESULT,
- false /* success */, "Requested cell info without WWAN permission");
- }
-}
-
-// Call APIs that require permissions and verify that they all refuse requests
-// from this nanoapp since it has no permissions.
-void checkPermissionGatedApis(uint32_t hostEndpointId) {
- checkAudioApis(hostEndpointId);
- checkGnssApis(hostEndpointId);
- checkWifiApis(hostEndpointId);
- checkWwanApis(hostEndpointId);
-}
-
-void handleMessageFromHost(uint32_t senderInstanceId,
- const chreMessageFromHostData *hostData) {
- bool success = false;
- uint32_t messageType = hostData->messageType;
- if (senderInstanceId != CHRE_INSTANCE_ID) {
- LOGE("Incorrect sender instance id: %" PRIu32, senderInstanceId);
- } else if (messageType != permission_test_MessageType_TEST_COMMAND) {
- LOGE("Invalid message type %" PRIu32, messageType);
- } else {
- // Method will abort if any failures are encountered.
- checkPermissionGatedApis(hostData->hostEndpoint);
- success = true;
- }
-
- test_shared::sendTestResultWithMsgToHost(
- hostData->hostEndpoint,
- permission_test_MessageType_TEST_RESULT /* messageType */, success,
- nullptr /* errMessage */);
-}
-
-} // anonymous namespace
-
-extern "C" void nanoappHandleEvent(uint32_t senderInstanceId,
- uint16_t eventType, const void *eventData) {
- if (eventType == CHRE_EVENT_MESSAGE_FROM_HOST) {
- handleMessageFromHost(
- senderInstanceId,
- static_cast<const chreMessageFromHostData *>(eventData));
- } else {
- LOGW("Got unknown event type from senderInstanceId %" PRIu32
- " and with eventType %" PRIu16,
- senderInstanceId, eventType);
- }
-}
-
-extern "C" bool nanoappStart(void) {
- return true;
-}
-
-extern "C" void nanoappEnd(void) {}
-
-} // namespace chre
diff --git a/apps/test/common/ping_test/Makefile b/apps/test/common/ping_test/Makefile
deleted file mode 100644
index 84e1b3ec..00000000
--- a/apps/test/common/ping_test/Makefile
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# Ping Test Nanoapp Makefile
-#
-# Environment Checks ###########################################################
-ifeq ($(CHRE_PREFIX),)
- ifneq ($(ANDROID_BUILD_TOP),)
- CHRE_PREFIX = $(ANDROID_BUILD_TOP)/system/chre
- else
- $(error "You must run 'lunch' to setup ANDROID_BUILD_TOP, or explicitly \
- define the CHRE_PREFIX environment variable to point to the CHRE root \
- directory.")
- endif
-endif
-
-# Nanoapp Configuration ########################################################
-
-NANOAPP_NAME = ping_test
-NANOAPP_ID = 0x476f6f6754000007
-NANOAPP_NAME_STRING = \"Ping\ Test\"
-NANOAPP_VERSION = 0x00000001
-
-NANOAPP_PATH = $(CHRE_PREFIX)/apps/test/common/ping_test
-TEST_SHARED_PATH = $(CHRE_PREFIX)/apps/test/common/shared
-
-# Protobuf Sources #############################################################
-
-NANOPB_EXTENSION = nanopb
-
-NANOPB_SRCS += $(NANOAPP_PATH)/../proto/ping_test.proto
-NANOPB_SRCS += $(NANOAPP_PATH)/../proto/chre_test_common.proto
-NANOPB_PROTO_PATH = $(NANOAPP_PATH)/../proto
-NANOPB_INCLUDES = $(NANOPB_PROTO_PATH)
-NANOPB_FLAGS += --proto_path=$(NANOPB_PROTO_PATH)
-
-# Source Code ##################################################################
-
-COMMON_SRCS += $(NANOAPP_PATH)/src/ping_test.cc
-COMMON_SRCS += $(TEST_SHARED_PATH)/src/send_message.cc
-COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/callbacks.cc
-
-# Compiler Flags ###############################################################
-
-# Defines
-COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
-
-# Includes
-COMMON_CFLAGS += -I$(TEST_SHARED_PATH)/inc
-
-# Permission declarations ######################################################
-
-# Use the audio compile-time flags to check permissions behavior
-CHRE_NANOAPP_USES_AUDIO = true
-
-# Makefile Includes ############################################################
-
-include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/test/common/ping_test/src/ping_test.cc b/apps/test/common/ping_test/src/ping_test.cc
deleted file mode 100644
index 990b4529..00000000
--- a/apps/test/common/ping_test/src/ping_test.cc
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 <chre.h>
-#include <cinttypes>
-
-#include <pb_decode.h>
-
-#include "chre/util/nanoapp/log.h"
-#include "ping_test.nanopb.h"
-#include "send_message.h"
-
-#define LOG_TAG "[PingTest]"
-
-namespace chre {
-
-namespace {
-
-//! The message payload to use when responding to a ping request.
-const char *kPingResponseMsg = "Pong!";
-
-void handleMessageFromHost(uint32_t senderInstanceId,
- const chreMessageFromHostData *hostData) {
- bool success = false;
- uint32_t messageType = hostData->messageType;
- if (senderInstanceId != CHRE_INSTANCE_ID) {
- LOGE("Incorrect sender instance id: %" PRIu32, senderInstanceId);
- } else if (messageType != ping_test_MessageType_PING_COMMAND) {
- LOGE("Invalid message type %" PRIu32, messageType);
- } else {
- pb_istream_t istream = pb_istream_from_buffer(
- static_cast<const pb_byte_t *>(hostData->message),
- hostData->messageSize);
- ping_test_PingCommand command = ping_test_PingCommand_init_default;
-
- if (!pb_decode(&istream, ping_test_PingCommand_fields, &command)) {
- LOGE("Failed to decode ping command error %s", PB_GET_ERROR(&istream));
- } else {
- uint32_t permissions = command.permissions;
- LOGI("Got ping command message with permission 0x%" PRIx32, permissions);
- success = chreSendMessageWithPermissions(
- const_cast<char *>(kPingResponseMsg), strlen(kPingResponseMsg) + 1,
- ping_test_MessageType_PING_RESPONSE, hostData->hostEndpoint,
- permissions, nullptr /* freeCallback */);
- }
- }
-
- if (!success) {
- test_shared::sendTestResultToHost(
- hostData->hostEndpoint,
- ping_test_MessageType_TEST_RESULT /* messageType */,
- false /* success */);
- }
-}
-
-} // anonymous namespace
-
-extern "C" void nanoappHandleEvent(uint32_t senderInstanceId,
- uint16_t eventType, const void *eventData) {
- if (eventType == CHRE_EVENT_MESSAGE_FROM_HOST) {
- handleMessageFromHost(
- senderInstanceId,
- static_cast<const chreMessageFromHostData *>(eventData));
- } else {
- LOGW("Got unknown event type from senderInstanceId %" PRIu32
- " and with eventType %" PRIu16,
- senderInstanceId, eventType);
- }
-}
-
-extern "C" bool nanoappStart(void) {
- return true;
-}
-
-extern "C" void nanoappEnd(void) {}
-
-} // namespace chre
diff --git a/apps/test/common/proto/Android.bp b/apps/test/common/proto/Android.bp
index de911b3f..a504ce26 100644
--- a/apps/test/common/proto/Android.bp
+++ b/apps/test/common/proto/Android.bp
@@ -14,15 +14,6 @@
// limitations under the License.
//
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
java_library {
name: "chrecrossvalidation_sensor_java_proto",
host_supported: true,
@@ -76,42 +67,6 @@ java_library {
}
java_library {
- name: "permission_test_java_proto",
- host_supported: true,
- srcs: [
- "./permission_test.proto",
- ],
- proto: {
- type: "lite",
- },
- sdk_version: "system_current",
-}
-
-java_library {
- name: "ping_test_java_proto",
- host_supported: true,
- srcs: [
- "./ping_test.proto",
- ],
- proto: {
- type: "lite",
- },
- sdk_version: "system_current",
-}
-
-java_library {
- name: "chre_stress_test_java_proto",
- host_supported: true,
- srcs: [
- "./chre_stress_test.proto",
- ],
- proto: {
- type: "lite",
- },
- sdk_version: "system_current",
-}
-
-java_library {
name: "chre_test_common_java_proto",
host_supported: true,
srcs: [
diff --git a/apps/test/common/proto/chre_cross_validation_wifi.proto b/apps/test/common/proto/chre_cross_validation_wifi.proto
index 8a681d09..d2fe7e01 100644
--- a/apps/test/common/proto/chre_cross_validation_wifi.proto
+++ b/apps/test/common/proto/chre_cross_validation_wifi.proto
@@ -31,8 +31,7 @@ enum MessageType {
enum Step {
// The initial step where no action is performed.
INIT = 0;
- // The step where the nanoapp is configured to monitor for wifi scans and the
- // scan results threshold message is sent.
+ // The step where the nanoapp is configured to monitor for wifi scans.
SETUP = 1;
// The validate step where the data is gathered and compared.
VALIDATE = 2;
@@ -69,7 +68,3 @@ message WifiScanResult {
message WifiCapabilities {
optional uint32 wifiCapabilities = 1;
}
-
-message UseScanResultsSizeThreshold {
- optional bool useThreshold = 1;
-}
diff --git a/apps/test/common/proto/chre_settings_test.proto b/apps/test/common/proto/chre_settings_test.proto
index 923f4bac..e2218a05 100644
--- a/apps/test/common/proto/chre_settings_test.proto
+++ b/apps/test/common/proto/chre_settings_test.proto
@@ -31,7 +31,6 @@ message TestCommand {
GNSS_LOCATION = 3;
GNSS_MEASUREMENT = 4;
WWAN_CELL_INFO = 5;
- AUDIO = 6;
}
// The state of this feature at the system level.
diff --git a/apps/test/common/proto/chre_stress_test.proto b/apps/test/common/proto/chre_stress_test.proto
deleted file mode 100644
index 4b6c645a..00000000
--- a/apps/test/common/proto/chre_stress_test.proto
+++ /dev/null
@@ -1,53 +0,0 @@
-syntax = "proto2";
-
-package chre_stress_test;
-
-option java_package = "com.google.android.chre.nanoapp.proto";
-option java_outer_classname = "ChreStressTest";
-
-// Nanoapp message type can be either host to chre (H2C) or chre to host (C2H)
-enum MessageType {
- // Reserved for corrupted messages
- UNDEFINED = 0;
-
- // H2C: A message to start/stop the test.
- // Payload must be TestCommand.
- TEST_COMMAND = 1;
-
- // C2H: A message indicating the test result. The nanoapp will only use this
- // message to report a failure.
- // Payload must be chre_test_common.TestResult.
- TEST_RESULT = 2;
-
- // C2H: A message indicating that the stress test nanoapp has received a
- // WiFi scan while enabling scan monitoring. This can be used for the host
- // to verify that the scan monitoring feature is working.
- // No payload.
- TEST_WIFI_SCAN_MONITOR_TRIGGERED = 3;
-
- // H2C: A message indicating that the host client has restarted. The nanoapp
- // should use this message to update its host endpoint tracking when sending
- // unicast messages.
- // No payload.
- TEST_HOST_RESTARTED = 4;
-}
-
-// A message to start the test.
-message TestCommand {
- enum Feature {
- FEATURE_UNDEFINED = 0;
- // WiFi stress testing, no scan monitoring.
- WIFI_ON_DEMAND_SCAN = 1;
- GNSS_LOCATION = 2;
- GNSS_MEASUREMENT = 3;
- WWAN = 4;
- // Enables WiFi scan monitoring only.
- WIFI_SCAN_MONITOR = 5;
- }
-
- // The feature to test.
- optional Feature feature = 1;
-
- // True to start the test, false to stop.
- optional bool start = 2;
-}
diff --git a/apps/test/common/proto/permission_test.proto b/apps/test/common/proto/permission_test.proto
deleted file mode 100644
index d1e2c8ee..00000000
--- a/apps/test/common/proto/permission_test.proto
+++ /dev/null
@@ -1,20 +0,0 @@
-syntax = "proto2";
-
-package permission_test;
-
-option java_package = "com.google.android.chre.nanoapp.proto";
-option java_outer_classname = "PermissionTest";
-
-// Nanoapp message type can be either host to chre (H2C) or chre to host (C2H)
-enum MessageType {
- // Reserved for corrupted messages
- UNDEFINED = 0;
-
- // H2C: A message to start the test. No payload.
- TEST_COMMAND = 1;
-
- // C2H: A message indicating the test result. The ping test nanoapp will only
- // use this message to report a failure.
- // Payload must be chre_test_common.TestResult.
- TEST_RESULT = 2;
-} \ No newline at end of file
diff --git a/apps/test/common/proto/ping_test.proto b/apps/test/common/proto/ping_test.proto
deleted file mode 100644
index aa9c059a..00000000
--- a/apps/test/common/proto/ping_test.proto
+++ /dev/null
@@ -1,32 +0,0 @@
-syntax = "proto2";
-
-package ping_test;
-
-option java_package = "com.google.android.chre.nanoapp.proto";
-option java_outer_classname = "PingTest";
-
-// Nanoapp message type can be either host to chre (H2C) or chre to host (C2H)
-enum MessageType {
- // Reserved for corrupted messages
- UNDEFINED = 0;
-
- // H2C: A message to ping the nanoapp. The nanoapp will respond to the host
- // with a message, with options specified by this command.
- // Payload must be PingCommand.
- PING_COMMAND = 1;
-
- // C2H: A message indicating the test result. The ping test nanoapp will only
- // use this message to report a failure.
- // Payload must be chre_test_common.TestResult.
- TEST_RESULT = 2;
-
- // C2H: A message indicating a response from a ping command.
- // Payload is arbitrary.
- PING_RESPONSE = 3;
-}
-
-// A message to ping the nanoapp, with some optional specifications.
-message PingCommand {
- // Specifies the permission to use in chreSendMessageWithPermissions().
- optional uint32 permissions = 1;
-}
diff --git a/apps/test/common/shared/inc/send_message.h b/apps/test/common/shared/inc/send_message.h
index 227da68d..2847c8fc 100644
--- a/apps/test/common/shared/inc/send_message.h
+++ b/apps/test/common/shared/inc/send_message.h
@@ -24,24 +24,15 @@ namespace chre {
namespace test_shared {
/**
- * Same as sendTestResultWithMsgToHost, but doesn't accept an error message and
- * uses the free callback specified in chre/util/nanoapp/callbacks.h
- */
-void sendTestResultToHost(uint16_t hostEndpointId, uint32_t messageType,
- bool success);
-
-/**
* Sends a test result to the host using the chre_test_common.TestResult
* message.
*
* @param hostEndpointId The endpoint ID of the host to send the result to.
* @param messageType The message type to associate with the test result.
* @param success True if the test succeeded.
- * @param errMessage Nullable error message to send to the host. Error message
- * will only be sent if success is false.
*/
-void sendTestResultWithMsgToHost(uint16_t hostEndpointId, uint32_t messageType,
- bool success, const char *errMessage);
+void sendTestResultToHost(uint16_t hostEndpointId, uint32_t messageType,
+ bool success);
/**
* Sends a message to the host with an empty payload.
diff --git a/apps/test/common/shared/src/send_message.cc b/apps/test/common/shared/src/send_message.cc
index 577e294a..fd2e8f9e 100644
--- a/apps/test/common/shared/src/send_message.cc
+++ b/apps/test/common/shared/src/send_message.cc
@@ -26,24 +26,11 @@
#define LOG_TAG "[TestShared]"
namespace chre {
-namespace test_shared {
-namespace {
-
-bool encodeErrorMessage(pb_ostream_t *stream, const pb_field_t * /*field*/,
- void *const *arg) {
- const char *str = static_cast<const char *>(const_cast<const void *>(*arg));
- size_t len = strlen(str);
- return pb_encode_tag_for_field(
- stream, &chre_test_common_TestResult_fields
- [chre_test_common_TestResult_errorMessage_tag - 1]) &&
- pb_encode_string(stream, reinterpret_cast<const pb_byte_t *>(str),
- len);
-}
-} // namespace
+namespace test_shared {
-void sendTestResultWithMsgToHost(uint16_t hostEndpointId, uint32_t messageType,
- bool success, const char *errMessage) {
+void sendTestResultToHost(uint16_t hostEndpointId, uint32_t messageType,
+ bool success) {
// Unspecified endpoint is not allowed in chreSendMessageToHostEndpoint.
if (hostEndpointId == CHRE_HOST_ENDPOINT_UNSPECIFIED) {
hostEndpointId = CHRE_HOST_ENDPOINT_BROADCAST;
@@ -55,11 +42,6 @@ void sendTestResultWithMsgToHost(uint16_t hostEndpointId, uint32_t messageType,
result.has_code = true;
result.code = success ? chre_test_common_TestResult_Code_PASSED
: chre_test_common_TestResult_Code_FAILED;
- if (!success && errMessage != nullptr) {
- result.errorMessage = {.funcs = {.encode = encodeErrorMessage},
- .arg = const_cast<char *>(errMessage)};
- LOGE("%s", errMessage);
- }
size_t size;
if (!pb_get_encoded_size(&size, chre_test_common_TestResult_fields,
&result)) {
@@ -86,12 +68,6 @@ void sendTestResultWithMsgToHost(uint16_t hostEndpointId, uint32_t messageType,
}
}
-void sendTestResultToHost(uint16_t hostEndpointId, uint32_t messageType,
- bool success) {
- sendTestResultWithMsgToHost(hostEndpointId, messageType, success,
- nullptr /* errMessage */);
-}
-
void sendEmptyMessageToHost(uint16_t hostEndpointId, uint32_t messageType) {
// Unspecified endpoint is not allowed in chreSendMessageToHostEndpoint.
if (hostEndpointId == CHRE_HOST_ENDPOINT_UNSPECIFIED) {
diff --git a/apps/test/pts/audio_enable_disable_test/Makefile b/apps/test/pts/audio_enable_disable_test/Makefile
index 66c8b6c4..2f9f19dd 100644
--- a/apps/test/pts/audio_enable_disable_test/Makefile
+++ b/apps/test/pts/audio_enable_disable_test/Makefile
@@ -41,10 +41,6 @@ COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/callbacks.cc
# Defines
COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_INFO
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_AUDIO = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/timer_world/timer_world.cc b/apps/timer_world/timer_world.cc
index b4a79e18..bdec29cf 100644
--- a/apps/timer_world/timer_world.cc
+++ b/apps/timer_world/timer_world.cc
@@ -79,8 +79,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(TimerWorld, chre::kTimerWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_NONE);
+CHRE_STATIC_NANOAPP_INIT(TimerWorld, chre::kTimerWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/unload_tester/unload_tester.cc b/apps/unload_tester/unload_tester.cc
index 32de7267..8fe31163 100644
--- a/apps/unload_tester/unload_tester.cc
+++ b/apps/unload_tester/unload_tester.cc
@@ -22,16 +22,13 @@
#include "chre/platform/log.h"
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
#include "chre/util/time.h"
#include "chre_api/chre.h"
/**
* @file
* A nanoapp exclusively for testing, which unloads the spammer nanoapp after a
- * short delay. Must only be compiled as a static/internal nanoapp, because it
- * accesses internal framework APIs to do the unload - generally, nanoapps are
- * not allowed to unload other nanoapps.
+ * short delay. Must only be compiled as a static/internal nanoapp.
*/
namespace chre {
@@ -39,7 +36,7 @@ namespace {
constexpr uint32_t kAppVersion = 99;
-void handleUnload(uint16_t /*type*/, void * /*data*/, void * /*extraData*/) {
+void handleUnload(uint16_t /* eventType */, void * /* data */) {
EventLoop &eventLoop = EventLoopManagerSingleton::get()->getEventLoop();
uint32_t instanceId;
@@ -104,5 +101,4 @@ void nanoappEnd() {}
} // anonymous namespace
} // namespace chre
-CHRE_STATIC_NANOAPP_INIT(UnloadTester, chre::kUnloadTesterAppId, kAppVersion,
- chre::NanoappPermissions::CHRE_PERMS_NONE);
+CHRE_STATIC_NANOAPP_INIT(UnloadTester, chre::kUnloadTesterAppId, kAppVersion);
diff --git a/apps/wifi_offload/Android.bp b/apps/wifi_offload/Android.bp
index 173ae5e4..ce2a07b8 100644
--- a/apps/wifi_offload/Android.bp
+++ b/apps/wifi_offload/Android.bp
@@ -14,15 +14,6 @@
* limitations under the License.
*/
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
cc_library_static {
name: "wifi_offload_types",
export_include_dirs: [
diff --git a/apps/wifi_world/Makefile b/apps/wifi_world/Makefile
index e11d5c11..488b0a3e 100644
--- a/apps/wifi_world/Makefile
+++ b/apps/wifi_world/Makefile
@@ -28,10 +28,6 @@ COMMON_CFLAGS += -DNANOAPP_MINIMUM_LOG_LEVEL=CHRE_LOG_LEVEL_DEBUG
COMMON_SRCS += wifi_world.cc
COMMON_SRCS += $(CHRE_PREFIX)/util/nanoapp/wifi.cc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_WIFI = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/wifi_world/wifi_world.cc b/apps/wifi_world/wifi_world.cc
index 2bb4b836..a53983b9 100644
--- a/apps/wifi_world/wifi_world.cc
+++ b/apps/wifi_world/wifi_world.cc
@@ -38,14 +38,13 @@ namespace {
namespace {
-//! A fake/unused cookie to pass into the configure scan monitoring async
-//! request.
+//! A dummy cookie to pass into the configure scan monitoring async request.
constexpr uint32_t kScanMonitoringCookie = 0x1337;
-//! A fake/unused cookie to pass into on-demand scan async request.
+//! A dummy cookie to pass into on-demand scan async request.
constexpr uint32_t kOnDemandScanCookie = 0xcafe;
-//! A fake/unused cookie to pass into ranging async request.
+//! A dummy cookie to pass into ranging async request.
constexpr uint32_t kRangingCookie = 0xbeef;
//! The interval for on-demand wifi scans.
@@ -94,6 +93,44 @@ uint64_t gLastRangingTimeNs = 0;
bool gPendingRanging = false;
/**
+ * Logs a CHRE wifi scan result.
+ *
+ * @param result the scan result to log.
+ */
+void logChreWifiResult(const chreWifiScanResult &result) {
+ const char *ssidStr = "<non-printable>";
+ char ssidBuffer[chre::kMaxSsidStrLen];
+ if (result.ssidLen == 0) {
+ ssidStr = "<empty>";
+ } else if (chre::parseSsidToStr(ssidBuffer, sizeof(ssidBuffer), result.ssid,
+ result.ssidLen)) {
+ ssidStr = ssidBuffer;
+ }
+
+ LOGI("Found network with SSID: %s", ssidStr);
+#ifdef WIFI_WORLD_VERBOSE_WIFI_RESULT_LOGS
+ const char *bssidStr = "<non-printable>";
+ char bssidBuffer[chre::kBssidStrLen];
+ if (chre::parseBssidToStr(result.bssid, bssidBuffer, sizeof(bssidBuffer))) {
+ bssidStr = bssidBuffer;
+ }
+
+ LOGI(" age (ms): %" PRIu32, result.ageMs);
+ LOGI(" capability info: %" PRIx16, result.capabilityInfo);
+ LOGI(" bssid: %s", bssidStr);
+ LOGI(" flags: %" PRIx8, result.flags);
+ LOGI(" rssi: %" PRId8 "dBm", result.rssi);
+ LOGI(" band: %s (%" PRIu8 ")", chre::parseChreWifiBand(result.band),
+ result.band);
+ LOGI(" primary channel: %" PRIu32, result.primaryChannel);
+ LOGI(" center frequency primary: %" PRIu32, result.centerFreqPrimary);
+ LOGI(" center frequency secondary: %" PRIu32, result.centerFreqSecondary);
+ LOGI(" channel width: %" PRIu8, result.channelWidth);
+ LOGI(" security mode: %" PRIx8, result.securityMode);
+#endif // WIFI_WORLD_VERBOSE_WIFI_RESULT_LOGS
+}
+
+/**
* Logs a CHRE WiFi ranging result.
*
* @param result the ranging result to log.
@@ -306,11 +343,7 @@ void handleWifiScanEvent(const chreWifiScanEvent *event) {
for (uint8_t i = 0; i < event->resultCount; i++) {
const chreWifiScanResult &result = event->results[i];
-#ifdef WIFI_WORLD_VERBOSE_WIFI_RESULT_LOGS
- chre::logChreWifiResult(result);
-#else
- chre::logChreWifiResult(result, true /* logSsidOnly */);
-#endif
+ logChreWifiResult(result);
}
}
@@ -404,8 +437,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(WifiWorld, chre::kWifiWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_WIFI);
+CHRE_STATIC_NANOAPP_INIT(WifiWorld, chre::kWifiWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/apps/wwan_world/Makefile b/apps/wwan_world/Makefile
index 54350a58..d8b1ed15 100644
--- a/apps/wwan_world/Makefile
+++ b/apps/wwan_world/Makefile
@@ -21,10 +21,6 @@ COMMON_CFLAGS += -I.
COMMON_SRCS += wwan_world.cc
-# Permission declarations ######################################################
-
-CHRE_NANOAPP_USES_WWAN = true
-
# Makefile Includes ############################################################
include $(CHRE_PREFIX)/build/nanoapp/app.mk
diff --git a/apps/wwan_world/wwan_world.cc b/apps/wwan_world/wwan_world.cc
index d54e7437..61a74dad 100644
--- a/apps/wwan_world/wwan_world.cc
+++ b/apps/wwan_world/wwan_world.cc
@@ -27,7 +27,7 @@ namespace chre {
namespace {
#endif // CHRE_NANOAPP_INTERNAL
-//! A fake/unused cookie to pass into the cell info request.
+//! A dummy cookie to pass into the cell info request.
const uint32_t kCellInfoCookie = 0x1337;
//! The interval for cell info requests.
@@ -210,8 +210,6 @@ void nanoappEnd() {
#include "chre/platform/static_nanoapp_init.h"
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_permissions.h"
-CHRE_STATIC_NANOAPP_INIT(WwanWorld, chre::kWwanWorldAppId, 0,
- chre::NanoappPermissions::CHRE_PERMS_WWAN);
+CHRE_STATIC_NANOAPP_INIT(WwanWorld, chre::kWwanWorldAppId, 0);
#endif // CHRE_NANOAPP_INTERNAL
diff --git a/ash/ash.mk b/ash/ash.mk
new file mode 100644
index 00000000..a387b5b8
--- /dev/null
+++ b/ash/ash.mk
@@ -0,0 +1,13 @@
+#
+# ASH Makefile
+#
+
+# Common Compiler Flags ########################################################
+
+# Include paths.
+COMMON_CFLAGS += -Iash/include
+COMMON_CFLAGS += -Iash/include/ash_api
+
+# Simulator-specific Source Files ##############################################
+
+SIM_SRCS += ash/platform/linux/ash.cc
diff --git a/ash/include/ash_api/ash.h b/ash/include/ash_api/ash.h
new file mode 100644
index 00000000..8e6a7639
--- /dev/null
+++ b/ash/include/ash_api/ash.h
@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * 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 ASH_H_
+#define ASH_H_
+
+/**
+ * @file
+ * Defines the interface for the Android Sensor Hub support.
+ * These APIs are only accessible to system nanoapps and allow them to interact
+ * with the underlying sensor framework.
+ * These APIs are not part of the CHRE API and their support is optional.
+ */
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * The values returned by this sensor cannot be trusted, calibration is needed
+ * or the environment doesn't allow readings.
+ */
+#define ASH_CAL_ACCURACY_UNRELIABLE UINT8_C(0)
+
+/**
+ * This sensor is reporting data with low accuracy, calibration with the
+ * environment is needed.
+ */
+#define ASH_CAL_ACCURACY_LOW UINT8_C(1)
+
+/**
+ * This sensor is reporting data with an average level of accuracy, calibration
+ * with the environment may improve the readings.
+ */
+#define ASH_CAL_ACCURACY_MEDIUM UINT8_C(2)
+
+/**
+ * This sensor is reporting data with maximum accuracy.
+ */
+#define ASH_CAL_ACCURACY_HIGH UINT8_C(3)
+
+/**
+ * Calibration info for a sensor which reports on a maximum of three axes.
+ *
+ * Let Su be the uncalibrated sensor data and Sc the calibrated one,
+ * Sc = compMatrix * (Su - bias)
+ *
+ */
+struct ashCalInfo {
+ /**
+ * The zero-bias vector in the x, y, z order. If the sensor reports on N
+ * axes with N < 3, only the first N elements are considered valid.
+ */
+ float bias[3];
+
+ /**
+ * The compensation matrix in the row major order. If the sensor reports on N
+ * axes with N < 3, only the first N elements of each row are considered
+ * valid.
+ */
+ float compMatrix[9];
+
+ /**
+ * One of the ASH_CAL_ACCURACY_* constants. This corresponds to the
+ * definition in the Android SensorManager. See
+ * https://developer.android.com/reference/android/hardware/SensorEvent.html#accuracy
+ * for more details.
+ * Note that this accuracy field is simply a suggestion to the platform and
+ * the platform can ignore or over-write it.
+ */
+ uint8_t accuracy;
+};
+
+//! This is used to indicate the persistent storage of the ASH implementaion.
+#define ASH_CAL_STORAGE_ASH UINT8_C(0)
+
+//! This is used to indicate the persistent storage in the sensor registry.
+#define ASH_CAL_STORAGE_SNS UINT8_C(1)
+
+//! Interval between cal params storage when AP is up, in usec.
+#define ASH_CAL_SAVE_INTERVAL_USEC UINT64_C(300000000)
+
+//! This is used to indicate that the cal params are invalid.
+#define ASH_CAL_PARAMS_SOURCE_NONE UINT8_C(0)
+
+//! This is used to indicate that the cal params were set by factory
+//! calibration.
+#define ASH_CAL_PARAMS_SOURCE_FACTORY UINT8_C(1)
+
+//! This is used to indicate that the cal params were set by runtime
+//! calibration.
+#define ASH_CAL_PARAMS_SOURCE_RUNTIME UINT8_C(2)
+
+/**
+ * A struct for calibration parameters to be saved to and loaded from a
+ * persistent area. The source of each section is indicated by the
+ * corresponding *Source field, which is one of the ASH_CAL_PARAMS_SOURCE_*
+ * constants.
+ */
+struct ashCalParams {
+ //! The offset of the sensor in the x, y and z axis at temperature
+ //! offsetTempCelsius.
+ float offset[3];
+
+ //! The temperature at which last offset was updated.
+ float offsetTempCelsius;
+
+ //! The temperature sensitivity of offset.
+ float tempSensitivity[3];
+
+ //! The estimated offset at zero degree Celsius.
+ float tempIntercept[3];
+
+ //! The scale factor of the x, y and z axis.
+ float scaleFactor[3];
+
+ //! The cross-axis factor in the [yx, zx, zy] order.
+ float crossAxis[3];
+
+ //! The source of offset[3]
+ uint8_t offsetSource;
+
+ //! The source of offsetTempCelsius
+ uint8_t offsetTempCelsiusSource;
+
+ //! The source of tempSensitivity[3]
+ uint8_t tempSensitivitySource;
+
+ //! The source of tempIntercept[3]
+ uint8_t tempInterceptSource;
+
+ uint8_t scaleFactorSource;
+
+ //! The source of crossAxis[3]
+ uint8_t crossAxisSource;
+};
+
+/**
+ * Updates the runtime calibration info of a given sensor type for the platform
+ * to compensate for. The calibration will be applied on top of the sensor's
+ * factory calibration if present.
+ *
+ * @param sensorType One of the CHRE_SENSOR_TYPE_* constants.
+ * @param calInfo A non-null pointer to ashCalInfo to update the sensor's
+ calibration.
+ * @return true if the calibration info has been successfully updated.
+ */
+bool ashSetCalibration(uint8_t sensorType, const struct ashCalInfo *calInfo);
+
+/**
+ * Loads the stored cal params from the specified storage area.
+ *
+ * If ASH_CAL_STORAGE_SNS is specified as the storage area, it reads from the
+ * sensor registry with factory cal params. This should only be used for
+ * debugging as it can wake up the AP.
+ *
+ * If ASH_CAL_STORAGE_ASH is specified as the storage area, the stored cal
+ * params in the ASH storage are provided if they exist. Otherwise, the sensor
+ * registry cal params are provided instead.
+ *
+ * @param sensorType One of the CHRE_SENSOR_TYPE_* constants.
+ * @param storage Either ASH_CAL_STORAGE_ASH or ASH_CAL_STORAGE_SNS.
+ * @param params A non-null pointer to a ashCalParams that the cal params will
+ * be populated to.
+ *
+ * @return true if the cal params have been successfully populated to the
+ * provided memory.
+ */
+bool ashLoadCalibrationParams(uint8_t sensorType, uint8_t storage,
+ struct ashCalParams *params);
+
+/**
+ * Saves the cal params to a local cache, and saves to ASH's persistent storage
+ * area when the AP wakes up, or when the AP is up and it has been
+ * ASH_CAL_SAVE_INTERVAL_USEC since the cal params were last saved to the ASH
+ * storage.
+ *
+ * @param sensorType One of the CHRE_SENSOR_TYPE_* constants.
+ * @param params A non-null pointer to a ashCalParams to be saved to the local
+ * cache.
+ *
+ * @return true if the cal params have been successfully saved to the local
+ * cache.
+ */
+bool ashSaveCalibrationParams(uint8_t sensorType,
+ const struct ashCalParams *params);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ASH_H_
diff --git a/platform/freertos/memory.cc b/ash/platform/linux/ash.cc
index ada67024..e48b6c0a 100644
--- a/platform/freertos/memory.cc
+++ b/ash/platform/linux/ash.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,27 +14,21 @@
* limitations under the License.
*/
-#include "chre/platform/memory.h"
-#include "chre/platform/shared/pal_system_api.h"
+#include "ash_api/ash.h"
-#include <cstdlib>
-
-namespace chre {
-
-void *memoryAlloc(size_t size) {
- return malloc(size);
+bool ashSetCalibration(uint8_t sensorType, const struct ashCalInfo *calInfo) {
+ // TODO: Implement this.
+ return false;
}
-void *palSystemApiMemoryAlloc(size_t size) {
- return malloc(size);
+bool ashLoadCalibrationParams(uint8_t sensorType, uint8_t storage,
+ struct ashCalParams *params) {
+ // TODO: Implement this.
+ return false;
}
-void memoryFree(void *pointer) {
- free(pointer);
+bool ashSaveCalibrationParams(uint8_t sensorType,
+ const struct ashCalParams *params) {
+ // TODO: Implement this.
+ return false;
}
-
-void palSystemApiMemoryFree(void *pointer) {
- free(pointer);
-}
-
-} // namespace chre
diff --git a/build/arch/x86.mk b/build/arch/x86.mk
index 43ae8215..695bd5af 100644
--- a/build/arch/x86.mk
+++ b/build/arch/x86.mk
@@ -9,7 +9,7 @@ $(error "You should supply an ANDROID_BUILD_TOP environment variable \
containing a path to the Android source tree. This is typically \
provided by initializing the Android build environment.")
endif
-export X86_TOOLS_PREFIX=$(ANDROID_BUILD_TOP)/prebuilts/clang/host/linux-x86/clang-r416183b/bin/
+export X86_TOOLS_PREFIX=$(ANDROID_BUILD_TOP)/prebuilts/clang/host/linux-x86/clang-r370808/bin/
# x86 Tools ####################################################################
@@ -28,9 +28,6 @@ TARGET_CFLAGS += -g
# Enable position independence.
TARGET_CFLAGS += -fpic
-# Disable double promotion warning for logging
-TARGET_CFLAGS += -Wno-double-promotion
-
# x86 Shared Object Linker Flags ###############################################
TARGET_SO_LDFLAGS += -shared
diff --git a/build/build_template.mk b/build/build_template.mk
index 0a956fda..c4c45e0d 100644
--- a/build/build_template.mk
+++ b/build/build_template.mk
@@ -110,11 +110,7 @@ $(1)_bin: $$($$(1)_BIN)
$(1)_header: $$($$(1)_HEADER)
.PHONY: $(1)
-ifeq ($(IS_ARCHIVE_ONLY_BUILD),true)
-$(1): $(1)_ar
-else
$(1): $(1)_ar $(1)_so $(1)_bin $(1)_header
-endif
# If building the runtime, simply add the archive and shared object to the all
# target. When building CHRE, it is expected that this runtime just be linked
@@ -139,7 +135,7 @@ endif
# uint32_t magic; // "NANO"
# uint64_t appId; // App Id, contains vendor id
# uint32_t appVersion; // Version of the app
-# uint32_t flags; // Signed, encrypted, TCM-capable
+# uint32_t flags; // Signed, encrypted
# uint64_t hwHubType; // Which hub type is this compiled for
# uint8_t targetChreApiMajorVersion; // CHRE API version
# uint8_t targetChreApiMinorVersion;
@@ -155,20 +151,13 @@ endif
# the nanoapp, the version and the app ID. Marshalling this data from the
# Makefile environment into something like python or even a small C program
# is an unnecessary step.
-#
-# For the flags field of the struct, the following values are currently defined:
-# Signed = 0x00000001
-# Encrypted = 0x00000002
-# TCM-capable = 0x00000004
-#
-# The highest order byte is reserved for platform-specific usage.
$$($$(1)_HEADER): $$(OUT)/$$$(1) $$($$$(1)_DIRS)
printf "00000000 %.8x " `$(BE_TO_LE_SCRIPT) 0x00000001` > $$@
printf "%.8x " `$(BE_TO_LE_SCRIPT) 0x4f4e414e` >> $$@
printf "%.16x\n" `$(BE_TO_LE_SCRIPT) $(NANOAPP_ID)` >> $$@
printf "00000010 %.8x " `$(BE_TO_LE_SCRIPT) $(NANOAPP_VERSION)` >> $$@
- printf "%.8x " `$(BE_TO_LE_SCRIPT) $(TARGET_NANOAPP_FLAGS)` >> $$@
+ printf "%.8x " `$(BE_TO_LE_SCRIPT) 0x00000001` >> $$@
printf "%.16x\n" `$(BE_TO_LE_SCRIPT) $(13)` >> $$@
printf "00000020 %.2x " \
`$(BE_TO_LE_SCRIPT) $(TARGET_CHRE_API_VERSION_MAJOR)` >> $$@
@@ -181,25 +170,21 @@ $$($$(1)_HEADER): $$(OUT)/$$$(1) $$($$$(1)_DIRS)
# Compile ######################################################################
-$$($$(1)_CPP_OBJS): $(OUT)/$$($$(1)_OBJS_DIR)/%.o: %.cpp $(MAKEFILE_LIST)
- @echo " [CPP] $$<"
- $(V)$(3) $(COMMON_CXX_CFLAGS) -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c \
- $$< -o $$@
+$$($$(1)_CPP_OBJS): $(OUT)/$$($$(1)_OBJS_DIR)/%.o: %.cpp
+ $(3) $(COMMON_CXX_CFLAGS) -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< \
+ -o $$@
-$$($$(1)_CC_OBJS): $(OUT)/$$($$(1)_OBJS_DIR)/%.o: %.cc $(MAKEFILE_LIST)
- @echo " [CC] $$<"
- $(V)$(3) $(COMMON_CXX_CFLAGS) -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c \
- $$< -o $$@
+$$($$(1)_CC_OBJS): $(OUT)/$$($$(1)_OBJS_DIR)/%.o: %.cc
+ $(3) $(COMMON_CXX_CFLAGS) -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< \
+ -o $$@
-$$($$(1)_C_OBJS): $(OUT)/$$($$(1)_OBJS_DIR)/%.o: %.c $(MAKEFILE_LIST)
- @echo " [C] $$<"
- $(V)$(3) $(COMMON_C_CFLAGS) -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< \
- -o $$@
+$$($$(1)_C_OBJS): $(OUT)/$$($$(1)_OBJS_DIR)/%.o: %.c
+ $(3) $(COMMON_C_CFLAGS) -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< \
+ -o $$@
-$$($$(1)_S_OBJS): $(OUT)/$$($$(1)_OBJS_DIR)/%.o: %.S $(MAKEFILE_LIST)
- @echo " [AS] $$<"
- $(V)$(3) -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< \
- -o $$@
+$$($$(1)_S_OBJS): $(OUT)/$$($$(1)_OBJS_DIR)/%.o: %.S
+ $(3) -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< \
+ -o $$@
# Archive ######################################################################
@@ -209,7 +194,7 @@ $$$(1)_ARFLAGS = $(COMMON_ARFLAGS) \
$$($$(1)_AR): $$(OUT)/$$$(1) $$($$$(1)_DIRS) $$($$(1)_CC_OBJS) \
$$($$(1)_CPP_OBJS) $$($$(1)_C_OBJS) $$($$(1)_S_OBJS)
- $(V)$(7) $$($$$(1)_ARFLAGS) $$@ $$(filter %.o, $$^)
+ $(7) $$($$$(1)_ARFLAGS) $$@ $$(filter %.o, $$^)
# Link #########################################################################
@@ -217,43 +202,43 @@ $$($$(1)_SO): $$(OUT)/$$$(1) $$($$$(1)_DIRS) $$($$(1)_CC_DEPS) \
$$($$(1)_CPP_DEPS) $$($$(1)_C_DEPS) $$($$(1)_S_DEPS) \
$$($$(1)_CC_OBJS) $$($$(1)_CPP_OBJS) $$($$(1)_C_OBJS) \
$$($$(1)_S_OBJS)
- $(V)$(5) $(4) -o $$@ $(11) $$(filter %.o, $$^) $(12)
+ $(5) $(4) -o $$@ $(11) $$(filter %.o, $$^) $(12)
$$($$(1)_BIN): $$(OUT)/$$$(1) $$($$$(1)_DIRS) $$($$(1)_CC_DEPS) \
$$($$(1)_CPP_DEPS) $$($$(1)_C_DEPS) $$($$(1)_S_DEPS) \
$$($$(1)_CC_OBJS) $$($$(1)_CPP_OBJS) $$($$(1)_C_OBJS) \
$$($$(1)_S_OBJS)
- $(V)$(3) -o $$@ $(11) $$(filter %.o, $$^) $(12) $(10)
+ $(3) -o $$@ $(11) $$(filter %.o, $$^) $(12) $(10)
# Output Directories ###########################################################
$$($$$(1)_DIRS):
- $(V)mkdir -p $$@
+ mkdir -p $$@
$$(OUT)/$$$(1):
- $(V)mkdir -p $$@
+ mkdir -p $$@
# Automatic Dependency Resolution ##############################################
$$($$(1)_CC_DEPS): $(OUT)/$$($$(1)_OBJS_DIR)/%.d: %.cc
- $(V)mkdir -p $$(dir $$@)
- $(V)$(3) $(DEP_CFLAGS) $(COMMON_CXX_CFLAGS) \
- -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< -o $$@
+ mkdir -p $$(dir $$@)
+ $(3) $(DEP_CFLAGS) $(COMMON_CXX_CFLAGS) \
+ -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< -o $$@
$$($$(1)_CPP_DEPS): $(OUT)/$$($$(1)_OBJS_DIR)/%.d: %.cpp
- $(V)mkdir -p $$(dir $$@)
- $(V)$(3) $(DEP_CFLAGS) $(COMMON_CXX_CFLAGS) \
- -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< -o $$@
+ mkdir -p $$(dir $$@)
+ $(3) $(DEP_CFLAGS) $(COMMON_CXX_CFLAGS) \
+ -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< -o $$@
$$($$(1)_C_DEPS): $(OUT)/$$($$(1)_OBJS_DIR)/%.d: %.c
- $(V)mkdir -p $$(dir $$@)
- $(V)$(3) $(DEP_CFLAGS) $(COMMON_C_CFLAGS) \
- -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< -o $$@
+ mkdir -p $$(dir $$@)
+ $(3) $(DEP_CFLAGS) $(COMMON_C_CFLAGS) \
+ -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< -o $$@
$$($$(1)_S_DEPS): $(OUT)/$$($$(1)_OBJS_DIR)/%.d: %.S
- $(V)mkdir -p $$(dir $$@)
- $(V)$(3) $(DEP_CFLAGS) \
- -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< -o $$@
+ mkdir -p $$(dir $$@)
+ $(3) $(DEP_CFLAGS) \
+ -DCHRE_FILENAME=\"$$(notdir $$<)\" $(2) -c $$< -o $$@
# Include generated dependency files if they are in the requested build target.
# This avoids dependency generation from occuring for a debug target when a
@@ -272,9 +257,6 @@ endif
TARGET_CFLAGS_LOCAL = $(TARGET_CFLAGS)
TARGET_CFLAGS_LOCAL += -DCHRE_PLATFORM_ID=$(TARGET_PLATFORM_ID)
-
-# Default the nanoapp header flag values to signed if not overidden.
-TARGET_NANOAPP_FLAGS ?= 0x00000001
$(eval $(call BUILD_TEMPLATE, $(TARGET_NAME), \
$(COMMON_CFLAGS) $(TARGET_CFLAGS_LOCAL), \
$(TARGET_CC), \
diff --git a/build/defs.mk b/build/defs.mk
index 6afd5cb2..58e6d138 100644
--- a/build/defs.mk
+++ b/build/defs.mk
@@ -9,9 +9,3 @@ OUT = out
# Helper Scripts ###############################################################
BE_TO_LE_SCRIPT = $(CHRE_PREFIX)/build/be_to_le.sh
-
-# Build verbosity ##############################################################
-
-ifneq ($(CHRE_BUILD_VERBOSE),true)
-V=@
-endif \ No newline at end of file
diff --git a/build/nanoapp/app.mk b/build/nanoapp/app.mk
index 14d4a31d..25f7791b 100644
--- a/build/nanoapp/app.mk
+++ b/build/nanoapp/app.mk
@@ -22,11 +22,6 @@ $(error "The NANOAPP_VERSION variable must be set to the version of the nanoapp.
This should be assigned by the Makefile that includes app.mk.")
endif
-ifeq ($(BUILD_ID),)
-# If BUILD_ID is unset this must be a local build.
-BUILD_ID = local
-endif
-
NANOAPP_VERSION := $(strip $(NANOAPP_VERSION))
MATCHED_NANOAPP_VERSION := $(shell echo $(NANOAPP_VERSION) \
| grep "^0x[0-9a-fA-F]\{8\}")
@@ -70,24 +65,6 @@ IS_NANOAPP_BUILD = true
OUTPUT_NAME = $(NANOAPP_NAME)
-# Permissions declaration ######################################################
-
-ifneq ($(CHRE_NANOAPP_USES_AUDIO),)
-COMMON_CFLAGS += -DCHRE_NANOAPP_USES_AUDIO
-endif
-
-ifneq ($(CHRE_NANOAPP_USES_GNSS),)
-COMMON_CFLAGS += -DCHRE_NANOAPP_USES_GNSS
-endif
-
-ifneq ($(CHRE_NANOAPP_USES_WIFI),)
-COMMON_CFLAGS += -DCHRE_NANOAPP_USES_WIFI
-endif
-
-ifneq ($(CHRE_NANOAPP_USES_WWAN),)
-COMMON_CFLAGS += -DCHRE_NANOAPP_USES_WWAN
-endif
-
# Common Compiler Flags ########################################################
# Add the CHRE API to the include search path.
@@ -110,12 +87,12 @@ COMMON_CFLAGS += -DNANOAPP_VENDOR_STRING=$(NANOAPP_VENDOR_STRING)
COMMON_CFLAGS += -DNANOAPP_NAME_STRING=$(NANOAPP_NAME_STRING)
COMMON_CFLAGS += -DNANOAPP_IS_SYSTEM_NANOAPP=$(NANOAPP_IS_SYSTEM_NANOAPP)
-# Unstable ID ##################################################################
+# Version String ###############################################################
COMMIT_HASH_DIRTY_SUFFIX = $(shell git diff --quiet || echo -dirty)
COMMIT_HASH = $(shell git log -1 --pretty="format:%h" .)$(COMMIT_HASH_DIRTY_SUFFIX)
-NANOAPP_UNSTABLE_ID = "nanoapp=$(NANOAPP_NAME)@$(BUILD_ID)"
-COMMON_CFLAGS += -DNANOAPP_UNSTABLE_ID="\"$(NANOAPP_UNSTABLE_ID)\""
+NANOAPP_VERSION_STRING = "nanoapp=$(NANOAPP_NAME)@$(COMMIT_HASH)"
+COMMON_CFLAGS += -DNANOAPP_VERSION_STRING="\"$(NANOAPP_VERSION_STRING)\""
# Variant-specific Nanoapp Support Source Files ################################
@@ -134,7 +111,6 @@ GOOGLE_HEXAGONV66_ADSP-SEE_SRCS += $(DSO_SUPPORT_LIB_SRCS)
GOOGLE_HEXAGONV66_ADSP-SEE-UIMG_SRCS += $(DSO_SUPPORT_LIB_SRCS)
GOOGLE_HEXAGONV66_SLPI-SEE_SRCS += $(DSO_SUPPORT_LIB_SRCS)
GOOGLE_HEXAGONV66_SLPI-SEE-UIMG_SRCS += $(DSO_SUPPORT_LIB_SRCS)
-GOOGLE_HEXAGONV66_SLPI-QSH_SRCS += $(DSO_SUPPORT_LIB_SRCS)
GOOGLE_ARM64_ANDROID_SRCS += $(DSO_SUPPORT_LIB_SRCS)
GOOGLE_X86_LINUX_SRCS += $(DSO_SUPPORT_LIB_SRCS)
QCOM_HEXAGONV60_NANOHUB_SRCS += $(APP_SUPPORT_PATH)/qcom_nanohub/app_support.cc
@@ -142,9 +118,6 @@ QCOM_HEXAGONV60_NANOHUB-UIMG_SRCS += $(APP_SUPPORT_PATH)/qcom_nanohub/app_suppor
# Makefile Includes ############################################################
-# Standard library overrides include
-include $(CHRE_PREFIX)/std_overrides/std_overrides.mk
-
# Common includes
include $(CHRE_PREFIX)/build/defs.mk
include $(CHRE_PREFIX)/build/common.mk
@@ -153,9 +126,6 @@ include $(CHRE_PREFIX)/build/common.mk
include $(CHRE_PREFIX)/chre_api/chre_api_version.mk
# Supported variants includes
-ifneq ($(CHRE_TARGET_EXTENSION),)
-include $(CHRE_TARGET_EXTENSION)
-endif
include $(CHRE_PREFIX)/build/variant/google_arm64_android.mk
include $(CHRE_PREFIX)/build/variant/google_cm4_nanohub.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv55_slpi-see.mk
@@ -170,7 +140,6 @@ include $(CHRE_PREFIX)/build/variant/google_hexagonv66_adsp-see.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv66_adsp-see-uimg.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv66_slpi-see.mk
include $(CHRE_PREFIX)/build/variant/google_hexagonv66_slpi-see-uimg.mk
-include $(CHRE_PREFIX)/build/variant/google_hexagonv66_slpi-qsh.mk
include $(CHRE_PREFIX)/build/variant/google_x86_linux.mk
include $(CHRE_PREFIX)/build/variant/qcom_hexagonv60_nanohub.mk
include $(CHRE_PREFIX)/build/variant/qcom_hexagonv60_nanohub-uimg.mk
diff --git a/build/nanopb.mk b/build/nanopb.mk
index 0ee35978..93fc3343 100644
--- a/build/nanopb.mk
+++ b/build/nanopb.mk
@@ -78,9 +78,8 @@ $(NANOPB_GEN_PATH)/%.$(NANOPB_EXTENSION).c \
$(NANOPB_GEN_PATH)/%.$(NANOPB_EXTENSION).h: %.proto \
%.options \
$(NANOPB_GENERATOR_SRCS)
- @echo " [NANOPB] $<"
- $(V)mkdir -p $(dir $@)
- $(V)$(PROTOC) --plugin=protoc-gen-nanopb=$(NANOPB_PROTOC) $(NANOPB_FLAGS) \
+ mkdir -p $(dir $@)
+ $(PROTOC) --plugin=protoc-gen-nanopb=$(NANOPB_PROTOC) $(NANOPB_FLAGS) \
--nanopb_out="$(NANOPB_GENERATOR_FLAGS) --options-file=$(basename $<).options:$(NANOPB_GEN_PATH)/$(NANOPB_PROTO_PATH)" \
$<
@@ -88,8 +87,7 @@ $(NANOPB_GEN_PATH)/%.$(NANOPB_EXTENSION).c \
$(NANOPB_GEN_PATH)/%.$(NANOPB_EXTENSION).h: %.proto \
$(NANOPB_OPTIONS) \
$(NANOPB_GENERATOR_SRCS)
- @echo " [NANOPB] $<"
- $(V)mkdir -p $(dir $@)
- $(V)$(PROTOC) --plugin=protoc-gen-nanopb=$(NANOPB_PROTOC) $(NANOPB_FLAGS) \
+ mkdir -p $(dir $@)
+ $(PROTOC) --plugin=protoc-gen-nanopb=$(NANOPB_PROTOC) $(NANOPB_FLAGS) \
--nanopb_out="$(NANOPB_GENERATOR_FLAGS) --options-file=$(NANOPB_OPTIONS):$(NANOPB_GEN_PATH)/$(NANOPB_PROTO_PATH)" \
$<
diff --git a/build/pw_unit_test.mk b/build/pw_unit_test.mk
deleted file mode 100644
index f0ef307c..00000000
--- a/build/pw_unit_test.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Makefile for Pigweed's Unit Test Framework
-#
-PW_DIR = $(ANDROID_BUILD_TOP)/external/pigweed
-PW_UT_DIR = $(PW_DIR)/pw_unit_test
-
-PW_UT_SRCS += $(PW_UT_DIR)/framework.cc
-
-PW_UT_CFLAGS += -I$(PW_UT_DIR)/public
-PW_UT_CFLAGS += -I$(PW_UT_DIR)/public_overrides
-PW_UT_CFLAGS += -I$(PW_DIR)/pw_polyfill/public
-PW_UT_CFLAGS += -I$(PW_DIR)/pw_polyfill/public_overrides
-PW_UT_CFLAGS += -I$(PW_DIR)/pw_polyfill/standard_library_public
-PW_UT_CFLAGS += -I$(PW_DIR)/pw_preprocessor/public
-PW_UT_CFLAGS += -I$(PW_DIR)/pw_span/public
-PW_UT_CFLAGS += -I$(PW_DIR)/pw_span/public_overrides
-PW_UT_CFLAGS += -I$(PW_DIR)/pw_string/public
diff --git a/build/sys_support/qcom/chre.scons b/build/sys_support/qcom/chre.scons
index 4547239b..446ec86e 100644
--- a/build/sys_support/qcom/chre.scons
+++ b/build/sys_support/qcom/chre.scons
@@ -298,7 +298,6 @@ chre_cc_src = [
"${BUILDPATH}/system/chre/platform/shared/host_protocol_chre.cc",
"${BUILDPATH}/system/chre/platform/shared/host_protocol_common.cc",
"${BUILDPATH}/system/chre/platform/shared/memory_manager.cc",
- "${BUILDPATH}/system/chre/platform/shared/nanoapp_load_manager.cc",
"${BUILDPATH}/system/chre/platform/shared/nanoapp/nanoapp_dso_util.cc",
"${BUILDPATH}/system/chre/platform/shared/pal_system_api.cc",
"${BUILDPATH}/system/chre/platform/shared/system_time.cc",
@@ -307,6 +306,7 @@ chre_cc_src = [
"${BUILDPATH}/system/chre/platform/slpi/init.cc",
"${BUILDPATH}/system/chre/platform/slpi/memory.cc",
"${BUILDPATH}/system/chre/platform/slpi/memory_manager.cc",
+ "${BUILDPATH}/system/chre/platform/slpi/nanoapp_load_manager.cc",
"${BUILDPATH}/system/chre/platform/slpi/platform_debug_dump_manager.cc",
"${BUILDPATH}/system/chre/platform/slpi/platform_nanoapp.cc",
"${BUILDPATH}/system/chre/platform/slpi/platform_pal.cc",
diff --git a/build/variant/google_hexagonv65_adsp-see-uimg.mk b/build/variant/google_hexagonv65_adsp-see-uimg.mk
index 945bf1ff..66afee3b 100644
--- a/build/variant/google_hexagonv65_adsp-see-uimg.mk
+++ b/build/variant/google_hexagonv65_adsp-see-uimg.mk
@@ -13,7 +13,6 @@ TARGET_CFLAGS += -DUIMG_DL_VER_MAJOR=2
TARGET_CFLAGS += -DCHRE_SLPI_UIMG_ENABLED
TARGET_CFLAGS += -DCHRE_THREAD_UTIL_ENABLED
TARGET_CFLAGS += $(GOOGLE_HEXAGONV65_ADSP-SEE-UIMG_CFLAGS)
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV65_ADSP-SEE-UIMG_SRCS)
TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV65_ADSP-SEE-UIMG_LATE_LIBS)
TARGET_PLATFORM_ID = 0x476f6f676c000006
diff --git a/build/variant/google_hexagonv65_adsp-see.mk b/build/variant/google_hexagonv65_adsp-see.mk
index ee1ab5a7..92157d63 100644
--- a/build/variant/google_hexagonv65_adsp-see.mk
+++ b/build/variant/google_hexagonv65_adsp-see.mk
@@ -11,7 +11,6 @@ TARGET_NAME = google_hexagonv65_adsp-see
TARGET_CFLAGS = -DCHRE_MESSAGE_TO_HOST_MAX_SIZE=4000
TARGET_CFLAGS += -DCHRE_THREAD_UTIL_ENABLED
TARGET_CFLAGS += $(GOOGLE_HEXAGONV65_ADSP-SEE_CFLAGS)
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV65_ADSP-SEE_SRCS)
TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV65_ADSP-SEE_LATE_LIBS)
TARGET_PLATFORM_ID = 0x476f6f676c000006
diff --git a/build/variant/google_hexagonv65_slpi-see-uimg.mk b/build/variant/google_hexagonv65_slpi-see-uimg.mk
index f3d4be6a..e17d996c 100644
--- a/build/variant/google_hexagonv65_slpi-see-uimg.mk
+++ b/build/variant/google_hexagonv65_slpi-see-uimg.mk
@@ -13,7 +13,6 @@ TARGET_CFLAGS += -DUIMG_DL_VER_MAJOR=2
TARGET_CFLAGS += -DCHRE_SLPI_UIMG_ENABLED
TARGET_CFLAGS += -DCHRE_THREAD_UTIL_ENABLED
TARGET_CFLAGS += $(GOOGLE_HEXAGONV65_SLPI-SEE-UIMG_CFLAGS)
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV65_SLPI-SEE-UIMG_SRCS)
TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV65_SLPI-SEE-UIMG_LATE_LIBS)
TARGET_PLATFORM_ID = 0x476f6f676c000003
diff --git a/build/variant/google_hexagonv65_slpi-see.mk b/build/variant/google_hexagonv65_slpi-see.mk
index 183b75d4..9aed1f39 100644
--- a/build/variant/google_hexagonv65_slpi-see.mk
+++ b/build/variant/google_hexagonv65_slpi-see.mk
@@ -11,7 +11,6 @@ TARGET_NAME = google_hexagonv65_slpi-see
TARGET_CFLAGS = -DCHRE_MESSAGE_TO_HOST_MAX_SIZE=4000
TARGET_CFLAGS += -DCHRE_THREAD_UTIL_ENABLED
TARGET_CFLAGS += $(GOOGLE_HEXAGONV65_SLPI-SEE_CFLAGS)
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV65_SLPI-SEE_SRCS)
TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV65_SLPI-SEE_LATE_LIBS)
TARGET_PLATFORM_ID = 0x476f6f676c000003
diff --git a/build/variant/google_hexagonv66_adsp-see-uimg.mk b/build/variant/google_hexagonv66_adsp-see-uimg.mk
index 47a7cb4f..5777cb3c 100644
--- a/build/variant/google_hexagonv66_adsp-see-uimg.mk
+++ b/build/variant/google_hexagonv66_adsp-see-uimg.mk
@@ -12,7 +12,6 @@ TARGET_CFLAGS = -DCHRE_MESSAGE_TO_HOST_MAX_SIZE=4000
TARGET_CFLAGS += -DUIMG_DL_VER_MAJOR=2
TARGET_CFLAGS += -DCHRE_SLPI_UIMG_ENABLED
TARGET_CFLAGS += -DCHRE_THREAD_UTIL_ENABLED
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
TARGET_CFLAGS += $(GOOGLE_HEXAGONV66_ADSP-SEE-UIMG_CFLAGS)
TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV66_ADSP-SEE-UIMG_SRCS)
TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV66_ADSP-SEE-UIMG_LATE_LIBS)
diff --git a/build/variant/google_hexagonv66_adsp-see.mk b/build/variant/google_hexagonv66_adsp-see.mk
index 7ecb8c36..b1d0c6d4 100644
--- a/build/variant/google_hexagonv66_adsp-see.mk
+++ b/build/variant/google_hexagonv66_adsp-see.mk
@@ -11,7 +11,6 @@ TARGET_NAME = google_hexagonv66_adsp-see
TARGET_CFLAGS = -DCHRE_MESSAGE_TO_HOST_MAX_SIZE=4000
TARGET_CFLAGS += -DCHRE_THREAD_UTIL_ENABLED
TARGET_CFLAGS += $(GOOGLE_HEXAGONV66_ADSP-SEE_CFLAGS)
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV66_ADSP-SEE_SRCS)
TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV66_ADSP-SEE_LATE_LIBS)
TARGET_PLATFORM_ID = 0x476f6f676c000007
diff --git a/build/variant/google_hexagonv66_slpi-qsh.mk b/build/variant/google_hexagonv66_slpi-qsh.mk
deleted file mode 100644
index 3f99da0d..00000000
--- a/build/variant/google_hexagonv66_slpi-qsh.mk
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# Google CHRE Reference Implementation for Hexagon v66 Architecture on SLPI
-# using QSH.
-#
-
-include $(CHRE_PREFIX)/build/clean_build_template_args.mk
-
-TARGET_NAME = google_hexagonv66_slpi-qsh
-# Sized based on the buffer allocated in the host daemon (4096 bytes), minus
-# FlatBuffer overhead (max 80 bytes), minus some extra space to make a nice
-# round number and allow for addition of new fields to the FlatBuffer
-TARGET_CFLAGS = -DCHRE_MESSAGE_TO_HOST_MAX_SIZE=4000
-TARGET_CFLAGS += -DCHRE_QSH_ENABLED
-TARGET_CFLAGS += -DCHRE_USE_FARF_LOGGING
-TARGET_CFLAGS += $(GOOGLE_HEXAGONV66_SLPI-QSH_CFLAGS)
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
-TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV66_SLPI-QSH_SRCS)
-TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV66_SLPI-QSH_LATE_LIBS)
-TARGET_PLATFORM_ID = 0x476f6f676c00000a
-HEXAGON_ARCH = v66
-
-TARGET_CFLAGS += $(SLPI_CFLAGS)
-TARGET_VARIANT_SRCS += $(SLPI_SRCS)
-
-# Add SLPI/QSH-specific compiler flags and source files
-TARGET_CFLAGS += $(SLPI_QSH_CFLAGS)
-TARGET_VARIANT_SRCS += $(SLPI_QSH_SRCS)
-
-CHRE_USE_BUFFERED_LOGGING = false
-
-ifneq ($(filter $(TARGET_NAME)% all, $(MAKECMDGOALS)),)
-ifneq ($(IS_NANOAPP_BUILD),)
-TARGET_SO_LATE_LIBS += $(CHRE_PREFIX)/build/app_support/google_slpi/libchre_slpi_skel.so
-include $(CHRE_PREFIX)/build/nanoapp/google_slpi.mk
-endif
-
-include $(CHRE_PREFIX)/build/arch/hexagon.mk
-include $(CHRE_PREFIX)/build/build_template.mk
-endif
diff --git a/build/variant/google_hexagonv66_slpi-see-uimg.mk b/build/variant/google_hexagonv66_slpi-see-uimg.mk
index 5e2e3f95..acc7e5d1 100644
--- a/build/variant/google_hexagonv66_slpi-see-uimg.mk
+++ b/build/variant/google_hexagonv66_slpi-see-uimg.mk
@@ -13,7 +13,6 @@ TARGET_CFLAGS += -DUIMG_DL_VER_MAJOR=2
TARGET_CFLAGS += -DCHRE_SLPI_UIMG_ENABLED
TARGET_CFLAGS += -DCHRE_THREAD_UTIL_ENABLED
TARGET_CFLAGS += $(GOOGLE_HEXAGONV66_SLPI-SEE-UIMG_CFLAGS)
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV66_SLPI-SEE-UIMG_SRCS)
TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV66_SLPI-SEE-UIMG_LATE_LIBS)
TARGET_PLATFORM_ID = 0x476f6f676c000005
diff --git a/build/variant/google_hexagonv66_slpi-see.mk b/build/variant/google_hexagonv66_slpi-see.mk
index 4158fef7..1006c096 100644
--- a/build/variant/google_hexagonv66_slpi-see.mk
+++ b/build/variant/google_hexagonv66_slpi-see.mk
@@ -11,7 +11,6 @@ TARGET_NAME = google_hexagonv66_slpi-see
TARGET_CFLAGS = -DCHRE_MESSAGE_TO_HOST_MAX_SIZE=4000
TARGET_CFLAGS += -DCHRE_THREAD_UTIL_ENABLED
TARGET_CFLAGS += $(GOOGLE_HEXAGONV66_SLPI-SEE_CFLAGS)
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_2
TARGET_VARIANT_SRCS = $(GOOGLE_HEXAGONV66_SLPI-SEE_SRCS)
TARGET_SO_LATE_LIBS = $(GOOGLE_HEXAGONV66_SLPI-SEE_LATE_LIBS)
TARGET_PLATFORM_ID = 0x476f6f676c000005
diff --git a/build/variant/google_x86_googletest.mk b/build/variant/google_x86_googletest.mk
index eb48c7bf..3e6313b8 100644
--- a/build/variant/google_x86_googletest.mk
+++ b/build/variant/google_x86_googletest.mk
@@ -7,14 +7,7 @@ include $(CHRE_PREFIX)/build/clean_build_template_args.mk
TARGET_NAME = google_x86_googletest
TARGET_CFLAGS = -DCHRE_MESSAGE_TO_HOST_MAX_SIZE=2048
TARGET_VARIANT_SRCS = $(GOOGLE_X86_GOOGLETEST_SRCS)
-TARGET_VARIANT_SRCS += $(GOOGLETEST_COMMON_SRCS)
-
-ifeq ($(RUN_PAL_IMPL_TESTS), true)
-TARGET_VARIANT_SRCS += $(GOOGLETEST_PAL_IMPL_SRCS)
-else
TARGET_VARIANT_SRCS += $(GOOGLETEST_SRCS)
-endif
-
TARGET_PLATFORM_ID = 0x476f6f676c000001
TARGET_CFLAGS += $(SIM_CFLAGS)
diff --git a/build/variant/google_x86_linux.mk b/build/variant/google_x86_linux.mk
index 00796f73..27c3818a 100644
--- a/build/variant/google_x86_linux.mk
+++ b/build/variant/google_x86_linux.mk
@@ -11,7 +11,6 @@ TARGET_BIN_LDFLAGS = $(GOOGLE_X86_LINUX_BIN_LDFLAGS)
TARGET_SO_EARLY_LIBS = $(GOOGLE_X86_LINUX_EARLY_LIBS)
TARGET_SO_LATE_LIBS = $(GOOGLE_X86_LINUX_LATE_LIBS)
TARGET_PLATFORM_ID = 0x476f6f676c000001
-TARGET_CFLAGS += -DCHRE_FIRST_SUPPORTED_API_VERSION=CHRE_API_VERSION_1_1
TARGET_CFLAGS += $(SIM_CFLAGS)
TARGET_VARIANT_SRCS += $(SIM_SRCS)
diff --git a/chpp/Android.bp b/chpp/Android.bp
index d62efb5c..e4852429 100644
--- a/chpp/Android.bp
+++ b/chpp/Android.bp
@@ -14,139 +14,20 @@
* limitations under the License.
*/
-
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
-cc_library_static {
+cc_library_host_static {
name: "chre_chpp_linux",
- vendor: true,
- cflags: [
- "-std=c89",
- "-Wall",
- "-Wcast-align",
- "-Wcast-qual",
- "-Wconversion",
- "-Werror",
- "-Wextra",
- "-Wmissing-prototypes",
- "-Wno-strict-aliasing",
- "-Wpointer-arith",
- "-Wsign-compare",
- "-Wshadow",
- "-Wstrict-prototypes",
- "-Wswitch",
- "-DCHPP_CHECKSUM_ENABLED",
- "-DCHPP_CLIENT_ENABLED_DISCOVERY",
- "-DCHPP_CLIENT_ENABLED_LOOPBACK",
- "-DCHPP_CLIENT_ENABLED_TIMESYNC",
- "-DCHPP_CLIENT_ENABLED_TRANSPORT_LOOPBACK",
- "-DCHPP_CLIENT_ENABLED_GNSS",
- "-DCHPP_CLIENT_ENABLED_WIFI",
- "-DCHPP_CLIENT_ENABLED_WWAN",
- "-DCHPP_SERVICE_ENABLED_GNSS",
- "-DCHPP_SERVICE_ENABLED_WIFI",
- "-DCHPP_SERVICE_ENABLED_WWAN",
- "-DCHPP_SERVICE_ENABLED_TRANSPORT_LOOPBACK",
- "-DCHPP_MAX_REGISTERED_CLIENTS=3",
- "-DCHPP_MAX_REGISTERED_SERVICES=3",
- "-DCHPP_DEBUG_ASSERT_ENABLED",
- // clock_gettime() requires _POSIX_C_SOURCE >= 199309L
- "-D_POSIX_C_SOURCE=199309L",
- // Required for pthread_setname_np()
- "-D_GNU_SOURCE"
- ],
- conlyflags: ["-std=c11"],
srcs: [
"transport.c",
- "app.c",
- "clients.c",
- "services.c",
- "clients/discovery.c",
- "clients/loopback.c",
- "clients/timesync.c",
- "clients/gnss.c",
- "clients/wifi.c",
- "clients/wwan.c",
- "common/gnss_convert.c",
- "common/wifi_convert.c",
- "common/wifi_utils.c",
- "common/wwan_convert.c",
- "services/discovery.c",
- "services/loopback.c",
- "services/nonhandle.c",
- "services/timesync.c",
- "services/gnss.c",
- "services/wifi.c",
- "services/wwan.c",
- "platform/pal_api.c",
- "platform/linux/link.c",
"platform/linux/memory.c",
- "platform/linux/notifier.c",
- "platform/shared/crc.c",
],
export_include_dirs: [
"platform/linux/include",
"include",
],
- header_libs: [
- "chre_pal",
- "chre_api",
- ],
- export_header_lib_headers: [
- "chre_pal",
- "chre_api",
- ],
- static_libs: ["chre_pal_linux"],
- host_supported: true,
}
cc_test_host {
name: "chre_chpp_linux_tests",
- cflags: [
- "-DCHPP_CLIENT_ENABLED_TRANSPORT_LOOPBACK",
- "-DCHPP_CHECKSUM_ENABLED",
- "-DCHPP_MAX_REGISTERED_CLIENTS=3",
- "-DCHPP_MAX_REGISTERED_SERVICES=3",
- ],
- srcs: [
- "test/app_test_base.cpp",
- "test/app_test.cpp",
- "test/transport_test.cpp",
- "test/clients_test.cpp",
- ],
- test_suites: [
- // Needed to support running on TreeHugger
- "general-tests",
- ],
- static_libs: [
- "chre_chpp_linux",
- "chre_pal_linux"
- ],
-}
-
-cc_test_host {
- name: "chre_chpp_convert_tests",
- cflags: [
- "-Wcast-align",
- "-Wsign-compare",
- ],
- header_libs: [
- "chre_test_common",
- ],
- srcs: [
- "test/wifi_convert_test.cpp",
- "test/wwan_convert_test.cpp"
- ],
- test_suites: [
- // Needed to support running on TreeHugger
- "general-tests",
- ],
+ srcs: ["test/transport_test.cpp"],
static_libs: ["chre_chpp_linux"],
}
diff --git a/chpp/QUICKSTART.md b/chpp/QUICKSTART.md
deleted file mode 100644
index de5deb59..00000000
--- a/chpp/QUICKSTART.md
+++ /dev/null
@@ -1,72 +0,0 @@
-# CHPP Integration
-
-This guide focuses on integrating and porting CHPP to your desired platform. For implementation details please refer to the included README.md instead. The minimum typical steps are provided.
-
-## CHPP Transport Layer Integration
-
-### 1. Platform-specific functionality
-
-Implement the platform-specific functionality utilized by CHPP. These can be found in chpp/platform and include:
-
-1. Memory allocation and deallocation
-1. Thread notification mechanisms and thread signalling
-1. Mutexes (or other resource sharing mechanism)
-1. Condition variables
-1. Logging (including defining CHPP_LOGx, CHPP_LOG_OOM, PRIuSIZE)
-1. CRC32 (a half-byte algorithm is provided in platform/shared, but it is recommended to use a platform-optimized / hardware algorithm when available)
-
-Sample Linux implementations are provided.
-
-### 1. Link-Layer APIs
-
-The APIs that are needed to tie CHPP to the serial port are as follows. Details are provided in link.h.
-
-1. void chppPlatformLinkInit(\*params)
-1. void chppPlatformLinkDeinit(\*params)
-1. void chppPlatformLinkReset(\*params)
-1. enum ChppLinkErrorCode chppPlatformLinkSend(\*params, \*buf, len)
-1. Depending on implementation, void chppLinkSendDoneCb(\*params)
-1. void chppPlatformLinkDoWork(\*params)
-1. bool chppRxDataCb(\*context, \*buf, len)
-1. Optionally, chppRxPacketCompleteCb(\*context)
-
-In addition, the system must implement and initialize the platform-specific linkParams data structure as part of platform_link.h
-
-### 1. Initialization
-
-In order to initialize CHPP, it is necessary to
-
-1. Allocate the transportContext and appContext structs that hold the state for each instance of the application and transport layers (in any order)
-1. Call the layers’ initialization functions, chppTransportInit and chppAppInit (in any order)
-1. Initialize the platform-specific linkParams struct (part of the transport struct)
-1. Call chppWorkThreadStart to start the main thread for CHPP's Transport Layer
-
-### 1. Testing
-
-Several unit tests are provided in transport_test.c. In addition, loopback functionality is already implemented in CHPP, and can be used for testing. For details on crafting a loopback datagram, please refer to README.md and the transport layer unit tests (transport_test.c).
-
-### 1. Termination
-
-In order to terminate CHPP's main transport layer thread, it is necessary to
-
-1. Call chppWorkThreadStop() to stop the main worker thread.
-1. Call the layers’ deinitialization functions, chppTransportDeinit and chppAppDeinit (in any order)
-1. Deallocate the transportContext, appContext, and the platform-specific linkParams structs
-
-### 1. Single-threaded systems
-
-If the system does not support multi-threading, the chppWorkThreadHandleSignal method can be used to directly handle signals without using chppWorkThreadStart.
-
-Note that the system MUST replicate the high-level behavior of chppWorkThreadStart exactly in this case. More details in the documentation of chppWorkThreadHandleSignal.
-
-For such systems, chppTransportGetTimeUntilNextDoWorkNs() can be used to replicate the functionality of chppNotifierTimedWait(). chppTransportGetTimeUntilNextDoWorkNs() returns the time until chppTransportDoWork() must be called again.
-
-## CHPP Services Integration
-
-CHPP provides several predefined services (including Loopback Test, Service Discovery), as well as three standard services that follow the CHRE PAL API to simplify integration and testing. CHPP allows for custom services as well, as described in README.md. The standard services included in CHPP are
-
-1. WWAN
-1. WiFi
-1. GNSS
-
-In order to integrate the standard services using the CHRE PAL API, please refer to each service's interface as provided in include/chre/pal/
diff --git a/chpp/README.md b/chpp/README.md
index 69f19447..10467be8 100644
--- a/chpp/README.md
+++ b/chpp/README.md
@@ -1,227 +1,6 @@
-# Context Hub Peripheral Protocol (CHPP)
+Context Hub Peripheral Protocol (CHPP), aka Chippy
-The Context Hub Runtime Environment (CHRE) is a feature built into Android which can run background applications on a lower power, always-on processor, with lower energy cost than what is possible when using the main applications processor (AP).
+WiP Work-in-Progress
-CHPP is designed to run over a serial link (e.g. UART, SPI) and enables an Android Context Hub (CHRE) running on a dedicated low-power processor to connect to peripherals (e.g. GNSS, WiFi). Using CHPP, CHRE can pull together various sources of information, including sensors, location, and audio, to enable a new generation of context-aware applications.
+ToDo: Add documentation
-CHPP is a communication protocol that spans from the Transport to the Application layer. The CHPP Transport layer is responsible for correct handling of ARQ, fragmentation, and ordering of datagrams, while the CHPP Application Layer is responsible for the services, including client-service messaging and service discovery.
-
-CHPP is designed to be flexible and future-proof while meeting the memory and processing constraints of both the CHRE and the peripherals that are often even-lower-resourced.
-
-CHPP provides several basic services that are necessary for debugging and service discovery, defines a number of services for the most commonly used sensors and peripherals, and also allows vendor-specific services as necessary. CHPP allows these services to coexist on a single link with very small overhead.
-
-## Integration Quick-Start
-
-A quick-start guide for integration is provided in QUICKSTART.md
-
-## Overview
-
-Within the CHPP transport layer, each endpoint is considered a peer, meaning there are no role differences. However, within the application layer, one endpoint exposes a service to the other endpoint, which is considered to be a client of said service. CHPP is point-to-point, therefore multiple clients to the same service over the same link are not supported. In a typical configuration, the endpoint where CHRE runs will be a client of one or more peripherals that each provide one or more services. For example, CHRE may be running on a microcontroller which has a serial connection to a discrete GNSS (Global Navigation Satellite System) chip that exposes the GNSS CHPP service. However, the protocol is designed such that endpoints can both provide services and serve as clients of remote services simultaneously.
-
-## Error Detection and Correction
-
-CHPP supports checksum based ARQ. CHPP supports implicit NACKs, and optionally supports explicit NACKs. The timeout is implementation dependent with a recommended value of 50 msec.
-
-## Conventions
-
-- Unless otherwise specified, CHPP follows the Little Endian convention.
-- Bit-level diagrams are presented with the most-significant bit occupying the leftmost cell
-- Bits are numbered with 0 being the least significant bit and 7 being the most significant bit in a byte.
-
-# Transport Layer Packetization
-
-CHPP packets consist of a 2-byte preamble (packet start delimiter) and 8 bytes of header information. The header is followed by zero or more bytes of application-layer payload, typically starting with a 6-byte app header, and ends with a 4-byte packet footer. Defined as a structure (ChppTransportHeader in transport.h), the CHPP transport header is as follows:
-
-- Preamble
-
- - uint16_t preamble;
-
-- Transport Header
-
- - uint8_t flags;
- - uint8_t packetCode;
- - uint8_t ackSeq;
- - uint8_t seq;
- - uint16_t length;
- - uint16_t reserved;
-
-## Preamble
-
-CHPP packets use a two-byte preamble as the packet start delimiter. If the receiving side is not actively within a packet, it assumes a packet starts whenever it sees the preamble. For the current version of CHPP, the preamble is 0x6843 (“Ch” in ASCII as a little endian 16-bit integer). For future versions, e.g. for a non-point-to-point version of CHPP, we expect only the LSB to change.
-
-## Packet Flags
-
-Up to 8 flags are supported as a bitmap as follows
-
-### 0x01: Fragmentation
-
-The fragmentation flag allows the transfer of data messages larger than the MTU. In such cases, the data message would be split into multiple fragments. A fragmentation flag of (0) indicates the last/only packet in a datagram. A fragmentation flag set to (1) indicates that the packet is part of an unfinished, fragmented datagram
-
-### 0x02 - 0x80: Reserved
-
-Reserved for future use
-
-## Packet Codes
-
-The packet code field consists of two nibbles. The lower nibble is used for optional error reporting. The higher nibble is used for transport layer configuration.
-
-### Error Reporting (lower nibble)
-
-Error reporting is a recommended feature and can help with debugging and potentially help improve performance. A non-zero explicit NACK code indicates an explicit NACK. The code provides the reason as follows:
-
-- 0x0: No explicit-NACK
-- 0x1: Checksum failure
-- 0x2: Out of memory
-- 0x3: Busy
-- 0x4: Invalid header
-- 0x5: Out of order packet
-
-### Attributes (higher nibble)
-
-- 0x0: Regular Packet
-- 0x1: Reset. The reset code is used at bootup to indicate that readiness, as well as to reset the state to post-bootup state in case of irrecoverable errors. If set, this indicates that the sending endpoint is requesting initialization of the CHPP protocol. The first packet sent after bootup always has this flag set, and endpoints may send a packet with this flag to attempt to recover from protocol failures. Upon receipt, the endpoint resets all its state, for example dropping any packets awaiting transmission, and resetting its service state. It then responds with a reset-ack.
- A reset packet may optionally populate the Error Reporting entry with the reason behind the reset.
- A reset packet has an optional configuration payload [TBD].
-- 0x2 Reset-ack. Similar to reset, but sent as a response to reset, as described above.
-
-## ACK Sequence Number
-
-The ack sequence number provides the next expected packets, effectively acknowledging all packets up to (n-1). The 1-byte ack allows for (optional, future) support of group ACKs (up to a window size of 127 packets). Note that fragmented messages have multiple sequence numbers, one for each fragment.
-The ack may be sent as part of a packet with or without a payload. In the latter case, the payload length would be set to zero.
-If an ACK is not received after a predetermined timeout, or an implicit NACK is received (through an ACK of a lower sequence number), the unacknowledged packet(s) shall be retransmitted.
-
-## Sequence Number
-
-Provides the 8-bit sequence number of this packet. Note that fragmented messages have multiple sequence numbers, one for each fragment.
-
-## Length
-
-Provides the payload length. Devices may have MTU sizes smaller than this limit. Data messages larger than the MTU size can be fragmented according to the Packet Flags: Fragmentation section above.
-A value of 0 indicates no payload, which is useful in cases where only transport layer data is relevant, for example when transmitting a bare acknowledgement message.
-
-## Payload
-
-The optional payload immediately follows a non-zero payload length. Its contents are described in the Application Layer section. It typically begins with an app layer header.
-
-## Checksum
-
-Provides an error detection code that is run over of the entire CHPP packet, i.e. anything between the preamble and the checksum fields.
-The checksum algorithm is [TBD].
-
-# CHPP Transport - Link Layer API
-
-To allow for a clean C implementation with clear separation of layers while supporting multiple CHPP instances per device, each CHPP layer state is stored in its own context struct.
-To tie corresponding transport and application layers together, each layer’s context struct includes a pointer to the context struct of the other corresponding layer (i.e. the transport layer’s context has a pointer to the corresponding app layer’s context struct and vice versa).
-Initializing CHPP involves:
-
-1. Allocating the structs for the application and transport layers (in any order).
-2. Calling the application and transport layers’ initialization functions (in any order)
-3. Initializing the platform-specific link layer parameters within the transport struct.
-
-## void chppTransportInit(\*transportContext, \*appContext)
-
-The CHPP Transport Layer state is stored in the ChppTransportState struct transportContext, and passed around between various functions. It is necessary to initialize the transport layer state for each transport layer instance on every platform.
-Each transport layer instance is associated with a single application layer instance. appContext points to the application layer status struct associated with this transport layer instance.
-After calling chppTransportInit, it is also necessary to separately initialize the platform-specific values of transportContext.linkParams.
-
-## void chppAppInit(\*transportContext, \*appContext)
-
-The CHPP Application Layer state is stored in the ChppAppState struct appContext, and passed around between various functions. It is necessary to initialize the application layer state for each application layer instance on every platform.
-Each application layer instance is associated with a single transport layer instance. transportContext points to the transport layer status struct associated with this application layer instance.
-
-## void chppAppInitWithClientServiceSet(\*transportContext, \*appContext, clientServiceSet)
-
-It is also possible to specify the client/service endpoints to be enabled at runtime.
-
-## bool chppRxDataCb(\*transportContext, \*buf, len)
-
-This function is the interface between the CHPP Transport layer and the communications link’s Rx path (e.g. from the UART driver). This function is called when any data is received at the serial interface. The data is provided through a pointer to *buf, with its length specified as len.
-The return value from chppRxData(*buf, len) can optionally be used at the communications link driver to improve performance. When the return value is true, the driver may stop sending all-zero payloads (e.g. as might happen when a serial link is idle).
-
-## bool chppRxPacketCompleteCb(\*transportContext)
-
-This is an optional function that enables the link layer to indicate the end of a packet. For packets with a corrupt length field, this function can enable the link layer to explicitly NACK the bad packet earlier.
-This function is designed exclusively for link layers that can identify the end of individual packets. The availability of this information depends on the link layer implementation.
-
-## enum ChppLinkErrorCode chppPlatformLinkSend(\*params, \*buf, len)
-
-This function is the interface between the CHPP Transport layer and the communications link’s Tx path (e.g. to the UART driver). This function is called when any data should be sent to the serial interface. The data is provided through a pointer to \*buf, with its length specified as len. The struct params is platform-specific and should include link details and parameters as initialized by the implementation.
-Both synchronous and asynchronous implementations of this function are supported. A synchronous implementation refers to one where chppPlatformLinkSend() is done with buf and len when it returns (i.e. the caller can free or reuse buf and len). An asynchronous implementation refers to one where chppPlatformLinkSend() returns before completely consuming buf and len (e.g. the send is completed at a later time). In this case, it is up to the platform implementation to call chppLinkSendDoneCb() after processing the contents of buf and len.
-This function returns CHPP_LINK_ERROR_NONE_SENT if the platform implementation for this function is synchronous and CHPP_LINK_ERROR_NONE_QUEUED if it is implemented asynchronously. It can also return an error code from enum ChppLinkErrorCode.
-
-## void chppLinkSendDoneCb(\*params)
-
-Notifies the transport layer that the link layer is done sending the previous payload (as provided to platformLinkSend() through buf and len) and can accept more data.
-On systems that implement the link layer Tx asynchronously, where platformLinkSend() returns False before consuming the payload provided to it, the platform implementation must call this function after platformLinkSend() is done with the payload (i.e. buf and len).
-
-## void chppWorkThreadStart(\*transportContext)
-
-Starts the main thread for CHPP's Transport Layer. This thread needs to be started after the Transport Layer is initialized through chppTransportInit() and provided with the transport layer context struct.
-
-## void chppWorkThreadStop(\*transportContext)
-
-Stops the main thread for CHPP's Transport Layer that has been started by calling chppWorkThreadStart(). Stopping this thread may be necessary for testing and debugging purposes. The parameter context provides the transport layer context struct.
-
-# Application Layer Messaging
-
-CHPP Application Layer datagrams typically have a 6-byte header. This is followed by zero or more bytes of application-layer payload. Both the header and payload are counted in the transport layer payload length. The transport layer 4-byte packet footer follows. Defined as a structure, the CHPP transport header looks like this:
-
-- uint8_t handle;
-- uint8_t type;
-- uint8_t transaction;
-- uint8_t reserved
-- uint16_t command;
-
-## Service Handle
-
-The Service Handle provides the capability of running multiple simultaneous clients / services over a single CHPP transport (physical) link. This allows differentiation between traffic destined for different services / applications / sensors on a single link. It also allows both sides to have clients and services simultaneously if necessary. Handles include reserved ones (0x00 - 0x0f) and assignable ones. Assigning a handle is through a handshaking phase on the reserved handle number 0x01. The handshake allows for a wide range of manufacturer IDs, devices, and protocol types/versions to be mapped into an 8-bit handle number to achieve efficiency as well as flexibility.
-
-### Handle
-
-- 0x00: Non-handle based P2P communication
-- 0x01: Loopback testing
-- 0x02 - 0x0e: reserved
-- 0x0f: CHPP service discovery handshake
-- 0x10 - 0xff: Handles for services negotiated through handshake
-
-## Message Type
-
-The message type clarifies the direction of the messages (client <-> service) and whether a response is expected
-
-- 0b00 (0): Request from client. Requires response with same command from service
-- 0b01 (1): Response from service (with the same command / transaction ID as the request)
-- 0b10 (2): Notification from client. Service shall not respond
-- 0b11 (3): Notification from service. Client shall not respond
-
-## Transaction ID
-
-CHPP has an 8-bit transaction ID for out-of-order responses which is optional for clients, and mandatory for services. The Transaction ID allows CHPP to have multiple requests outstanding for not just different commands, but for a single command. To allow multiple outstanding requests, the service shall relay back the Transaction ID of a request in its response. The client shall not issue the same command unless it has either received the response or has changed / incremented the Transaction ID.
-
-## Commands
-
-The CHPP messaging structure allocates 16 bits for commands. CHPP Service Discovery uses the same messaging structure. Note that each vendor and service (as indicated by the Vendor ID and Service ID) can define their own commands and therefore command codes for different services and vendors can overlap.
-
-# CHPP Basic Services
-
-CHPP’s built-in basic services take advantage of reserved handle numbers, ranging from 0x00 - 0x0f to support debugging and development as well as discovery of other services. These basic services currently are as follows.
-
-## Handleless Communication Service (0x00)
-
-The handle 0x00 is reserved for use cases that do not need the flexibility provided by handles and avoid the need for discovery.
-
-## Loopback Testing Service (0x01)
-
-Loopback testing is a mandatory service where the loopback service relays the entire received datagram back to the client.
-The client requesting the loopback must set the handle to 0x01, and the message type to 0 (i.e. request from client). The server responding with the loopback will respond on the same handle but with the message type to 1 (service response). Any (application layer) data following the handle and message type fields will be identically relayed back to the client.
-
-## Discovery Service (0x0f)
-
-Service Discovery is mapps a 8-bit handle to a number of coexisting services. In response to a discovery command, the discovery service responds with a list of available services (UUID + name + version) on the device. The first service in the list corresponds to handle 0x10, and so on.
-
-# CHPP Predefined Service Protocols
-
-CHPP supports the following services using the CHRE PAL. The standard UUIDs for these services are defined in common/standard_uuids.h.
-
-- WWAN
-- WiFi
-- GNSS
diff --git a/chpp/RELEASE_NOTES.md b/chpp/RELEASE_NOTES.md
deleted file mode 100644
index 71f67eb4..00000000
--- a/chpp/RELEASE_NOTES.md
+++ /dev/null
@@ -1,177 +0,0 @@
-# CHPP Release Notes
-
-A summary of notable changes is provided in the form of release notes. Dates are provided as yyyy-mm-dd. Note that this is not meant to be a detailed changelog; for a detailed change list, please refer to git commits.
-
-### 2020-03-04 (4c668b3)
-
-Initial release of CHPP.
-
-- CHPP transport and app layers
-- Loopback testing service
-
-### 2020-07-28 (7cebe57)
-
-This release enables service integration with WWAN / WiFi / GNSS devices based on the CHRE PAL API.
-
-- New functionality
-
- - Reset and reset-ack implementation to allow either peer to initialize the other (e.g., upon boot)
- - Discovery service to provide a list of services
- - Discovery client to match clients with discovered services
- - Standard WWAN service based on the CHRE PAL API
- - Standard WiFi service based on the CHRE PAL API
- - Standard GNSS service based on the CHRE PAL API
- - Standard WWAN client based on the CHRE PAL API
-
-- Updates and bug fixes to existing layers, including
-
- - Better logging to assist verification and debugging
- - Error replies are sent over the wire for transport layer errors
- - Over-the-wire preamble has been corrected (byte shifting error)
-
-- API and integration changes
-
- - App layer header now includes an error code
- - App layer message type now occupies only the least significant nibble (LSN). The most significant nibble (MSN) is reserved
- - chppPlatformLinkSend() now returns an error code instead of a boolean
- - Added initialization, deinitialization, and reset functionality for the link layer (see link.h)
- - Condition variables functionality needs to be supported alongside other platform functionality (see chpp/platform/)
- - Name changes for the logging APIs
-
-### 2020-08-07 (0b41306)
-
-This release contains bug fixes as well as the loopback client.
-
-- New functionality
-
- - Loopback client to run and verify a loopback test using a provided data buffer
-
-- Cleanup and bug fixes
-
- - Corrected sequence number handling
- - Updated log messages
- - More accurate casting into enums
-
-### 2020-08-27 (8ab5c23)
-
-This release contains additional clients, a virtual link layer for testing (e.g., using loopback), and several important bug fixes.
-
-- New functionality
-
- - Basic implementation of the standard WiFi client based on the CHRE PAL API
- - Basic implementation of the standard GNSS client based on the CHRE PAL API
- - Virtual link layer that connects CHPP with itself on Linux to enable testing, including reset, discovery, and loopback
-
-- Cleanup and bug fixes
-
- - Client implementation cleanup
- - Client-side handling of close responses
- - Reset / reset-ack handshaking mechanism fixed
- - Loopback client fixed
- - Enhanced log messages
- - Service command #s are now sequential
-
-- API and integration changes
-
- - Platform-specific time functionality (platform_time.h)
-
-### 2020-10-01 (95829e3)
-
-This release updates client functionality using the parser, adds a transport-layer loopback mechanism for testing and debugging, and includes several important bug fixes.
-
-- New functionality
-
- - Parser for CHPP -> CHRE Data Structure Decoding
- - Completed client functionality using parser-generated functions
- - Transport-layer-loopback client and service. The Transport-layer loopback ignores app layer functionality and state, as well as checksums and sequence numbers
-
-- Cleanup and bug fixes
-
- - Improved compiler compatibility for MSVC, as well as when enabling additional compiler warning flags
- - Fixed handling of fragmented datagrams
- - Corrected MTU calculation
- - Corrected loopback assert
- - Slimmer OOM logging
- - Parser code and header files were relocated
-
-### 2021-02-08 (f1d249c)
-
-In addition to enhancements and bug fixes, this release enables error and reset handling and several other features.
-
-- New functionality
-
- - ARQ implementation. Note that it is necessary to either implement chppNotifierTimedWait() or a single-threaded workaround as described in QUICKSTART.md to detect timeouts
- - Checksum support via IEEE CRC-32. A sample implementation is provided, but it is expected that most devices have optimized implementations available or may prefer implementations with alternate optimization criteria
- - Timesync functionality and timestamp offset correction for WiFi and WWAN measurements
- - Reset handling throughout the transport layer, clients, and services, opening and recovering state as needed
- - WiFi RTT client and service support
- - Multiple loopback client support
- - Transport-layer-loopback client validates response and returns the result
- - Support for pseudo-opening services at the client, so they appear always available
- - Correct responses generated at clients when async requests fail at services
-
-- Cleanup and bug fixes
-
- - Client and service fixes including length and bound checks, missing implementations
- - Parser fixes including empty pointers set to null, compatibility with processors lacking unaligned access support
- - Stability fixes throughout CHPP and tests
- - Improved compiler compatibility for C99+ and pre-C99 systems (even though CHPP does not officially support pre-C99)
- - Updated documentation and logging
-
-### 2021-03-25 (f908420)
-
-This release updates the built-in timesync and checksum functionality and addresses bugs and compatibility issues.
-
-- Updated functionality
-
- - Timesync is redesigned to become non-blocking
- - Outgoing checksums are enabled by default
- - An updated sample CRC32 implementation is provided (It is still expected that devices that have existing, optimized implementations use their own)
- - Client deinitialization and reset support
-
-- Cleanup and bug fixes
-
- - Logging updates, including reset reasoning, avoiding %s for compatibility
- - Stability fixes and cleanup throughout CHPP and tests, including the reopening flow, permanent_failure state, and a memory leak
- - Testing improvements
-
-### 2021-05-24 (c9bfae3)
-
-This release enables better identification of end-of-packets as well as addressing bugs and compatibility issues.
-
-- Updated functionality
-
- - Rx timeout detection
- - Rx MTU enforcement
- - Support for Rx end-of-packet notifications from the link layer (optional, platform dependent)
-
-- Cleanup and bug fixes
-
- - Reset functionality cleanup, including updating the functionality of CHPP_TRANSPORT_MAX_RETX and CHPP_TRANSPORT_MAX_RESET to reflect their intent accurately
- - Pseudo-open clients remain pseudo-open after open failures
- - Fixed reopen failures after transport reset
- - Added missing WiFi ranging service response
- - Memory allocation and initialization improvements
- - Mutex handling improvements
- - Compatibility fixes
- - Testing improvements
-
-### 2021-06-17 (this)
-
-This release adds request timeout support at the client and addresses several bugs and compatibility issues throughout CHPP, including fixing open-state tracking at the service. Note that with the corrected open-state tracking, it is essential for services to correctly implement the close() PAL API so that it disables any ongoing requests and returns to a clean state.
-
-- Updated functionality
-
- - Client request timeout support
-
-- Cleanup and bug fixes
-
- - Service open-state tracking
- - Memory handling fixes
- - Added GNSS passive location listener service response
- - Enforced error code requirements on service responses
- - Fixed ARQ handling of duplicate packets
- - Client request/response state refactoring
- - Client registration cleanup
- - Reset handling fixes
- - Testing improvements
diff --git a/chpp/TEST_MAPPING b/chpp/TEST_MAPPING
deleted file mode 100644
index f9eb7f8e..00000000
--- a/chpp/TEST_MAPPING
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "presubmit" : [
- {
- "name" : "chre_chpp_linux_tests",
- "host" : true
- },
- {
- "name" : "chre_chpp_convert_tests",
- "host" : true
- }
- ]
-}
diff --git a/chpp/api_parser/.gitignore b/chpp/api_parser/.gitignore
deleted file mode 100644
index e431c531..00000000
--- a/chpp/api_parser/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-parser_cache
diff --git a/chpp/api_parser/README.md b/chpp/api_parser/README.md
deleted file mode 100644
index 8d775052..00000000
--- a/chpp/api_parser/README.md
+++ /dev/null
@@ -1,160 +0,0 @@
-# CHRE API Parser + Code Generator for CHPP
-
-Since one of the main use cases of CHPP is to support remoting a CHRE PAL
-implementation to a peripheral component, we leverage the CHRE PAL API
-definitions for the platform-specific implementation of those services, such
-as the WWAN service. However, the structures used in the CHRE PAL APIs are the
-same as those used in the CHRE API for nanoapps, which are not inherently
-serializable, as they include things like pointers to other structures. So we
-must create slightly updated versions of these to send over the wire with CHPP.
-
-The `chre_api_to_chpp.py` script in this directory parses CHRE APIs according
-to instructions given in `chre_api_annotations.json` and generates structures
-and conversion code used for serialization and deserialization.
-
-## Serialization format
-
-_TL;DR: The CHPP format is just a packed and flattened version of the CHRE
-structures, replacing pointers with offsets._
-
-The serialized output is meant to match the source CHRE structure as closely as
-possible, however some special handling is needed to be able to send them over
-the wire to a different processor in the system. The general process for
- generating a serializable CHPP version of a CHRE structure is as follows:
-
- 1. Rewrite the name to start with "Chpp" instead of "chre" and mark it packed,
- to ensure there's no padding between fields (which is compiler-dependent)
- 1. Flatten the structure by replacing pointers to nested structures/arrays with
- a ChppOffset which describes the location in the payload where the nested
- data resides.
- 1. A CHPP application layer header is allocated for convenience when used in
- CHPP. The header values need to be set by CHPP and they are not zeroed out.
- The header length is not included in the offset calculation.
-
-ChppOffset is a collection of a 16-bit offset from the beginning of the payload,
-and a length. While we could implicitly derive the offset, the length cannot
-exceed 16 bits due to limitations in the encapsulating CHPP protocol
-(and we don't expect to bump up against this limit anyways), and including the
-offset field helps simplify decoding.
-
-This approach allows for a highly optimized, in-place encoding and decoding that
-only requires converting between pointer and ChppOffset types, if the following
-conditions are met:
-
- 1. The size of the CHRE and CHPP structures are the same, and the offsets to
- all contained fields are the same, and the same property holds for all
- nested structures/unions
- 1. (Encoding only) All nested structures appear in contiguous memory - for
- example, if a structure has a pointer to an array, then the array appears
- immediately after the structure in memory, with no padding
- 1. (Decoding only) Processor alignment constraints are met for all fields, such
- that they can be safely accessed through normal means at the location in
- memory at which they reside, when accounting for any headers, etc.
-
-If conditions 2 or 3 are not met, then optimized encode/decode is still possible
-after copying the memory to a separate allocation. So in-place conversion can't
-be done, but the only translation needed is between pointer and ChppOffset. If
-the first condition is not met, then conversion is done using field-wise
-assignment, which allows the compiler to generate the necessary instructions to
-handle differences in alignment and packing.
-
-All generated code currently assumes that it's running on a little endian CPU,
-as the wire format requires little endian byte order.
-
-TODO: The script currently only generates code for the pessimistic case, where
-none of the constraints are met. By generating code that checks sizeof/offsetof
-on all fields and placing the optimized path in an if/else condition, the
-compiler can evaluate condition 1 and prune away code for the less-optimal path.
-
-## Annotations
-
-As the C API does not have enough information for the script to know how to
-handle things like variable-length arrays (VLAs), we use the
-`chre_api_annotations.json` file to provide this detail. The supported fields
- are explained in the illustrated example below:
-
-```json
-[// A list of entries for each input file
-{
- // Path starting at <android_root>/system/chre to the input file
- "filename": "chre_api/include/chre_api/chre/wwan.h",
- // List of #includes that also need to be parsed, e.g. because they provide
- // struct definitions that are used in the file
- "includes": [
- "chre_api/include/chre_api/chre/common.h"
- ],
- // Which files the output header should pull in to satisfy dependencies
- "output_includes": [
- "chpp/common/common_types.h",
- "chre_api/chre/wwan.h"
- ],
- // A list of entries providing additional information for structs/unions that
- // appear in the input
- "struct_info": [
- {
- "name": "chreWwanCellInfoResult",
- // List of annotations for fields within the struct
- "annotations": [
- // Instead of copying the input, always force setting a specific value
- // for a field. The value is whatever should appear in the code for the
- // assignment statement, or the value to memset it to for an array type.
- {
- // Which field within the struct this annotation applies to
- "field": "version",
- // The type of annotation we're supplying
- "annotation": "fixed_value",
- // Additional information is dependent upon the annotation type
- "value": "CHRE_WWAN_CELL_INFO_RESULT_VERSION"
- },
- // Since the 'cookie' field here is a void*, we're rewriting to a
- // uint32_t to keep the same structure size + field offsets (on 32-bit
- // architectures) - in practice we'll also force the value to 0
- {
- "field": "cookie",
- "annotation": "rewrite_type",
- "type_override": "uint32_t"
- },
- // Indicates a variable length array field, with the number of elements
- // given by another field in the same structure called cellInfoCount
- {
- "field": "cells",
- "annotation": "var_len_array",
- "length_field": "cellInfoCount"
- }
- ]
- },
- {
- "name": "chreWwanCellInfo",
- "annotations": [
- // In this case, we have a union field, where only one of the members is
- // used, according to the provided mapping on the adjacent discriminator
- // field
- {
- "field": "CellInfo",
- "annotation": "union_variant",
- "discriminator": "cellInfoType",
- "mapping": [
- ["CHRE_WWAN_CELL_INFO_TYPE_GSM", "gsm"],
- ["CHRE_WWAN_CELL_INFO_TYPE_CDMA", "cdma"],
- ["CHRE_WWAN_CELL_INFO_TYPE_LTE", "lte"],
- ["CHRE_WWAN_CELL_INFO_TYPE_WCDMA", "wcdma"],
- ["CHRE_WWAN_CELL_INFO_TYPE_TD_SCDMA", "tdscdma"],
- ["CHRE_WWAN_CELL_INFO_TYPE_NR", "nr"]
- ]
- }
- ]
- }
- ],
- // The list of top-level structures appearing in the input that we should
- // create conversion routines for
- "root_structs": [
- "chreWwanCellInfoResult"
- ]
-}]
-```
-
-## Requirements
-
-Tested with Python 3.7, but most versions of Python 3 should work.
-
-Requires pyclibrary - see requirements.txt.
diff --git a/chpp/api_parser/chre_api_annotations.json b/chpp/api_parser/chre_api_annotations.json
deleted file mode 100644
index 3322ada0..00000000
--- a/chpp/api_parser/chre_api_annotations.json
+++ /dev/null
@@ -1,257 +0,0 @@
-[{
- "filename": "chre_api/include/chre_api/chre/wwan.h",
- "includes": [
- "chre_api/include/chre_api/chre/common.h"
- ],
- "output_includes": [
- "chpp/common/common_types.h",
- "chre_api/chre/wwan.h"
- ],
- "struct_info": [
- {
- "name": "chreWwanCellInfoResult",
- "annotations": [
- {
- "field": "version",
- "annotation": "fixed_value",
- "value": "CHRE_WWAN_CELL_INFO_RESULT_VERSION"
- },
- {
- "field": "errorCode",
- "annotation": "enum",
- "enum_type": "chreError"
- },
- {
- "field": "cookie",
- "annotation": "fixed_value",
- "value": "0"
- },
- {
- "field": "cookie",
- "annotation": "rewrite_type",
- "type_override": "uint32_t"
- },
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- },
- {
- "field": "cells",
- "annotation": "var_len_array",
- "length_field": "cellInfoCount"
- }
- ]
- },
- {
- "name": "chreWwanCellInfo",
- "annotations": [
- {
- "field": "cellInfoType",
- "annotation": "enum",
- "enum_type": "chreWwanCellInfoType"
- },
- {
- "field": "CellInfo",
- "annotation": "union_variant",
- "discriminator": "cellInfoType",
- "mapping": [
- ["CHRE_WWAN_CELL_INFO_TYPE_GSM", "gsm"],
- ["CHRE_WWAN_CELL_INFO_TYPE_CDMA", "cdma"],
- ["CHRE_WWAN_CELL_INFO_TYPE_LTE", "lte"],
- ["CHRE_WWAN_CELL_INFO_TYPE_WCDMA", "wcdma"],
- ["CHRE_WWAN_CELL_INFO_TYPE_TD_SCDMA", "tdscdma"],
- ["CHRE_WWAN_CELL_INFO_TYPE_NR", "nr"]
- ]
- },
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- }
- ]
- },
- {
- "name": "chreWwanCellIdentityGsm",
- "annotations": [
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- }
- ]
- }
- ],
- "root_structs": [
- "chreWwanCellInfoResult"
- ]
-},
-{
- "filename": "chre_api/include/chre_api/chre/wifi.h",
- "includes": [
- "chre_api/include/chre_api/chre/common.h"
- ],
- "output_includes": [
- "chpp/common/common_types.h",
- "chre_api/chre/wifi.h"
- ],
- "struct_info": [
- {
- "name": "chreWifiScanEvent",
- "annotations": [
- {
- "field": "version",
- "annotation": "fixed_value",
- "value": "CHRE_WIFI_SCAN_EVENT_VERSION"
- },
- {
- "field": "scannedFreqList",
- "annotation": "var_len_array",
- "length_field": "scannedFreqListLen"
- },
- {
- "field": "results",
- "annotation": "var_len_array",
- "length_field": "resultCount"
- }
- ]
- },
- {
- "name": "chreWifiScanResult",
- "annotations": [
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- }
- ]
- },
- {
- "name": "chreWifiScanParams",
- "annotations": [
- {
- "field": "frequencyList",
- "annotation": "var_len_array",
- "length_field": "frequencyListLen"
- },
- {
- "field": "ssidList",
- "annotation": "var_len_array",
- "length_field": "ssidListLen"
- }
- ]
- },
- {
- "name": "chreWifiRangingEvent",
- "annotations": [
- {
- "field": "version",
- "annotation": "fixed_value",
- "value": "CHRE_WIFI_RANGING_EVENT_VERSION"
- },
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- },
- {
- "field": "results",
- "annotation": "var_len_array",
- "length_field": "resultCount"
- }
- ]
- },
- {
- "name": "chreWifiRangingResult",
- "annotations": [
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- }
- ]
- },
- {
- "name": "chreWifiRangingParams",
- "annotations": [
- {
- "field": "targetList",
- "annotation": "var_len_array",
- "length_field": "targetListLen"
- }
- ]
- },
- {
- "name": "chreWifiRangingTarget",
- "annotations": [
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- }
- ]
- }
- ],
- "root_structs": [
- "chreWifiScanEvent",
- "chreWifiScanParams",
- "chreWifiRangingEvent",
- "chreWifiRangingParams"
- ]
-},
-{
- "filename": "chre_api/include/chre_api/chre/gnss.h",
- "includes": [
- "chre_api/include/chre_api/chre/common.h"
- ],
- "output_includes": [
- "chpp/common/common_types.h",
- "chre_api/chre/gnss.h"
- ],
- "struct_info": [
- {
- "name": "chreGnssDataEvent",
- "annotations": [
- {
- "field": "version",
- "annotation": "fixed_value",
- "value": "CHRE_GNSS_DATA_EVENT_VERSION"
- },
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- },
- {
- "field": "measurements",
- "annotation": "var_len_array",
- "length_field": "measurement_count"
- }
- ]
- },
- {
- "name": "chreGnssLocationEvent",
- "annotations": [
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- }
- ]
- },
- {
- "name": "chreGnssClock",
- "annotations": [
- {
- "field": "reserved",
- "annotation": "fixed_value",
- "value": "0"
- }
- ]
- }
- ],
- "root_structs": [
- "chreGnssDataEvent",
- "chreGnssLocationEvent"
- ]
-}]
diff --git a/chpp/api_parser/chre_api_to_chpp.py b/chpp/api_parser/chre_api_to_chpp.py
deleted file mode 100755
index 54f070fa..00000000
--- a/chpp/api_parser/chre_api_to_chpp.py
+++ /dev/null
@@ -1,1046 +0,0 @@
-#!/usr/bin/python3
-#
-# Copyright (C) 2020 The Android Open Source Project
-#
-# 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.
-#
-
-import argparse
-import json
-import os.path
-import subprocess
-from collections import defaultdict
-from datetime import datetime
-
-from pyclibrary import CParser
-
-LICENSE_HEADER = """/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-"""
-
-# Paths for output, relative to system/chre
-CHPP_PARSER_INCLUDE_PATH = "chpp/include/chpp/common"
-CHPP_PARSER_SOURCE_PATH = "chpp/common"
-
-
-def system_chre_abs_path():
- """Gets the absolute path to the system/chre directory containing this script."""
- script_dir = os.path.dirname(os.path.realpath(__file__))
- # Assuming we're at system/chre/chpp/api_parser (i.e. up 2 to get to system/chre)
- chre_project_base_dir = os.path.normpath(script_dir + "/../..")
- return chre_project_base_dir
-
-
-class CodeGenerator:
- """Given an ApiParser object, generates a header file with structure definitions in CHPP format.
- """
-
- def __init__(self, api, commit_hash):
- """
- :param api: ApiParser object
- """
- self.api = api
- self.json = api.json
- # Turn "chre_api/include/chre_api/chre/wwan.h" into "wwan"
- self.service_name = self.json['filename'].split('/')[-1].split('.')[0]
- self.capitalized_service_name = self.service_name[0].upper() + self.service_name[1:]
- self.commit_hash = commit_hash
-
- # ----------------------------------------------------------------------------------------------
- # Header generation methods (plus some methods shared with encoder generation)
- # ----------------------------------------------------------------------------------------------
-
- def _autogen_notice(self):
- out = []
- out.append("// This file was automatically generated by {}\n".format(
- os.path.basename(__file__)))
- out.append("// Date: {} UTC\n".format(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')))
- out.append("// Source: {} @ commit {}\n\n".format(self.json['filename'], self.commit_hash))
- out.append("// DO NOT modify this file directly, as those changes will be lost the next\n")
- out.append("// time the script is executed\n\n")
- return out
-
- def _dump_to_file(self, output_filename, contents, dry_run, skip_clang_fomat):
- """Outputs contents to output_filename, or prints contents if dry_run is True"""
- if dry_run:
- print("---- {} ----".format(output_filename))
- print(contents)
- print("---- end of {} ----\n".format(output_filename))
- else:
- with open(output_filename, 'w') as f:
- f.write(contents)
-
- if not skip_clang_fomat:
- clang_format_path = os.path.normpath(
- "../../../../prebuilts/clang/host/linux-x86/clang-stable/bin/clang-format")
- args = [clang_format_path, '-i', output_filename]
- result = subprocess.run(args)
- result.check_returncode()
-
- def _is_array_type(self, type_info):
- # If this is an array type, declarators will be a tuple containing a list of
- # a single int element giving the size of the array
- return len(type_info.declarators) == 1 and isinstance(type_info.declarators[0], list)
-
- def _get_array_len(self, type_info):
- return type_info.declarators[0][0]
-
- def _get_chpp_type_from_chre(self, chre_type):
- """Given 'chreWwanCellInfo' returns 'struct ChppWwanCellInfo', etc."""
- prefix = self._get_struct_or_union_prefix(chre_type)
-
- # First see if we have an explicit name override (e.g. for anonymous types)
- for annotation in self.api.annotations[chre_type]["."]:
- if annotation['annotation'] == "rename_type":
- return prefix + annotation['type_override']
-
- # Otherwise, use the existing type name, just replace the "chre" prefix with "Chpp"
- if chre_type.startswith('chre'):
- return prefix + 'Chpp' + chre_type[4:]
- else:
- raise RuntimeError("Couldn't figure out new type name for {}".format(chre_type))
-
- def _get_chre_type_with_prefix(self, chre_type):
- """Given 'chreWwanCellInfo' returns 'struct chreWwanCellInfo', etc."""
- return self._get_struct_or_union_prefix(chre_type) + chre_type
-
- def _get_chpp_header_type_from_chre(self, chre_type):
- """Given 'chreWwanCellInfo' returns 'struct ChppWwanCellInfoWithHeader', etc."""
- return self._get_chpp_type_from_chre(chre_type) + 'WithHeader'
-
- def _get_member_comment(self, member_info):
- for annotation in member_info['annotations']:
- if annotation['annotation'] == "fixed_value":
- return " // Input ignored; always set to {}".format(annotation['value'])
- elif annotation['annotation'] == "var_len_array":
- return " // References {} instances of {}".format(
- annotation['length_field'], self._get_member_type(member_info))
- return ""
-
- def _get_member_type(self, member_info, underlying_vla_type=False):
- """Gets the CHPP type specification prefix for a struct/union member.
-
- :param member_info: a dict element from self.api.structs_and_unions[struct]['members']
- :param underlying_vla_type: (used only for var-len array types) False to output
- 'struct ChppOffset', and True to output the type that ChppOffset references
- :return: type specification string that prefixes the field name, e.g. 'uint8_t'
- """
- # 4 cases to handle:
- # 1) Annotation gives explicit type that we should use
- # 2) Annotation says this is a variable length array (so use ChppOffset if
- # underlying_vla_type is False)
- # 3) This is a struct/union type, so use the renamed (CHPP) type name
- # 4) Regular type, e.g. uint32_t, so just use the type spec as-is
- for annotation in member_info['annotations']:
- if annotation['annotation'] == "rewrite_type":
- return annotation['type_override']
- elif not underlying_vla_type and annotation['annotation'] == "var_len_array":
- return "struct ChppOffset"
-
- if not underlying_vla_type and len(member_info['type'].declarators) > 0 and \
- member_info['type'].declarators[0] == "*":
- # This case should either be handled by rewrite_type (e.g. to uint32_t as
- # opaque/ignored), or var_len_array
- raise RuntimeError("Pointer types require annotation\n{}".format(
- member_info))
-
- if member_info['is_nested_type']:
- return self._get_chpp_type_from_chre(member_info['nested_type_name'])
-
- return member_info['type'].type_spec
-
- def _get_member_type_suffix(self, member_info):
- if self._is_array_type(member_info['type']):
- return "[{}]".format(self._get_array_len(member_info['type']))
- return ""
-
- def _get_struct_or_union_prefix(self, chre_type):
- return 'struct ' if not self.api.structs_and_unions[chre_type]['is_union'] else 'union '
-
- def _gen_header_includes(self):
- """Generates #include directives for use in <service>_types.h"""
- out = ["#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n\n"]
-
- includes = ["chpp/app.h", "chpp/macros.h", "chre_api/chre/version.h"]
- includes.extend(self.json['output_includes'])
- for incl in sorted(includes):
- out.append("#include \"{}\"\n".format(incl))
- out.append("\n")
- return out
-
- def _gen_struct_or_union(self, name):
- """Generates the definition for a single struct/union type"""
- out = []
- if not name.startswith('anon'):
- out.append("//! See {{@link {}}} for details\n".format(name))
- out.append("{} {{\n".format(self._get_chpp_type_from_chre(name)))
- for member_info in self.api.structs_and_unions[name]['members']:
- out.append(" {} {}{};{}\n".format(self._get_member_type(member_info),
- member_info['name'],
- self._get_member_type_suffix(member_info),
- self._get_member_comment(member_info)))
-
- out.append("} CHPP_PACKED_ATTR;\n\n")
- return out
-
- def _gen_header_struct(self, chre_type):
- """Generates the definition for the type with header (WithHeader)"""
- out = []
- out.append("//! CHPP app header plus {}\n".format(
- self._get_chpp_header_type_from_chre(chre_type)))
-
- out.append("{} {{\n".format(self._get_chpp_header_type_from_chre(chre_type)))
- out.append(" struct ChppAppHeader header;\n")
- out.append(" {} payload;\n".format(self._get_chpp_type_from_chre(chre_type)))
- out.append("} CHPP_PACKED_ATTR;\n\n")
-
- return out
-
- def _gen_structs_and_unions(self):
- """Generates definitions for all struct/union types required for the root structs."""
- out = []
- out.append("CHPP_PACKED_START\n\n")
-
- sorted_structs = self._sorted_structs(self.json['root_structs'])
- for type_name in sorted_structs:
- out.extend(self._gen_struct_or_union(type_name))
-
- for chre_type in self.json['root_structs']:
- out.extend(self._gen_header_struct(chre_type))
-
- out.append("CHPP_PACKED_END\n\n")
- return out
-
- def _sorted_structs(self, root_nodes):
- """Implements a topological sort on self.api.structs_and_unions.
-
- Elements are ordered by definition dependency, i.e. if A includes a field of type B,
- then B will appear before A in the returned list.
- :return: list of keys in self.api.structs_and_unions, sorted by dependency order
- """
- result = []
- visited = set()
-
- def sort_helper(collection, key):
- for dep in sorted(collection[key]['dependencies']):
- if dep not in visited:
- visited.add(dep)
- sort_helper(collection, dep)
- result.append(key)
-
- for node in sorted(root_nodes):
- sort_helper(self.api.structs_and_unions, node)
- return result
-
- # ----------------------------------------------------------------------------------------------
- # Encoder function generation methods (CHRE --> CHPP)
- # ----------------------------------------------------------------------------------------------
-
- def _get_chpp_member_sizeof_call(self, member_info):
- """Returns invocation used to determine the size of the provided member when encoded.
-
- Will be either sizeof(<type in CHPP struct>) or a function call if the member contains a VLA
- :param member_info: a dict element from self.api.structs_and_unions[struct]['members']
- :return: string
- """
- type_name = None
- if member_info['is_nested_type']:
- chre_type = member_info['nested_type_name']
- if self.api.structs_and_unions[chre_type]['has_vla_member']:
- return "{}(in->{})".format(self._get_chpp_sizeof_function_name(chre_type),
- member_info['name'])
- else:
- type_name = self._get_chpp_type_from_chre(chre_type)
- else:
- type_name = member_info['type'].type_spec
- return "sizeof({})".format(type_name)
-
- def _gen_chpp_sizeof_function(self, chre_type):
- """Generates a function to determine the encoded size of the CHRE struct, if necessary."""
- out = []
-
- # Note that this function *should* work with unions as well, but at the time of writing
- # it'll only be used with structs, so names, etc. are written with that in mind
- struct_info = self.api.structs_and_unions[chre_type]
- if not struct_info['has_vla_member']:
- # No codegen necessary, just sizeof on the CHPP structure name is sufficient
- return out
-
- core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
- parameter_name = core_type_name[0].lower() + core_type_name[1:]
- chpp_type_name = self._get_chpp_header_type_from_chre(chre_type)
- out.append("//! @return number of bytes required to represent the given\n"
- "//! {} along with the CHPP header as\n"
- "//! {}\n"
- .format(chre_type, chpp_type_name))
- out.append("static size_t {}(\n const {}{} *{}) {{\n"
- .format(self._get_chpp_sizeof_function_name(chre_type),
- self._get_struct_or_union_prefix(chre_type), chre_type,
- parameter_name))
-
- # sizeof(this struct)
- out.append(" size_t encodedSize = sizeof({});\n".format(chpp_type_name))
-
- # Plus count * sizeof(type) for each var-len array included in this struct
- for member_info in self.api.structs_and_unions[chre_type]['members']:
- for annotation in member_info['annotations']:
- if annotation['annotation'] == "var_len_array":
- # If the VLA field itself contains a VLA, then we'd need to generate a for
- # loop to calculate the size of each element individually - I don't think we
- # have any of these in the CHRE API today, so leaving this functionality out.
- # Also note that to support that case we'd also want to recursively call this
- # function to generate sizeof functions for nested fields.
- if member_info['is_nested_type'] and \
- self.api.structs_and_unions[member_info['nested_type_name']][
- 'has_vla_member']:
- raise RuntimeError(
- "Nested variable-length arrays is not currently supported ({} "
- "in {})".format(member_info['name'], chre_type))
-
- out.append(" encodedSize += {}->{} * sizeof({});\n".format(
- parameter_name, annotation['length_field'],
- self._get_member_type(member_info, True)))
-
- out.append(" return encodedSize;\n}\n\n")
- return out
-
- def _gen_chpp_sizeof_functions(self):
- """For each root struct, generate necessary functions to determine their encoded size."""
- out = []
- for struct in self.json['root_structs']:
- out.extend(self._gen_chpp_sizeof_function(struct))
- return out
-
- def _gen_conversion_includes(self):
- """Generates #include directives for the conversion source file"""
- out = ["#include \"chpp/macros.h\"\n"
- "#include \"chpp/memory.h\"\n"
- "#include \"chpp/common/{}_types.h\"\n\n".format(self.service_name)]
- out.append("#include <stddef.h>\n#include <stdint.h>\n#include <string.h>\n\n")
- return out
-
- def _get_chpp_sizeof_function_name(self, chre_struct):
- """Function name used to compute the encoded size of the given struct at runtime"""
- core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_struct)
- return "chpp{}SizeOf{}FromChre".format(self.capitalized_service_name, core_type_name)
-
- def _get_encoding_function_name(self, chre_type):
- core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
- return "chpp{}Convert{}FromChre".format(self.capitalized_service_name, core_type_name)
-
- def _gen_encoding_function_signature(self, chre_type):
- out = []
- out.append("void {}(\n".format(self._get_encoding_function_name(chre_type)))
- out.append(" const {}{} *in,\n".format(
- self._get_struct_or_union_prefix(chre_type), chre_type))
- out.append(" {} *out".format(self._get_chpp_type_from_chre(chre_type)))
- if self.api.structs_and_unions[chre_type]['has_vla_member']:
- out.append(",\n")
- out.append(" uint8_t *payload,\n")
- out.append(" size_t payloadSize,\n")
- out.append(" uint16_t *vlaOffset")
- out.append(")")
- return out
-
- def _gen_vla_encoding(self, member_info, annotation):
- out = []
-
- variable_name = member_info['name']
- chpp_type = self._get_member_type(member_info, True)
-
- if member_info['is_nested_type']:
- out.append("\n {} *{} = ({} *) &payload[*vlaOffset];\n".format(
- chpp_type, variable_name, chpp_type))
-
- out.append(" out->{}.length = in->{} * {};\n".format(
- member_info['name'], annotation['length_field'],
- self._get_chpp_member_sizeof_call(member_info)))
-
- out.append(" CHPP_ASSERT((size_t)(*vlaOffset + out->{}.length) <= payloadSize);\n".format(
- member_info['name']))
-
- out.append(" if (out->{}.length > 0 &&\n"
- " *vlaOffset + out->{}.length <= payloadSize) {{\n".format(
- member_info['name'], member_info['name']))
-
- if member_info['is_nested_type']:
- out.append(" for (size_t i = 0; i < in->{}; i++) {{\n".format(
- annotation['length_field']))
- out.append(" {}".format(
- self._get_assignment_statement_for_field(member_info, in_vla_loop=True)))
- out.append(" }\n")
- else:
- out.append("memcpy(&payload[*vlaOffset], in->{}, in->{} * sizeof({}));\n".format(
- member_info['name'], annotation['length_field'], chpp_type))
-
- out.append(" out->{}.offset = *vlaOffset;\n".format(member_info['name']))
- out.append(" *vlaOffset += out->{}.length;\n".format(member_info['name']))
-
- out.append(" } else {\n")
- out.append(" out->{}.offset = 0;\n".format(member_info['name']))
- out.append(" }\n");
-
- return out
-
- # ----------------------------------------------------------------------------------------------
- # Encoder / decoder function generation methods (CHRE <--> CHPP)
- # ----------------------------------------------------------------------------------------------
-
- def _get_assignment_statement_for_field(self, member_info, in_vla_loop=False,
- containing_field_name=None,
- decode_mode=False):
- """Returns a statement to assign the provided member
-
- :param member_info:
- :param in_vla_loop: True if we're currently inside a loop and should append [i]
- :param containing_field_name: Additional member name to use to access the target field, or
- None; for example the normal case is "out->field = in->field", but if we're generating
- assignments in the parent conversion function (e.g. as used for union variants), we need to
- do "out->nested_field.field = in->nested_field.field"
- :param decode_mode: True converts from CHPP to CHRE. False from CHRE to CHPP
- :return: assignment statement as a string
- """
- array_index = "[i]" if in_vla_loop else ""
- output_accessor = "" if in_vla_loop else "out->"
- containing_field = containing_field_name + "." if containing_field_name is not None else ""
-
- output_variable = "{}{}{}{}".format(output_accessor, containing_field, member_info['name'],
- array_index)
- input_variable = "in->{}{}{}".format(containing_field, member_info['name'], array_index)
-
- if decode_mode and in_vla_loop:
- output_variable = "{}Out{}".format(member_info['name'], array_index)
- input_variable = "{}In{}".format(member_info['name'], array_index)
-
- if member_info['is_nested_type']:
- chre_type = member_info['nested_type_name']
- has_vla_member = self.api.structs_and_unions[chre_type]['has_vla_member']
- if decode_mode:
- # Use decoding function
- vla_params = ", inSize" if has_vla_member else ""
- out = "if (!{}(&{}, &{}{})) {{\n".format(
- self._get_decoding_function_name(chre_type), input_variable,
- output_variable, vla_params)
- if has_vla_member:
- out += " CHPP_FREE_AND_NULLIFY({}Out);\n".format(member_info['name'])
- out += " return false;\n"
- out += "}\n"
- return out
- else:
- # Use encoding function
- vla_params = ", payload, payloadSize, vlaOffset" if has_vla_member else ""
- return "{}(&{}, &{}{});\n".format(
- self._get_encoding_function_name(chre_type), input_variable, output_variable,
- vla_params)
- elif self._is_array_type(member_info['type']):
- # Array of primitive type (e.g. uint32_t[8]) - use memcpy
- return "memcpy({}, {}, sizeof({}));\n".format(output_variable, input_variable,
- output_variable)
- else:
- # Regular assignment
- return "{} = {};\n".format(output_variable, input_variable)
-
- def _gen_union_variant_conversion_code(self, member_info, annotation, decode_mode):
- """Generates a switch statement to encode the "active"/"used" field within a union.
-
- Handles cases where a union has multiple types, but there's another peer/adjacent field
- which tells you which field in the union is to be used. Outputs code like this:
- switch (in->{discriminator field}) {
- case {first discriminator value associated with a fields}:
- {conversion code for the field associated with this discriminator value}
- ...
- :param chre_type: CHRE type of the union
- :param annotation: Reference to JSON annotation data with the discriminator mapping data
- :param decode_mode: False encodes from CHRE to CHPP. True decodes from CHPP to CHRE
- :return: list of strings
- """
- out = []
- chre_type = member_info['nested_type_name']
- struct_info = self.api.structs_and_unions[chre_type]
-
- # Start off by zeroing out the union field so any padding is set to a consistent value
- out.append(" memset(&out->{}, 0, sizeof(out->{}));\n".format(member_info['name'],
- member_info['name']))
-
- # Next, generate the switch statement that will copy over the proper values
- out.append(" switch (in->{}) {{\n".format(annotation['discriminator']))
- for value, field_name in annotation['mapping']:
- out.append(" case {}:\n".format(value))
-
- found = False
- for nested_member_info in struct_info['members']:
- if nested_member_info['name'] == field_name:
- out.append(" {}".format(
- self._get_assignment_statement_for_field(
- nested_member_info,
- containing_field_name=member_info['name'],
- decode_mode=decode_mode)))
- found = True
- break
-
- if not found:
- raise RuntimeError("Invalid mapping - couldn't find target field {} in struct {}"
- .format(field_name, chre_type))
-
- out.append(" break;\n")
-
- out.append(" default:\n"
- " CHPP_ASSERT(false);\n"
- " }\n")
-
- return out
-
- def _gen_conversion_function(self, chre_type, already_generated, decode_mode):
- out = []
-
- struct_info = self.api.structs_and_unions[chre_type]
- for dependency in sorted(struct_info['dependencies']):
- if dependency not in already_generated:
- out.extend(
- self._gen_conversion_function(dependency, already_generated, decode_mode))
-
- # Skip if we've already generated code for this type, or if it's a union (in which case we
- # handle the assignment in the parent structure to enable support for discrimination of
- # which field in the union to use)
- if chre_type in already_generated or struct_info['is_union']:
- return out
- already_generated.add(chre_type)
-
- out.append("static ")
- if decode_mode:
- out.extend(self._gen_decoding_function_signature(chre_type))
- else:
- out.extend(self._gen_encoding_function_signature(chre_type))
- out.append(" {\n")
-
- for member_info in self.api.structs_and_unions[chre_type]['members']:
- generated_by_annotation = False
- for annotation in member_info['annotations']:
- if annotation['annotation'] == "fixed_value":
- if self._is_array_type(member_info['type']):
- out.append(" memset(&out->{}, {}, sizeof(out->{}));\n".format(
- member_info['name'], annotation['value'], member_info['name']))
- else:
- out.append(" out->{} = {};\n".format(member_info['name'],
- annotation['value']))
- generated_by_annotation = True
- break
- elif annotation['annotation'] == "enum":
- # TODO: generate range verification code?
- pass
- elif annotation['annotation'] == "var_len_array":
- if decode_mode:
- out.extend(self._gen_vla_decoding(member_info, annotation))
- else:
- out.extend(self._gen_vla_encoding(member_info, annotation))
- generated_by_annotation = True
- break
- elif annotation['annotation'] == "union_variant":
- out.extend(self._gen_union_variant_conversion_code(
- member_info, annotation, decode_mode))
- generated_by_annotation = True
- break
-
- if not generated_by_annotation:
- out.append(" {}".format(
- self._get_assignment_statement_for_field(member_info, decode_mode=decode_mode)))
-
- if decode_mode:
- out.append("\n return true;\n")
-
- out.append("}\n\n")
- return out
-
- def _gen_conversion_functions(self, decode_mode):
- out = []
- already_generated = set()
- for struct in self.json['root_structs']:
- out.extend(self._gen_conversion_function(struct, already_generated, decode_mode))
- return out
-
- def _strip_prefix_and_service_from_chre_struct_name(self, struct):
- """Strip 'chre' and service prefix, e.g. 'chreWwanCellResultInfo' -> 'CellResultInfo'"""
- chre_stripped = struct[4:]
- upcased_service_name = self.service_name[0].upper() + self.service_name[1:]
- if not struct.startswith('chre') or not chre_stripped.startswith(upcased_service_name):
- # If this happens, we need to update the script to handle it. Right we assume struct
- # naming follows the pattern "chre<Service_name><Thing_name>"
- raise RuntimeError("Unexpected structure name {}".format(struct))
-
- return chre_stripped[len(self.service_name):]
-
- # ----------------------------------------------------------------------------------------------
- # Memory allocation generation methods
- # ----------------------------------------------------------------------------------------------
-
- def _get_chpp_sizeof_call(self, chre_type):
- """Returns invocation used to determine the size of the provided CHRE struct (with the CHPP
- app header) after encoding.
-
- Like _get_chpp_member_sizeof_call(), except for a top-level type assigned to the variable
- "in" rather than a member within a structure (e.g. a VLA field)
- :param chre_type: CHRE type name
- :return: string
- """
- if self.api.structs_and_unions[chre_type]['has_vla_member']:
- return "{}(in)".format(self._get_chpp_sizeof_function_name(chre_type))
- else:
- return "sizeof({})".format(self._get_chpp_header_type_from_chre(chre_type))
-
- def _get_encode_allocation_function_name(self, chre_type):
- core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
- return "chpp{}{}FromChre".format(self.capitalized_service_name, core_type_name)
-
- def _gen_encode_allocation_function_signature(self, chre_type, gen_docs=False):
- out = []
- if gen_docs:
- out.append("/**\n"
- " * Converts from given CHRE structure to serialized CHPP type.\n"
- " *\n"
- " * @param in Fully-formed CHRE structure.\n"
- " * @param out Upon success, will point to a buffer allocated with "
- "chppMalloc().\n"
- " * It is the responsibility of the caller to set the values of the CHPP "
- "app layer header, and to free the buffer when it is no longer needed via "
- "chppFree() or CHPP_FREE_AND_NULLIFY().\n"
- " * @param outSize Upon success, will be set to the size of the output "
- "buffer, in bytes.\n"
- " *\n"
- " * @return true on success, false if memory allocation failed.\n"
- " */\n")
- out.append("bool {}(\n".format(self._get_encode_allocation_function_name(chre_type)))
- out.append(" const {}{} *in,\n".format(
- self._get_struct_or_union_prefix(chre_type), chre_type))
- out.append(" {} **out,\n".format(self._get_chpp_header_type_from_chre(chre_type)))
- out.append(" size_t *outSize)")
- return out
-
- def _gen_encode_allocation_function(self, chre_type):
- out = []
-
- out.extend(self._gen_encode_allocation_function_signature(chre_type))
- out.append(" {\n")
- out.append(" CHPP_NOT_NULL(out);\n")
- out.append(" CHPP_NOT_NULL(outSize);\n\n")
- out.append(" size_t payloadSize = {};\n".format(
- self._get_chpp_sizeof_call(chre_type)))
- out.append(" *out = chppMalloc(payloadSize);\n")
-
- out.append(" if (*out != NULL) {\n")
-
- struct_info = self.api.structs_and_unions[chre_type]
- if struct_info['has_vla_member']:
- out.append(" uint8_t *payload = (uint8_t *) &(*out)->payload;\n")
- out.append(" uint16_t vlaOffset = sizeof({});\n".format(
- self._get_chpp_type_from_chre(chre_type)))
-
- out.append(" {}(in, &(*out)->payload".format(
- self._get_encoding_function_name(chre_type)))
- if struct_info['has_vla_member']:
- out.append(", payload, payloadSize, &vlaOffset")
- out.append(");\n")
- out.append(" *outSize = payloadSize;\n")
- out.append(" return true;\n")
- out.append(" }\n")
-
- out.append(" return false;\n}\n\n")
- return out
-
- def _gen_encode_allocation_functions(self):
- out = []
- for chre_type in self.json['root_structs']:
- out.extend(self._gen_encode_allocation_function(chre_type))
- return out
-
- def _gen_encode_allocation_function_signatures(self):
- out = []
- for chre_type in self.json['root_structs']:
- out.extend(self._gen_encode_allocation_function_signature(chre_type, True))
- out.append(";\n\n")
- return out
-
- # ----------------------------------------------------------------------------------------------
- # Decoder function generation methods (CHPP --> CHRE)
- # ----------------------------------------------------------------------------------------------
-
- def _get_decoding_function_name(self, chre_type):
- core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
- return "chpp{}Convert{}ToChre".format(self.capitalized_service_name, core_type_name)
-
- def _gen_decoding_function_signature(self, chre_type):
- out = []
- out.append("bool {}(\n".format(self._get_decoding_function_name(chre_type)))
- out.append(" const {} *in,\n".format(self._get_chpp_type_from_chre(chre_type)))
- out.append(" {} *out".format(self._get_chre_type_with_prefix(chre_type)))
- if self.api.structs_and_unions[chre_type]['has_vla_member']:
- out.append(",\n")
- out.append(" size_t inSize")
- out.append(")")
- return out
-
- def _gen_vla_decoding(self, member_info, annotation):
- out = []
-
- variable_name = member_info['name']
- chpp_type = self._get_member_type(member_info, True)
- if member_info['is_nested_type']:
- chre_type = self._get_chre_type_with_prefix(member_info['nested_type_name'])
- else:
- chre_type = chpp_type
-
- out.append("\n")
- out.append(" if (in->{}.length == 0) {{\n".format(variable_name))
- out.append(" out->{} = NULL;\n".format(variable_name))
- out.append(" }\n")
- out.append(" else {\n")
- out.append(" if (in->{}.offset + in->{}.length > inSize ||\n".format(
- variable_name, variable_name))
- out.append(" in->{}.length != in->{} * sizeof({})) {{\n".format(
- variable_name, annotation['length_field'], chpp_type))
-
- out.append(" return false;\n")
- out.append(" }\n\n")
-
- if member_info['is_nested_type']:
- out.append(" const {} *{}In =\n".format(chpp_type, variable_name))
- out.append(" (const {} *) &((const uint8_t *)in)[in->{}.offset];\n\n".format(
- chpp_type, variable_name))
-
- out.append(" {} *{}Out = chppMalloc(in->{} * sizeof({}));\n".format(
- chre_type, variable_name, annotation['length_field'], chre_type))
- out.append(" if ({}Out == NULL) {{\n".format(variable_name))
- out.append(" return false;\n")
- out.append(" }\n\n")
-
- if member_info['is_nested_type']:
- out.append(" for (size_t i = 0; i < in->{}; i++) {{\n".format(
- annotation['length_field'], variable_name))
- out.append(" {}".format(self._get_assignment_statement_for_field(
- member_info, in_vla_loop=True, decode_mode=True)))
- out.append(" }\n")
- else:
- out.append(" memcpy({}Out, &((const uint8_t *)in)[in->{}.offset],\n".format(
- variable_name, variable_name))
- out.append(" in->{} * sizeof({}));\n".format(
- annotation['length_field'], chre_type))
-
- out.append(" out->{} = {}Out;\n".format(variable_name, variable_name))
- out.append(" }\n\n")
-
- return out
-
- def _get_decode_allocation_function_name(self, chre_type):
- core_type_name = self._strip_prefix_and_service_from_chre_struct_name(chre_type)
- return "chpp{}{}ToChre".format(self.capitalized_service_name, core_type_name)
-
- def _gen_decode_allocation_function_signature(self, chre_type, gen_docs=False):
- out = []
- if gen_docs:
- out.append("/**\n"
- " * Converts from serialized CHPP structure to a CHRE type.\n"
- " *\n"
- " * @param in Fully-formed CHPP structure.\n"
- " * @param in Size of the CHPP structure in bytes.\n"
- " *\n"
- " * @return If successful, a pointer to a CHRE structure allocated with "
- "chppMalloc(). If unsuccessful, null.\n"
- " * It is the responsibility of the caller to free the buffer when it is no "
- "longer needed via chppFree() or CHPP_FREE_AND_NULLIFY().\n"
- " */\n")
-
- out.append("{} *{}(\n".format(
- self._get_chre_type_with_prefix(chre_type),
- self._get_decode_allocation_function_name(chre_type)))
- out.append(" const {} *in,\n".format(self._get_chpp_type_from_chre(chre_type)))
- out.append(" size_t inSize)")
- return out
-
- def _gen_decode_allocation_function(self, chre_type):
- out = []
-
- out.extend(self._gen_decode_allocation_function_signature(chre_type))
- out.append(" {\n")
-
- out.append(" {} *out = NULL;\n\n".format(
- self._get_chre_type_with_prefix(chre_type)))
-
- out.append(" if (inSize >= sizeof({})) {{\n".format(
- self._get_chpp_type_from_chre(chre_type)))
-
- out.append(" out = chppMalloc(sizeof({}));\n".format(
- self._get_chre_type_with_prefix(chre_type)))
- out.append(" if (out != NULL) {\n")
-
- struct_info = self.api.structs_and_unions[chre_type]
-
- out.append(" if (!{}(in, out".format(self._get_decoding_function_name(chre_type)))
- if struct_info['has_vla_member']:
- out.append(", inSize")
- out.append(")) {")
- out.append(" CHPP_FREE_AND_NULLIFY(out);\n")
- out.append(" }\n")
-
- out.append(" }\n")
- out.append(" }\n\n")
- out.append(" return out;\n")
- out.append("}\n")
- return out
-
- def _gen_decode_allocation_functions(self):
- out = []
- for chre_type in self.json['root_structs']:
- out.extend(self._gen_decode_allocation_function(chre_type))
- return out
-
- def _gen_decode_allocation_function_signatures(self):
- out = []
- for chre_type in self.json['root_structs']:
- out.extend(self._gen_decode_allocation_function_signature(chre_type, True))
- out.append(";\n\n")
- return out
-
- # ----------------------------------------------------------------------------------------------
- # Public methods
- # ----------------------------------------------------------------------------------------------
-
- def generate_header_file(self, dry_run=False, skip_clang_format=False):
- """Creates a C header file for this API and writes it to the file indicated in the JSON."""
- filename = self.service_name + "_types.h"
- if not dry_run:
- print("Generating {} ... ".format(filename), end='', flush=True)
- output_file = os.path.join(system_chre_abs_path(), CHPP_PARSER_INCLUDE_PATH, filename)
- header = self.generate_header_string()
- self._dump_to_file(output_file, header, dry_run, skip_clang_format)
- if not dry_run:
- print("done")
-
- def generate_header_string(self):
- """Returns a C header with structure definitions for this API."""
- # To defer concatenation (speed things up), build the file as a list of strings then only
- # concatenate once at the end
- out = [LICENSE_HEADER]
-
- header_guard = "CHPP_{}_TYPES_H_".format(self.service_name.upper())
-
- out.append("#ifndef {}\n#define {}\n\n".format(header_guard, header_guard))
- out.extend(self._autogen_notice())
- out.extend(self._gen_header_includes())
- out.append("#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n")
- out.extend(self._gen_structs_and_unions())
-
- out.append("\n// Encoding functions (CHRE --> CHPP)\n\n")
- out.extend(self._gen_encode_allocation_function_signatures())
-
- out.append("\n// Decoding functions (CHPP --> CHRE)\n\n")
- out.extend(self._gen_decode_allocation_function_signatures())
-
- out.append("#ifdef __cplusplus\n}\n#endif\n\n")
- out.append("#endif // {}\n".format(header_guard))
- return ''.join(out)
-
- def generate_conversion_file(self, dry_run=False, skip_clang_format=False):
- """Generates a .c file with functions for encoding CHRE structs into CHPP and vice versa."""
- filename = self.service_name + "_convert.c"
- if not dry_run:
- print("Generating {} ... ".format(filename), end='', flush=True)
- contents = self.generate_conversion_string()
- output_file = os.path.join(system_chre_abs_path(), CHPP_PARSER_SOURCE_PATH, filename)
- self._dump_to_file(output_file, contents, dry_run, skip_clang_format)
- if not dry_run:
- print("done")
-
- def generate_conversion_string(self):
- """Returns C code for encoding CHRE structs into CHPP and vice versa."""
- out = [LICENSE_HEADER, "\n"]
-
- out.extend(self._autogen_notice())
- out.extend(self._gen_conversion_includes())
-
- out.append("\n// Encoding (CHRE --> CHPP) size functions\n\n")
- out.extend(self._gen_chpp_sizeof_functions())
- out.append("\n// Encoding (CHRE --> CHPP) conversion functions\n\n")
- out.extend(self._gen_conversion_functions(False))
- out.append("\n// Encoding (CHRE --> CHPP) top-level functions\n\n")
- out.extend(self._gen_encode_allocation_functions())
-
- out.append("\n// Decoding (CHPP --> CHRE) conversion functions\n\n")
- out.extend(self._gen_conversion_functions(True))
- out.append("\n// Decoding (CHPP --> CHRE) top-level functions\n\n")
- out.extend(self._gen_decode_allocation_functions())
-
- return ''.join(out)
-
-
-class ApiParser:
- """Given a file-specific set of annotations (extracted from JSON annotations file), parses a
- single API header file into data structures suitable for use with code generation.
- """
-
- def __init__(self, json_obj):
- """Initialize and parse the API file described in the provided JSON-derived object.
-
- :param json_obj: Extracted file-specific annotations from JSON
- """
- self.json = json_obj
- self.structs_and_unions = {}
- self._parse_annotations()
- self._parse_api()
-
- def _parse_annotations(self):
- # Convert annotations list to a more usable data structure: dict keyed by structure name,
- # containing a dict keyed by field name, containing a list of annotations (as they
- # appear in the JSON). In other words, we can easily get all of the annotations for the
- # "version" field in "chreWwanCellInfoResult" via
- # annotations['chreWwanCellInfoResult']['version']. This is also a defaultdict, so it's safe
- # to access if there are no annotations for this structure + field; it'll just give you
- # an empty list in that case.
- self.annotations = defaultdict(lambda: defaultdict(list))
- for struct_info in self.json['struct_info']:
- for annotation in struct_info['annotations']:
- self.annotations[struct_info['name']][annotation['field']].append(annotation)
-
- def _files_to_parse(self):
- """Returns a list of files to supply as input to CParser"""
- # Input paths for CParser are stored in JSON relative to <android_root>/system/chre
- # Reformulate these to absolute paths, and add in some default includes that we always
- # supply
- chre_project_base_dir = system_chre_abs_path()
- default_includes = ["chpp/api_parser/parser_defines.h",
- "chre_api/include/chre_api/chre/version.h"]
- files = default_includes + self.json['includes'] + [self.json['filename']]
- return [os.path.join(chre_project_base_dir, file) for file in files]
-
- def _parse_structs_and_unions(self):
- # Starting with the root structures (i.e. those that will appear at the top-level in one
- # or more CHPP messages), build a data structure containing all of the information we'll
- # need to emit the CHPP structure definition and conversion code.
- structs_and_unions_to_parse = self.json['root_structs'].copy()
- while len(structs_and_unions_to_parse) > 0:
- type_name = structs_and_unions_to_parse.pop()
- if type_name in self.structs_and_unions:
- continue
-
- entry = {
- 'appears_in': set(), # Other types this type is nested within
- 'dependencies': set(), # Types that are nested in this type
- 'has_vla_member': False, # True if this type or any dependency has a VLA member
- 'members': [], # Info about each member of this type
- }
- if type_name in self.parser.defs['structs']:
- defs = self.parser.defs['structs'][type_name]
- entry['is_union'] = False
- elif type_name in self.parser.defs['unions']:
- defs = self.parser.defs['unions'][type_name]
- entry['is_union'] = True
- else:
- raise RuntimeError("Couldn't find {} in parsed structs/unions".format(type_name))
-
- for member_name, member_type, _ in defs['members']:
- member_info = {
- 'name': member_name,
- 'type': member_type,
- 'annotations': self.annotations[type_name][member_name],
- 'is_nested_type': False,
- }
-
- if member_type.type_spec.startswith('struct ') or \
- member_type.type_spec.startswith('union '):
- member_info['is_nested_type'] = True
- member_type_name = member_type.type_spec.split(' ')[1]
- member_info['nested_type_name'] = member_type_name
- entry['dependencies'].add(member_type_name)
- structs_and_unions_to_parse.append(member_type_name)
-
- entry['members'].append(member_info)
-
- # Flip a flag if this structure has at least one variable-length array member, which
- # means that the encoded size can only be computed at runtime
- if not entry['has_vla_member']:
- for annotation in self.annotations[type_name][member_name]:
- if annotation['annotation'] == "var_len_array":
- entry['has_vla_member'] = True
-
- self.structs_and_unions[type_name] = entry
-
- # Build reverse linkage of dependency chain (i.e. lookup between a type and the other types
- # it appears in)
- for type_name, type_info in self.structs_and_unions.items():
- for dependency in type_info['dependencies']:
- self.structs_and_unions[dependency]['appears_in'].add(type_name)
-
- # Bubble up "has_vla_member" to types each type it appears in, i.e. if this flag is set to
- # True on a leaf node, then all its ancestors should also have the flag set to True
- for type_name, type_info in self.structs_and_unions.items():
- if type_info['has_vla_member']:
- types_to_mark = list(type_info['appears_in'])
- while len(types_to_mark) > 0:
- type_to_mark = types_to_mark.pop()
- self.structs_and_unions[type_to_mark]['has_vla_member'] = True
- types_to_mark.extend(list(self.structs_and_unions[type_to_mark]['appears_in']))
-
- def _parse_api(self):
- file_to_parse = self._files_to_parse()
- self.parser = CParser(file_to_parse, cache='parser_cache')
- self._parse_structs_and_unions()
-
-
-def run(args):
- with open('chre_api_annotations.json') as f:
- js = json.load(f)
-
- commit_hash = subprocess.getoutput("git describe --always --long --dirty --exclude '*'")
- for file in js:
- if args.file_filter:
- matched = False
- for matcher in args.file_filter:
- if matcher in file['filename']:
- matched = True
- break
- if not matched:
- print("Skipping {} - doesn't match filter(s) {}".format(file['filename'],
- args.file_filter))
- continue
- print("Parsing {} ... ".format(file['filename']), end='', flush=True)
- api_parser = ApiParser(file)
- code_gen = CodeGenerator(api_parser, commit_hash)
- print("done")
- code_gen.generate_header_file(args.dry_run, args.skip_clang_format)
- code_gen.generate_conversion_file(args.dry_run, args.skip_clang_format)
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser(description='Generate CHPP serialization code from CHRE APIs.')
- parser.add_argument('-n', dest='dry_run', action='store_true',
- help='Print the output instead of writing to a file')
- parser.add_argument('--skip-clang-format', dest='skip_clang_format', action='store_true',
- help='Skip running clang-format on the output files (doesn\'t apply to dry '
- 'runs)')
- parser.add_argument('file_filter', nargs='*',
- help='Filters the input files (filename field in the JSON) to generate a '
- 'subset of the typical output, e.g. "wifi" to just generate conversion'
- ' routines for wifi.h')
- args = parser.parse_args()
- run(args)
diff --git a/chpp/api_parser/parser_defines.h b/chpp/api_parser/parser_defines.h
deleted file mode 100644
index d12561e0..00000000
--- a/chpp/api_parser/parser_defines.h
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-// A collection of definitions that normally come from standard library
-// headers, and are necessary for proper parsing by pyclibrary. We could direct
-// pyclibrary to system includes, but since those tend to be layered across
-// many files, and pyclibrary doesn't follow #include directives, we simply
-// redefine only the necessary things here.
-
-#define UINT8_MAX 255 \ No newline at end of file
diff --git a/chpp/api_parser/requirements.txt b/chpp/api_parser/requirements.txt
deleted file mode 100644
index 9b9ec0a5..00000000
--- a/chpp/api_parser/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-future==0.18.2
-pyclibrary==0.1.4
diff --git a/chpp/app.c b/chpp/app.c
deleted file mode 100644
index 3b90edff..00000000
--- a/chpp/app.c
+++ /dev/null
@@ -1,798 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/app.h"
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "chpp/clients.h"
-#include "chpp/clients/discovery.h"
-#ifdef CHPP_CLIENT_ENABLED_LOOPBACK
-#include "chpp/clients/loopback.h"
-#endif
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
-#include "chpp/clients/timesync.h"
-#endif
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/notifier.h"
-#include "chpp/pal_api.h"
-#include "chpp/services.h"
-#include "chpp/services/discovery.h"
-#include "chpp/services/loopback.h"
-#include "chpp/services/nonhandle.h"
-#include "chpp/services/timesync.h"
-#include "chre_api/chre/common.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static bool chppProcessPredefinedClientRequest(struct ChppAppState *context,
- uint8_t *buf, size_t len);
-static bool chppProcessPredefinedServiceResponse(struct ChppAppState *context,
- uint8_t *buf, size_t len);
-static bool chppProcessPredefinedClientNotification(
- struct ChppAppState *context, uint8_t *buf, size_t len);
-static bool chppProcessPredefinedServiceNotification(
- struct ChppAppState *context, uint8_t *buf, size_t len);
-
-static bool chppDatagramLenIsOk(struct ChppAppState *context,
- struct ChppAppHeader *rxHeader, size_t len);
-ChppDispatchFunction *chppGetDispatchFunction(struct ChppAppState *context,
- uint8_t handle,
- enum ChppMessageType type);
-ChppNotifierFunction *chppGetClientResetNotifierFunction(
- struct ChppAppState *context, uint8_t index);
-ChppNotifierFunction *chppGetServiceResetNotifierFunction(
- struct ChppAppState *context, uint8_t index);
-static inline const struct ChppService *chppServiceOfHandle(
- struct ChppAppState *appContext, uint8_t handle);
-static inline const struct ChppClient *chppClientOfHandle(
- struct ChppAppState *appContext, uint8_t handle);
-static inline void *chppServiceContextOfHandle(struct ChppAppState *appContext,
- uint8_t handle);
-static inline void *chppClientContextOfHandle(struct ChppAppState *appContext,
- uint8_t handle);
-static void *chppClientServiceContextOfHandle(struct ChppAppState *appContext,
- uint8_t handle,
- enum ChppMessageType type);
-
-static void chppProcessPredefinedHandleDatagram(struct ChppAppState *context,
- uint8_t *buf, size_t len);
-static void chppProcessNegotiatedHandleDatagram(struct ChppAppState *context,
- uint8_t *buf, size_t len);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Processes a client request that is determined to be for a predefined CHPP
- * service.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return False if handle is invalid. True otherwise.
- */
-static bool chppProcessPredefinedClientRequest(struct ChppAppState *context,
- uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- bool handleValid = true;
- bool dispatchResult = true;
-
- switch (rxHeader->handle) {
- case CHPP_HANDLE_LOOPBACK: {
- dispatchResult = chppDispatchLoopbackClientRequest(context, buf, len);
- break;
- }
-
- case CHPP_HANDLE_TIMESYNC: {
- dispatchResult = chppDispatchTimesyncClientRequest(context, buf, len);
- break;
- }
-
- case CHPP_HANDLE_DISCOVERY: {
- dispatchResult = chppDispatchDiscoveryClientRequest(context, buf, len);
- break;
- }
-
- default: {
- handleValid = false;
- }
- }
-
- if (dispatchResult == false) {
- CHPP_LOGE("H#%" PRIu8 " unknown request. cmd=%#x, ID=%" PRIu8,
- rxHeader->handle, rxHeader->command, rxHeader->transaction);
- }
-
- return handleValid;
-}
-
-/**
- * Processes a service response that is determined to be for a predefined CHPP
- * client.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return False if handle is invalid. True otherwise.
- */
-static bool chppProcessPredefinedServiceResponse(struct ChppAppState *context,
- uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- bool handleValid = true;
- bool dispatchResult = true;
-
- switch (rxHeader->handle) {
-#ifdef CHPP_CLIENT_ENABLED_LOOPBACK
- case CHPP_HANDLE_LOOPBACK: {
- dispatchResult = chppDispatchLoopbackServiceResponse(context, buf, len);
- break;
- }
-#endif // CHPP_CLIENT_ENABLED_LOOPBACK
-
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
- case CHPP_HANDLE_TIMESYNC: {
- dispatchResult = chppDispatchTimesyncServiceResponse(context, buf, len);
- break;
- }
-#endif // CHPP_CLIENT_ENABLED_TIMESYNC
-
-#ifdef CHPP_CLIENT_ENABLED_DISCOVERY
- case CHPP_HANDLE_DISCOVERY: {
- dispatchResult = chppDispatchDiscoveryServiceResponse(context, buf, len);
- break;
- }
-#endif // CHPP_CLIENT_ENABLED_DISCOVERY
-
- default: {
- handleValid = false;
- }
- }
-
- if (dispatchResult == false) {
- CHPP_LOGE("H#%" PRIu8 " unknown response. cmd=%#x, ID=%" PRIu8
- ", len=%" PRIuSIZE,
- rxHeader->handle, rxHeader->command, rxHeader->transaction, len);
- }
-
- return handleValid;
-}
-
-/**
- * Processes a client notification that is determined to be for a predefined
- * CHPP service.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return False if handle is invalid. True otherwise.
- */
-static bool chppProcessPredefinedClientNotification(
- struct ChppAppState *context, uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- bool handleValid = true;
- bool dispatchResult = true;
-
- // No predefined services support these yet
- handleValid = false;
-
- UNUSED_VAR(context);
- UNUSED_VAR(len);
- UNUSED_VAR(rxHeader);
- UNUSED_VAR(dispatchResult);
-
- return handleValid;
-}
-
-/**
- * Processes a service notification that is determined to be for a predefined
- * CHPP client.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return False if handle is invalid. True otherwise.
- */
-static bool chppProcessPredefinedServiceNotification(
- struct ChppAppState *context, uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- bool handleValid = true;
- bool dispatchResult = true;
-
- // No predefined clients support these yet
- handleValid = false;
-
- UNUSED_VAR(context);
- UNUSED_VAR(len);
- UNUSED_VAR(rxHeader);
- UNUSED_VAR(dispatchResult);
-
- return handleValid;
-}
-
-/**
- * Verifies if the length of a Rx Datagram from the transport layer is
- * sufficient for the associated service.
- *
- * @param context Maintains status for each app layer instance.
- * @param rxHeader The pointer to the datagram RX header.
- * @param len Length of the datagram in bytes.
- *
- * @return true if length is ok.
- */
-static bool chppDatagramLenIsOk(struct ChppAppState *context,
- struct ChppAppHeader *rxHeader, size_t len) {
- size_t minLen = SIZE_MAX;
- uint8_t handle = rxHeader->handle;
-
- if (handle < CHPP_HANDLE_NEGOTIATED_RANGE_START) { // Predefined
- switch (handle) {
- case CHPP_HANDLE_NONE:
- minLen = sizeof_member(struct ChppAppHeader, handle);
- break;
-
- case CHPP_HANDLE_LOOPBACK:
- minLen = sizeof_member(struct ChppAppHeader, handle) +
- sizeof_member(struct ChppAppHeader, type);
- break;
-
- case CHPP_HANDLE_TIMESYNC:
- case CHPP_HANDLE_DISCOVERY:
- minLen = sizeof(struct ChppAppHeader);
- break;
-
- default:
- CHPP_LOGE("Invalid H#%" PRIu8, handle);
- }
-
- } else { // Negotiated
- enum ChppMessageType messageType =
- CHPP_APP_GET_MESSAGE_TYPE(rxHeader->type);
-
- switch (messageType) {
- case CHPP_MESSAGE_TYPE_CLIENT_REQUEST:
- case CHPP_MESSAGE_TYPE_CLIENT_NOTIFICATION: {
- const struct ChppService *service =
- chppServiceOfHandle(context, handle);
- if (service != NULL) {
- minLen = service->minLength;
- }
- break;
- }
- case CHPP_MESSAGE_TYPE_SERVICE_RESPONSE:
- case CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION: {
- const struct ChppClient *client = chppClientOfHandle(context, handle);
- if (client != NULL) {
- minLen = client->minLength;
- }
- break;
- }
- default: {
- break;
- }
- }
-
- if (minLen == SIZE_MAX) {
- CHPP_LOGE("Invalid type=%d or H#%" PRIu8, messageType, handle);
- }
- }
-
- if ((len < minLen) && (minLen != SIZE_MAX)) {
- CHPP_LOGE("Datagram len=%" PRIuSIZE " < %" PRIuSIZE " for H#%" PRIu8, len,
- minLen, handle);
- }
- return (len >= minLen) && (minLen != SIZE_MAX);
-}
-
-/**
- * Returns the dispatch function of a particular negotiated client/service
- * handle and message type. This shall be null if it is unsupported by the
- * service.
- *
- * @param context Maintains status for each app layer instance.
- * @param handle Handle number for the client/service.
- * @param type Message type.
- *
- * @return Pointer to a function that dispatches incoming datagrams for any
- * particular client/service.
- */
-ChppDispatchFunction *chppGetDispatchFunction(struct ChppAppState *context,
- uint8_t handle,
- enum ChppMessageType type) {
- // chppDatagramLenIsOk() has already confirmed that the handle # is valid.
- // Therefore, no additional checks are necessary for chppClientOfHandle(),
- // chppServiceOfHandle(), or chppClientServiceContextOfHandle().
-
- switch (CHPP_APP_GET_MESSAGE_TYPE(type)) {
- case CHPP_MESSAGE_TYPE_CLIENT_REQUEST: {
- return chppServiceOfHandle(context, handle)->requestDispatchFunctionPtr;
- break;
- }
- case CHPP_MESSAGE_TYPE_SERVICE_RESPONSE: {
- struct ChppClientState *clientState =
- (struct ChppClientState *)chppClientServiceContextOfHandle(
- context, handle, type);
- if (clientState->openState == CHPP_OPEN_STATE_CLOSED) {
- CHPP_LOGE("Rx service response but client closed");
- } else {
- return chppClientOfHandle(context, handle)->responseDispatchFunctionPtr;
- }
- break;
- }
- case CHPP_MESSAGE_TYPE_CLIENT_NOTIFICATION: {
- return chppServiceOfHandle(context, handle)
- ->notificationDispatchFunctionPtr;
- break;
- }
- case CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION: {
- struct ChppClientState *clientState =
- (struct ChppClientState *)chppClientServiceContextOfHandle(
- context, handle, type);
- if (clientState->openState == CHPP_OPEN_STATE_CLOSED) {
- CHPP_LOGE("Rx service notification but client closed");
- } else {
- return chppClientOfHandle(context, handle)
- ->notificationDispatchFunctionPtr;
- }
- break;
- }
- }
-
- return NULL;
-}
-
-/**
- * Returns the reset notification function pointer of a particular negotiated
- * client. The function pointer will be set to null by clients that do not need
- * or support a reset notification.
- *
- * @param context Maintains status for each app layer instance.
- * @param index Index of the registered client.
- *
- * @return Pointer to the reset notification function.
- */
-ChppNotifierFunction *chppGetClientResetNotifierFunction(
- struct ChppAppState *context, uint8_t index) {
- return context->registeredClients[index]->resetNotifierFunctionPtr;
-}
-
-/**
- * Returns the reset function pointer of a particular registered service. The
- * function pointer will be set to null by services that do not need or support
- * a reset notification.
- *
- * @param context Maintains status for each app layer instance.
- * @param index Index of the registered service.
- *
- * @return Pointer to the reset function.
- */
-ChppNotifierFunction *chppGetServiceResetNotifierFunction(
- struct ChppAppState *context, uint8_t index) {
- return context->registeredServices[index]->resetNotifierFunctionPtr;
-}
-
-/**
- * Returns a pointer to the ChppService struct of the service matched to a
- * negotiated handle. Returns null if a service doesn't exist for the handle.
- *
- * @param context Maintains status for each app layer instance.
- * @param handle Handle number.
- *
- * @return Pointer to the ChppService struct of a particular service handle.
- */
-static inline const struct ChppService *chppServiceOfHandle(
- struct ChppAppState *context, uint8_t handle) {
- uint8_t serviceIndex = CHPP_SERVICE_INDEX_OF_HANDLE(handle);
- if (serviceIndex < context->registeredServiceCount) {
- return context->registeredServices[serviceIndex];
- }
-
- return NULL;
-}
-
-/**
- * Returns a pointer to the ChppClient struct of the client matched to a
- * negotiated handle. Returns null if a client doesn't exist for the handle.
- *
- * @param context Maintains status for each app layer instance.
- * @param handle Handle number.
- *
- * @return Pointer to the ChppClient struct matched to a particular handle.
- */
-static inline const struct ChppClient *chppClientOfHandle(
- struct ChppAppState *context, uint8_t handle) {
- uint8_t serviceIndex = CHPP_SERVICE_INDEX_OF_HANDLE(handle);
- if (serviceIndex < context->discoveredServiceCount) {
- uint8_t clientIndex = context->clientIndexOfServiceIndex[serviceIndex];
- if (clientIndex < context->registeredClientCount) {
- return context->registeredClients[clientIndex];
- }
- }
-
- return NULL;
-}
-
-/**
- * Returns a pointer to the service struct of a particular negotiated service
- * handle.
- * It is up to the caller to ensure the handle number is valid.
- *
- * @param context Maintains status for each app layer instance.
- * @param handle Handle number for the service.
- *
- * @return Pointer to the context struct of the service.
- */
-static inline void *chppServiceContextOfHandle(struct ChppAppState *context,
- uint8_t handle) {
- CHPP_DEBUG_ASSERT(CHPP_SERVICE_INDEX_OF_HANDLE(handle) <
- context->registeredServiceCount);
- return context
- ->registeredServiceContexts[CHPP_SERVICE_INDEX_OF_HANDLE(handle)];
-}
-
-/**
- * Returns a pointer to the client struct of a particular negotiated client
- * handle.
- * It is up to the caller to ensure the handle number is valid.
- *
- * @param context Maintains status for each app layer instance.
- * @param handle Handle number for the service.
- *
- * @return Pointer to the ChppService struct of the client.
- */
-static inline void *chppClientContextOfHandle(struct ChppAppState *context,
- uint8_t handle) {
- CHPP_DEBUG_ASSERT(CHPP_SERVICE_INDEX_OF_HANDLE(handle) <
- context->registeredClientCount);
- return context
- ->registeredClientContexts[context->clientIndexOfServiceIndex
- [CHPP_SERVICE_INDEX_OF_HANDLE(handle)]];
-}
-
-/**
- * Returns a pointer to the client/service struct of a particular negotiated
- * client/service handle.
- * It is up to the caller to ensure the handle number is valid.
- *
- * @param appContext Maintains status for each app layer instance.
- * @param handle Handle number for the service.
- * @param type Message type (indicates if this is for a client or service).
- *
- * @return Pointer to the client/service struct of the service handle.
- */
-static void *chppClientServiceContextOfHandle(struct ChppAppState *appContext,
- uint8_t handle,
- enum ChppMessageType type) {
- switch (CHPP_APP_GET_MESSAGE_TYPE(type)) {
- case CHPP_MESSAGE_TYPE_CLIENT_REQUEST:
- case CHPP_MESSAGE_TYPE_CLIENT_NOTIFICATION: {
- return chppServiceContextOfHandle(appContext, handle);
- break;
- }
- case CHPP_MESSAGE_TYPE_SERVICE_RESPONSE:
- case CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION: {
- return chppClientContextOfHandle(appContext, handle);
- break;
- }
- default: {
- CHPP_LOGE("Unknown type=0x%" PRIx8 " (H#%" PRIu8 ")", type, handle);
- return NULL;
- }
- }
-}
-
-/**
- * Processes a received datagram that is determined to be for a predefined CHPP
- * service. Responds with an error if unsuccessful.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppProcessPredefinedHandleDatagram(struct ChppAppState *context,
- uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- bool success = true;
-
- switch (CHPP_APP_GET_MESSAGE_TYPE(rxHeader->type)) {
- case CHPP_MESSAGE_TYPE_CLIENT_REQUEST: {
- success = chppProcessPredefinedClientRequest(context, buf, len);
- break;
- }
- case CHPP_MESSAGE_TYPE_CLIENT_NOTIFICATION: {
- success = chppProcessPredefinedClientNotification(context, buf, len);
- break;
- }
- case CHPP_MESSAGE_TYPE_SERVICE_RESPONSE: {
- success = chppProcessPredefinedServiceResponse(context, buf, len);
- break;
- }
- case CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION: {
- success = chppProcessPredefinedServiceNotification(context, buf, len);
- break;
- }
- default: {
- success = false;
- }
- }
-
- if (success == false) {
- CHPP_LOGE("H#%" PRIu8 " undefined msg type=0x%" PRIx8 " (len=%" PRIuSIZE
- ", ID=%" PRIu8 ")",
- rxHeader->handle, rxHeader->type, len, rxHeader->transaction);
- chppEnqueueTxErrorDatagram(context->transportContext,
- CHPP_TRANSPORT_ERROR_APPLAYER);
- }
-}
-
-/**
- * Processes a received datagram that is determined to be for a negotiated CHPP
- * client or service. Responds with an error if unsuccessful.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppProcessNegotiatedHandleDatagram(struct ChppAppState *context,
- uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- enum ChppMessageType messageType = CHPP_APP_GET_MESSAGE_TYPE(rxHeader->type);
-
- void *clientServiceContext =
- chppClientServiceContextOfHandle(context, rxHeader->handle, messageType);
- if (clientServiceContext == NULL) {
- CHPP_LOGE("H#%" PRIu8 " missing ctx (msg=0x%" PRIx8 " len=%" PRIuSIZE
- ", ID=%" PRIu8 ")",
- rxHeader->handle, rxHeader->type, len, rxHeader->transaction);
- chppEnqueueTxErrorDatagram(context->transportContext,
- CHPP_TRANSPORT_ERROR_APPLAYER);
- CHPP_DEBUG_ASSERT(false);
-
- } else {
- ChppDispatchFunction *dispatchFunc =
- chppGetDispatchFunction(context, rxHeader->handle, messageType);
- if (dispatchFunc == NULL) {
- CHPP_LOGE("H#%" PRIu8 " unsupported msg=0x%" PRIx8 " (len=%" PRIuSIZE
- ", ID=%" PRIu8 ")",
- rxHeader->handle, rxHeader->type, len, rxHeader->transaction);
- chppEnqueueTxErrorDatagram(context->transportContext,
- CHPP_TRANSPORT_ERROR_APPLAYER);
-
- } else {
- // All good. Dispatch datagram and possibly notify a waiting client
-
- enum ChppAppErrorCode error =
- dispatchFunc(clientServiceContext, buf, len);
- if (error != CHPP_APP_ERROR_NONE) {
- CHPP_LOGE("RX dispatch err=0x%" PRIx16 " H#%" PRIu8 " type=0x%" PRIx8
- " ID=%" PRIu8 " cmd=0x%" PRIx16 " len=%" PRIuSIZE,
- error, rxHeader->handle, rxHeader->type,
- rxHeader->transaction, rxHeader->command, len);
-
- // Only client requests require a dispatch failure response.
- if (messageType == CHPP_MESSAGE_TYPE_CLIENT_REQUEST) {
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(rxHeader, struct ChppAppHeader);
- if (response == NULL) {
- CHPP_LOG_OOM();
- } else {
- response->error = (uint8_t)error;
- chppEnqueueTxDatagramOrFail(context->transportContext, response,
- sizeof(*response));
- }
- }
- } else if (messageType == CHPP_MESSAGE_TYPE_SERVICE_RESPONSE) {
- // Datagram is a service response. Check for synchronous operation and
- // notify waiting client if needed.
-
- struct ChppClientState *clientState =
- (struct ChppClientState *)clientServiceContext;
- chppMutexLock(&clientState->responseMutex);
- clientState->responseReady = true;
- CHPP_LOGD(
- "Finished dispatching a service response. Notifying a potential "
- "synchronous client");
- chppConditionVariableSignal(&clientState->responseCondVar);
- chppMutexUnlock(&clientState->responseMutex);
- }
- }
- }
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppAppInit(struct ChppAppState *appContext,
- struct ChppTransportState *transportContext) {
- // Default initialize all service/clients
- struct ChppClientServiceSet set;
- memset(&set, 0xff, sizeof(set)); // set all bits to 1
-
- chppAppInitWithClientServiceSet(appContext, transportContext, set);
-}
-
-void chppAppInitWithClientServiceSet(
- struct ChppAppState *appContext,
- struct ChppTransportState *transportContext,
- struct ChppClientServiceSet clientServiceSet) {
- CHPP_NOT_NULL(appContext);
-
- CHPP_LOGD("App Init");
-
- memset(appContext, 0, sizeof(*appContext));
-
- appContext->clientServiceSet = clientServiceSet;
- appContext->transportContext = transportContext;
- appContext->nextRequestTimeoutNs = CHPP_TIME_MAX;
-
- chppPalSystemApiInit(appContext);
-
-#ifdef CHPP_SERVICE_ENABLED
- chppRegisterCommonServices(appContext);
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED
- chppRegisterCommonClients(appContext);
- chppInitBasicClients(appContext);
-#endif
-}
-
-void chppAppDeinit(struct ChppAppState *appContext) {
- CHPP_LOGD("App deinit");
-
-#ifdef CHPP_CLIENT_ENABLED
- chppDeinitMatchedClients(appContext);
- chppDeinitBasicClients(appContext);
- chppDeregisterCommonClients(appContext);
-#endif
-
-#ifdef CHPP_SERVICE_ENABLED
- chppDeregisterCommonServices(appContext);
-#endif
-
- chppPalSystemApiDeinit(appContext);
-}
-
-void chppAppProcessRxDatagram(struct ChppAppState *context, uint8_t *buf,
- size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
-
- if (len == 0) {
- CHPP_LOGE("App rx w/ len 0");
- CHPP_DEBUG_ASSERT(false);
-
- } else if (len < sizeof(struct ChppAppHeader)) {
- uint8_t *handle = (uint8_t *)buf;
- CHPP_LOGD("RX datagram len=%" PRIuSIZE " H#%" PRIu8, len, *handle);
-
- } else if (rxHeader->error != CHPP_APP_ERROR_NONE) {
- CHPP_LOGE("RX datagram len=%" PRIuSIZE " H#%" PRIu8 " type=0x%" PRIx8
- " ID=%" PRIu8 " ERR=%" PRIu8 " cmd=0x%" PRIx16,
- len, rxHeader->handle, rxHeader->type, rxHeader->transaction,
- rxHeader->error, rxHeader->command);
- } else {
- CHPP_LOGD("RX datagram len=%" PRIuSIZE " H#%" PRIu8 " type=0x%" PRIx8
- " ID=%" PRIu8 " err=%" PRIu8 " cmd=0x%" PRIx16,
- len, rxHeader->handle, rxHeader->type, rxHeader->transaction,
- rxHeader->error, rxHeader->command);
- }
-
- if (!chppDatagramLenIsOk(context, rxHeader, len)) {
- chppEnqueueTxErrorDatagram(context->transportContext,
- CHPP_TRANSPORT_ERROR_APPLAYER);
-
- } else {
- if (rxHeader->handle == CHPP_HANDLE_NONE) {
- chppDispatchNonHandle(context, buf, len);
-
- } else if (rxHeader->handle < CHPP_HANDLE_NEGOTIATED_RANGE_START) {
- chppProcessPredefinedHandleDatagram(context, buf, len);
-
- } else {
- chppProcessNegotiatedHandleDatagram(context, buf, len);
- }
- }
-
- chppDatagramProcessDoneCb(context->transportContext, buf);
-}
-
-void chppAppProcessReset(struct ChppAppState *context) {
-#ifdef CHPP_CLIENT_ENABLED_DISCOVERY
- if (!context->isDiscoveryComplete) {
- chppInitiateDiscovery(context);
-
- } else {
- // Notify matched clients that a reset happened
- for (uint8_t i = 0; i < context->discoveredServiceCount; i++) {
- uint8_t clientIndex = context->clientIndexOfServiceIndex[i];
- if (clientIndex != CHPP_CLIENT_INDEX_NONE) {
- // Discovered service has a matched client
- ChppNotifierFunction *ResetNotifierFunction =
- chppGetClientResetNotifierFunction(context, clientIndex);
-
- CHPP_LOGD("Client #%" PRIu8 " (H#%d) reset notifier found=%d",
- clientIndex, CHPP_SERVICE_HANDLE_OF_INDEX(i),
- (ResetNotifierFunction != NULL));
-
- if (ResetNotifierFunction != NULL) {
- ResetNotifierFunction(context->registeredClientContexts[clientIndex]);
- }
- }
- }
- }
-#endif // CHPP_CLIENT_ENABLED_DISCOVERY
-
- // Notify registered services that a reset happened
- for (uint8_t i = 0; i < context->registeredServiceCount; i++) {
- ChppNotifierFunction *ResetNotifierFunction =
- chppGetServiceResetNotifierFunction(context, i);
-
- CHPP_LOGD("Service #%" PRIu8 " (H#%d) reset notifier found=%d", i,
- CHPP_SERVICE_HANDLE_OF_INDEX(i), (ResetNotifierFunction != NULL));
-
- if (ResetNotifierFunction != NULL) {
- ResetNotifierFunction(context->registeredServiceContexts[i]);
- }
- }
-
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
- // Reinitialize time offset
- chppTimesyncClientReset(context);
-#endif
-}
-
-void chppUuidToStr(const uint8_t uuid[CHPP_SERVICE_UUID_LEN],
- char strOut[CHPP_SERVICE_UUID_STRING_LEN]) {
- snprintf(
- strOut, CHPP_SERVICE_UUID_STRING_LEN,
- "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
- uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
- uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14],
- uuid[15]);
-}
-
-uint8_t chppAppErrorToChreError(uint8_t chppError) {
- switch (chppError) {
- case CHPP_APP_ERROR_NONE:
- case CHPP_APP_ERROR_INVALID_ARG:
- case CHPP_APP_ERROR_BUSY:
- case CHPP_APP_ERROR_OOM:
- case CHPP_APP_ERROR_UNSUPPORTED:
- case CHPP_APP_ERROR_TIMEOUT:
- case CHPP_APP_ERROR_DISABLED:
- case CHPP_APP_ERROR_RATELIMITED: {
- // CHRE and CHPP error values are identical in these cases
- return chppError;
- }
- default: {
- return CHRE_ERROR;
- }
- }
-}
diff --git a/chpp/clients.c b/chpp/clients.c
deleted file mode 100644
index c8b564be..00000000
--- a/chpp/clients.c
+++ /dev/null
@@ -1,598 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/clients.h"
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#ifdef CHPP_CLIENT_ENABLED_DISCOVERY
-#include "chpp/clients/discovery.h"
-#endif
-#ifdef CHPP_CLIENT_ENABLED_GNSS
-#include "chpp/clients/gnss.h"
-#endif
-#ifdef CHPP_CLIENT_ENABLED_LOOPBACK
-#include "chpp/clients/loopback.h"
-#endif
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
-#include "chpp/clients/timesync.h"
-#endif
-#ifdef CHPP_CLIENT_ENABLED_WIFI
-#include "chpp/clients/wifi.h"
-#endif
-#ifdef CHPP_CLIENT_ENABLED_WWAN
-#include "chpp/clients/wwan.h"
-#endif
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chpp/time.h"
-#include "chpp/transport.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static bool chppIsClientApiReady(struct ChppClientState *clientState);
-ChppClientDeinitFunction *chppGetClientDeinitFunction(
- struct ChppAppState *context, uint8_t index);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Determines whether a client is ready to accept commands via its API (i.e. is
- * initialized and opened). If the client is in the process of reopening, it
- * will wait for the client to reopen.
- *
- * @param clientState State of the client sending the client request.
- *
- * @return Indicates whetherthe client is ready.
- */
-static bool chppIsClientApiReady(struct ChppClientState *clientState) {
- bool result = false;
-
- if (clientState->initialized) {
- switch (clientState->openState) {
- case (CHPP_OPEN_STATE_CLOSED):
- case (CHPP_OPEN_STATE_WAITING_TO_OPEN): {
- // result remains false
- break;
- }
-
- case (CHPP_OPEN_STATE_OPENED): {
- result = true;
- break;
- }
-
- case (CHPP_OPEN_STATE_OPENING): {
- // Allow the open request to go through
- clientState->openState = CHPP_OPEN_STATE_WAITING_TO_OPEN;
- result = true;
- break;
- }
- }
- }
-
- if (!result) {
- CHPP_LOGE("Client not ready (everInit=%d, init=%d, open=%" PRIu8 ")",
- clientState->everInitialized, clientState->initialized,
- clientState->openState);
- }
- return result;
-}
-
-/**
- * Returns the deinitialization function pointer of a particular negotiated
- * client.
- *
- * @param context Maintains status for each app layer instance.
- * @param index Index of the registered client.
- *
- * @return Pointer to the match notification function.
- */
-ChppClientDeinitFunction *chppGetClientDeinitFunction(
- struct ChppAppState *context, uint8_t index) {
- return context->registeredClients[index]->deinitFunctionPtr;
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppRegisterCommonClients(struct ChppAppState *context) {
- UNUSED_VAR(context);
- CHPP_LOGD("Registering Clients");
-
-#ifdef CHPP_CLIENT_ENABLED_WWAN
- if (context->clientServiceSet.wwanClient) {
- chppRegisterWwanClient(context);
- }
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_WIFI
- if (context->clientServiceSet.wifiClient) {
- chppRegisterWifiClient(context);
- }
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_GNSS
- if (context->clientServiceSet.gnssClient) {
- chppRegisterGnssClient(context);
- }
-#endif
-}
-
-void chppDeregisterCommonClients(struct ChppAppState *context) {
- UNUSED_VAR(context);
- CHPP_LOGD("Deregistering Clients");
-
-#ifdef CHPP_CLIENT_ENABLED_WWAN
- if (context->clientServiceSet.wwanClient) {
- chppDeregisterWwanClient(context);
- }
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_WIFI
- if (context->clientServiceSet.wifiClient) {
- chppDeregisterWifiClient(context);
- }
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_GNSS
- if (context->clientServiceSet.gnssClient) {
- chppDeregisterGnssClient(context);
- }
-#endif
-}
-
-void chppRegisterClient(struct ChppAppState *appContext, void *clientContext,
- struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRStates,
- const struct ChppClient *newClient) {
- CHPP_NOT_NULL(newClient);
-
- if (appContext->registeredClientCount >= CHPP_MAX_REGISTERED_CLIENTS) {
- CHPP_LOGE("Max clients registered: %" PRIu8,
- appContext->registeredClientCount);
-
- } else {
- clientState->appContext = appContext;
- clientState->rRStates = rRStates;
- clientState->index = appContext->registeredClientCount;
-
- appContext->registeredClientContexts[appContext->registeredClientCount] =
- clientContext;
- appContext->registeredClientStates[appContext->registeredClientCount] =
- clientState;
- appContext->registeredClients[appContext->registeredClientCount] =
- newClient;
-
- char uuidText[CHPP_SERVICE_UUID_STRING_LEN];
- chppUuidToStr(newClient->descriptor.uuid, uuidText);
- CHPP_LOGD("Client # %" PRIu8 " UUID=%s, version=%" PRIu8 ".%" PRIu8
- ".%" PRIu16 ", min_len=%" PRIuSIZE,
- appContext->registeredClientCount, uuidText,
- newClient->descriptor.version.major,
- newClient->descriptor.version.minor,
- newClient->descriptor.version.patch, newClient->minLength);
-
- appContext->registeredClientCount++;
- }
-}
-
-void chppInitBasicClients(struct ChppAppState *context) {
- UNUSED_VAR(context);
- CHPP_LOGD("Initializing basic clients");
-
-#ifdef CHPP_CLIENT_ENABLED_LOOPBACK
- if (context->clientServiceSet.loopbackClient) {
- chppLoopbackClientInit(context);
- }
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
- chppTimesyncClientInit(context);
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_DISCOVERY
- chppDiscoveryInit(context);
-#endif
-}
-
-void chppClientInit(struct ChppClientState *clientState, uint8_t handle) {
- CHPP_ASSERT_LOG(!clientState->initialized,
- "Client H#%" PRIu8 " already initialized", handle);
-
- if (!clientState->everInitialized) {
- clientState->handle = handle;
- chppMutexInit(&clientState->responseMutex);
- chppConditionVariableInit(&clientState->responseCondVar);
- clientState->everInitialized = true;
- }
-
- clientState->initialized = true;
-}
-
-void chppClientDeinit(struct ChppClientState *clientState) {
- CHPP_ASSERT_LOG(clientState->initialized,
- "Client H#%" PRIu8 " already deinitialized",
- clientState->handle);
-
- clientState->initialized = false;
-}
-
-void chppDeinitBasicClients(struct ChppAppState *context) {
- UNUSED_VAR(context);
- CHPP_LOGD("Deinitializing basic clients");
-
-#ifdef CHPP_CLIENT_ENABLED_LOOPBACK
- if (context->clientServiceSet.loopbackClient) {
- chppLoopbackClientDeinit(context);
- }
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
- chppTimesyncClientDeinit(context);
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_DISCOVERY
- chppDiscoveryDeinit(context);
-#endif
-}
-
-void chppDeinitMatchedClients(struct ChppAppState *context) {
- CHPP_LOGD("Deinitializing matched clients");
-
- for (uint8_t i = 0; i < context->discoveredServiceCount; i++) {
- uint8_t clientIndex = context->clientIndexOfServiceIndex[i];
- if (clientIndex != CHPP_CLIENT_INDEX_NONE) {
- // Discovered service has a matched client
- ChppClientDeinitFunction *clientDeinitFunction =
- chppGetClientDeinitFunction(context, clientIndex);
-
- CHPP_LOGD("Client #%" PRIu8 " (H#%d) deinit fp found=%d", clientIndex,
- CHPP_SERVICE_HANDLE_OF_INDEX(i),
- (clientDeinitFunction != NULL));
-
- if (clientDeinitFunction != NULL) {
- clientDeinitFunction(context->registeredClientContexts[clientIndex]);
- }
- }
- }
-}
-
-struct ChppAppHeader *chppAllocClientRequest(
- struct ChppClientState *clientState, size_t len) {
- CHPP_ASSERT(len >= CHPP_APP_MIN_LEN_HEADER_WITH_TRANSACTION);
-
- struct ChppAppHeader *result = chppMalloc(len);
- if (result != NULL) {
- result->handle = clientState->handle;
- result->type = CHPP_MESSAGE_TYPE_CLIENT_REQUEST;
- result->transaction = clientState->transaction;
- result->error = CHPP_APP_ERROR_NONE;
- result->command = CHPP_APP_COMMAND_NONE;
-
- clientState->transaction++;
- }
- return result;
-}
-
-struct ChppAppHeader *chppAllocClientRequestCommand(
- struct ChppClientState *clientState, uint16_t command) {
- struct ChppAppHeader *result =
- chppAllocClientRequest(clientState, sizeof(struct ChppAppHeader));
-
- if (result != NULL) {
- result->command = command;
- }
- return result;
-}
-
-void chppClientTimestampRequest(struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState,
- struct ChppAppHeader *requestHeader,
- uint64_t timeoutNs) {
- if (rRState->requestState == CHPP_REQUEST_STATE_REQUEST_SENT) {
- CHPP_LOGE("Dupe req ID=%" PRIu8 " existing ID=%" PRIu8 " from t=%" PRIu64,
- requestHeader->transaction, rRState->transaction,
- rRState->requestTimeNs / CHPP_NSEC_PER_MSEC);
-
- // Clear a possible pending timeout from the previous request
- rRState->responseTimeNs = CHPP_TIME_MAX;
- chppClientRecalculateNextTimeout(clientState->appContext);
- }
-
- rRState->requestTimeNs = chppGetCurrentTimeNs();
- rRState->requestState = CHPP_REQUEST_STATE_REQUEST_SENT;
- rRState->transaction = requestHeader->transaction;
-
- if (timeoutNs == CHPP_CLIENT_REQUEST_TIMEOUT_INFINITE) {
- rRState->responseTimeNs = CHPP_TIME_MAX;
-
- } else {
- rRState->responseTimeNs = timeoutNs + rRState->requestTimeNs;
-
- clientState->appContext->nextRequestTimeoutNs = MIN(
- clientState->appContext->nextRequestTimeoutNs, rRState->responseTimeNs);
- }
-
- CHPP_LOGD("Timestamp req ID=%" PRIu8 " at t=%" PRIu64 " timeout=%" PRIu64
- " (requested=%" PRIu64 "), next timeout=%" PRIu64,
- rRState->transaction, rRState->requestTimeNs / CHPP_NSEC_PER_MSEC,
- rRState->responseTimeNs / CHPP_NSEC_PER_MSEC,
- timeoutNs / CHPP_NSEC_PER_MSEC,
- clientState->appContext->nextRequestTimeoutNs / CHPP_NSEC_PER_MSEC);
-}
-
-bool chppClientTimestampResponse(struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState,
- const struct ChppAppHeader *responseHeader) {
- bool success = false;
- uint64_t responseTime = chppGetCurrentTimeNs();
-
- switch (rRState->requestState) {
- case CHPP_REQUEST_STATE_NONE: {
- CHPP_LOGE("Resp with no req t=%" PRIu64,
- responseTime / CHPP_NSEC_PER_MSEC);
- break;
- }
-
- case CHPP_REQUEST_STATE_RESPONSE_RCV: {
- CHPP_LOGE("Extra resp at t=%" PRIu64 " for req t=%" PRIu64,
- responseTime / CHPP_NSEC_PER_MSEC,
- rRState->requestTimeNs / CHPP_NSEC_PER_MSEC);
- break;
- }
-
- case CHPP_REQUEST_STATE_RESPONSE_TIMEOUT: {
- CHPP_LOGE("Late resp at t=%" PRIu64 " for req t=%" PRIu64,
- responseTime / CHPP_NSEC_PER_MSEC,
- rRState->requestTimeNs / CHPP_NSEC_PER_MSEC);
- break;
- }
-
- case CHPP_REQUEST_STATE_REQUEST_SENT: {
- if (responseHeader->transaction != rRState->transaction) {
- CHPP_LOGE("Invalid resp ID=%" PRIu8 " at t=%" PRIu64
- " expected=%" PRIu8,
- responseHeader->transaction,
- responseTime / CHPP_NSEC_PER_MSEC, rRState->transaction);
- } else {
- rRState->requestState = (responseTime > rRState->responseTimeNs)
- ? CHPP_REQUEST_STATE_RESPONSE_TIMEOUT
- : CHPP_REQUEST_STATE_RESPONSE_RCV;
- success = true;
-
- CHPP_LOGD(
- "Timestamp resp ID=%" PRIu8 " req t=%" PRIu64 " resp t=%" PRIu64
- " timeout t=%" PRIu64 " (RTT=%" PRIu64 ", timeout = %s)",
- rRState->transaction, rRState->requestTimeNs / CHPP_NSEC_PER_MSEC,
- responseTime / CHPP_NSEC_PER_MSEC,
- rRState->responseTimeNs / CHPP_NSEC_PER_MSEC,
- (responseTime - rRState->requestTimeNs) / CHPP_NSEC_PER_MSEC,
- (responseTime > rRState->responseTimeNs) ? "yes" : "no");
- }
- break;
- }
-
- default: {
- CHPP_DEBUG_ASSERT(false);
- }
- }
-
- if (success) {
- if (rRState->responseTimeNs ==
- clientState->appContext->nextRequestTimeoutNs) {
- // This was the next upcoming timeout
- chppClientRecalculateNextTimeout(clientState->appContext);
- }
- rRState->responseTimeNs = responseTime;
- }
- return success;
-}
-
-bool chppSendTimestampedRequestOrFail(struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState,
- void *buf, size_t len,
- uint64_t timeoutNs) {
- CHPP_ASSERT(len >= CHPP_APP_MIN_LEN_HEADER_WITH_TRANSACTION);
- if (!chppIsClientApiReady(clientState)) {
- CHPP_FREE_AND_NULLIFY(buf);
- return false;
- }
-
- chppClientTimestampRequest(clientState, rRState, buf, timeoutNs);
- clientState->responseReady = false;
-
- bool success = chppEnqueueTxDatagramOrFail(
- clientState->appContext->transportContext, buf, len);
-
- // Failure to enqueue a TX datagram means that a request was known to be not
- // transmitted. We explicitly set requestState to be in the NONE state, so
- // that unintended app layer timeouts do not occur.
- if (!success) {
- rRState->requestState = CHPP_REQUEST_STATE_NONE;
- }
-
- return success;
-}
-
-bool chppSendTimestampedRequestAndWait(struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState,
- void *buf, size_t len) {
- return chppSendTimestampedRequestAndWaitTimeout(
- clientState, rRState, buf, len, CHPP_CLIENT_REQUEST_TIMEOUT_DEFAULT);
-}
-
-bool chppSendTimestampedRequestAndWaitTimeout(
- struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState, void *buf, size_t len,
- uint64_t timeoutNs) {
- bool result = chppSendTimestampedRequestOrFail(
- clientState, rRState, buf, len, CHPP_CLIENT_REQUEST_TIMEOUT_INFINITE);
-
- if (result) {
- chppMutexLock(&clientState->responseMutex);
-
- while (result && !clientState->responseReady) {
- result = chppConditionVariableTimedWait(&clientState->responseCondVar,
- &clientState->responseMutex,
- timeoutNs);
- }
- if (!clientState->responseReady) {
- rRState->requestState = CHPP_REQUEST_STATE_RESPONSE_TIMEOUT;
- CHPP_LOGE("Response timeout after %" PRIu64 " ms",
- timeoutNs / CHPP_NSEC_PER_MSEC);
- result = false;
- }
-
- chppMutexUnlock(&clientState->responseMutex);
- }
-
- return result;
-}
-
-void chppClientPseudoOpen(struct ChppClientState *clientState) {
- clientState->pseudoOpen = true;
-}
-
-bool chppClientSendOpenRequest(struct ChppClientState *clientState,
- struct ChppRequestResponseState *openRRState,
- uint16_t openCommand, bool blocking) {
- bool result = false;
- uint8_t priorState = clientState->openState;
-
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
- chppTimesyncMeasureOffset(clientState->appContext);
-#endif
-
- struct ChppAppHeader *request =
- chppAllocClientRequestCommand(clientState, openCommand);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
-
- } else {
- clientState->openState = CHPP_OPEN_STATE_OPENING;
-
- if (blocking) {
- CHPP_LOGD("Opening service - blocking");
- result = chppSendTimestampedRequestAndWait(clientState, openRRState,
- request, sizeof(*request));
- } else {
- CHPP_LOGD("Opening service - non-blocking");
- result = chppSendTimestampedRequestOrFail(
- clientState, openRRState, request, sizeof(*request),
- CHPP_CLIENT_REQUEST_TIMEOUT_INFINITE);
- }
-
- if (!result) {
- CHPP_LOGE("Service open fail from state=%" PRIu8 " psudo=%d blocking=%d",
- priorState, clientState->pseudoOpen, blocking);
- clientState->openState = CHPP_OPEN_STATE_CLOSED;
-
- } else if (blocking) {
- result = (clientState->openState == CHPP_OPEN_STATE_OPENED);
- }
- }
-
- return result;
-}
-
-void chppClientProcessOpenResponse(struct ChppClientState *clientState,
- uint8_t *buf, size_t len) {
- UNUSED_VAR(len); // Necessary depending on assert macro below
- // Assert condition already guaranteed by chppAppProcessRxDatagram() but
- // checking again since this is a public function
- CHPP_ASSERT(len >= sizeof(struct ChppAppHeader));
-
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- if (rxHeader->error != CHPP_APP_ERROR_NONE) {
- CHPP_LOGE("Service open failed at service");
- clientState->openState = CHPP_OPEN_STATE_CLOSED;
- } else {
- CHPP_LOGI("Service open succeeded at service");
- clientState->openState = CHPP_OPEN_STATE_OPENED;
- }
-}
-
-void chppClientRecalculateNextTimeout(struct ChppAppState *context) {
- context->nextRequestTimeoutNs = CHPP_TIME_MAX;
-
- for (uint8_t clientIdx = 0; clientIdx < context->registeredClientCount;
- clientIdx++) {
- for (uint16_t cmdIdx = 0;
- cmdIdx < context->registeredClients[clientIdx]->rRStateCount;
- cmdIdx++) {
- struct ChppRequestResponseState *rRState =
- &context->registeredClientStates[clientIdx]->rRStates[cmdIdx];
-
- if (rRState->requestState == CHPP_REQUEST_STATE_REQUEST_SENT) {
- context->nextRequestTimeoutNs =
- MIN(context->nextRequestTimeoutNs, rRState->responseTimeNs);
- }
- }
- }
-
- CHPP_LOGD("nextReqTimeout=%" PRIu64,
- context->nextRequestTimeoutNs / CHPP_NSEC_PER_MSEC);
-}
-
-void chppClientCloseOpenRequests(struct ChppClientState *clientState,
- const struct ChppClient *client,
- bool clearOnly) {
- bool recalcNeeded = false;
-
- for (uint16_t cmdIdx = 0; cmdIdx < client->rRStateCount; cmdIdx++) {
- if (clientState->rRStates[cmdIdx].requestState ==
- CHPP_REQUEST_STATE_REQUEST_SENT) {
- recalcNeeded = true;
-
- CHPP_LOGE("Closing open req #%" PRIu16 " clear %d", cmdIdx, clearOnly);
-
- if (clearOnly) {
- clientState->rRStates[cmdIdx].requestState =
- CHPP_REQUEST_STATE_RESPONSE_TIMEOUT;
- } else {
- struct ChppAppHeader *response =
- chppMalloc(sizeof(struct ChppAppHeader));
- if (response == NULL) {
- CHPP_LOG_OOM();
- } else {
- response->handle = clientState->handle;
- response->type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
- response->transaction = clientState->rRStates[cmdIdx].transaction;
- response->error = CHPP_APP_ERROR_TIMEOUT;
- response->command = cmdIdx;
-
- chppAppProcessRxDatagram(clientState->appContext, (uint8_t *)response,
- sizeof(struct ChppAppHeader));
- }
- }
- }
- }
-
- if (recalcNeeded) {
- chppClientRecalculateNextTimeout(clientState->appContext);
- }
-}
diff --git a/chpp/clients/discovery.c b/chpp/clients/discovery.c
deleted file mode 100644
index c8fb7703..00000000
--- a/chpp/clients/discovery.c
+++ /dev/null
@@ -1,340 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/clients/discovery.h"
-
-#include <inttypes.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "chpp/app.h"
-#include "chpp/common/discovery.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chpp/transport.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static inline bool chppIsClientCompatibleWithService(
- const struct ChppClientDescriptor *client,
- const struct ChppServiceDescriptor *service);
-static uint8_t chppFindMatchingClient(
- struct ChppAppState *context, const struct ChppServiceDescriptor *service);
-static void chppDiscoveryProcessDiscoverAll(struct ChppAppState *context,
- const uint8_t *buf, size_t len);
-ChppNotifierFunction *chppGetClientMatchNotifierFunction(
- struct ChppAppState *context, uint8_t index);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Determines if a client is compatible with a service. Compatibility
- * requirements are:
- * 1. UUIDs must match
- * 2. Major version numbers must match
- *
- * @param client ChppClientDescriptor of client.
- * @param service ChppServiceDescriptor of service.
- *
- * @param return True if compatible.
- */
-static inline bool chppIsClientCompatibleWithService(
- const struct ChppClientDescriptor *client,
- const struct ChppServiceDescriptor *service) {
- return (memcmp(client->uuid, service->uuid, CHPP_SERVICE_UUID_LEN) == 0 &&
- client->version.major == service->version.major);
-}
-
-/**
- * Attempts to match a registered client to a (discovered) service, responding
- * with either the client index or CHPP_CLIENT_INDEX_NONE if it fails.
- *
- * @param context Maintains status for each app layer instance.
- * @param service ChppServiceDescriptor of service.
- *
- * @param return Index of client matching the service, or CHPP_CLIENT_INDEX_NONE
- * if there is none.
- */
-static uint8_t chppFindMatchingClient(
- struct ChppAppState *context, const struct ChppServiceDescriptor *service) {
- uint8_t result = CHPP_CLIENT_INDEX_NONE;
-
- for (uint8_t i = 0; i < context->registeredClientCount; i++) {
- if (chppIsClientCompatibleWithService(
- &context->registeredClients[i]->descriptor, service)) {
- result = i;
- break;
- }
- }
-
- return result;
-}
-
-/**
- * Processes the Discover All Services response
- * (CHPP_DISCOVERY_COMMAND_DISCOVER_ALL).
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input (request) datagram. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppDiscoveryProcessDiscoverAll(struct ChppAppState *context,
- const uint8_t *buf, size_t len) {
- if (context->isDiscoveryComplete) {
- CHPP_LOGE("Duplicate discovery response");
- return;
- }
-
- const struct ChppDiscoveryResponse *response =
- (const struct ChppDiscoveryResponse *)buf;
- size_t servicesLen = len - sizeof(struct ChppAppHeader);
- uint8_t serviceCount =
- (uint8_t)(servicesLen / sizeof(struct ChppServiceDescriptor));
-
- if (servicesLen != serviceCount * sizeof(struct ChppServiceDescriptor)) {
- // Incomplete service list
- CHPP_LOGE("Descriptor len=%" PRIuSIZE " doesn't match count=%" PRIu8
- " and size=%" PRIuSIZE,
- servicesLen, serviceCount, sizeof(struct ChppServiceDescriptor));
- CHPP_DEBUG_ASSERT(false);
- }
-
- if (serviceCount > CHPP_MAX_DISCOVERED_SERVICES) {
- CHPP_LOGE("Service count=%" PRIu8 " larger than max=%d", serviceCount,
- CHPP_MAX_DISCOVERED_SERVICES);
- CHPP_DEBUG_ASSERT(false);
- }
-
- CHPP_LOGI("Discovered %" PRIu8 " services", serviceCount);
-
- uint8_t matchedClients = 0;
- for (uint8_t i = 0; i < MIN(serviceCount, CHPP_MAX_DISCOVERED_SERVICES);
- i++) {
- // Update lookup table
- context->clientIndexOfServiceIndex[i] =
- chppFindMatchingClient(context, &response->services[i]);
-
- char uuidText[CHPP_SERVICE_UUID_STRING_LEN];
- chppUuidToStr(response->services[i].uuid, uuidText);
-
- if (context->clientIndexOfServiceIndex[i] == CHPP_CLIENT_INDEX_NONE) {
- CHPP_LOGE(
- "No matching client for service: %d"
- " name=%s, UUID=%s, version=%" PRIu8 ".%" PRIu8 ".%" PRIu16,
- CHPP_SERVICE_HANDLE_OF_INDEX(i), response->services[i].name, uuidText,
- response->services[i].version.major,
- response->services[i].version.minor,
- response->services[i].version.patch);
-
- } else {
- CHPP_LOGD(
- "Client # %" PRIu8
- " matched to service on handle %d"
- " with name=%s, UUID=%s. "
- "client version=%" PRIu8 ".%" PRIu8 ".%" PRIu16
- ", service version=%" PRIu8 ".%" PRIu8 ".%" PRIu16,
- context->clientIndexOfServiceIndex[i],
- CHPP_SERVICE_HANDLE_OF_INDEX(i), response->services[i].name, uuidText,
- context->registeredClients[context->clientIndexOfServiceIndex[i]]
- ->descriptor.version.major,
- context->registeredClients[context->clientIndexOfServiceIndex[i]]
- ->descriptor.version.minor,
- context->registeredClients[context->clientIndexOfServiceIndex[i]]
- ->descriptor.version.patch,
- response->services[i].version.major,
- response->services[i].version.minor,
- response->services[i].version.patch);
-
- // Initialize client
- uint8_t idx = context->clientIndexOfServiceIndex[i];
- if (context->registeredClients[idx]->initFunctionPtr(
- context->registeredClientContexts[idx],
- CHPP_SERVICE_HANDLE_OF_INDEX(i),
- response->services[i].version) == false) {
- CHPP_LOGE(
- "Client rejected init: client ver=%" PRIu8 ".%" PRIu8 ".%" PRIu16
- ", service ver=%" PRIu8 ".%" PRIu8 ".%" PRIu16,
- context->registeredClients[context->clientIndexOfServiceIndex[i]]
- ->descriptor.version.major,
- context->registeredClients[context->clientIndexOfServiceIndex[i]]
- ->descriptor.version.minor,
- context->registeredClients[context->clientIndexOfServiceIndex[i]]
- ->descriptor.version.patch,
- response->services[i].version.major,
- response->services[i].version.minor,
- response->services[i].version.patch);
- } else {
- matchedClients++;
- }
- }
- }
-
- CHPP_LOGD("Matched %" PRIu8 " out of %" PRIu8 " clients and %" PRIu8
- " services",
- matchedClients, context->registeredClientCount, serviceCount);
-
- // Notify any clients waiting on discovery completion
- chppMutexLock(&context->discoveryMutex);
- context->isDiscoveryComplete = true;
- context->matchedClientCount = matchedClients;
- context->discoveredServiceCount = serviceCount;
- chppConditionVariableSignal(&context->discoveryCv);
- chppMutexUnlock(&context->discoveryMutex);
-
- // Notify clients of match
- for (uint8_t i = 0; i < context->discoveredServiceCount; i++) {
- uint8_t clientIndex = context->clientIndexOfServiceIndex[i];
- if (clientIndex != CHPP_CLIENT_INDEX_NONE) {
- // Discovered service has a matched client
- ChppNotifierFunction *MatchNotifierFunction =
- chppGetClientMatchNotifierFunction(context, clientIndex);
-
- CHPP_LOGD("Client #%" PRIu8 " (H#%d) match notifier found=%d",
- clientIndex, CHPP_SERVICE_HANDLE_OF_INDEX(i),
- (MatchNotifierFunction != NULL));
-
- if (MatchNotifierFunction != NULL) {
- MatchNotifierFunction(context->registeredClientContexts[clientIndex]);
- }
- }
- }
-}
-
-/**
- * Returns the match notification function pointer of a particular negotiated
- * client. The function pointer will be set to null by clients that do not need
- * or support a match notification.
- *
- * @param context Maintains status for each app layer instance.
- * @param index Index of the registered client.
- *
- * @return Pointer to the match notification function.
- */
-ChppNotifierFunction *chppGetClientMatchNotifierFunction(
- struct ChppAppState *context, uint8_t index) {
- return context->registeredClients[index]->matchNotifierFunctionPtr;
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppDiscoveryInit(struct ChppAppState *context) {
- CHPP_ASSERT_LOG(!context->isDiscoveryClientInitialized,
- "Discovery client already initialized");
-
- CHPP_LOGD("Initializing CHPP discovery client");
-
- if (!context->isDiscoveryClientInitialized) {
- chppMutexInit(&context->discoveryMutex);
- chppConditionVariableInit(&context->discoveryCv);
- context->isDiscoveryClientInitialized = true;
- }
-
- context->matchedClientCount = 0;
- context->isDiscoveryComplete = false;
- context->isDiscoveryClientInitialized = true;
-}
-
-void chppDiscoveryDeinit(struct ChppAppState *context) {
- CHPP_ASSERT_LOG(context->isDiscoveryClientInitialized,
- "Discovery client already deinitialized");
-
- CHPP_LOGD("Deinitializing CHPP discovery client");
- context->isDiscoveryClientInitialized = false;
-}
-
-bool chppWaitForDiscoveryComplete(struct ChppAppState *context,
- uint64_t timeoutMs) {
- bool success = false;
-
- if (!context->isDiscoveryClientInitialized) {
- timeoutMs = 0;
- } else {
- success = true;
-
- chppMutexLock(&context->discoveryMutex);
- if (timeoutMs == 0) {
- success = context->isDiscoveryComplete;
- } else {
- while (success && !context->isDiscoveryComplete) {
- success = chppConditionVariableTimedWait(
- &context->discoveryCv, &context->discoveryMutex,
- timeoutMs * CHPP_NSEC_PER_MSEC);
- }
- }
- chppMutexUnlock(&context->discoveryMutex);
- }
-
- if (!success) {
- CHPP_LOGE("Discovery incomplete after %" PRIu64 " ms", timeoutMs);
- }
- return success;
-}
-
-bool chppDispatchDiscoveryServiceResponse(struct ChppAppState *context,
- const uint8_t *buf, size_t len) {
- const struct ChppAppHeader *rxHeader = (const struct ChppAppHeader *)buf;
- bool success = true;
-
- switch (rxHeader->command) {
- case CHPP_DISCOVERY_COMMAND_DISCOVER_ALL: {
- chppDiscoveryProcessDiscoverAll(context, buf, len);
- break;
- }
- default: {
- success = false;
- break;
- }
- }
- return success;
-}
-
-void chppInitiateDiscovery(struct ChppAppState *context) {
- if (context->isDiscoveryComplete) {
- CHPP_LOGE("Duplicate discovery init");
- return;
- }
-
- for (uint8_t i = 0; i < CHPP_MAX_DISCOVERED_SERVICES; i++) {
- context->clientIndexOfServiceIndex[i] = CHPP_CLIENT_INDEX_NONE;
- }
-
- struct ChppAppHeader *request = chppMalloc(sizeof(struct ChppAppHeader));
- request->handle = CHPP_HANDLE_DISCOVERY;
- request->type = CHPP_MESSAGE_TYPE_CLIENT_REQUEST;
- request->transaction = 0;
- request->error = CHPP_APP_ERROR_NONE;
- request->command = CHPP_DISCOVERY_COMMAND_DISCOVER_ALL;
-
- chppEnqueueTxDatagramOrFail(context->transportContext, request,
- sizeof(*request));
-}
-
-bool chppAreAllClientsMatched(struct ChppAppState *context) {
- bool success = false;
- chppMutexLock(&context->discoveryMutex);
- success = (context->isDiscoveryComplete) &&
- (context->registeredClientCount == context->matchedClientCount);
- chppMutexUnlock(&context->discoveryMutex);
- return success;
-}
diff --git a/chpp/clients/gnss.c b/chpp/clients/gnss.c
deleted file mode 100644
index b98a2db9..00000000
--- a/chpp/clients/gnss.c
+++ /dev/null
@@ -1,871 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/clients/gnss.h"
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-#include "chpp/clients/discovery.h"
-#include "chpp/common/gnss.h"
-#include "chpp/common/gnss_types.h"
-#include "chpp/common/standard_uuids.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chre/pal/gnss.h"
-#include "chre_api/chre/gnss.h"
-
-#ifndef CHPP_GNSS_DISCOVERY_TIMEOUT_MS
-#define CHPP_GNSS_DISCOVERY_TIMEOUT_MS CHPP_DISCOVERY_DEFAULT_TIMEOUT_MS
-#endif
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppDispatchGnssResponse(void *clientContext,
- uint8_t *buf, size_t len);
-static enum ChppAppErrorCode chppDispatchGnssNotification(void *clientContext,
- uint8_t *buf,
- size_t len);
-static bool chppGnssClientInit(void *clientContext, uint8_t handle,
- struct ChppVersion serviceVersion);
-static void chppGnssClientDeinit(void *clientContext);
-static void chppGnssClientNotifyReset(void *clientContext);
-static void chppGnssClientNotifyMatch(void *clientContext);
-
-/************************************************
- * Private Definitions
- ***********************************************/
-
-/**
- * Structure to maintain state for the GNSS client and its Request/Response
- * (RR) functionality.
- */
-struct ChppGnssClientState {
- struct ChppClientState client; // GNSS client state
- const struct chrePalGnssApi *api; // GNSS PAL API
-
- struct ChppRequestResponseState rRState[CHPP_GNSS_CLIENT_REQUEST_MAX + 1];
-
- uint32_t capabilities; // Cached GetCapabilities result
- bool requestStateResyncPending; // requestStateResync() is waiting to be
- // processed
-};
-
-// Note: This global definition of gGnssClientContext supports only one
-// instance of the CHPP GNSS client at a time.
-struct ChppGnssClientState gGnssClientContext;
-static const struct chrePalSystemApi *gSystemApi;
-static const struct chrePalGnssCallbacks *gCallbacks;
-
-/**
- * Configuration parameters for this client
- */
-static const struct ChppClient kGnssClientConfig = {
- .descriptor.uuid = CHPP_UUID_GNSS_STANDARD,
-
- // Version
- .descriptor.version.major = 1,
- .descriptor.version.minor = 0,
- .descriptor.version.patch = 0,
-
- // Notifies client if CHPP is reset
- .resetNotifierFunctionPtr = &chppGnssClientNotifyReset,
-
- // Notifies client if they are matched to a service
- .matchNotifierFunctionPtr = &chppGnssClientNotifyMatch,
-
- // Service response dispatch function pointer
- .responseDispatchFunctionPtr = &chppDispatchGnssResponse,
-
- // Service notification dispatch function pointer
- .notificationDispatchFunctionPtr = &chppDispatchGnssNotification,
-
- // Service response dispatch function pointer
- .initFunctionPtr = &chppGnssClientInit,
-
- // Service notification dispatch function pointer
- .deinitFunctionPtr = &chppGnssClientDeinit,
-
- // Number of request-response states in the rRStates array.
- .rRStateCount = ARRAY_SIZE(gGnssClientContext.rRState),
-
- // Min length is the entire header
- .minLength = sizeof(struct ChppAppHeader),
-};
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static bool chppGnssClientOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalGnssCallbacks *callbacks);
-static void chppGnssClientClose(void);
-static uint32_t chppGnssClientGetCapabilities(void);
-static bool chppGnssClientControlLocationSession(bool enable,
- uint32_t minIntervalMs,
- uint32_t minTimeToNextFixMs);
-static void chppGnssClientReleaseLocationEvent(
- struct chreGnssLocationEvent *event);
-static bool chppGnssClientControlMeasurementSession(bool enable,
- uint32_t minIntervalMs);
-static void chppGnssClientReleaseMeasurementDataEvent(
- struct chreGnssDataEvent *event);
-static bool chppGnssClientConfigurePassiveLocationListener(bool enable);
-
-static void chppGnssCloseResult(struct ChppGnssClientState *clientContext,
- uint8_t *buf, size_t len);
-static void chppGnssGetCapabilitiesResult(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len);
-static void chppGnssControlLocationSessionResult(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len);
-static void chppGnssControlMeasurementSessionResult(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len);
-static void chppGnssConfigurePassiveLocationListenerResult(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len);
-
-static void chppGnssStateResyncNotification(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len);
-static void chppGnssLocationResultNotification(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len);
-static void chppGnssMeasurementResultNotification(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Dispatches a service response from the transport layer that is determined to
- * be for the GNSS client.
- *
- * This function is called from the app layer using its function pointer given
- * during client registration.
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppDispatchGnssResponse(void *clientContext,
- uint8_t *buf,
- size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- struct ChppGnssClientState *gnssClientContext =
- (struct ChppGnssClientState *)clientContext;
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (rxHeader->command > CHPP_GNSS_CLIENT_REQUEST_MAX) {
- error = CHPP_APP_ERROR_INVALID_COMMAND;
-
- } else if (!chppClientTimestampResponse(
- &gnssClientContext->client,
- &gnssClientContext->rRState[rxHeader->command], rxHeader)) {
- error = CHPP_APP_ERROR_UNEXPECTED_RESPONSE;
-
- } else {
- switch (rxHeader->command) {
- case CHPP_GNSS_OPEN: {
- chppClientProcessOpenResponse(&gnssClientContext->client, buf, len);
- if (gnssClientContext->requestStateResyncPending) {
- gCallbacks->requestStateResync();
- gnssClientContext->requestStateResyncPending = false;
- }
- break;
- }
-
- case CHPP_GNSS_CLOSE: {
- chppGnssCloseResult(gnssClientContext, buf, len);
- break;
- }
-
- case CHPP_GNSS_GET_CAPABILITIES: {
- chppGnssGetCapabilitiesResult(gnssClientContext, buf, len);
- break;
- }
-
- case CHPP_GNSS_CONTROL_LOCATION_SESSION: {
- chppGnssControlLocationSessionResult(gnssClientContext, buf, len);
- break;
- }
-
- case CHPP_GNSS_CONTROL_MEASUREMENT_SESSION: {
- chppGnssControlMeasurementSessionResult(gnssClientContext, buf, len);
- break;
- }
-
- case CHPP_GNSS_CONFIGURE_PASSIVE_LOCATION_LISTENER: {
- chppGnssConfigurePassiveLocationListenerResult(gnssClientContext, buf,
- len);
- break;
- }
-
- default: {
- error = CHPP_APP_ERROR_INVALID_COMMAND;
- break;
- }
- }
- }
-
- return error;
-}
-
-/**
- * Dispatches a service notification from the transport layer that is determined
- * to be for the GNSS client.
- *
- * This function is called from the app layer using its function pointer given
- * during client registration.
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppDispatchGnssNotification(void *clientContext,
- uint8_t *buf,
- size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- struct ChppGnssClientState *gnssClientContext =
- (struct ChppGnssClientState *)clientContext;
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- switch (rxHeader->command) {
- case CHPP_GNSS_REQUEST_STATE_RESYNC_NOTIFICATION: {
- chppGnssStateResyncNotification(gnssClientContext, buf, len);
- break;
- }
-
- case CHPP_GNSS_LOCATION_RESULT_NOTIFICATION: {
- chppGnssLocationResultNotification(gnssClientContext, buf, len);
- break;
- }
-
- case CHPP_GNSS_MEASUREMENT_RESULT_NOTIFICATION: {
- chppGnssMeasurementResultNotification(gnssClientContext, buf, len);
- break;
- }
-
- default: {
- error = CHPP_APP_ERROR_INVALID_COMMAND;
- break;
- }
- }
-
- return error;
-}
-
-/**
- * Initializes the client and provides its handle number and the version of the
- * matched service when/if it the client is matched with a service during
- * discovery.
- *
- * @param clientContext Maintains status for each client instance.
- * @param handle Handle number for this client.
- * @param serviceVersion Version of the matched service.
- *
- * @return True if client is compatible and successfully initialized.
- */
-static bool chppGnssClientInit(void *clientContext, uint8_t handle,
- struct ChppVersion serviceVersion) {
- UNUSED_VAR(serviceVersion);
-
- struct ChppGnssClientState *gnssClientContext =
- (struct ChppGnssClientState *)clientContext;
- chppClientInit(&gnssClientContext->client, handle);
-
- return true;
-}
-
-/**
- * Deinitializes the client.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppGnssClientDeinit(void *clientContext) {
- struct ChppGnssClientState *gnssClientContext =
- (struct ChppGnssClientState *)clientContext;
- chppClientDeinit(&gnssClientContext->client);
-}
-
-/**
- * Notifies the client of an incoming reset.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppGnssClientNotifyReset(void *clientContext) {
- struct ChppGnssClientState *gnssClientContext =
- (struct ChppGnssClientState *)clientContext;
-
- chppClientCloseOpenRequests(&gnssClientContext->client, &kGnssClientConfig,
- false /* clearOnly */);
-
- if (gnssClientContext->client.openState != CHPP_OPEN_STATE_OPENED &&
- !gnssClientContext->client.pseudoOpen) {
- CHPP_LOGW("GNSS client reset but wasn't open");
- } else {
- CHPP_LOGI("GNSS client reopening from state=%" PRIu8,
- gnssClientContext->client.openState);
- gnssClientContext->requestStateResyncPending = true;
- chppClientSendOpenRequest(&gGnssClientContext.client,
- &gGnssClientContext.rRState[CHPP_GNSS_OPEN],
- CHPP_GNSS_OPEN,
- /*blocking=*/false);
- }
-}
-
-/**
- * Notifies the client of being matched to a service.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppGnssClientNotifyMatch(void *clientContext) {
- struct ChppGnssClientState *gnssClientContext =
- (struct ChppGnssClientState *)clientContext;
-
- if (gnssClientContext->client.pseudoOpen) {
- CHPP_LOGD("Pseudo-open GNSS client opening");
- chppClientSendOpenRequest(&gGnssClientContext.client,
- &gGnssClientContext.rRState[CHPP_GNSS_OPEN],
- CHPP_GNSS_OPEN,
- /*blocking=*/false);
- }
-}
-
-/**
- * Handles the service response for the close client request.
- *
- * This function is called from chppDispatchGnssResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppGnssCloseResult(struct ChppGnssClientState *clientContext,
- uint8_t *buf, size_t len) {
- // TODO
- UNUSED_VAR(clientContext);
- UNUSED_VAR(buf);
- UNUSED_VAR(len);
-}
-
-/**
- * Handles the service response for the get capabilities client request.
- *
- * This function is called from chppDispatchGnssResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppGnssGetCapabilitiesResult(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len) {
- if (len < sizeof(struct ChppGnssGetCapabilitiesResponse)) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- CHPP_LOGE("GetCapabilities resp. too short. err=%" PRIu8, rxHeader->error);
-
- } else {
- struct ChppGnssGetCapabilitiesParameters *result =
- &((struct ChppGnssGetCapabilitiesResponse *)buf)->params;
-
- CHPP_LOGD("chppGnssGetCapabilitiesResult received capabilities=0x%" PRIx32,
- result->capabilities);
-
-#ifdef CHPP_GNSS_DEFAULT_CAPABILITIES
- CHPP_ASSERT_LOG((result->capabilities == CHPP_GNSS_DEFAULT_CAPABILITIES),
- "Unexpected capability 0x%" PRIx32 " != 0x%" PRIx32,
- result->capabilities, CHPP_GNSS_DEFAULT_CAPABILITIES);
-#endif
-
- clientContext->capabilities = result->capabilities;
- }
-}
-
-/**
- * Handles the service response for the Control Location Session client request.
- *
- * This function is called from chppDispatchGnssResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppGnssControlLocationSessionResult(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
-
- if (len < sizeof(struct ChppGnssControlLocationSessionResponse)) {
- // Short response length indicates an error
-
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- CHPP_LOGE("ControlLocation resp. too short. err=%" PRIu8, rxHeader->error);
-
- if (rxHeader->error == CHPP_APP_ERROR_NONE) {
- rxHeader->error = CHPP_APP_ERROR_INVALID_LENGTH;
- }
- gCallbacks->locationStatusChangeCallback(
- false, chppAppErrorToChreError(rxHeader->error));
-
- } else {
- struct ChppGnssControlLocationSessionResponse *result =
- (struct ChppGnssControlLocationSessionResponse *)buf;
-
- CHPP_LOGD(
- "chppGnssControlLocationSessionResult received enable=%d, "
- "errorCode=%" PRIu8,
- result->enabled, result->errorCode);
-
- gCallbacks->locationStatusChangeCallback(result->enabled,
- result->errorCode);
- }
-}
-
-/**
- * Handles the service response for the Control Measurement Session client
- * request.
- *
- * This function is called from chppDispatchGnssResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppGnssControlMeasurementSessionResult(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
-
- if (len < sizeof(struct ChppGnssControlMeasurementSessionResponse)) {
- // Short response length indicates an error
-
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- CHPP_LOGE("Measurement resp. too short. err=%" PRIu8, rxHeader->error);
-
- if (rxHeader->error == CHPP_APP_ERROR_NONE) {
- rxHeader->error = CHPP_APP_ERROR_INVALID_LENGTH;
- }
- gCallbacks->measurementStatusChangeCallback(
- false, chppAppErrorToChreError(rxHeader->error));
-
- } else {
- struct ChppGnssControlMeasurementSessionResponse *result =
- (struct ChppGnssControlMeasurementSessionResponse *)buf;
-
- CHPP_LOGD(
- "chppGnssControlMeasurementSessionResult received enable=%d, "
- "errorCode=%" PRIu8,
- result->enabled, result->errorCode);
-
- gCallbacks->measurementStatusChangeCallback(result->enabled,
- result->errorCode);
- }
-}
-
-/**
- * Handles the service response for the Configure Passive Location Listener
- * client request.
- *
- * This function is called from chppDispatchGnssResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppGnssConfigurePassiveLocationListenerResult(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
- UNUSED_VAR(len);
-
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
-
- if (rxHeader->error != CHPP_APP_ERROR_NONE) {
- CHPP_LOGE("Passive scan failed at service err=%" PRIu8, rxHeader->error);
- CHPP_DEBUG_ASSERT(false);
-
- } else {
- CHPP_LOGD(
- "WiFi ConfigurePassiveLocationListener request accepted at service");
- }
-}
-
-/**
- * Handles the State Resync service notification.
- *
- * This function is called from chppDispatchGnssNotification().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppGnssStateResyncNotification(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(buf);
- UNUSED_VAR(len);
- if (clientContext->client.openState == CHPP_OPEN_STATE_WAITING_TO_OPEN) {
- // If the GNSS client is waiting for the open to proceed, the CHRE handler
- // for requestStateResync() may fail, so we set a flag to process it later
- // when the open has succeeded.
- clientContext->requestStateResyncPending = true;
- } else {
- gCallbacks->requestStateResync();
- clientContext->requestStateResyncPending = false;
- }
-}
-
-/**
- * Handles the Location Result service notification.
- *
- * This function is called from chppDispatchGnssNotification().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppGnssLocationResultNotification(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
- CHPP_LOGD("chppGnssLocationResultNotification received data len=%" PRIuSIZE,
- len);
-
- buf += sizeof(struct ChppAppHeader);
- len -= sizeof(struct ChppAppHeader);
-
- struct chreGnssLocationEvent *chre =
- chppGnssLocationEventToChre((struct ChppGnssLocationEvent *)buf, len);
-
- if (chre == NULL) {
- CHPP_LOGE("Location result conversion failed: len=%" PRIuSIZE, len);
- } else {
- gCallbacks->locationEventCallback(chre);
- }
-}
-
-/**
- * Handles the Measurement Result service notification.
- *
- * This function is called from chppDispatchGnssNotification().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppGnssMeasurementResultNotification(
- struct ChppGnssClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
- CHPP_LOGD(
- "chppGnssMeasurementResultNotification received data len=%" PRIuSIZE,
- len);
-
- buf += sizeof(struct ChppAppHeader);
- len -= sizeof(struct ChppAppHeader);
-
- struct chreGnssDataEvent *chre =
- chppGnssDataEventToChre((struct ChppGnssDataEvent *)buf, len);
-
- if (chre == NULL) {
- CHPP_LOGE("Measurement result conversion failed len=%" PRIuSIZE, len);
- } else {
- gCallbacks->measurementEventCallback(chre);
- }
-}
-
-/**
- * Initializes the GNSS client upon an open request from CHRE and responds
- * with the result.
- *
- * @param systemApi CHRE system function pointers.
- * @param callbacks CHRE entry points.
- *
- * @return True if successful. False otherwise.
- */
-static bool chppGnssClientOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalGnssCallbacks *callbacks) {
- CHPP_DEBUG_ASSERT(systemApi != NULL);
- CHPP_DEBUG_ASSERT(callbacks != NULL);
-
- bool result = false;
- gSystemApi = systemApi;
- gCallbacks = callbacks;
-
- CHPP_LOGD("GNSS client opening");
-
- if (chppWaitForDiscoveryComplete(gGnssClientContext.client.appContext,
- CHPP_GNSS_DISCOVERY_TIMEOUT_MS)) {
- result = chppClientSendOpenRequest(
- &gGnssClientContext.client, &gGnssClientContext.rRState[CHPP_GNSS_OPEN],
- CHPP_GNSS_OPEN,
- /*blocking=*/true);
- }
-
-#ifdef CHPP_GNSS_CLIENT_OPEN_ALWAYS_SUCCESS
- chppClientPseudoOpen(&gGnssClientContext.client);
- result = true;
-#endif
-
- return result;
-}
-
-/**
- * Deinitializes the GNSS client.
- */
-static void chppGnssClientClose(void) {
- // Remote
- struct ChppAppHeader *request = chppAllocClientRequestCommand(
- &gGnssClientContext.client, CHPP_GNSS_CLOSE);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else if (chppSendTimestampedRequestAndWait(
- &gGnssClientContext.client,
- &gGnssClientContext.rRState[CHPP_GNSS_CLOSE], request,
- sizeof(*request))) {
- gGnssClientContext.client.openState = CHPP_OPEN_STATE_CLOSED;
- gGnssClientContext.capabilities = CHRE_GNSS_CAPABILITIES_NONE;
- chppClientCloseOpenRequests(&gGnssClientContext.client, &kGnssClientConfig,
- true /* clearOnly */);
- }
-}
-
-/**
- * Retrieves a set of flags indicating the GNSS features supported by the
- * current implementation.
- *
- * @return Capabilities flags.
- */
-static uint32_t chppGnssClientGetCapabilities(void) {
-#ifdef CHPP_GNSS_DEFAULT_CAPABILITIES
- uint32_t capabilities = CHPP_GNSS_DEFAULT_CAPABILITIES;
-#else
- uint32_t capabilities = CHRE_GNSS_CAPABILITIES_NONE;
-#endif
-
- if (gGnssClientContext.capabilities != CHRE_GNSS_CAPABILITIES_NONE) {
- // Result already cached
- capabilities = gGnssClientContext.capabilities;
-
- } else {
- struct ChppAppHeader *request = chppAllocClientRequestCommand(
- &gGnssClientContext.client, CHPP_GNSS_GET_CAPABILITIES);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else {
- if (chppSendTimestampedRequestAndWait(
- &gGnssClientContext.client,
- &gGnssClientContext.rRState[CHPP_GNSS_GET_CAPABILITIES], request,
- sizeof(*request))) {
- // Success. gGnssClientContext.capabilities is now populated
- capabilities = gGnssClientContext.capabilities;
- }
- }
- }
-
- return capabilities;
-}
-
-/**
- * Start/stop/modify the GNSS location session used for clients of the CHRE
- * API.
- *
- * @param enable true to start/modify the session, false to stop the
- * session. If false, other parameters are ignored.
- * @param minIntervalMs See chreGnssLocationSessionStartAsync()
- * @param minTimeToNextFixMs See chreGnssLocationSessionStartAsync()
- *
- * @return True indicates the request was sent off to the service.
- */
-
-static bool chppGnssClientControlLocationSession(bool enable,
- uint32_t minIntervalMs,
- uint32_t minTimeToNextFixMs) {
- bool result = false;
-
- struct ChppGnssControlLocationSessionRequest *request =
- chppAllocClientRequestFixed(&gGnssClientContext.client,
- struct ChppGnssControlLocationSessionRequest);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else {
- request->header.command = CHPP_GNSS_CONTROL_LOCATION_SESSION;
- request->params.enable = enable;
- request->params.minIntervalMs = minIntervalMs;
- request->params.minTimeToNextFixMs = minTimeToNextFixMs;
-
- result = chppSendTimestampedRequestOrFail(
- &gGnssClientContext.client,
- &gGnssClientContext.rRState[CHPP_GNSS_CONTROL_LOCATION_SESSION],
- request, sizeof(*request), CHRE_GNSS_ASYNC_RESULT_TIMEOUT_NS);
- }
-
- return result;
-}
-
-/**
- * Releases the memory held for the location event callback.
- *
- * @param event Location event to be released.
- */
-static void chppGnssClientReleaseLocationEvent(
- struct chreGnssLocationEvent *event) {
- CHPP_FREE_AND_NULLIFY(event);
-}
-
-/**
- * Start/stop/modify the raw GNSS measurement session used for clients of the
- * CHRE API.
- *
- * @param enable true to start/modify the session, false to stop the
- * session. If false, other parameters are ignored.
- * @param minIntervalMs See chreGnssMeasurementSessionStartAsync()
- *
- * @return True indicates the request was sent off to the service.
- */
-
-static bool chppGnssClientControlMeasurementSession(bool enable,
- uint32_t minIntervalMs) {
- bool result = false;
-
- struct ChppGnssControlMeasurementSessionRequest *request =
- chppAllocClientRequestFixed(
- &gGnssClientContext.client,
- struct ChppGnssControlMeasurementSessionRequest);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else {
- request->header.command = CHPP_GNSS_CONTROL_MEASUREMENT_SESSION;
- request->params.enable = enable;
- request->params.minIntervalMs = minIntervalMs;
-
- result = chppSendTimestampedRequestOrFail(
- &gGnssClientContext.client,
- &gGnssClientContext.rRState[CHPP_GNSS_CONTROL_MEASUREMENT_SESSION],
- request, sizeof(*request), CHRE_GNSS_ASYNC_RESULT_TIMEOUT_NS);
- }
-
- return result;
-}
-
-/**
- * Releases the memory held for the measurement event callback.
- *
- * @param event Measurement event to be released.
- */
-static void chppGnssClientReleaseMeasurementDataEvent(
- struct chreGnssDataEvent *event) {
- if (event->measurement_count > 0) {
- void *measurements = CHPP_CONST_CAST_POINTER(event->measurements);
- CHPP_FREE_AND_NULLIFY(measurements);
- }
-
- CHPP_FREE_AND_NULLIFY(event);
-}
-
-/**
- * Starts/stops opportunistic delivery of location fixes.
- *
- * @param enable true to turn the passive location listener on, false to
- * turn it off.
- *
- * @return True indicates the request was sent off to the service.
- */
-static bool chppGnssClientConfigurePassiveLocationListener(bool enable) {
- bool result = false;
-
- struct ChppGnssConfigurePassiveLocationListenerRequest *request =
- chppAllocClientRequestFixed(
- &gGnssClientContext.client,
- struct ChppGnssConfigurePassiveLocationListenerRequest);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else {
- request->header.command = CHPP_GNSS_CONFIGURE_PASSIVE_LOCATION_LISTENER;
- request->params.enable = enable;
-
- result = chppSendTimestampedRequestOrFail(
- &gGnssClientContext.client,
- &gGnssClientContext
- .rRState[CHPP_GNSS_CONFIGURE_PASSIVE_LOCATION_LISTENER],
- request, sizeof(*request), CHPP_CLIENT_REQUEST_TIMEOUT_DEFAULT);
- }
-
- return result;
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppRegisterGnssClient(struct ChppAppState *appContext) {
- chppRegisterClient(appContext, (void *)&gGnssClientContext,
- &gGnssClientContext.client, gGnssClientContext.rRState,
- &kGnssClientConfig);
-}
-
-void chppDeregisterGnssClient(struct ChppAppState *appContext) {
- // TODO
-
- UNUSED_VAR(appContext);
-}
-
-struct ChppClientState *getChppGnssClientState(void) {
- return &gGnssClientContext.client;
-}
-
-#ifdef CHPP_CLIENT_ENABLED_GNSS
-
-#ifdef CHPP_CLIENT_ENABLED_CHRE_GNSS
-const struct chrePalGnssApi *chrePalGnssGetApi(uint32_t requestedApiVersion) {
-#else
-const struct chrePalGnssApi *chppPalGnssGetApi(uint32_t requestedApiVersion) {
-#endif
-
- static const struct chrePalGnssApi api = {
- .moduleVersion = CHPP_PAL_GNSS_API_VERSION,
- .open = chppGnssClientOpen,
- .close = chppGnssClientClose,
- .getCapabilities = chppGnssClientGetCapabilities,
- .controlLocationSession = chppGnssClientControlLocationSession,
- .releaseLocationEvent = chppGnssClientReleaseLocationEvent,
- .controlMeasurementSession = chppGnssClientControlMeasurementSession,
- .releaseMeasurementDataEvent = chppGnssClientReleaseMeasurementDataEvent,
- .configurePassiveLocationListener =
- chppGnssClientConfigurePassiveLocationListener,
- };
-
- CHPP_STATIC_ASSERT(
- CHRE_PAL_GNSS_API_CURRENT_VERSION == CHPP_PAL_GNSS_API_VERSION,
- "A newer CHRE PAL API version is available. Please update.");
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(api.moduleVersion,
- requestedApiVersion)) {
- return NULL;
- } else {
- return &api;
- }
-}
-
-#endif
diff --git a/chpp/clients/loopback.c b/chpp/clients/loopback.c
deleted file mode 100644
index 29db1269..00000000
--- a/chpp/clients/loopback.c
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/clients/loopback.h"
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-#include "chpp/log.h"
-#include "chpp/memory.h"
-#include "chpp/transport.h"
-
-#include "chpp/clients/discovery.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-/************************************************
- * Private Definitions
- ***********************************************/
-
-/**
- * Structure to maintain state for the loopback client and its Request/Response
- * (RR) functionality.
- */
-struct ChppLoopbackClientState {
- struct ChppClientState client; // Loopback client state
- struct ChppRequestResponseState runLoopbackTest; // Loopback test state
-
- struct ChppLoopbackTestResult testResult; // Last test result
- const uint8_t *loopbackData; // Pointer to loopback data
-};
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppLoopbackClientInit(struct ChppAppState *context) {
- CHPP_LOGD("Loopback client init");
-
- context->loopbackClientContext =
- chppMalloc(sizeof(struct ChppLoopbackClientState));
- CHPP_NOT_NULL(context->loopbackClientContext);
- memset(context->loopbackClientContext, 0,
- sizeof(struct ChppLoopbackClientState));
-
- context->loopbackClientContext->client.appContext = context;
- chppClientInit(&context->loopbackClientContext->client, CHPP_HANDLE_LOOPBACK);
- context->loopbackClientContext->testResult.error = CHPP_APP_ERROR_NONE;
- context->loopbackClientContext->client.openState = CHPP_OPEN_STATE_OPENED;
-}
-
-void chppLoopbackClientDeinit(struct ChppAppState *context) {
- CHPP_LOGD("Loopback client deinit");
-
- CHPP_NOT_NULL(context);
- CHPP_NOT_NULL(context->loopbackClientContext);
-
- chppClientDeinit(&context->loopbackClientContext->client);
- CHPP_FREE_AND_NULLIFY(context->loopbackClientContext);
-}
-
-bool chppDispatchLoopbackServiceResponse(struct ChppAppState *context,
- const uint8_t *response, size_t len) {
- CHPP_LOGD("Loopback client dispatch service response");
-
- CHPP_ASSERT(len >= CHPP_LOOPBACK_HEADER_LEN);
- CHPP_NOT_NULL(response);
- CHPP_NOT_NULL(context->loopbackClientContext);
- CHPP_NOT_NULL(context->loopbackClientContext->loopbackData);
-
- CHPP_ASSERT(chppClientTimestampResponse(
- &context->loopbackClientContext->client,
- &context->loopbackClientContext->runLoopbackTest,
- (const struct ChppAppHeader *)response));
-
- context->loopbackClientContext->testResult.error = CHPP_APP_ERROR_NONE;
- context->loopbackClientContext->testResult.responseLen = len;
- context->loopbackClientContext->testResult.firstError = len;
- context->loopbackClientContext->testResult.byteErrors = 0;
- context->loopbackClientContext->testResult.rttNs =
- context->loopbackClientContext->runLoopbackTest.responseTimeNs -
- context->loopbackClientContext->runLoopbackTest.requestTimeNs;
-
- if (context->loopbackClientContext->testResult.requestLen !=
- context->loopbackClientContext->testResult.responseLen) {
- context->loopbackClientContext->testResult.error =
- CHPP_APP_ERROR_INVALID_LENGTH;
- context->loopbackClientContext->testResult.firstError =
- MIN(context->loopbackClientContext->testResult.requestLen,
- context->loopbackClientContext->testResult.responseLen);
- }
-
- for (size_t loc = CHPP_LOOPBACK_HEADER_LEN;
- loc < MIN(context->loopbackClientContext->testResult.requestLen,
- context->loopbackClientContext->testResult.responseLen);
- loc++) {
- if (context->loopbackClientContext
- ->loopbackData[loc - CHPP_LOOPBACK_HEADER_LEN] != response[loc]) {
- context->loopbackClientContext->testResult.error =
- CHPP_APP_ERROR_UNSPECIFIED;
- context->loopbackClientContext->testResult.firstError =
- MIN(context->loopbackClientContext->testResult.firstError,
- loc - CHPP_LOOPBACK_HEADER_LEN);
- context->loopbackClientContext->testResult.byteErrors++;
- }
- }
-
- CHPP_LOGI("Loopback client RX response. Error code=0x%" PRIx16
- ", response len=%" PRIuSIZE ", request len=%" PRIuSIZE
- ", first err=%" PRIuSIZE ", total err=%" PRIuSIZE,
- context->loopbackClientContext->testResult.error,
- context->loopbackClientContext->testResult.responseLen,
- context->loopbackClientContext->testResult.requestLen,
- context->loopbackClientContext->testResult.firstError,
- context->loopbackClientContext->testResult.byteErrors);
-
- // Notify waiting (synchronous) client
- chppMutexLock(&context->loopbackClientContext->client.responseMutex);
- context->loopbackClientContext->client.responseReady = true;
- chppConditionVariableSignal(
- &context->loopbackClientContext->client.responseCondVar);
- chppMutexUnlock(&context->loopbackClientContext->client.responseMutex);
-
- return true;
-}
-
-struct ChppLoopbackTestResult chppRunLoopbackTest(struct ChppAppState *context,
- const uint8_t *buf,
- size_t len) {
- CHPP_LOGI("Loopback test. payload len=%" PRIuSIZE ", request len=%" PRIuSIZE,
- len, len + CHPP_LOOPBACK_HEADER_LEN);
-
- if (!chppWaitForDiscoveryComplete(context, 0 /* timeoutMs */)) {
- static const struct ChppLoopbackTestResult result = {
- .error = CHPP_APP_ERROR_NOT_READY,
- };
- return result;
- }
-
- CHPP_NOT_NULL(context->loopbackClientContext);
- if (context->loopbackClientContext->testResult.error ==
- CHPP_APP_ERROR_BLOCKED) {
- CHPP_LOGE("Loopback test cannot be run while another is in progress");
- CHPP_DEBUG_ASSERT(false);
-
- } else {
- context->loopbackClientContext->testResult.error = CHPP_APP_ERROR_BLOCKED;
- context->loopbackClientContext->testResult.requestLen =
- len + CHPP_LOOPBACK_HEADER_LEN;
- context->loopbackClientContext->testResult.responseLen = 0;
- context->loopbackClientContext->testResult.firstError = 0;
- context->loopbackClientContext->testResult.byteErrors = 0;
- context->loopbackClientContext->testResult.rttNs = 0;
- context->loopbackClientContext->runLoopbackTest.requestTimeNs =
- CHPP_TIME_NONE;
- context->loopbackClientContext->runLoopbackTest.responseTimeNs =
- CHPP_TIME_NONE;
-
- if (len == 0) {
- CHPP_LOGE("Loopback payload too short (0)");
- context->loopbackClientContext->testResult.error =
- CHPP_APP_ERROR_INVALID_LENGTH;
-
- } else {
- uint8_t *loopbackRequest = (uint8_t *)chppAllocClientRequest(
- &context->loopbackClientContext->client,
- context->loopbackClientContext->testResult.requestLen);
-
- if (loopbackRequest == NULL) {
- // OOM
- context->loopbackClientContext->testResult.requestLen = 0;
- context->loopbackClientContext->testResult.error = CHPP_APP_ERROR_OOM;
- CHPP_LOG_OOM();
-
- } else {
- context->loopbackClientContext->loopbackData = buf;
- memcpy(&loopbackRequest[CHPP_LOOPBACK_HEADER_LEN], buf, len);
-
- if (!chppSendTimestampedRequestAndWaitTimeout(
- &context->loopbackClientContext->client,
- &context->loopbackClientContext->runLoopbackTest,
- loopbackRequest,
- context->loopbackClientContext->testResult.requestLen,
- CHPP_NSEC_PER_SEC /* 1s */)) {
- context->loopbackClientContext->testResult.error =
- CHPP_APP_ERROR_UNSPECIFIED;
- } // else {context->loopbackClientContext->testResult is now populated}
- }
- }
- }
-
- return context->loopbackClientContext->testResult;
-}
diff --git a/chpp/clients/timesync.c b/chpp/clients/timesync.c
deleted file mode 100644
index e431835c..00000000
--- a/chpp/clients/timesync.c
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/clients/timesync.h"
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-#include "chpp/common/timesync.h"
-#include "chpp/log.h"
-#include "chpp/memory.h"
-#include "chpp/time.h"
-#include "chpp/transport.h"
-
-#include "chpp/clients/discovery.h"
-
-/************************************************
- * Private Definitions
- ***********************************************/
-
-/**
- * Structure to maintain state for the Timesync client and its Request/Response
- * (RR) functionality.
- */
-struct ChppTimesyncClientState {
- struct ChppClientState client; // Timesync client state
- struct ChppRequestResponseState measureOffset; // Request response state
-
- struct ChppTimesyncResult timesyncResult; // Result of measureOffset
-};
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppTimesyncClientInit(struct ChppAppState *context) {
- CHPP_LOGD("Timesync client init");
-
- context->timesyncClientContext =
- chppMalloc(sizeof(struct ChppTimesyncClientState));
- CHPP_NOT_NULL(context->timesyncClientContext);
- memset(context->timesyncClientContext, 0,
- sizeof(struct ChppTimesyncClientState));
-
- context->timesyncClientContext->client.appContext = context;
- context->timesyncClientContext->timesyncResult.error = CHPP_APP_ERROR_NONE;
-
- chppClientInit(&context->timesyncClientContext->client, CHPP_HANDLE_TIMESYNC);
- context->timesyncClientContext->timesyncResult.error =
- CHPP_APP_ERROR_UNSPECIFIED;
- context->timesyncClientContext->client.openState = CHPP_OPEN_STATE_OPENED;
-}
-
-void chppTimesyncClientDeinit(struct ChppAppState *context) {
- CHPP_LOGD("Timesync client deinit");
-
- CHPP_NOT_NULL(context->timesyncClientContext);
- chppClientDeinit(&context->timesyncClientContext->client);
- CHPP_FREE_AND_NULLIFY(context->timesyncClientContext);
-}
-
-void chppTimesyncClientReset(struct ChppAppState *context) {
- CHPP_LOGD("Timesync client reset");
-
- CHPP_NOT_NULL(context->timesyncClientContext);
-
- context->timesyncClientContext->timesyncResult.error = CHPP_APP_ERROR_NONE;
- context->timesyncClientContext->timesyncResult.offsetNs = 0;
- context->timesyncClientContext->timesyncResult.rttNs = 0;
- context->timesyncClientContext->timesyncResult.measurementTimeNs = 0;
-}
-
-bool chppDispatchTimesyncServiceResponse(struct ChppAppState *context,
- const uint8_t *buf, size_t len) {
- CHPP_LOGD("Timesync client dispatch service response");
-
- CHPP_NOT_NULL(context->timesyncClientContext);
- CHPP_NOT_NULL(buf);
-
- if (len < sizeof(struct ChppTimesyncResponse)) {
- CHPP_LOGE("Timesync resp short len=%" PRIuSIZE, len);
- context->timesyncClientContext->timesyncResult.error =
- CHPP_APP_ERROR_INVALID_LENGTH;
- return false;
- }
-
- const struct ChppTimesyncResponse *response =
- (const struct ChppTimesyncResponse *)buf;
- if (chppClientTimestampResponse(
- &context->timesyncClientContext->client,
- &context->timesyncClientContext->measureOffset, &response->header)) {
- context->timesyncClientContext->timesyncResult.rttNs =
- context->timesyncClientContext->measureOffset.responseTimeNs -
- context->timesyncClientContext->measureOffset.requestTimeNs;
- int64_t offsetNs =
- (int64_t)(response->timeNs -
- context->timesyncClientContext->measureOffset.responseTimeNs);
- int64_t offsetChangeNs =
- offsetNs - context->timesyncClientContext->timesyncResult.offsetNs;
-
- int64_t clippedOffsetChangeNs = offsetChangeNs;
- if (context->timesyncClientContext->timesyncResult.offsetNs != 0) {
- clippedOffsetChangeNs = MIN(clippedOffsetChangeNs,
- (int64_t)CHPP_CLIENT_TIMESYNC_MAX_CHANGE_NS);
- clippedOffsetChangeNs = MAX(clippedOffsetChangeNs,
- -(int64_t)CHPP_CLIENT_TIMESYNC_MAX_CHANGE_NS);
- }
-
- context->timesyncClientContext->timesyncResult.offsetNs +=
- clippedOffsetChangeNs;
-
- if (offsetChangeNs != clippedOffsetChangeNs) {
- CHPP_LOGW("Drift=%" PRId64 " clipped to %" PRId64 " at t=%" PRIu64,
- offsetChangeNs / (int64_t)CHPP_NSEC_PER_MSEC,
- clippedOffsetChangeNs / (int64_t)CHPP_NSEC_PER_MSEC,
- context->timesyncClientContext->measureOffset.responseTimeNs /
- CHPP_NSEC_PER_MSEC);
- } else {
- context->timesyncClientContext->timesyncResult.measurementTimeNs =
- context->timesyncClientContext->measureOffset.responseTimeNs;
- }
-
- context->timesyncClientContext->timesyncResult.error = CHPP_APP_ERROR_NONE;
-
- CHPP_LOGI("Timesync RTT=%" PRIu64 " correction=%" PRId64 " offset=%" PRId64
- " t=%" PRIu64,
- context->timesyncClientContext->timesyncResult.rttNs /
- CHPP_NSEC_PER_MSEC,
- clippedOffsetChangeNs / (int64_t)CHPP_NSEC_PER_MSEC,
- offsetNs / (int64_t)CHPP_NSEC_PER_MSEC,
- context->timesyncClientContext->timesyncResult.measurementTimeNs /
- CHPP_NSEC_PER_MSEC);
- }
-
- return true;
-}
-
-bool chppTimesyncMeasureOffset(struct ChppAppState *context) {
- bool result = false;
- CHPP_LOGI("Measuring timesync t=%" PRIu64,
- chppGetCurrentTimeNs() / CHPP_NSEC_PER_MSEC);
-
- CHPP_NOT_NULL(context->timesyncClientContext);
-
- context->timesyncClientContext->timesyncResult.error =
- CHPP_APP_ERROR_BUSY; // A measurement is in progress
-
- struct ChppAppHeader *request = chppAllocClientRequestCommand(
- &context->timesyncClientContext->client, CHPP_TIMESYNC_COMMAND_GETTIME);
- size_t requestLen = sizeof(*request);
-
- if (request == NULL) {
- context->timesyncClientContext->timesyncResult.error = CHPP_APP_ERROR_OOM;
- CHPP_LOG_OOM();
-
- } else if (!chppSendTimestampedRequestOrFail(
- &context->timesyncClientContext->client,
- &context->timesyncClientContext->measureOffset, request,
- requestLen, CHPP_CLIENT_REQUEST_TIMEOUT_INFINITE)) {
- context->timesyncClientContext->timesyncResult.error =
- CHPP_APP_ERROR_UNSPECIFIED;
-
- } else {
- result = true;
- }
-
- return result;
-}
-
-int64_t chppTimesyncGetOffset(struct ChppAppState *context,
- uint64_t maxTimesyncAgeNs) {
- bool timesyncNeverDone =
- (context->timesyncClientContext->timesyncResult.offsetNs == 0);
- bool timesyncIsStale =
- (chppGetCurrentTimeNs() -
- context->timesyncClientContext->timesyncResult.measurementTimeNs >
- maxTimesyncAgeNs);
-
- if (timesyncNeverDone || timesyncIsStale) {
- chppTimesyncMeasureOffset(context);
- } else {
- CHPP_LOGD("No need to timesync at t~=%" PRIu64 "offset=%" PRId64,
- chppGetCurrentTimeNs() / CHPP_NSEC_PER_MSEC,
- context->timesyncClientContext->timesyncResult.offsetNs /
- (int64_t)CHPP_NSEC_PER_MSEC);
- }
-
- return context->timesyncClientContext->timesyncResult.offsetNs;
-}
-
-const struct ChppTimesyncResult *chppTimesyncGetResult(
- struct ChppAppState *context) {
- return &context->timesyncClientContext->timesyncResult;
-}
diff --git a/chpp/clients/wifi.c b/chpp/clients/wifi.c
deleted file mode 100644
index 5ea79406..00000000
--- a/chpp/clients/wifi.c
+++ /dev/null
@@ -1,897 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/clients/wifi.h"
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-#include "chpp/clients/discovery.h"
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
-#include "chpp/clients/timesync.h"
-#endif
-#include "chpp/common/standard_uuids.h"
-#include "chpp/common/wifi.h"
-#include "chpp/common/wifi_types.h"
-#include "chpp/common/wifi_utils.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chre/pal/wifi.h"
-#include "chre_api/chre/wifi.h"
-
-#ifndef CHPP_WIFI_DISCOVERY_TIMEOUT_MS
-#define CHPP_WIFI_DISCOVERY_TIMEOUT_MS CHPP_DISCOVERY_DEFAULT_TIMEOUT_MS
-#endif
-
-#ifndef CHPP_WIFI_MAX_TIMESYNC_AGE_NS
-#define CHPP_WIFI_MAX_TIMESYNC_AGE_NS CHPP_TIMESYNC_DEFAULT_MAX_AGE_NS
-#endif
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppDispatchWifiResponse(void *clientContext,
- uint8_t *buf, size_t len);
-static enum ChppAppErrorCode chppDispatchWifiNotification(void *clientContext,
- uint8_t *buf,
- size_t len);
-static bool chppWifiClientInit(void *clientContext, uint8_t handle,
- struct ChppVersion serviceVersion);
-static void chppWifiClientDeinit(void *clientContext);
-static void chppWifiClientNotifyReset(void *clientContext);
-static void chppWifiClientNotifyMatch(void *clientContext);
-
-/************************************************
- * Private Definitions
- ***********************************************/
-
-/**
- * Structure to maintain state for the WiFi client and its Request/Response
- * (RR) functionality.
- */
-struct ChppWifiClientState {
- struct ChppClientState client; // WiFi client state
- const struct chrePalWifiApi *api; // WiFi PAL API
-
- struct ChppRequestResponseState rRState[CHPP_WIFI_CLIENT_REQUEST_MAX + 1];
-
- uint32_t capabilities; // Cached GetCapabilities result
- bool scanMonitorEnabled; // Scan monitoring is enabled
- bool scanMonitorSilenceCallback; // Silence callback during recovery from a
- // service reset
-};
-
-// Note: This global definition of gWifiClientContext supports only one
-// instance of the CHPP WiFi client at a time.
-struct ChppWifiClientState gWifiClientContext;
-static const struct chrePalSystemApi *gSystemApi;
-static const struct chrePalWifiCallbacks *gCallbacks;
-
-/**
- * Configuration parameters for this client
- */
-static const struct ChppClient kWifiClientConfig = {
- .descriptor.uuid = CHPP_UUID_WIFI_STANDARD,
-
- // Version
- .descriptor.version.major = 1,
- .descriptor.version.minor = 0,
- .descriptor.version.patch = 0,
-
- // Notifies client if CHPP is reset
- .resetNotifierFunctionPtr = &chppWifiClientNotifyReset,
-
- // Notifies client if they are matched to a service
- .matchNotifierFunctionPtr = &chppWifiClientNotifyMatch,
-
- // Service response dispatch function pointer
- .responseDispatchFunctionPtr = &chppDispatchWifiResponse,
-
- // Service notification dispatch function pointer
- .notificationDispatchFunctionPtr = &chppDispatchWifiNotification,
-
- // Service response dispatch function pointer
- .initFunctionPtr = &chppWifiClientInit,
-
- // Service notification dispatch function pointer
- .deinitFunctionPtr = &chppWifiClientDeinit,
-
- // Number of request-response states in the rRStates array.
- .rRStateCount = ARRAY_SIZE(gWifiClientContext.rRState),
-
- // Min length is the entire header
- .minLength = sizeof(struct ChppAppHeader),
-};
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static bool chppWifiClientOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalWifiCallbacks *callbacks);
-static void chppWifiClientClose(void);
-static uint32_t chppWifiClientGetCapabilities(void);
-static bool chppWifiClientConfigureScanMonitor(bool enable);
-static bool chppWifiClientRequestScan(const struct chreWifiScanParams *params);
-static void chppWifiClientReleaseScanEvent(struct chreWifiScanEvent *event);
-static bool chppWifiClientRequestRanging(
- const struct chreWifiRangingParams *params);
-static void chppWifiClientReleaseRangingEvent(
- struct chreWifiRangingEvent *event);
-
-static void chppWiFiRecoverScanMonitor(
- struct ChppWifiClientState *clientContext);
-static void chppWifiCloseResult(struct ChppWifiClientState *clientContext,
- uint8_t *buf, size_t len);
-static void chppWifiGetCapabilitiesResult(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len);
-static void chppWifiConfigureScanMonitorResult(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len);
-static void chppWifiRequestScanResult(struct ChppWifiClientState *clientContext,
- uint8_t *buf, size_t len);
-static void chppWifiRequestRangingResult(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len);
-
-static void chppWifiScanEventNotification(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len);
-static void chppWifiRangingEventNotification(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Dispatches a service response from the transport layer that is determined to
- * be for the WiFi client.
- *
- * This function is called from the app layer using its function pointer given
- * during client registration.
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppDispatchWifiResponse(void *clientContext,
- uint8_t *buf,
- size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- struct ChppWifiClientState *wifiClientContext =
- (struct ChppWifiClientState *)clientContext;
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (rxHeader->command > CHPP_WIFI_CLIENT_REQUEST_MAX) {
- error = CHPP_APP_ERROR_INVALID_COMMAND;
-
- } else if (!chppClientTimestampResponse(
- &wifiClientContext->client,
- &wifiClientContext->rRState[rxHeader->command], rxHeader)) {
- error = CHPP_APP_ERROR_UNEXPECTED_RESPONSE;
-
- } else {
- switch (rxHeader->command) {
- case CHPP_WIFI_OPEN: {
- chppClientProcessOpenResponse(&wifiClientContext->client, buf, len);
- chppWiFiRecoverScanMonitor(wifiClientContext);
- break;
- }
-
- case CHPP_WIFI_CLOSE: {
- chppWifiCloseResult(wifiClientContext, buf, len);
- break;
- }
-
- case CHPP_WIFI_GET_CAPABILITIES: {
- chppWifiGetCapabilitiesResult(wifiClientContext, buf, len);
- break;
- }
-
- case CHPP_WIFI_CONFIGURE_SCAN_MONITOR_ASYNC: {
- chppWifiConfigureScanMonitorResult(wifiClientContext, buf, len);
- break;
- }
-
- case CHPP_WIFI_REQUEST_SCAN_ASYNC: {
- chppWifiRequestScanResult(wifiClientContext, buf, len);
- break;
- }
-
- case CHPP_WIFI_REQUEST_RANGING_ASYNC: {
- chppWifiRequestRangingResult(wifiClientContext, buf, len);
- break;
- }
-
- default: {
- error = CHPP_APP_ERROR_INVALID_COMMAND;
- break;
- }
- }
- }
-
- return error;
-}
-
-/**
- * Dispatches a service notification from the transport layer that is determined
- * to be for the WiFi client.
- *
- * This function is called from the app layer using its function pointer given
- * during client registration.
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppDispatchWifiNotification(void *clientContext,
- uint8_t *buf,
- size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- struct ChppWifiClientState *wifiClientContext =
- (struct ChppWifiClientState *)clientContext;
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- switch (rxHeader->command) {
- case CHPP_WIFI_REQUEST_SCAN_ASYNC: {
- chppWifiScanEventNotification(wifiClientContext, buf, len);
- break;
- }
-
- case CHPP_WIFI_REQUEST_RANGING_ASYNC: {
- chppWifiRangingEventNotification(wifiClientContext, buf, len);
- break;
- }
-
- default: {
- error = CHPP_APP_ERROR_INVALID_COMMAND;
- break;
- }
- }
-
- return error;
-}
-
-/**
- * Initializes the client and provides its handle number and the version of the
- * matched service when/if it the client is matched with a service during
- * discovery.
- *
- * @param clientContext Maintains status for each client instance.
- * @param handle Handle number for this client.
- * @param serviceVersion Version of the matched service.
- *
- * @return True if client is compatible and successfully initialized.
- */
-static bool chppWifiClientInit(void *clientContext, uint8_t handle,
- struct ChppVersion serviceVersion) {
- UNUSED_VAR(serviceVersion);
-
- struct ChppWifiClientState *wifiClientContext =
- (struct ChppWifiClientState *)clientContext;
- chppClientInit(&wifiClientContext->client, handle);
-
- return true;
-}
-
-/**
- * Deinitializes the client.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppWifiClientDeinit(void *clientContext) {
- struct ChppWifiClientState *wifiClientContext =
- (struct ChppWifiClientState *)clientContext;
- chppClientDeinit(&wifiClientContext->client);
-}
-
-/**
- * Notifies the client of an incoming reset.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppWifiClientNotifyReset(void *clientContext) {
- struct ChppWifiClientState *wifiClientContext =
- (struct ChppWifiClientState *)clientContext;
-
- chppClientCloseOpenRequests(&wifiClientContext->client, &kWifiClientConfig,
- false /* clearOnly */);
- chppCheckWifiScanEventNotificationReset();
-
- if (wifiClientContext->client.openState != CHPP_OPEN_STATE_OPENED &&
- !wifiClientContext->client.pseudoOpen) {
- CHPP_LOGW("WiFi client reset but wasn't open");
- } else {
- CHPP_LOGI("WiFi client reopening from state=%" PRIu8,
- wifiClientContext->client.openState);
- chppClientSendOpenRequest(&wifiClientContext->client,
- &wifiClientContext->rRState[CHPP_WIFI_OPEN],
- CHPP_WIFI_OPEN,
- /*blocking=*/false);
- }
-}
-
-/**
- * Notifies the client of being matched to a service.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppWifiClientNotifyMatch(void *clientContext) {
- struct ChppWifiClientState *wifiClientContext =
- (struct ChppWifiClientState *)clientContext;
-
- if (wifiClientContext->client.pseudoOpen) {
- CHPP_LOGD("Pseudo-open WiFi client opening");
- chppClientSendOpenRequest(&wifiClientContext->client,
- &wifiClientContext->rRState[CHPP_WIFI_OPEN],
- CHPP_WIFI_OPEN,
- /*blocking=*/false);
- }
-}
-
-/**
- * Restores the state of scan monitoring after an incoming reset.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppWiFiRecoverScanMonitor(
- struct ChppWifiClientState *clientContext) {
- if (clientContext->scanMonitorEnabled) {
- CHPP_LOGI("Re-enabling WiFi scan monitoring after reset");
- clientContext->scanMonitorEnabled = false;
- clientContext->scanMonitorSilenceCallback = true;
-
- if (!chppWifiClientConfigureScanMonitor(true)) {
- clientContext->scanMonitorSilenceCallback = false;
- CHPP_DEBUG_ASSERT_LOG(
- false, "Unable to re-enable WiFi scan monitoring after reset");
- }
- }
-}
-
-/**
- * Handles the service response for the close client request.
- *
- * This function is called from chppDispatchWifiResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWifiCloseResult(struct ChppWifiClientState *clientContext,
- uint8_t *buf, size_t len) {
- // TODO
- UNUSED_VAR(clientContext);
- UNUSED_VAR(buf);
- UNUSED_VAR(len);
-}
-
-/**
- * Handles the service response for the get capabilities client request.
- *
- * This function is called from chppDispatchWifiResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWifiGetCapabilitiesResult(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len) {
- if (len < sizeof(struct ChppWifiGetCapabilitiesResponse)) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- CHPP_LOGE("GetCapabilities resp. too short. err=%" PRIu8, rxHeader->error);
-
- } else {
- struct ChppWifiGetCapabilitiesParameters *result =
- &((struct ChppWifiGetCapabilitiesResponse *)buf)->params;
-
- CHPP_LOGD("chppWifiGetCapabilitiesResult received capabilities=0x%" PRIx32,
- result->capabilities);
-
-#ifdef CHPP_WIFI_DEFAULT_CAPABILITIES
- CHPP_ASSERT_LOG((result->capabilities == CHPP_WIFI_DEFAULT_CAPABILITIES),
- "Unexpected capability 0x%" PRIx32 " != 0x%" PRIx32,
- result->capabilities, CHPP_WIFI_DEFAULT_CAPABILITIES);
-#endif
-
- clientContext->capabilities = result->capabilities;
- }
-}
-
-/**
- * Handles the service response for the Configure Scan Monitor client request.
- *
- * This function is called from chppDispatchWifiResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWifiConfigureScanMonitorResult(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
-
- if (len < sizeof(struct ChppWifiConfigureScanMonitorAsyncResponse)) {
- // Short response length indicates an error
-
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- CHPP_LOGE("ScanMonitor resp. too short. err=%" PRIu8, rxHeader->error);
-
- if (rxHeader->error == CHPP_APP_ERROR_NONE) {
- rxHeader->error = CHPP_APP_ERROR_INVALID_LENGTH;
- }
- gCallbacks->scanMonitorStatusChangeCallback(
- false, chppAppErrorToChreError(rxHeader->error));
-
- } else {
- struct ChppWifiConfigureScanMonitorAsyncResponseParameters *result =
- &((struct ChppWifiConfigureScanMonitorAsyncResponse *)buf)->params;
-
- gWifiClientContext.scanMonitorEnabled = result->enabled;
- CHPP_LOGD(
- "chppWifiConfigureScanMonitorResult received enable=%d, "
- "errorCode=%" PRIu8,
- result->enabled, result->errorCode);
-
- if (!gWifiClientContext.scanMonitorSilenceCallback) {
- // Per the scanMonitorStatusChangeCallback API contract, unsolicited
- // calls to scanMonitorStatusChangeCallback must not be made, and it
- // should only be invoked as the direct result of an earlier call to
- // configureScanMonitor.
- gCallbacks->scanMonitorStatusChangeCallback(result->enabled,
- result->errorCode);
- } // Else, the WiFi subsystem has been reset and we are required to
- // silently reenable the scan monitor.
-
- gWifiClientContext.scanMonitorSilenceCallback = false;
- }
-}
-
-/**
- * Handles the service response for the Request Scan Result client request.
- *
- * This function is called from chppDispatchWifiResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWifiRequestScanResult(struct ChppWifiClientState *clientContext,
- uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
-
- if (len < sizeof(struct ChppWifiRequestScanResponse)) {
- // Short response length indicates an error
-
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- CHPP_LOGE("ScanRequest resp. too short. err=%" PRIu8, rxHeader->error);
-
- if (rxHeader->error == CHPP_APP_ERROR_NONE) {
- rxHeader->error = CHPP_APP_ERROR_INVALID_LENGTH;
- }
- gCallbacks->scanResponseCallback(false,
- chppAppErrorToChreError(rxHeader->error));
-
- } else {
- struct ChppWifiRequestScanResponseParameters *result =
- &((struct ChppWifiRequestScanResponse *)buf)->params;
- CHPP_LOGI("Scan request success=%d (at service)", result->pending);
- gCallbacks->scanResponseCallback(result->pending, result->errorCode);
- }
-}
-
-/**
- * Handles the service response for the Request Ranging Result client request.
- *
- * This function is called from chppDispatchWifiResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWifiRequestRangingResult(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
- UNUSED_VAR(len);
-
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
-
- if (rxHeader->error != CHPP_APP_ERROR_NONE) {
- CHPP_LOGE("RangingRequest failed at service err=%" PRIu8, rxHeader->error);
- gCallbacks->rangingEventCallback(chppAppErrorToChreError(rxHeader->error),
- NULL);
-
- } else {
- CHPP_LOGD("Ranging request accepted at service");
- }
-}
-
-/**
- * Handles the WiFi scan event service notification.
- *
- * This function is called from chppDispatchWifiNotification().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWifiScanEventNotification(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
- CHPP_LOGD("chppWifiScanEventNotification received data len=%" PRIuSIZE, len);
-
- buf += sizeof(struct ChppAppHeader);
- len -= sizeof(struct ChppAppHeader);
-
- struct chreWifiScanEvent *chre =
- chppWifiScanEventToChre((struct ChppWifiScanEvent *)buf, len);
-
- if (chre == NULL) {
- CHPP_LOGE("Scan event conversion failed: len=%" PRIuSIZE, len);
- } else {
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
- uint64_t correctedTime =
- chre->referenceTime -
- (uint64_t)chppTimesyncGetOffset(gWifiClientContext.client.appContext,
- CHPP_WIFI_MAX_TIMESYNC_AGE_NS);
- CHPP_LOGD("WiFi scan time corrected from %" PRIu64 "to %" PRIu64,
- chre->referenceTime / CHPP_NSEC_PER_MSEC,
- correctedTime / CHPP_NSEC_PER_MSEC);
- chre->referenceTime = correctedTime;
-#endif
-
- CHPP_DEBUG_ASSERT(chppCheckWifiScanEventNotification(chre));
-
- gCallbacks->scanEventCallback(chre);
- }
-}
-
-/**
- * Handles the WiFi ranging event service notification.
- *
- * This function is called from chppDispatchWifiNotification().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWifiRangingEventNotification(
- struct ChppWifiClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
-
- CHPP_LOGD("chppWifiRangingEventNotification received data len=%" PRIuSIZE,
- len);
-
- buf += sizeof(struct ChppAppHeader);
- len -= sizeof(struct ChppAppHeader);
-
- // Timestamp correction prior to conversion to avoid const casting issues.
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
- struct ChppWifiRangingEvent *event = (struct ChppWifiRangingEvent *)buf;
-
- for (size_t i = 0; i < event->resultCount; i++) {
- struct ChppWifiRangingResult *results =
- (struct ChppWifiRangingResult *)&buf[event->results.offset];
-
- uint64_t correctedTime =
- results[i].timestamp -
- (uint64_t)chppTimesyncGetOffset(gWifiClientContext.client.appContext,
- CHPP_WIFI_MAX_TIMESYNC_AGE_NS);
- CHPP_LOGD("WiFi ranging result time corrected from %" PRIu64 "to %" PRIu64,
- results[i].timestamp / CHPP_NSEC_PER_MSEC,
- correctedTime / CHPP_NSEC_PER_MSEC);
- results[i].timestamp = correctedTime;
- }
-#endif
-
- struct chreWifiRangingEvent *chre =
- chppWifiRangingEventToChre((struct ChppWifiRangingEvent *)buf, len);
-
- uint8_t error = CHRE_ERROR_NONE;
- if (chre == NULL) {
- error = CHRE_ERROR;
- CHPP_LOGE("Ranging event conversion failed len=%" PRIuSIZE, len);
- }
-
- gCallbacks->rangingEventCallback(error, chre);
-}
-
-/**
- * Initializes the WiFi client upon an open request from CHRE and responds
- * with the result.
- *
- * @param systemApi CHRE system function pointers.
- * @param callbacks CHRE entry points.
- *
- * @return True if successful. False otherwise.
- */
-static bool chppWifiClientOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalWifiCallbacks *callbacks) {
- CHPP_DEBUG_ASSERT(systemApi != NULL);
- CHPP_DEBUG_ASSERT(callbacks != NULL);
-
- bool result = false;
- gSystemApi = systemApi;
- gCallbacks = callbacks;
-
- CHPP_LOGD("WiFi client opening");
-
- if (chppWaitForDiscoveryComplete(gWifiClientContext.client.appContext,
- CHPP_WIFI_DISCOVERY_TIMEOUT_MS)) {
- result = chppClientSendOpenRequest(
- &gWifiClientContext.client, &gWifiClientContext.rRState[CHPP_WIFI_OPEN],
- CHPP_WIFI_OPEN,
- /*blocking=*/true);
- }
-
-#ifdef CHPP_WIFI_CLIENT_OPEN_ALWAYS_SUCCESS
- chppClientPseudoOpen(&gWifiClientContext.client);
- result = true;
-#endif
-
- return result;
-}
-
-/**
- * Deinitializes the WiFi client.
- */
-static void chppWifiClientClose(void) {
- // Remote
- struct ChppAppHeader *request = chppAllocClientRequestCommand(
- &gWifiClientContext.client, CHPP_WIFI_CLOSE);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else if (chppSendTimestampedRequestAndWait(
- &gWifiClientContext.client,
- &gWifiClientContext.rRState[CHPP_WIFI_CLOSE], request,
- sizeof(*request))) {
- gWifiClientContext.client.openState = CHPP_OPEN_STATE_CLOSED;
- gWifiClientContext.capabilities = CHRE_WIFI_CAPABILITIES_NONE;
- chppClientCloseOpenRequests(&gWifiClientContext.client, &kWifiClientConfig,
- true /* clearOnly */);
- }
-}
-
-/**
- * Retrieves a set of flags indicating the WiFi features supported by the
- * current implementation.
- *
- * @return Capabilities flags.
- */
-static uint32_t chppWifiClientGetCapabilities(void) {
-#ifdef CHPP_WIFI_DEFAULT_CAPABILITIES
- uint32_t capabilities = CHPP_WIFI_DEFAULT_CAPABILITIES;
-#else
- uint32_t capabilities = CHRE_WIFI_CAPABILITIES_NONE;
-#endif
-
- if (gWifiClientContext.capabilities != CHRE_WIFI_CAPABILITIES_NONE) {
- // Result already cached
- capabilities = gWifiClientContext.capabilities;
-
- } else {
- struct ChppAppHeader *request = chppAllocClientRequestCommand(
- &gWifiClientContext.client, CHPP_WIFI_GET_CAPABILITIES);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else {
- if (chppSendTimestampedRequestAndWait(
- &gWifiClientContext.client,
- &gWifiClientContext.rRState[CHPP_WIFI_GET_CAPABILITIES], request,
- sizeof(*request))) {
- // Success. gWifiClientContext.capabilities is now populated
- capabilities = gWifiClientContext.capabilities;
- }
- }
- }
-
- return capabilities;
-}
-
-/**
- * Enables/disables receiving unsolicited scan results (scan monitoring).
- *
- * @param enable True to enable.
- *
- * @return True indicates the request was sent off to the service.
- */
-static bool chppWifiClientConfigureScanMonitor(bool enable) {
- bool result = false;
-
- struct ChppWifiConfigureScanMonitorAsyncRequest *request =
- chppAllocClientRequestFixed(
- &gWifiClientContext.client,
- struct ChppWifiConfigureScanMonitorAsyncRequest);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else {
- request->header.command = CHPP_WIFI_CONFIGURE_SCAN_MONITOR_ASYNC;
- request->params.enable = enable;
- request->params.cookie =
- &gWifiClientContext.rRState[CHPP_WIFI_CONFIGURE_SCAN_MONITOR_ASYNC];
-
- result = chppSendTimestampedRequestOrFail(
- &gWifiClientContext.client,
- &gWifiClientContext.rRState[CHPP_WIFI_CONFIGURE_SCAN_MONITOR_ASYNC],
- request, sizeof(*request), CHPP_CLIENT_REQUEST_TIMEOUT_DEFAULT);
- }
-
- return result;
-}
-
-/**
- * Request that the WiFi chipset perform a scan or deliver results from its
- * cache.
- *
- * @param params See chreWifiRequestScanAsync().
- *
- * @return True indicates the request was sent off to the service.
- */
-static bool chppWifiClientRequestScan(const struct chreWifiScanParams *params) {
- struct ChppWifiScanParamsWithHeader *request;
- size_t requestLen;
-
- bool result = chppWifiScanParamsFromChre(params, &request, &requestLen);
-
- if (!result) {
- CHPP_LOG_OOM();
- } else {
- request->header.handle = gWifiClientContext.client.handle;
- request->header.type = CHPP_MESSAGE_TYPE_CLIENT_REQUEST;
- request->header.transaction = gWifiClientContext.client.transaction++;
- request->header.error = CHPP_APP_ERROR_NONE;
- request->header.command = CHPP_WIFI_REQUEST_SCAN_ASYNC;
-
- result = chppSendTimestampedRequestOrFail(
- &gWifiClientContext.client,
- &gWifiClientContext.rRState[CHPP_WIFI_REQUEST_SCAN_ASYNC], request,
- requestLen, CHRE_WIFI_SCAN_RESULT_TIMEOUT_NS);
- }
-
- return result;
-}
-
-/**
- * Releases the memory held for the scan event callback.
- *
- * @param event Location event to be released.
- */
-static void chppWifiClientReleaseScanEvent(struct chreWifiScanEvent *event) {
- if (event->scannedFreqListLen > 0) {
- void *scannedFreqList = CHPP_CONST_CAST_POINTER(event->scannedFreqList);
- CHPP_FREE_AND_NULLIFY(scannedFreqList);
- }
-
- if (event->resultCount > 0) {
- void *results = CHPP_CONST_CAST_POINTER(event->results);
- CHPP_FREE_AND_NULLIFY(results);
- }
-
- CHPP_FREE_AND_NULLIFY(event);
-}
-
-/**
- * Request that the WiFi chipset perform RTT ranging.
- *
- * @param params See chreWifiRequestRangingAsync().
- *
- * @return True indicates the request was sent off to the service.
- */
-static bool chppWifiClientRequestRanging(
- const struct chreWifiRangingParams *params) {
- struct ChppWifiRangingParamsWithHeader *request;
- size_t requestLen;
-
- bool result = chppWifiRangingParamsFromChre(params, &request, &requestLen);
-
- if (!result) {
- CHPP_LOG_OOM();
- } else {
- request->header.handle = gWifiClientContext.client.handle;
- request->header.type = CHPP_MESSAGE_TYPE_CLIENT_REQUEST;
- request->header.transaction = gWifiClientContext.client.transaction++;
- request->header.error = CHPP_APP_ERROR_NONE;
- request->header.command = CHPP_WIFI_REQUEST_RANGING_ASYNC;
-
- result = chppSendTimestampedRequestOrFail(
- &gWifiClientContext.client,
- &gWifiClientContext.rRState[CHPP_WIFI_REQUEST_RANGING_ASYNC], request,
- requestLen, CHRE_WIFI_RANGING_RESULT_TIMEOUT_NS);
- }
-
- return result;
-}
-
-/**
- * Releases the memory held for the RTT ranging event callback.
- *
- * @param event Location event to be released.
- */
-static void chppWifiClientReleaseRangingEvent(
- struct chreWifiRangingEvent *event) {
- if (event->resultCount > 0) {
- void *results = CHPP_CONST_CAST_POINTER(event->results);
- CHPP_FREE_AND_NULLIFY(results);
- }
-
- CHPP_FREE_AND_NULLIFY(event);
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppRegisterWifiClient(struct ChppAppState *appContext) {
- chppRegisterClient(appContext, (void *)&gWifiClientContext,
- &gWifiClientContext.client, gWifiClientContext.rRState,
- &kWifiClientConfig);
-}
-
-void chppDeregisterWifiClient(struct ChppAppState *appContext) {
- // TODO
-
- UNUSED_VAR(appContext);
-}
-
-struct ChppClientState *getChppWifiClientState(void) {
- return &gWifiClientContext.client;
-}
-
-#ifdef CHPP_CLIENT_ENABLED_WIFI
-
-#ifdef CHPP_CLIENT_ENABLED_CHRE_WIFI
-const struct chrePalWifiApi *chrePalWifiGetApi(uint32_t requestedApiVersion) {
-#else
-const struct chrePalWifiApi *chppPalWifiGetApi(uint32_t requestedApiVersion) {
-#endif
-
- static const struct chrePalWifiApi api = {
- .moduleVersion = CHPP_PAL_WIFI_API_VERSION,
- .open = chppWifiClientOpen,
- .close = chppWifiClientClose,
- .getCapabilities = chppWifiClientGetCapabilities,
- .configureScanMonitor = chppWifiClientConfigureScanMonitor,
- .requestScan = chppWifiClientRequestScan,
- .releaseScanEvent = chppWifiClientReleaseScanEvent,
- .requestRanging = chppWifiClientRequestRanging,
- .releaseRangingEvent = chppWifiClientReleaseRangingEvent,
- };
-
- CHPP_STATIC_ASSERT(
- CHRE_PAL_WIFI_API_CURRENT_VERSION == CHPP_PAL_WIFI_API_VERSION,
- "A newer CHRE PAL API version is available. Please update.");
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(api.moduleVersion,
- requestedApiVersion)) {
- return NULL;
- } else {
- return &api;
- }
-}
-
-#endif
diff --git a/chpp/clients/wwan.c b/chpp/clients/wwan.c
deleted file mode 100644
index 836d9a42..00000000
--- a/chpp/clients/wwan.c
+++ /dev/null
@@ -1,578 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/clients/wwan.h"
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/clients/discovery.h"
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
-#include "chpp/clients/timesync.h"
-#endif
-#include "chpp/common/standard_uuids.h"
-#include "chpp/common/wwan.h"
-#include "chpp/common/wwan_types.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chre/pal/wwan.h"
-
-#ifndef CHPP_WWAN_DISCOVERY_TIMEOUT_MS
-#define CHPP_WWAN_DISCOVERY_TIMEOUT_MS CHPP_DISCOVERY_DEFAULT_TIMEOUT_MS
-#endif
-
-#ifndef CHPP_WWAN_MAX_TIMESYNC_AGE_NS
-#define CHPP_WWAN_MAX_TIMESYNC_AGE_NS CHPP_TIMESYNC_DEFAULT_MAX_AGE_NS
-#endif
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppDispatchWwanResponse(void *clientContext,
- uint8_t *buf, size_t len);
-static bool chppWwanClientInit(void *clientContext, uint8_t handle,
- struct ChppVersion serviceVersion);
-static void chppWwanClientDeinit(void *clientContext);
-static void chppWwanClientNotifyReset(void *clientContext);
-static void chppWwanClientNotifyMatch(void *clientContext);
-
-/************************************************
- * Private Definitions
- ***********************************************/
-
-/**
- * Structure to maintain state for the WWAN client and its Request/Response
- * (RR) functionality.
- */
-struct ChppWwanClientState {
- struct ChppClientState client; // WWAN client state
- const struct chrePalWwanApi *api; // WWAN PAL API
-
- struct ChppRequestResponseState rRState[CHPP_WWAN_CLIENT_REQUEST_MAX + 1];
-
- uint32_t capabilities; // Cached GetCapabilities result
-};
-
-// Note: This global definition of gWwanClientContext supports only one
-// instance of the CHPP WWAN client at a time.
-struct ChppWwanClientState gWwanClientContext;
-static const struct chrePalSystemApi *gSystemApi;
-static const struct chrePalWwanCallbacks *gCallbacks;
-
-/**
- * Configuration parameters for this client
- */
-static const struct ChppClient kWwanClientConfig = {
- .descriptor.uuid = CHPP_UUID_WWAN_STANDARD,
-
- // Version
- .descriptor.version.major = 1,
- .descriptor.version.minor = 0,
- .descriptor.version.patch = 0,
-
- // Notifies client if CHPP is reset
- .resetNotifierFunctionPtr = &chppWwanClientNotifyReset,
-
- // Notifies client if they are matched to a service
- .matchNotifierFunctionPtr = &chppWwanClientNotifyMatch,
-
- // Service response dispatch function pointer
- .responseDispatchFunctionPtr = &chppDispatchWwanResponse,
-
- // Service notification dispatch function pointer
- .notificationDispatchFunctionPtr = NULL, // Not supported
-
- // Service response dispatch function pointer
- .initFunctionPtr = &chppWwanClientInit,
-
- // Service notification dispatch function pointer
- .deinitFunctionPtr = &chppWwanClientDeinit,
-
- // Number of request-response states in the rRStates array.
- .rRStateCount = ARRAY_SIZE(gWwanClientContext.rRState),
-
- // Min length is the entire header
- .minLength = sizeof(struct ChppAppHeader),
-};
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static bool chppWwanClientOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalWwanCallbacks *callbacks);
-static void chppWwanClientClose(void);
-static uint32_t chppWwanClientGetCapabilities(void);
-static bool chppWwanClientGetCellInfoAsync(void);
-static void chppWwanClientReleaseCellInfoResult(
- struct chreWwanCellInfoResult *result);
-
-static void chppWwanCloseResult(struct ChppWwanClientState *clientContext,
- uint8_t *buf, size_t len);
-static void chppWwanGetCapabilitiesResult(
- struct ChppWwanClientState *clientContext, uint8_t *buf, size_t len);
-static void chppWwanGetCellInfoAsyncResult(
- struct ChppWwanClientState *clientContext, uint8_t *buf, size_t len);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Dispatches a service response from the transport layer that is determined to
- * be for the WWAN client.
- *
- * This function is called from the app layer using its function pointer given
- * during client registration.
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppDispatchWwanResponse(void *clientContext,
- uint8_t *buf,
- size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- struct ChppWwanClientState *wwanClientContext =
- (struct ChppWwanClientState *)clientContext;
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (rxHeader->command > CHPP_WWAN_CLIENT_REQUEST_MAX) {
- error = CHPP_APP_ERROR_INVALID_COMMAND;
-
- } else if (!chppClientTimestampResponse(
- &wwanClientContext->client,
- &wwanClientContext->rRState[rxHeader->command], rxHeader)) {
- error = CHPP_APP_ERROR_UNEXPECTED_RESPONSE;
-
- } else {
- switch (rxHeader->command) {
- case CHPP_WWAN_OPEN: {
- chppClientProcessOpenResponse(&wwanClientContext->client, buf, len);
- break;
- }
-
- case CHPP_WWAN_CLOSE: {
- chppWwanCloseResult(wwanClientContext, buf, len);
- break;
- }
-
- case CHPP_WWAN_GET_CAPABILITIES: {
- chppWwanGetCapabilitiesResult(wwanClientContext, buf, len);
- break;
- }
-
- case CHPP_WWAN_GET_CELLINFO_ASYNC: {
- chppWwanGetCellInfoAsyncResult(wwanClientContext, buf, len);
- break;
- }
-
- default: {
- error = CHPP_APP_ERROR_INVALID_COMMAND;
- break;
- }
- }
- }
-
- return error;
-}
-
-/**
- * Initializes the client and provides its handle number and the version of the
- * matched service when/if it the client is matched with a service during
- * discovery.
- *
- * @param clientContext Maintains status for each client instance.
- * @param handle Handle number for this client.
- * @param serviceVersion Version of the matched service.
- *
- * @return True if client is compatible and successfully initialized.
- */
-static bool chppWwanClientInit(void *clientContext, uint8_t handle,
- struct ChppVersion serviceVersion) {
- UNUSED_VAR(serviceVersion);
-
- struct ChppWwanClientState *wwanClientContext =
- (struct ChppWwanClientState *)clientContext;
- chppClientInit(&wwanClientContext->client, handle);
-
- return true;
-}
-
-/**
- * Deinitializes the client.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppWwanClientDeinit(void *clientContext) {
- struct ChppWwanClientState *wwanClientContext =
- (struct ChppWwanClientState *)clientContext;
- chppClientDeinit(&wwanClientContext->client);
-}
-
-/**
- * Notifies the client of an incoming reset.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppWwanClientNotifyReset(void *clientContext) {
- struct ChppWwanClientState *wwanClientContext =
- (struct ChppWwanClientState *)clientContext;
-
- chppClientCloseOpenRequests(&wwanClientContext->client, &kWwanClientConfig,
- false /* clearOnly */);
-
- if (wwanClientContext->client.openState != CHPP_OPEN_STATE_OPENED &&
- !wwanClientContext->client.pseudoOpen) {
- CHPP_LOGW("WWAN client reset but wasn't open");
- } else {
- CHPP_LOGI("WWAN client reopening from state=%" PRIu8,
- wwanClientContext->client.openState);
- chppClientSendOpenRequest(&wwanClientContext->client,
- &wwanClientContext->rRState[CHPP_WWAN_OPEN],
- CHPP_WWAN_OPEN,
- /*blocking=*/false);
- }
-}
-
-/**
- * Notifies the client of being matched to a service.
- *
- * @param clientContext Maintains status for each client instance.
- */
-static void chppWwanClientNotifyMatch(void *clientContext) {
- struct ChppWwanClientState *wwanClientContext =
- (struct ChppWwanClientState *)clientContext;
-
- if (wwanClientContext->client.pseudoOpen) {
- CHPP_LOGD("Pseudo-open WWAN client opening");
- chppClientSendOpenRequest(&wwanClientContext->client,
- &wwanClientContext->rRState[CHPP_WWAN_OPEN],
- CHPP_WWAN_OPEN,
- /*blocking=*/false);
- }
-}
-
-/**
- * Handles the service response for the close client request.
- *
- * This function is called from chppDispatchWwanResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWwanCloseResult(struct ChppWwanClientState *clientContext,
- uint8_t *buf, size_t len) {
- // TODO
- UNUSED_VAR(clientContext);
- UNUSED_VAR(buf);
- UNUSED_VAR(len);
-}
-
-/**
- * Handles the service response for the get capabilities client request.
- *
- * This function is called from chppDispatchWwanResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWwanGetCapabilitiesResult(
- struct ChppWwanClientState *clientContext, uint8_t *buf, size_t len) {
- if (len < sizeof(struct ChppWwanGetCapabilitiesResponse)) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- CHPP_LOGE("GetCapabilities resp. too short. err=%" PRIu8, rxHeader->error);
-
- } else {
- struct ChppWwanGetCapabilitiesParameters *result =
- &((struct ChppWwanGetCapabilitiesResponse *)buf)->params;
-
- CHPP_LOGD("chppWwanGetCapabilitiesResult received capabilities=0x%" PRIx32,
- result->capabilities);
-
-#ifdef CHPP_WWAN_DEFAULT_CAPABILITIES
- CHPP_ASSERT_LOG((result->capabilities == CHPP_WWAN_DEFAULT_CAPABILITIES),
- "Unexpected capability 0x%" PRIx32 " != 0x%" PRIx32,
- result->capabilities, CHPP_WWAN_DEFAULT_CAPABILITIES);
-#endif
-
- clientContext->capabilities = result->capabilities;
- }
-}
-
-/**
- * Handles the service response for the asynchronous get cell info client
- * request.
- *
- * This function is called from chppDispatchWwanResponse().
- *
- * @param clientContext Maintains status for each client instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppWwanGetCellInfoAsyncResult(
- struct ChppWwanClientState *clientContext, uint8_t *buf, size_t len) {
- UNUSED_VAR(clientContext);
- CHPP_LOGD("chppWwanGetCellInfoAsyncResult received data len=%" PRIuSIZE, len);
-
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- struct chreWwanCellInfoResult *chre = NULL;
- uint8_t errorCode = CHRE_ERROR;
-
- if (len == sizeof(struct ChppAppHeader)) {
- // Short response length indicates an error
- CHPP_LOGE("GetCellInfo resp. too short. err=%" PRIu8, rxHeader->error);
-
- if (rxHeader->error == CHPP_APP_ERROR_NONE) {
- errorCode = CHPP_APP_ERROR_INVALID_LENGTH;
- } else {
- errorCode = chppAppErrorToChreError(rxHeader->error);
- }
-
- } else {
- buf += sizeof(struct ChppAppHeader);
- len -= sizeof(struct ChppAppHeader);
- chre =
- chppWwanCellInfoResultToChre((struct ChppWwanCellInfoResult *)buf, len);
-
- if (chre == NULL) {
- CHPP_LOGE("Cell info conversion failed len=%" PRIuSIZE " err=%" PRIu8,
- len, rxHeader->error);
- }
- }
-
- if (chre == NULL) {
- chre = chppMalloc(sizeof(struct chreWwanCellInfoResult));
- if (chre == NULL) {
- CHPP_LOG_OOM();
- } else {
- chre->version = CHRE_WWAN_CELL_INFO_RESULT_VERSION;
- chre->errorCode = errorCode;
- chre->cellInfoCount = 0;
- chre->reserved = 0;
- chre->cookie = 0;
- chre->cells = NULL;
- }
-
- } else {
-#ifdef CHPP_CLIENT_ENABLED_TIMESYNC
- int64_t offset = chppTimesyncGetOffset(gWwanClientContext.client.appContext,
- CHPP_WWAN_MAX_TIMESYNC_AGE_NS);
- for (uint8_t i = 0; i < chre->cellInfoCount; i++) {
- uint64_t *timeStamp =
- (uint64_t *)(CHPP_CONST_CAST_POINTER(&chre->cells[i].timeStamp));
- *timeStamp -= (uint64_t)offset;
- }
-#endif
- }
-
- if (chre != NULL) {
- gCallbacks->cellInfoResultCallback(chre);
- }
-}
-
-/**
- * Initializes the WWAN client upon an open request from CHRE and responds with
- * the result.
- *
- * @param systemApi CHRE system function pointers.
- * @param callbacks CHRE entry points.
- *
- * @return True if successful. False otherwise.
- */
-static bool chppWwanClientOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalWwanCallbacks *callbacks) {
- CHPP_DEBUG_ASSERT(systemApi != NULL);
- CHPP_DEBUG_ASSERT(callbacks != NULL);
-
- bool result = false;
- gSystemApi = systemApi;
- gCallbacks = callbacks;
-
- CHPP_LOGD("WWAN client opening");
-
- // Wait for discovery to complete for "open" call to succeed
- if (chppWaitForDiscoveryComplete(gWwanClientContext.client.appContext,
- CHPP_WWAN_DISCOVERY_TIMEOUT_MS)) {
- result = chppClientSendOpenRequest(
- &gWwanClientContext.client, &gWwanClientContext.rRState[CHPP_WWAN_OPEN],
- CHPP_WWAN_OPEN,
- /*blocking=*/true);
- }
-
-#ifdef CHPP_WWAN_CLIENT_OPEN_ALWAYS_SUCCESS
- chppClientPseudoOpen(&gWwanClientContext.client);
- result = true;
-#endif
-
- return result;
-}
-
-/**
- * Deinitializes the WWAN client.
- */
-static void chppWwanClientClose(void) {
- // Remote
- struct ChppAppHeader *request = chppAllocClientRequestCommand(
- &gWwanClientContext.client, CHPP_WWAN_CLOSE);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else if (chppSendTimestampedRequestAndWait(
- &gWwanClientContext.client,
- &gWwanClientContext.rRState[CHPP_WWAN_CLOSE], request,
- sizeof(*request))) {
- gWwanClientContext.client.openState = CHPP_OPEN_STATE_CLOSED;
- gWwanClientContext.capabilities = CHRE_WWAN_CAPABILITIES_NONE;
- chppClientCloseOpenRequests(&gWwanClientContext.client, &kWwanClientConfig,
- true /* clearOnly */);
- }
-}
-
-/**
- * Retrieves a set of flags indicating the WWAN features supported by the
- * current implementation.
- *
- * @return Capabilities flags.
- */
-static uint32_t chppWwanClientGetCapabilities(void) {
-#ifdef CHPP_WWAN_DEFAULT_CAPABILITIES
- uint32_t capabilities = CHPP_WWAN_DEFAULT_CAPABILITIES;
-#else
- uint32_t capabilities = CHRE_WWAN_CAPABILITIES_NONE;
-#endif
-
- if (gWwanClientContext.capabilities != CHRE_WWAN_CAPABILITIES_NONE) {
- // Result already cached
- capabilities = gWwanClientContext.capabilities;
-
- } else {
- struct ChppAppHeader *request = chppAllocClientRequestCommand(
- &gWwanClientContext.client, CHPP_WWAN_GET_CAPABILITIES);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else {
- if (chppSendTimestampedRequestAndWait(
- &gWwanClientContext.client,
- &gWwanClientContext.rRState[CHPP_WWAN_GET_CAPABILITIES], request,
- sizeof(*request))) {
- // Success. gWwanClientContext.capabilities is now populated
- capabilities = gWwanClientContext.capabilities;
- }
- }
- }
-
- return capabilities;
-}
-
-/**
- * Query information about the current serving cell and its neighbors. This does
- * not perform a network scan, but should return state from the current network
- * registration data stored in the cellular modem.
- *
- * @return True indicates the request was sent off to the service.
- */
-static bool chppWwanClientGetCellInfoAsync(void) {
- bool result = false;
-
- struct ChppAppHeader *request = chppAllocClientRequestCommand(
- &gWwanClientContext.client, CHPP_WWAN_GET_CELLINFO_ASYNC);
-
- if (request == NULL) {
- CHPP_LOG_OOM();
- } else {
- result = chppSendTimestampedRequestOrFail(
- &gWwanClientContext.client,
- &gWwanClientContext.rRState[CHPP_WWAN_GET_CELLINFO_ASYNC], request,
- sizeof(*request), CHPP_CLIENT_REQUEST_TIMEOUT_DEFAULT);
- }
-
- return result;
-}
-
-/**
- * Releases the memory held for the GetCellInfoAsync result.
- */
-static void chppWwanClientReleaseCellInfoResult(
- struct chreWwanCellInfoResult *result) {
- if (result->cellInfoCount > 0) {
- void *cells = CHPP_CONST_CAST_POINTER(result->cells);
- CHPP_FREE_AND_NULLIFY(cells);
- }
-
- CHPP_FREE_AND_NULLIFY(result);
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppRegisterWwanClient(struct ChppAppState *appContext) {
- chppRegisterClient(appContext, (void *)&gWwanClientContext,
- &gWwanClientContext.client, gWwanClientContext.rRState,
- &kWwanClientConfig);
-}
-
-void chppDeregisterWwanClient(struct ChppAppState *appContext) {
- // TODO
-
- UNUSED_VAR(appContext);
-}
-
-struct ChppClientState *getChppWwanClientState(void) {
- return &gWwanClientContext.client;
-}
-
-#ifdef CHPP_CLIENT_ENABLED_WWAN
-
-#ifdef CHPP_CLIENT_ENABLED_CHRE_WWAN
-const struct chrePalWwanApi *chrePalWwanGetApi(uint32_t requestedApiVersion) {
-#else
-const struct chrePalWwanApi *chppPalWwanGetApi(uint32_t requestedApiVersion) {
-#endif
-
- static const struct chrePalWwanApi api = {
- .moduleVersion = CHPP_PAL_WWAN_API_VERSION,
- .open = chppWwanClientOpen,
- .close = chppWwanClientClose,
- .getCapabilities = chppWwanClientGetCapabilities,
- .requestCellInfo = chppWwanClientGetCellInfoAsync,
- .releaseCellInfoResult = chppWwanClientReleaseCellInfoResult,
- };
-
- CHPP_STATIC_ASSERT(
- CHRE_PAL_WWAN_API_CURRENT_VERSION == CHPP_PAL_WWAN_API_VERSION,
- "A newer CHRE PAL API version is available. Please update.");
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(api.moduleVersion,
- requestedApiVersion)) {
- return NULL;
- } else {
- return &api;
- }
-}
-
-#endif
diff --git a/chpp/common/gnss_convert.c b/chpp/common/gnss_convert.c
deleted file mode 100644
index b2c69335..00000000
--- a/chpp/common/gnss_convert.c
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-// This file was automatically generated by chre_api_to_chpp.py
-// Date: 2021-05-24 15:46:26 UTC
-// Source: chre_api/include/chre_api/chre/gnss.h @ commit 833a6241
-
-// DO NOT modify this file directly, as those changes will be lost the next
-// time the script is executed
-
-#include "chpp/common/gnss_types.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-// Encoding (CHRE --> CHPP) size functions
-
-//! @return number of bytes required to represent the given
-//! chreGnssDataEvent along with the CHPP header as
-//! struct ChppGnssDataEventWithHeader
-static size_t chppGnssSizeOfDataEventFromChre(
- const struct chreGnssDataEvent *dataEvent) {
- size_t encodedSize = sizeof(struct ChppGnssDataEventWithHeader);
- encodedSize +=
- dataEvent->measurement_count * sizeof(struct ChppGnssMeasurement);
- return encodedSize;
-}
-
-// Encoding (CHRE --> CHPP) conversion functions
-
-static void chppGnssConvertClockFromChre(const struct chreGnssClock *in,
- struct ChppGnssClock *out) {
- out->time_ns = in->time_ns;
- out->full_bias_ns = in->full_bias_ns;
- out->bias_ns = in->bias_ns;
- out->drift_nsps = in->drift_nsps;
- out->bias_uncertainty_ns = in->bias_uncertainty_ns;
- out->drift_uncertainty_nsps = in->drift_uncertainty_nsps;
- out->hw_clock_discontinuity_count = in->hw_clock_discontinuity_count;
- out->flags = in->flags;
- memset(&out->reserved, 0, sizeof(out->reserved));
-}
-
-static void chppGnssConvertMeasurementFromChre(
- const struct chreGnssMeasurement *in, struct ChppGnssMeasurement *out) {
- out->time_offset_ns = in->time_offset_ns;
- out->accumulated_delta_range_um = in->accumulated_delta_range_um;
- out->received_sv_time_in_ns = in->received_sv_time_in_ns;
- out->received_sv_time_uncertainty_in_ns =
- in->received_sv_time_uncertainty_in_ns;
- out->pseudorange_rate_mps = in->pseudorange_rate_mps;
- out->pseudorange_rate_uncertainty_mps = in->pseudorange_rate_uncertainty_mps;
- out->accumulated_delta_range_uncertainty_m =
- in->accumulated_delta_range_uncertainty_m;
- out->c_n0_dbhz = in->c_n0_dbhz;
- out->snr_db = in->snr_db;
- out->state = in->state;
- out->accumulated_delta_range_state = in->accumulated_delta_range_state;
- out->svid = in->svid;
- out->constellation = in->constellation;
- out->multipath_indicator = in->multipath_indicator;
- out->carrier_frequency_hz = in->carrier_frequency_hz;
-}
-
-static void chppGnssConvertDataEventFromChre(const struct chreGnssDataEvent *in,
- struct ChppGnssDataEvent *out,
- uint8_t *payload,
- size_t payloadSize,
- uint16_t *vlaOffset) {
- out->version = CHRE_GNSS_DATA_EVENT_VERSION;
- out->measurement_count = in->measurement_count;
- memset(&out->reserved, 0, sizeof(out->reserved));
- chppGnssConvertClockFromChre(&in->clock, &out->clock);
-
- struct ChppGnssMeasurement *measurements =
- (struct ChppGnssMeasurement *)&payload[*vlaOffset];
- out->measurements.length =
- in->measurement_count * sizeof(struct ChppGnssMeasurement);
- CHPP_ASSERT((size_t)(*vlaOffset + out->measurements.length) <= payloadSize);
- if (out->measurements.length > 0 &&
- *vlaOffset + out->measurements.length <= payloadSize) {
- for (size_t i = 0; i < in->measurement_count; i++) {
- chppGnssConvertMeasurementFromChre(&in->measurements[i],
- &measurements[i]);
- }
- out->measurements.offset = *vlaOffset;
- *vlaOffset += out->measurements.length;
- } else {
- out->measurements.offset = 0;
- }
-}
-
-static void chppGnssConvertLocationEventFromChre(
- const struct chreGnssLocationEvent *in, struct ChppGnssLocationEvent *out) {
- out->timestamp = in->timestamp;
- out->latitude_deg_e7 = in->latitude_deg_e7;
- out->longitude_deg_e7 = in->longitude_deg_e7;
- out->altitude = in->altitude;
- out->speed = in->speed;
- out->bearing = in->bearing;
- out->accuracy = in->accuracy;
- out->flags = in->flags;
- memset(&out->reserved, 0, sizeof(out->reserved));
- out->altitude_accuracy = in->altitude_accuracy;
- out->speed_accuracy = in->speed_accuracy;
- out->bearing_accuracy = in->bearing_accuracy;
-}
-
-// Encoding (CHRE --> CHPP) top-level functions
-
-bool chppGnssDataEventFromChre(const struct chreGnssDataEvent *in,
- struct ChppGnssDataEventWithHeader **out,
- size_t *outSize) {
- CHPP_NOT_NULL(out);
- CHPP_NOT_NULL(outSize);
-
- size_t payloadSize = chppGnssSizeOfDataEventFromChre(in);
- *out = chppMalloc(payloadSize);
- if (*out != NULL) {
- uint8_t *payload = (uint8_t *)&(*out)->payload;
- uint16_t vlaOffset = sizeof(struct ChppGnssDataEvent);
- chppGnssConvertDataEventFromChre(in, &(*out)->payload, payload, payloadSize,
- &vlaOffset);
- *outSize = payloadSize;
- return true;
- }
- return false;
-}
-
-bool chppGnssLocationEventFromChre(const struct chreGnssLocationEvent *in,
- struct ChppGnssLocationEventWithHeader **out,
- size_t *outSize) {
- CHPP_NOT_NULL(out);
- CHPP_NOT_NULL(outSize);
-
- size_t payloadSize = sizeof(struct ChppGnssLocationEventWithHeader);
- *out = chppMalloc(payloadSize);
- if (*out != NULL) {
- chppGnssConvertLocationEventFromChre(in, &(*out)->payload);
- *outSize = payloadSize;
- return true;
- }
- return false;
-}
-
-// Decoding (CHPP --> CHRE) conversion functions
-
-static bool chppGnssConvertClockToChre(const struct ChppGnssClock *in,
- struct chreGnssClock *out) {
- out->time_ns = in->time_ns;
- out->full_bias_ns = in->full_bias_ns;
- out->bias_ns = in->bias_ns;
- out->drift_nsps = in->drift_nsps;
- out->bias_uncertainty_ns = in->bias_uncertainty_ns;
- out->drift_uncertainty_nsps = in->drift_uncertainty_nsps;
- out->hw_clock_discontinuity_count = in->hw_clock_discontinuity_count;
- out->flags = in->flags;
- memset(&out->reserved, 0, sizeof(out->reserved));
-
- return true;
-}
-
-static bool chppGnssConvertMeasurementToChre(
- const struct ChppGnssMeasurement *in, struct chreGnssMeasurement *out) {
- out->time_offset_ns = in->time_offset_ns;
- out->accumulated_delta_range_um = in->accumulated_delta_range_um;
- out->received_sv_time_in_ns = in->received_sv_time_in_ns;
- out->received_sv_time_uncertainty_in_ns =
- in->received_sv_time_uncertainty_in_ns;
- out->pseudorange_rate_mps = in->pseudorange_rate_mps;
- out->pseudorange_rate_uncertainty_mps = in->pseudorange_rate_uncertainty_mps;
- out->accumulated_delta_range_uncertainty_m =
- in->accumulated_delta_range_uncertainty_m;
- out->c_n0_dbhz = in->c_n0_dbhz;
- out->snr_db = in->snr_db;
- out->state = in->state;
- out->accumulated_delta_range_state = in->accumulated_delta_range_state;
- out->svid = in->svid;
- out->constellation = in->constellation;
- out->multipath_indicator = in->multipath_indicator;
- out->carrier_frequency_hz = in->carrier_frequency_hz;
-
- return true;
-}
-
-static bool chppGnssConvertDataEventToChre(const struct ChppGnssDataEvent *in,
- struct chreGnssDataEvent *out,
- size_t inSize) {
- out->version = CHRE_GNSS_DATA_EVENT_VERSION;
- out->measurement_count = in->measurement_count;
- memset(&out->reserved, 0, sizeof(out->reserved));
- if (!chppGnssConvertClockToChre(&in->clock, &out->clock)) {
- return false;
- }
-
- if (in->measurements.length == 0) {
- out->measurements = NULL;
- } else {
- if (in->measurements.offset + in->measurements.length > inSize ||
- in->measurements.length !=
- in->measurement_count * sizeof(struct ChppGnssMeasurement)) {
- return false;
- }
-
- const struct ChppGnssMeasurement *measurementsIn =
- (const struct ChppGnssMeasurement *)&(
- (const uint8_t *)in)[in->measurements.offset];
-
- struct chreGnssMeasurement *measurementsOut =
- chppMalloc(in->measurement_count * sizeof(struct chreGnssMeasurement));
- if (measurementsOut == NULL) {
- return false;
- }
-
- for (size_t i = 0; i < in->measurement_count; i++) {
- if (!chppGnssConvertMeasurementToChre(&measurementsIn[i],
- &measurementsOut[i])) {
- return false;
- }
- }
- out->measurements = measurementsOut;
- }
-
- return true;
-}
-
-static bool chppGnssConvertLocationEventToChre(
- const struct ChppGnssLocationEvent *in, struct chreGnssLocationEvent *out) {
- out->timestamp = in->timestamp;
- out->latitude_deg_e7 = in->latitude_deg_e7;
- out->longitude_deg_e7 = in->longitude_deg_e7;
- out->altitude = in->altitude;
- out->speed = in->speed;
- out->bearing = in->bearing;
- out->accuracy = in->accuracy;
- out->flags = in->flags;
- memset(&out->reserved, 0, sizeof(out->reserved));
- out->altitude_accuracy = in->altitude_accuracy;
- out->speed_accuracy = in->speed_accuracy;
- out->bearing_accuracy = in->bearing_accuracy;
-
- return true;
-}
-
-// Decoding (CHPP --> CHRE) top-level functions
-
-struct chreGnssDataEvent *chppGnssDataEventToChre(
- const struct ChppGnssDataEvent *in, size_t inSize) {
- struct chreGnssDataEvent *out = NULL;
-
- if (inSize >= sizeof(struct ChppGnssDataEvent)) {
- out = chppMalloc(sizeof(struct chreGnssDataEvent));
- if (out != NULL) {
- if (!chppGnssConvertDataEventToChre(in, out, inSize)) {
- CHPP_FREE_AND_NULLIFY(out);
- }
- }
- }
-
- return out;
-}
-struct chreGnssLocationEvent *chppGnssLocationEventToChre(
- const struct ChppGnssLocationEvent *in, size_t inSize) {
- struct chreGnssLocationEvent *out = NULL;
-
- if (inSize >= sizeof(struct ChppGnssLocationEvent)) {
- out = chppMalloc(sizeof(struct chreGnssLocationEvent));
- if (out != NULL) {
- if (!chppGnssConvertLocationEventToChre(in, out)) {
- CHPP_FREE_AND_NULLIFY(out);
- }
- }
- }
-
- return out;
-}
diff --git a/chpp/common/wifi_convert.c b/chpp/common/wifi_convert.c
deleted file mode 100644
index dae3ed71..00000000
--- a/chpp/common/wifi_convert.c
+++ /dev/null
@@ -1,679 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-// This file was automatically generated by chre_api_to_chpp.py
-// Date: 2021-05-24 15:46:25 UTC
-// Source: chre_api/include/chre_api/chre/wifi.h @ commit 833a6241
-
-// DO NOT modify this file directly, as those changes will be lost the next
-// time the script is executed
-
-#include "chpp/common/wifi_types.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-// Encoding (CHRE --> CHPP) size functions
-
-//! @return number of bytes required to represent the given
-//! chreWifiScanEvent along with the CHPP header as
-//! struct ChppWifiScanEventWithHeader
-static size_t chppWifiSizeOfScanEventFromChre(
- const struct chreWifiScanEvent *scanEvent) {
- size_t encodedSize = sizeof(struct ChppWifiScanEventWithHeader);
- encodedSize += scanEvent->scannedFreqListLen * sizeof(uint32_t);
- encodedSize += scanEvent->resultCount * sizeof(struct ChppWifiScanResult);
- return encodedSize;
-}
-
-//! @return number of bytes required to represent the given
-//! chreWifiScanParams along with the CHPP header as
-//! struct ChppWifiScanParamsWithHeader
-static size_t chppWifiSizeOfScanParamsFromChre(
- const struct chreWifiScanParams *scanParams) {
- size_t encodedSize = sizeof(struct ChppWifiScanParamsWithHeader);
- encodedSize += scanParams->frequencyListLen * sizeof(uint32_t);
- encodedSize += scanParams->ssidListLen * sizeof(struct ChppWifiSsidListItem);
- return encodedSize;
-}
-
-//! @return number of bytes required to represent the given
-//! chreWifiRangingEvent along with the CHPP header as
-//! struct ChppWifiRangingEventWithHeader
-static size_t chppWifiSizeOfRangingEventFromChre(
- const struct chreWifiRangingEvent *rangingEvent) {
- size_t encodedSize = sizeof(struct ChppWifiRangingEventWithHeader);
- encodedSize +=
- rangingEvent->resultCount * sizeof(struct ChppWifiRangingResult);
- return encodedSize;
-}
-
-//! @return number of bytes required to represent the given
-//! chreWifiRangingParams along with the CHPP header as
-//! struct ChppWifiRangingParamsWithHeader
-static size_t chppWifiSizeOfRangingParamsFromChre(
- const struct chreWifiRangingParams *rangingParams) {
- size_t encodedSize = sizeof(struct ChppWifiRangingParamsWithHeader);
- encodedSize +=
- rangingParams->targetListLen * sizeof(struct ChppWifiRangingTarget);
- return encodedSize;
-}
-
-// Encoding (CHRE --> CHPP) conversion functions
-
-static void chppWifiConvertScanResultFromChre(
- const struct chreWifiScanResult *in, struct ChppWifiScanResult *out) {
- out->ageMs = in->ageMs;
- out->capabilityInfo = in->capabilityInfo;
- out->ssidLen = in->ssidLen;
- memcpy(out->ssid, in->ssid, sizeof(out->ssid));
- memcpy(out->bssid, in->bssid, sizeof(out->bssid));
- out->flags = in->flags;
- out->rssi = in->rssi;
- out->band = in->band;
- out->primaryChannel = in->primaryChannel;
- out->centerFreqPrimary = in->centerFreqPrimary;
- out->centerFreqSecondary = in->centerFreqSecondary;
- out->channelWidth = in->channelWidth;
- out->securityMode = in->securityMode;
- out->radioChain = in->radioChain;
- out->rssiChain0 = in->rssiChain0;
- out->rssiChain1 = in->rssiChain1;
- memset(&out->reserved, 0, sizeof(out->reserved));
-}
-
-static void chppWifiConvertScanEventFromChre(const struct chreWifiScanEvent *in,
- struct ChppWifiScanEvent *out,
- uint8_t *payload,
- size_t payloadSize,
- uint16_t *vlaOffset) {
- out->version = CHRE_WIFI_SCAN_EVENT_VERSION;
- out->resultCount = in->resultCount;
- out->resultTotal = in->resultTotal;
- out->eventIndex = in->eventIndex;
- out->scanType = in->scanType;
- out->ssidSetSize = in->ssidSetSize;
- out->scannedFreqListLen = in->scannedFreqListLen;
- out->referenceTime = in->referenceTime;
- out->scannedFreqList.length = in->scannedFreqListLen * sizeof(uint32_t);
- CHPP_ASSERT((size_t)(*vlaOffset + out->scannedFreqList.length) <=
- payloadSize);
- if (out->scannedFreqList.length > 0 &&
- *vlaOffset + out->scannedFreqList.length <= payloadSize) {
- memcpy(&payload[*vlaOffset], in->scannedFreqList,
- in->scannedFreqListLen * sizeof(uint32_t));
- out->scannedFreqList.offset = *vlaOffset;
- *vlaOffset += out->scannedFreqList.length;
- } else {
- out->scannedFreqList.offset = 0;
- }
-
- struct ChppWifiScanResult *results =
- (struct ChppWifiScanResult *)&payload[*vlaOffset];
- out->results.length = in->resultCount * sizeof(struct ChppWifiScanResult);
- CHPP_ASSERT((size_t)(*vlaOffset + out->results.length) <= payloadSize);
- if (out->results.length > 0 &&
- *vlaOffset + out->results.length <= payloadSize) {
- for (size_t i = 0; i < in->resultCount; i++) {
- chppWifiConvertScanResultFromChre(&in->results[i], &results[i]);
- }
- out->results.offset = *vlaOffset;
- *vlaOffset += out->results.length;
- } else {
- out->results.offset = 0;
- }
- out->radioChainPref = in->radioChainPref;
-}
-
-static void chppWifiConvertSsidListItemFromChre(
- const struct chreWifiSsidListItem *in, struct ChppWifiSsidListItem *out) {
- out->ssidLen = in->ssidLen;
- memcpy(out->ssid, in->ssid, sizeof(out->ssid));
-}
-
-static void chppWifiConvertScanParamsFromChre(
- const struct chreWifiScanParams *in, struct ChppWifiScanParams *out,
- uint8_t *payload, size_t payloadSize, uint16_t *vlaOffset) {
- out->scanType = in->scanType;
- out->maxScanAgeMs = in->maxScanAgeMs;
- out->frequencyListLen = in->frequencyListLen;
- out->frequencyList.length = in->frequencyListLen * sizeof(uint32_t);
- CHPP_ASSERT((size_t)(*vlaOffset + out->frequencyList.length) <= payloadSize);
- if (out->frequencyList.length > 0 &&
- *vlaOffset + out->frequencyList.length <= payloadSize) {
- memcpy(&payload[*vlaOffset], in->frequencyList,
- in->frequencyListLen * sizeof(uint32_t));
- out->frequencyList.offset = *vlaOffset;
- *vlaOffset += out->frequencyList.length;
- } else {
- out->frequencyList.offset = 0;
- }
- out->ssidListLen = in->ssidListLen;
-
- struct ChppWifiSsidListItem *ssidList =
- (struct ChppWifiSsidListItem *)&payload[*vlaOffset];
- out->ssidList.length = in->ssidListLen * sizeof(struct ChppWifiSsidListItem);
- CHPP_ASSERT((size_t)(*vlaOffset + out->ssidList.length) <= payloadSize);
- if (out->ssidList.length > 0 &&
- *vlaOffset + out->ssidList.length <= payloadSize) {
- for (size_t i = 0; i < in->ssidListLen; i++) {
- chppWifiConvertSsidListItemFromChre(&in->ssidList[i], &ssidList[i]);
- }
- out->ssidList.offset = *vlaOffset;
- *vlaOffset += out->ssidList.length;
- } else {
- out->ssidList.offset = 0;
- }
- out->radioChainPref = in->radioChainPref;
- out->channelSet = in->channelSet;
-}
-
-static void chppWifiConvertLciFromChre(const struct chreWifiLci *in,
- struct ChppWifiLci *out) {
- out->latitude = in->latitude;
- out->longitude = in->longitude;
- out->altitude = in->altitude;
- out->latitudeUncertainty = in->latitudeUncertainty;
- out->longitudeUncertainty = in->longitudeUncertainty;
- out->altitudeType = in->altitudeType;
- out->altitudeUncertainty = in->altitudeUncertainty;
-}
-
-static void chppWifiConvertRangingResultFromChre(
- const struct chreWifiRangingResult *in, struct ChppWifiRangingResult *out) {
- out->timestamp = in->timestamp;
- memcpy(out->macAddress, in->macAddress, sizeof(out->macAddress));
- out->status = in->status;
- out->rssi = in->rssi;
- out->distance = in->distance;
- out->distanceStdDev = in->distanceStdDev;
- chppWifiConvertLciFromChre(&in->lci, &out->lci);
- out->flags = in->flags;
- memset(&out->reserved, 0, sizeof(out->reserved));
-}
-
-static void chppWifiConvertRangingEventFromChre(
- const struct chreWifiRangingEvent *in, struct ChppWifiRangingEvent *out,
- uint8_t *payload, size_t payloadSize, uint16_t *vlaOffset) {
- out->version = CHRE_WIFI_RANGING_EVENT_VERSION;
- out->resultCount = in->resultCount;
- memset(&out->reserved, 0, sizeof(out->reserved));
-
- struct ChppWifiRangingResult *results =
- (struct ChppWifiRangingResult *)&payload[*vlaOffset];
- out->results.length = in->resultCount * sizeof(struct ChppWifiRangingResult);
- CHPP_ASSERT((size_t)(*vlaOffset + out->results.length) <= payloadSize);
- if (out->results.length > 0 &&
- *vlaOffset + out->results.length <= payloadSize) {
- for (size_t i = 0; i < in->resultCount; i++) {
- chppWifiConvertRangingResultFromChre(&in->results[i], &results[i]);
- }
- out->results.offset = *vlaOffset;
- *vlaOffset += out->results.length;
- } else {
- out->results.offset = 0;
- }
-}
-
-static void chppWifiConvertRangingTargetFromChre(
- const struct chreWifiRangingTarget *in, struct ChppWifiRangingTarget *out) {
- memcpy(out->macAddress, in->macAddress, sizeof(out->macAddress));
- out->primaryChannel = in->primaryChannel;
- out->centerFreqPrimary = in->centerFreqPrimary;
- out->centerFreqSecondary = in->centerFreqSecondary;
- out->channelWidth = in->channelWidth;
- memset(&out->reserved, 0, sizeof(out->reserved));
-}
-
-static void chppWifiConvertRangingParamsFromChre(
- const struct chreWifiRangingParams *in, struct ChppWifiRangingParams *out,
- uint8_t *payload, size_t payloadSize, uint16_t *vlaOffset) {
- out->targetListLen = in->targetListLen;
-
- struct ChppWifiRangingTarget *targetList =
- (struct ChppWifiRangingTarget *)&payload[*vlaOffset];
- out->targetList.length =
- in->targetListLen * sizeof(struct ChppWifiRangingTarget);
- CHPP_ASSERT((size_t)(*vlaOffset + out->targetList.length) <= payloadSize);
- if (out->targetList.length > 0 &&
- *vlaOffset + out->targetList.length <= payloadSize) {
- for (size_t i = 0; i < in->targetListLen; i++) {
- chppWifiConvertRangingTargetFromChre(&in->targetList[i], &targetList[i]);
- }
- out->targetList.offset = *vlaOffset;
- *vlaOffset += out->targetList.length;
- } else {
- out->targetList.offset = 0;
- }
-}
-
-// Encoding (CHRE --> CHPP) top-level functions
-
-bool chppWifiScanEventFromChre(const struct chreWifiScanEvent *in,
- struct ChppWifiScanEventWithHeader **out,
- size_t *outSize) {
- CHPP_NOT_NULL(out);
- CHPP_NOT_NULL(outSize);
-
- size_t payloadSize = chppWifiSizeOfScanEventFromChre(in);
- *out = chppMalloc(payloadSize);
- if (*out != NULL) {
- uint8_t *payload = (uint8_t *)&(*out)->payload;
- uint16_t vlaOffset = sizeof(struct ChppWifiScanEvent);
- chppWifiConvertScanEventFromChre(in, &(*out)->payload, payload, payloadSize,
- &vlaOffset);
- *outSize = payloadSize;
- return true;
- }
- return false;
-}
-
-bool chppWifiScanParamsFromChre(const struct chreWifiScanParams *in,
- struct ChppWifiScanParamsWithHeader **out,
- size_t *outSize) {
- CHPP_NOT_NULL(out);
- CHPP_NOT_NULL(outSize);
-
- size_t payloadSize = chppWifiSizeOfScanParamsFromChre(in);
- *out = chppMalloc(payloadSize);
- if (*out != NULL) {
- uint8_t *payload = (uint8_t *)&(*out)->payload;
- uint16_t vlaOffset = sizeof(struct ChppWifiScanParams);
- chppWifiConvertScanParamsFromChre(in, &(*out)->payload, payload,
- payloadSize, &vlaOffset);
- *outSize = payloadSize;
- return true;
- }
- return false;
-}
-
-bool chppWifiRangingEventFromChre(const struct chreWifiRangingEvent *in,
- struct ChppWifiRangingEventWithHeader **out,
- size_t *outSize) {
- CHPP_NOT_NULL(out);
- CHPP_NOT_NULL(outSize);
-
- size_t payloadSize = chppWifiSizeOfRangingEventFromChre(in);
- *out = chppMalloc(payloadSize);
- if (*out != NULL) {
- uint8_t *payload = (uint8_t *)&(*out)->payload;
- uint16_t vlaOffset = sizeof(struct ChppWifiRangingEvent);
- chppWifiConvertRangingEventFromChre(in, &(*out)->payload, payload,
- payloadSize, &vlaOffset);
- *outSize = payloadSize;
- return true;
- }
- return false;
-}
-
-bool chppWifiRangingParamsFromChre(const struct chreWifiRangingParams *in,
- struct ChppWifiRangingParamsWithHeader **out,
- size_t *outSize) {
- CHPP_NOT_NULL(out);
- CHPP_NOT_NULL(outSize);
-
- size_t payloadSize = chppWifiSizeOfRangingParamsFromChre(in);
- *out = chppMalloc(payloadSize);
- if (*out != NULL) {
- uint8_t *payload = (uint8_t *)&(*out)->payload;
- uint16_t vlaOffset = sizeof(struct ChppWifiRangingParams);
- chppWifiConvertRangingParamsFromChre(in, &(*out)->payload, payload,
- payloadSize, &vlaOffset);
- *outSize = payloadSize;
- return true;
- }
- return false;
-}
-
-// Decoding (CHPP --> CHRE) conversion functions
-
-static bool chppWifiConvertScanResultToChre(const struct ChppWifiScanResult *in,
- struct chreWifiScanResult *out) {
- out->ageMs = in->ageMs;
- out->capabilityInfo = in->capabilityInfo;
- out->ssidLen = in->ssidLen;
- memcpy(out->ssid, in->ssid, sizeof(out->ssid));
- memcpy(out->bssid, in->bssid, sizeof(out->bssid));
- out->flags = in->flags;
- out->rssi = in->rssi;
- out->band = in->band;
- out->primaryChannel = in->primaryChannel;
- out->centerFreqPrimary = in->centerFreqPrimary;
- out->centerFreqSecondary = in->centerFreqSecondary;
- out->channelWidth = in->channelWidth;
- out->securityMode = in->securityMode;
- out->radioChain = in->radioChain;
- out->rssiChain0 = in->rssiChain0;
- out->rssiChain1 = in->rssiChain1;
- memset(&out->reserved, 0, sizeof(out->reserved));
-
- return true;
-}
-
-static bool chppWifiConvertScanEventToChre(const struct ChppWifiScanEvent *in,
- struct chreWifiScanEvent *out,
- size_t inSize) {
- out->version = CHRE_WIFI_SCAN_EVENT_VERSION;
- out->resultCount = in->resultCount;
- out->resultTotal = in->resultTotal;
- out->eventIndex = in->eventIndex;
- out->scanType = in->scanType;
- out->ssidSetSize = in->ssidSetSize;
- out->scannedFreqListLen = in->scannedFreqListLen;
- out->referenceTime = in->referenceTime;
-
- if (in->scannedFreqList.length == 0) {
- out->scannedFreqList = NULL;
- } else {
- if (in->scannedFreqList.offset + in->scannedFreqList.length > inSize ||
- in->scannedFreqList.length !=
- in->scannedFreqListLen * sizeof(uint32_t)) {
- return false;
- }
-
- uint32_t *scannedFreqListOut =
- chppMalloc(in->scannedFreqListLen * sizeof(uint32_t));
- if (scannedFreqListOut == NULL) {
- return false;
- }
-
- memcpy(scannedFreqListOut,
- &((const uint8_t *)in)[in->scannedFreqList.offset],
- in->scannedFreqListLen * sizeof(uint32_t));
- out->scannedFreqList = scannedFreqListOut;
- }
-
- if (in->results.length == 0) {
- out->results = NULL;
- } else {
- if (in->results.offset + in->results.length > inSize ||
- in->results.length !=
- in->resultCount * sizeof(struct ChppWifiScanResult)) {
- return false;
- }
-
- const struct ChppWifiScanResult *resultsIn =
- (const struct ChppWifiScanResult *)&(
- (const uint8_t *)in)[in->results.offset];
-
- struct chreWifiScanResult *resultsOut =
- chppMalloc(in->resultCount * sizeof(struct chreWifiScanResult));
- if (resultsOut == NULL) {
- return false;
- }
-
- for (size_t i = 0; i < in->resultCount; i++) {
- if (!chppWifiConvertScanResultToChre(&resultsIn[i], &resultsOut[i])) {
- return false;
- }
- }
- out->results = resultsOut;
- }
-
- out->radioChainPref = in->radioChainPref;
-
- return true;
-}
-
-static bool chppWifiConvertSsidListItemToChre(
- const struct ChppWifiSsidListItem *in, struct chreWifiSsidListItem *out) {
- out->ssidLen = in->ssidLen;
- memcpy(out->ssid, in->ssid, sizeof(out->ssid));
-
- return true;
-}
-
-static bool chppWifiConvertScanParamsToChre(const struct ChppWifiScanParams *in,
- struct chreWifiScanParams *out,
- size_t inSize) {
- out->scanType = in->scanType;
- out->maxScanAgeMs = in->maxScanAgeMs;
- out->frequencyListLen = in->frequencyListLen;
-
- if (in->frequencyList.length == 0) {
- out->frequencyList = NULL;
- } else {
- if (in->frequencyList.offset + in->frequencyList.length > inSize ||
- in->frequencyList.length != in->frequencyListLen * sizeof(uint32_t)) {
- return false;
- }
-
- uint32_t *frequencyListOut =
- chppMalloc(in->frequencyListLen * sizeof(uint32_t));
- if (frequencyListOut == NULL) {
- return false;
- }
-
- memcpy(frequencyListOut, &((const uint8_t *)in)[in->frequencyList.offset],
- in->frequencyListLen * sizeof(uint32_t));
- out->frequencyList = frequencyListOut;
- }
-
- out->ssidListLen = in->ssidListLen;
-
- if (in->ssidList.length == 0) {
- out->ssidList = NULL;
- } else {
- if (in->ssidList.offset + in->ssidList.length > inSize ||
- in->ssidList.length !=
- in->ssidListLen * sizeof(struct ChppWifiSsidListItem)) {
- return false;
- }
-
- const struct ChppWifiSsidListItem *ssidListIn =
- (const struct ChppWifiSsidListItem *)&(
- (const uint8_t *)in)[in->ssidList.offset];
-
- struct chreWifiSsidListItem *ssidListOut =
- chppMalloc(in->ssidListLen * sizeof(struct chreWifiSsidListItem));
- if (ssidListOut == NULL) {
- return false;
- }
-
- for (size_t i = 0; i < in->ssidListLen; i++) {
- if (!chppWifiConvertSsidListItemToChre(&ssidListIn[i], &ssidListOut[i])) {
- return false;
- }
- }
- out->ssidList = ssidListOut;
- }
-
- out->radioChainPref = in->radioChainPref;
- out->channelSet = in->channelSet;
-
- return true;
-}
-
-static bool chppWifiConvertLciToChre(const struct ChppWifiLci *in,
- struct chreWifiLci *out) {
- out->latitude = in->latitude;
- out->longitude = in->longitude;
- out->altitude = in->altitude;
- out->latitudeUncertainty = in->latitudeUncertainty;
- out->longitudeUncertainty = in->longitudeUncertainty;
- out->altitudeType = in->altitudeType;
- out->altitudeUncertainty = in->altitudeUncertainty;
-
- return true;
-}
-
-static bool chppWifiConvertRangingResultToChre(
- const struct ChppWifiRangingResult *in, struct chreWifiRangingResult *out) {
- out->timestamp = in->timestamp;
- memcpy(out->macAddress, in->macAddress, sizeof(out->macAddress));
- out->status = in->status;
- out->rssi = in->rssi;
- out->distance = in->distance;
- out->distanceStdDev = in->distanceStdDev;
- if (!chppWifiConvertLciToChre(&in->lci, &out->lci)) {
- return false;
- }
- out->flags = in->flags;
- memset(&out->reserved, 0, sizeof(out->reserved));
-
- return true;
-}
-
-static bool chppWifiConvertRangingEventToChre(
- const struct ChppWifiRangingEvent *in, struct chreWifiRangingEvent *out,
- size_t inSize) {
- out->version = CHRE_WIFI_RANGING_EVENT_VERSION;
- out->resultCount = in->resultCount;
- memset(&out->reserved, 0, sizeof(out->reserved));
-
- if (in->results.length == 0) {
- out->results = NULL;
- } else {
- if (in->results.offset + in->results.length > inSize ||
- in->results.length !=
- in->resultCount * sizeof(struct ChppWifiRangingResult)) {
- return false;
- }
-
- const struct ChppWifiRangingResult *resultsIn =
- (const struct ChppWifiRangingResult *)&(
- (const uint8_t *)in)[in->results.offset];
-
- struct chreWifiRangingResult *resultsOut =
- chppMalloc(in->resultCount * sizeof(struct chreWifiRangingResult));
- if (resultsOut == NULL) {
- return false;
- }
-
- for (size_t i = 0; i < in->resultCount; i++) {
- if (!chppWifiConvertRangingResultToChre(&resultsIn[i], &resultsOut[i])) {
- return false;
- }
- }
- out->results = resultsOut;
- }
-
- return true;
-}
-
-static bool chppWifiConvertRangingTargetToChre(
- const struct ChppWifiRangingTarget *in, struct chreWifiRangingTarget *out) {
- memcpy(out->macAddress, in->macAddress, sizeof(out->macAddress));
- out->primaryChannel = in->primaryChannel;
- out->centerFreqPrimary = in->centerFreqPrimary;
- out->centerFreqSecondary = in->centerFreqSecondary;
- out->channelWidth = in->channelWidth;
- memset(&out->reserved, 0, sizeof(out->reserved));
-
- return true;
-}
-
-static bool chppWifiConvertRangingParamsToChre(
- const struct ChppWifiRangingParams *in, struct chreWifiRangingParams *out,
- size_t inSize) {
- out->targetListLen = in->targetListLen;
-
- if (in->targetList.length == 0) {
- out->targetList = NULL;
- } else {
- if (in->targetList.offset + in->targetList.length > inSize ||
- in->targetList.length !=
- in->targetListLen * sizeof(struct ChppWifiRangingTarget)) {
- return false;
- }
-
- const struct ChppWifiRangingTarget *targetListIn =
- (const struct ChppWifiRangingTarget *)&(
- (const uint8_t *)in)[in->targetList.offset];
-
- struct chreWifiRangingTarget *targetListOut =
- chppMalloc(in->targetListLen * sizeof(struct chreWifiRangingTarget));
- if (targetListOut == NULL) {
- return false;
- }
-
- for (size_t i = 0; i < in->targetListLen; i++) {
- if (!chppWifiConvertRangingTargetToChre(&targetListIn[i],
- &targetListOut[i])) {
- return false;
- }
- }
- out->targetList = targetListOut;
- }
-
- return true;
-}
-
-// Decoding (CHPP --> CHRE) top-level functions
-
-struct chreWifiScanEvent *chppWifiScanEventToChre(
- const struct ChppWifiScanEvent *in, size_t inSize) {
- struct chreWifiScanEvent *out = NULL;
-
- if (inSize >= sizeof(struct ChppWifiScanEvent)) {
- out = chppMalloc(sizeof(struct chreWifiScanEvent));
- if (out != NULL) {
- if (!chppWifiConvertScanEventToChre(in, out, inSize)) {
- CHPP_FREE_AND_NULLIFY(out);
- }
- }
- }
-
- return out;
-}
-struct chreWifiScanParams *chppWifiScanParamsToChre(
- const struct ChppWifiScanParams *in, size_t inSize) {
- struct chreWifiScanParams *out = NULL;
-
- if (inSize >= sizeof(struct ChppWifiScanParams)) {
- out = chppMalloc(sizeof(struct chreWifiScanParams));
- if (out != NULL) {
- if (!chppWifiConvertScanParamsToChre(in, out, inSize)) {
- CHPP_FREE_AND_NULLIFY(out);
- }
- }
- }
-
- return out;
-}
-struct chreWifiRangingEvent *chppWifiRangingEventToChre(
- const struct ChppWifiRangingEvent *in, size_t inSize) {
- struct chreWifiRangingEvent *out = NULL;
-
- if (inSize >= sizeof(struct ChppWifiRangingEvent)) {
- out = chppMalloc(sizeof(struct chreWifiRangingEvent));
- if (out != NULL) {
- if (!chppWifiConvertRangingEventToChre(in, out, inSize)) {
- CHPP_FREE_AND_NULLIFY(out);
- }
- }
- }
-
- return out;
-}
-struct chreWifiRangingParams *chppWifiRangingParamsToChre(
- const struct ChppWifiRangingParams *in, size_t inSize) {
- struct chreWifiRangingParams *out = NULL;
-
- if (inSize >= sizeof(struct ChppWifiRangingParams)) {
- out = chppMalloc(sizeof(struct chreWifiRangingParams));
- if (out != NULL) {
- if (!chppWifiConvertRangingParamsToChre(in, out, inSize)) {
- CHPP_FREE_AND_NULLIFY(out);
- }
- }
- }
-
- return out;
-}
diff --git a/chpp/common/wifi_utils.c b/chpp/common/wifi_utils.c
deleted file mode 100644
index 8a9a7793..00000000
--- a/chpp/common/wifi_utils.c
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 "chpp/common/wifi_utils.h"
-
-#include <inttypes.h>
-
-#include "chpp/log.h"
-
-static uint8_t gResultTotal = 0;
-static uint8_t gResultAcc = 0;
-static uint8_t gExpectedIndex = 0;
-
-void chppCheckWifiScanEventNotificationReset() {
- gResultTotal = 0;
- gResultAcc = 0;
- gExpectedIndex = 0;
-}
-
-bool chppCheckWifiScanEventNotification(const struct chreWifiScanEvent *chre) {
- bool success = true;
-
- if (chre->eventIndex != gExpectedIndex) {
- CHPP_LOGE("Unexpected scan index %" PRIu8 " exp %" PRIu8, chre->eventIndex,
- gExpectedIndex);
- success = false;
- }
- if (chre->eventIndex == 0) {
- if (gResultAcc < gResultTotal) {
- CHPP_LOGE("Too few prev scan results (%" PRIu8 " missing)",
- gResultTotal - gResultAcc);
- success = false;
- }
- gExpectedIndex = 0;
- gResultAcc = 0;
- gResultTotal = chre->resultTotal;
- }
-
- if (gResultTotal != chre->resultTotal) {
- CHPP_LOGE("Inconsistent result total %" PRIu8 " exp %" PRIu8,
- chre->resultTotal, gResultTotal);
- success = false;
- }
-
- gResultAcc += chre->resultCount;
-
- if (gResultAcc >= gResultTotal) {
- if (gResultAcc > gResultTotal) {
- CHPP_LOGE("Too many scan results (%" PRIu8 " extra)",
- gResultAcc - gResultTotal);
- success = false;
- }
- gExpectedIndex = 0;
- } else {
- gExpectedIndex++;
- }
-
- return success;
-}
diff --git a/chpp/common/wwan_convert.c b/chpp/common/wwan_convert.c
deleted file mode 100644
index 9cf7872f..00000000
--- a/chpp/common/wwan_convert.c
+++ /dev/null
@@ -1,649 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-// This file was automatically generated by chre_api_to_chpp.py
-// Date: 2021-05-24 15:46:25 UTC
-// Source: chre_api/include/chre_api/chre/wwan.h @ commit 833a6241
-
-// DO NOT modify this file directly, as those changes will be lost the next
-// time the script is executed
-
-#include "chpp/common/wwan_types.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-// Encoding (CHRE --> CHPP) size functions
-
-//! @return number of bytes required to represent the given
-//! chreWwanCellInfoResult along with the CHPP header as
-//! struct ChppWwanCellInfoResultWithHeader
-static size_t chppWwanSizeOfCellInfoResultFromChre(
- const struct chreWwanCellInfoResult *cellInfoResult) {
- size_t encodedSize = sizeof(struct ChppWwanCellInfoResultWithHeader);
- encodedSize +=
- cellInfoResult->cellInfoCount * sizeof(struct ChppWwanCellInfo);
- return encodedSize;
-}
-
-// Encoding (CHRE --> CHPP) conversion functions
-
-static void chppWwanConvertCellIdentityCdmaFromChre(
- const struct chreWwanCellIdentityCdma *in,
- struct ChppWwanCellIdentityCdma *out) {
- out->networkId = in->networkId;
- out->systemId = in->systemId;
- out->basestationId = in->basestationId;
- out->longitude = in->longitude;
- out->latitude = in->latitude;
-}
-
-static void chppWwanConvertSignalStrengthCdmaFromChre(
- const struct chreWwanSignalStrengthCdma *in,
- struct ChppWwanSignalStrengthCdma *out) {
- out->dbm = in->dbm;
- out->ecio = in->ecio;
-}
-
-static void chppWwanConvertSignalStrengthEvdoFromChre(
- const struct chreWwanSignalStrengthEvdo *in,
- struct ChppWwanSignalStrengthEvdo *out) {
- out->dbm = in->dbm;
- out->ecio = in->ecio;
- out->signalNoiseRatio = in->signalNoiseRatio;
-}
-
-static void chppWwanConvertCellInfoCdmaFromChre(
- const struct chreWwanCellInfoCdma *in, struct ChppWwanCellInfoCdma *out) {
- chppWwanConvertCellIdentityCdmaFromChre(&in->cellIdentityCdma,
- &out->cellIdentityCdma);
- chppWwanConvertSignalStrengthCdmaFromChre(&in->signalStrengthCdma,
- &out->signalStrengthCdma);
- chppWwanConvertSignalStrengthEvdoFromChre(&in->signalStrengthEvdo,
- &out->signalStrengthEvdo);
-}
-
-static void chppWwanConvertCellIdentityGsmFromChre(
- const struct chreWwanCellIdentityGsm *in,
- struct ChppWwanCellIdentityGsm *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->lac = in->lac;
- out->cid = in->cid;
- out->arfcn = in->arfcn;
- out->bsic = in->bsic;
- memset(&out->reserved, 0, sizeof(out->reserved));
-}
-
-static void chppWwanConvertSignalStrengthGsmFromChre(
- const struct chreWwanSignalStrengthGsm *in,
- struct ChppWwanSignalStrengthGsm *out) {
- out->signalStrength = in->signalStrength;
- out->bitErrorRate = in->bitErrorRate;
- out->timingAdvance = in->timingAdvance;
-}
-
-static void chppWwanConvertCellInfoGsmFromChre(
- const struct chreWwanCellInfoGsm *in, struct ChppWwanCellInfoGsm *out) {
- chppWwanConvertCellIdentityGsmFromChre(&in->cellIdentityGsm,
- &out->cellIdentityGsm);
- chppWwanConvertSignalStrengthGsmFromChre(&in->signalStrengthGsm,
- &out->signalStrengthGsm);
-}
-
-static void chppWwanConvertCellIdentityLteFromChre(
- const struct chreWwanCellIdentityLte *in,
- struct ChppWwanCellIdentityLte *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->ci = in->ci;
- out->pci = in->pci;
- out->tac = in->tac;
- out->earfcn = in->earfcn;
-}
-
-static void chppWwanConvertSignalStrengthLteFromChre(
- const struct chreWwanSignalStrengthLte *in,
- struct ChppWwanSignalStrengthLte *out) {
- out->signalStrength = in->signalStrength;
- out->rsrp = in->rsrp;
- out->rsrq = in->rsrq;
- out->rssnr = in->rssnr;
- out->cqi = in->cqi;
- out->timingAdvance = in->timingAdvance;
-}
-
-static void chppWwanConvertCellInfoLteFromChre(
- const struct chreWwanCellInfoLte *in, struct ChppWwanCellInfoLte *out) {
- chppWwanConvertCellIdentityLteFromChre(&in->cellIdentityLte,
- &out->cellIdentityLte);
- chppWwanConvertSignalStrengthLteFromChre(&in->signalStrengthLte,
- &out->signalStrengthLte);
-}
-
-static void chppWwanConvertCellIdentityNrFromChre(
- const struct chreWwanCellIdentityNr *in,
- struct ChppWwanCellIdentityNr *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->nci0 = in->nci0;
- out->nci1 = in->nci1;
- out->pci = in->pci;
- out->tac = in->tac;
- out->nrarfcn = in->nrarfcn;
-}
-
-static void chppWwanConvertSignalStrengthNrFromChre(
- const struct chreWwanSignalStrengthNr *in,
- struct ChppWwanSignalStrengthNr *out) {
- out->ssRsrp = in->ssRsrp;
- out->ssRsrq = in->ssRsrq;
- out->ssSinr = in->ssSinr;
- out->csiRsrp = in->csiRsrp;
- out->csiRsrq = in->csiRsrq;
- out->csiSinr = in->csiSinr;
-}
-
-static void chppWwanConvertCellInfoNrFromChre(
- const struct chreWwanCellInfoNr *in, struct ChppWwanCellInfoNr *out) {
- chppWwanConvertCellIdentityNrFromChre(&in->cellIdentityNr,
- &out->cellIdentityNr);
- chppWwanConvertSignalStrengthNrFromChre(&in->signalStrengthNr,
- &out->signalStrengthNr);
-}
-
-static void chppWwanConvertCellIdentityTdscdmaFromChre(
- const struct chreWwanCellIdentityTdscdma *in,
- struct ChppWwanCellIdentityTdscdma *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->lac = in->lac;
- out->cid = in->cid;
- out->cpid = in->cpid;
-}
-
-static void chppWwanConvertSignalStrengthTdscdmaFromChre(
- const struct chreWwanSignalStrengthTdscdma *in,
- struct ChppWwanSignalStrengthTdscdma *out) {
- out->rscp = in->rscp;
-}
-
-static void chppWwanConvertCellInfoTdscdmaFromChre(
- const struct chreWwanCellInfoTdscdma *in,
- struct ChppWwanCellInfoTdscdma *out) {
- chppWwanConvertCellIdentityTdscdmaFromChre(&in->cellIdentityTdscdma,
- &out->cellIdentityTdscdma);
- chppWwanConvertSignalStrengthTdscdmaFromChre(&in->signalStrengthTdscdma,
- &out->signalStrengthTdscdma);
-}
-
-static void chppWwanConvertCellIdentityWcdmaFromChre(
- const struct chreWwanCellIdentityWcdma *in,
- struct ChppWwanCellIdentityWcdma *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->lac = in->lac;
- out->cid = in->cid;
- out->psc = in->psc;
- out->uarfcn = in->uarfcn;
-}
-
-static void chppWwanConvertSignalStrengthWcdmaFromChre(
- const struct chreWwanSignalStrengthWcdma *in,
- struct ChppWwanSignalStrengthWcdma *out) {
- out->signalStrength = in->signalStrength;
- out->bitErrorRate = in->bitErrorRate;
-}
-
-static void chppWwanConvertCellInfoWcdmaFromChre(
- const struct chreWwanCellInfoWcdma *in, struct ChppWwanCellInfoWcdma *out) {
- chppWwanConvertCellIdentityWcdmaFromChre(&in->cellIdentityWcdma,
- &out->cellIdentityWcdma);
- chppWwanConvertSignalStrengthWcdmaFromChre(&in->signalStrengthWcdma,
- &out->signalStrengthWcdma);
-}
-
-static void chppWwanConvertCellInfoFromChre(const struct chreWwanCellInfo *in,
- struct ChppWwanCellInfo *out) {
- out->timeStamp = in->timeStamp;
- out->cellInfoType = in->cellInfoType;
- out->timeStampType = in->timeStampType;
- out->registered = in->registered;
- out->reserved = 0;
- memset(&out->CellInfo, 0, sizeof(out->CellInfo));
- switch (in->cellInfoType) {
- case CHRE_WWAN_CELL_INFO_TYPE_GSM:
- chppWwanConvertCellInfoGsmFromChre(&in->CellInfo.gsm, &out->CellInfo.gsm);
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_CDMA:
- chppWwanConvertCellInfoCdmaFromChre(&in->CellInfo.cdma,
- &out->CellInfo.cdma);
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_LTE:
- chppWwanConvertCellInfoLteFromChre(&in->CellInfo.lte, &out->CellInfo.lte);
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_WCDMA:
- chppWwanConvertCellInfoWcdmaFromChre(&in->CellInfo.wcdma,
- &out->CellInfo.wcdma);
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_TD_SCDMA:
- chppWwanConvertCellInfoTdscdmaFromChre(&in->CellInfo.tdscdma,
- &out->CellInfo.tdscdma);
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_NR:
- chppWwanConvertCellInfoNrFromChre(&in->CellInfo.nr, &out->CellInfo.nr);
- break;
- default:
- CHPP_ASSERT(false);
- }
-}
-
-static void chppWwanConvertCellInfoResultFromChre(
- const struct chreWwanCellInfoResult *in, struct ChppWwanCellInfoResult *out,
- uint8_t *payload, size_t payloadSize, uint16_t *vlaOffset) {
- out->version = CHRE_WWAN_CELL_INFO_RESULT_VERSION;
- out->errorCode = in->errorCode;
- out->cellInfoCount = in->cellInfoCount;
- out->reserved = 0;
- out->cookie = 0;
-
- struct ChppWwanCellInfo *cells =
- (struct ChppWwanCellInfo *)&payload[*vlaOffset];
- out->cells.length = in->cellInfoCount * sizeof(struct ChppWwanCellInfo);
- CHPP_ASSERT((size_t)(*vlaOffset + out->cells.length) <= payloadSize);
- if (out->cells.length > 0 && *vlaOffset + out->cells.length <= payloadSize) {
- for (size_t i = 0; i < in->cellInfoCount; i++) {
- chppWwanConvertCellInfoFromChre(&in->cells[i], &cells[i]);
- }
- out->cells.offset = *vlaOffset;
- *vlaOffset += out->cells.length;
- } else {
- out->cells.offset = 0;
- }
-}
-
-// Encoding (CHRE --> CHPP) top-level functions
-
-bool chppWwanCellInfoResultFromChre(
- const struct chreWwanCellInfoResult *in,
- struct ChppWwanCellInfoResultWithHeader **out, size_t *outSize) {
- CHPP_NOT_NULL(out);
- CHPP_NOT_NULL(outSize);
-
- size_t payloadSize = chppWwanSizeOfCellInfoResultFromChre(in);
- *out = chppMalloc(payloadSize);
- if (*out != NULL) {
- uint8_t *payload = (uint8_t *)&(*out)->payload;
- uint16_t vlaOffset = sizeof(struct ChppWwanCellInfoResult);
- chppWwanConvertCellInfoResultFromChre(in, &(*out)->payload, payload,
- payloadSize, &vlaOffset);
- *outSize = payloadSize;
- return true;
- }
- return false;
-}
-
-// Decoding (CHPP --> CHRE) conversion functions
-
-static bool chppWwanConvertCellIdentityCdmaToChre(
- const struct ChppWwanCellIdentityCdma *in,
- struct chreWwanCellIdentityCdma *out) {
- out->networkId = in->networkId;
- out->systemId = in->systemId;
- out->basestationId = in->basestationId;
- out->longitude = in->longitude;
- out->latitude = in->latitude;
-
- return true;
-}
-
-static bool chppWwanConvertSignalStrengthCdmaToChre(
- const struct ChppWwanSignalStrengthCdma *in,
- struct chreWwanSignalStrengthCdma *out) {
- out->dbm = in->dbm;
- out->ecio = in->ecio;
-
- return true;
-}
-
-static bool chppWwanConvertSignalStrengthEvdoToChre(
- const struct ChppWwanSignalStrengthEvdo *in,
- struct chreWwanSignalStrengthEvdo *out) {
- out->dbm = in->dbm;
- out->ecio = in->ecio;
- out->signalNoiseRatio = in->signalNoiseRatio;
-
- return true;
-}
-
-static bool chppWwanConvertCellInfoCdmaToChre(
- const struct ChppWwanCellInfoCdma *in, struct chreWwanCellInfoCdma *out) {
- if (!chppWwanConvertCellIdentityCdmaToChre(&in->cellIdentityCdma,
- &out->cellIdentityCdma)) {
- return false;
- }
- if (!chppWwanConvertSignalStrengthCdmaToChre(&in->signalStrengthCdma,
- &out->signalStrengthCdma)) {
- return false;
- }
- if (!chppWwanConvertSignalStrengthEvdoToChre(&in->signalStrengthEvdo,
- &out->signalStrengthEvdo)) {
- return false;
- }
-
- return true;
-}
-
-static bool chppWwanConvertCellIdentityGsmToChre(
- const struct ChppWwanCellIdentityGsm *in,
- struct chreWwanCellIdentityGsm *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->lac = in->lac;
- out->cid = in->cid;
- out->arfcn = in->arfcn;
- out->bsic = in->bsic;
- memset(&out->reserved, 0, sizeof(out->reserved));
-
- return true;
-}
-
-static bool chppWwanConvertSignalStrengthGsmToChre(
- const struct ChppWwanSignalStrengthGsm *in,
- struct chreWwanSignalStrengthGsm *out) {
- out->signalStrength = in->signalStrength;
- out->bitErrorRate = in->bitErrorRate;
- out->timingAdvance = in->timingAdvance;
-
- return true;
-}
-
-static bool chppWwanConvertCellInfoGsmToChre(
- const struct ChppWwanCellInfoGsm *in, struct chreWwanCellInfoGsm *out) {
- if (!chppWwanConvertCellIdentityGsmToChre(&in->cellIdentityGsm,
- &out->cellIdentityGsm)) {
- return false;
- }
- if (!chppWwanConvertSignalStrengthGsmToChre(&in->signalStrengthGsm,
- &out->signalStrengthGsm)) {
- return false;
- }
-
- return true;
-}
-
-static bool chppWwanConvertCellIdentityLteToChre(
- const struct ChppWwanCellIdentityLte *in,
- struct chreWwanCellIdentityLte *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->ci = in->ci;
- out->pci = in->pci;
- out->tac = in->tac;
- out->earfcn = in->earfcn;
-
- return true;
-}
-
-static bool chppWwanConvertSignalStrengthLteToChre(
- const struct ChppWwanSignalStrengthLte *in,
- struct chreWwanSignalStrengthLte *out) {
- out->signalStrength = in->signalStrength;
- out->rsrp = in->rsrp;
- out->rsrq = in->rsrq;
- out->rssnr = in->rssnr;
- out->cqi = in->cqi;
- out->timingAdvance = in->timingAdvance;
-
- return true;
-}
-
-static bool chppWwanConvertCellInfoLteToChre(
- const struct ChppWwanCellInfoLte *in, struct chreWwanCellInfoLte *out) {
- if (!chppWwanConvertCellIdentityLteToChre(&in->cellIdentityLte,
- &out->cellIdentityLte)) {
- return false;
- }
- if (!chppWwanConvertSignalStrengthLteToChre(&in->signalStrengthLte,
- &out->signalStrengthLte)) {
- return false;
- }
-
- return true;
-}
-
-static bool chppWwanConvertCellIdentityNrToChre(
- const struct ChppWwanCellIdentityNr *in,
- struct chreWwanCellIdentityNr *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->nci0 = in->nci0;
- out->nci1 = in->nci1;
- out->pci = in->pci;
- out->tac = in->tac;
- out->nrarfcn = in->nrarfcn;
-
- return true;
-}
-
-static bool chppWwanConvertSignalStrengthNrToChre(
- const struct ChppWwanSignalStrengthNr *in,
- struct chreWwanSignalStrengthNr *out) {
- out->ssRsrp = in->ssRsrp;
- out->ssRsrq = in->ssRsrq;
- out->ssSinr = in->ssSinr;
- out->csiRsrp = in->csiRsrp;
- out->csiRsrq = in->csiRsrq;
- out->csiSinr = in->csiSinr;
-
- return true;
-}
-
-static bool chppWwanConvertCellInfoNrToChre(const struct ChppWwanCellInfoNr *in,
- struct chreWwanCellInfoNr *out) {
- if (!chppWwanConvertCellIdentityNrToChre(&in->cellIdentityNr,
- &out->cellIdentityNr)) {
- return false;
- }
- if (!chppWwanConvertSignalStrengthNrToChre(&in->signalStrengthNr,
- &out->signalStrengthNr)) {
- return false;
- }
-
- return true;
-}
-
-static bool chppWwanConvertCellIdentityTdscdmaToChre(
- const struct ChppWwanCellIdentityTdscdma *in,
- struct chreWwanCellIdentityTdscdma *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->lac = in->lac;
- out->cid = in->cid;
- out->cpid = in->cpid;
-
- return true;
-}
-
-static bool chppWwanConvertSignalStrengthTdscdmaToChre(
- const struct ChppWwanSignalStrengthTdscdma *in,
- struct chreWwanSignalStrengthTdscdma *out) {
- out->rscp = in->rscp;
-
- return true;
-}
-
-static bool chppWwanConvertCellInfoTdscdmaToChre(
- const struct ChppWwanCellInfoTdscdma *in,
- struct chreWwanCellInfoTdscdma *out) {
- if (!chppWwanConvertCellIdentityTdscdmaToChre(&in->cellIdentityTdscdma,
- &out->cellIdentityTdscdma)) {
- return false;
- }
- if (!chppWwanConvertSignalStrengthTdscdmaToChre(
- &in->signalStrengthTdscdma, &out->signalStrengthTdscdma)) {
- return false;
- }
-
- return true;
-}
-
-static bool chppWwanConvertCellIdentityWcdmaToChre(
- const struct ChppWwanCellIdentityWcdma *in,
- struct chreWwanCellIdentityWcdma *out) {
- out->mcc = in->mcc;
- out->mnc = in->mnc;
- out->lac = in->lac;
- out->cid = in->cid;
- out->psc = in->psc;
- out->uarfcn = in->uarfcn;
-
- return true;
-}
-
-static bool chppWwanConvertSignalStrengthWcdmaToChre(
- const struct ChppWwanSignalStrengthWcdma *in,
- struct chreWwanSignalStrengthWcdma *out) {
- out->signalStrength = in->signalStrength;
- out->bitErrorRate = in->bitErrorRate;
-
- return true;
-}
-
-static bool chppWwanConvertCellInfoWcdmaToChre(
- const struct ChppWwanCellInfoWcdma *in, struct chreWwanCellInfoWcdma *out) {
- if (!chppWwanConvertCellIdentityWcdmaToChre(&in->cellIdentityWcdma,
- &out->cellIdentityWcdma)) {
- return false;
- }
- if (!chppWwanConvertSignalStrengthWcdmaToChre(&in->signalStrengthWcdma,
- &out->signalStrengthWcdma)) {
- return false;
- }
-
- return true;
-}
-
-static bool chppWwanConvertCellInfoToChre(const struct ChppWwanCellInfo *in,
- struct chreWwanCellInfo *out) {
- out->timeStamp = in->timeStamp;
- out->cellInfoType = in->cellInfoType;
- out->timeStampType = in->timeStampType;
- out->registered = in->registered;
- out->reserved = 0;
- memset(&out->CellInfo, 0, sizeof(out->CellInfo));
- switch (in->cellInfoType) {
- case CHRE_WWAN_CELL_INFO_TYPE_GSM:
- if (!chppWwanConvertCellInfoGsmToChre(&in->CellInfo.gsm,
- &out->CellInfo.gsm)) {
- return false;
- }
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_CDMA:
- if (!chppWwanConvertCellInfoCdmaToChre(&in->CellInfo.cdma,
- &out->CellInfo.cdma)) {
- return false;
- }
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_LTE:
- if (!chppWwanConvertCellInfoLteToChre(&in->CellInfo.lte,
- &out->CellInfo.lte)) {
- return false;
- }
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_WCDMA:
- if (!chppWwanConvertCellInfoWcdmaToChre(&in->CellInfo.wcdma,
- &out->CellInfo.wcdma)) {
- return false;
- }
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_TD_SCDMA:
- if (!chppWwanConvertCellInfoTdscdmaToChre(&in->CellInfo.tdscdma,
- &out->CellInfo.tdscdma)) {
- return false;
- }
- break;
- case CHRE_WWAN_CELL_INFO_TYPE_NR:
- if (!chppWwanConvertCellInfoNrToChre(&in->CellInfo.nr,
- &out->CellInfo.nr)) {
- return false;
- }
- break;
- default:
- CHPP_ASSERT(false);
- }
-
- return true;
-}
-
-static bool chppWwanConvertCellInfoResultToChre(
- const struct ChppWwanCellInfoResult *in, struct chreWwanCellInfoResult *out,
- size_t inSize) {
- out->version = CHRE_WWAN_CELL_INFO_RESULT_VERSION;
- out->errorCode = in->errorCode;
- out->cellInfoCount = in->cellInfoCount;
- out->reserved = 0;
- out->cookie = 0;
-
- if (in->cells.length == 0) {
- out->cells = NULL;
- } else {
- if (in->cells.offset + in->cells.length > inSize ||
- in->cells.length !=
- in->cellInfoCount * sizeof(struct ChppWwanCellInfo)) {
- return false;
- }
-
- const struct ChppWwanCellInfo *cellsIn = (const struct ChppWwanCellInfo *)&(
- (const uint8_t *)in)[in->cells.offset];
-
- struct chreWwanCellInfo *cellsOut =
- chppMalloc(in->cellInfoCount * sizeof(struct chreWwanCellInfo));
- if (cellsOut == NULL) {
- return false;
- }
-
- for (size_t i = 0; i < in->cellInfoCount; i++) {
- if (!chppWwanConvertCellInfoToChre(&cellsIn[i], &cellsOut[i])) {
- return false;
- }
- }
- out->cells = cellsOut;
- }
-
- return true;
-}
-
-// Decoding (CHPP --> CHRE) top-level functions
-
-struct chreWwanCellInfoResult *chppWwanCellInfoResultToChre(
- const struct ChppWwanCellInfoResult *in, size_t inSize) {
- struct chreWwanCellInfoResult *out = NULL;
-
- if (inSize >= sizeof(struct ChppWwanCellInfoResult)) {
- out = chppMalloc(sizeof(struct chreWwanCellInfoResult));
- if (out != NULL) {
- if (!chppWwanConvertCellInfoResultToChre(in, out, inSize)) {
- CHPP_FREE_AND_NULLIFY(out);
- }
- }
- }
-
- return out;
-}
diff --git a/chpp/include/chpp/app.h b/chpp/include/chpp/app.h
deleted file mode 100644
index 291a3a62..00000000
--- a/chpp/include/chpp/app.h
+++ /dev/null
@@ -1,507 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_APP_H_
-#define CHPP_APP_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/condition_variable.h"
-#include "chpp/macros.h"
-#include "chpp/transport.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/**
- * Maximum number of services that can be registered by CHPP (not including
- * predefined services), if not defined by the build system.
- */
-#ifndef CHPP_MAX_REGISTERED_SERVICES
-#define CHPP_MAX_REGISTERED_SERVICES 1
-#endif
-
-/**
- * Maximum number of clients that can be registered by CHPP (not including
- * predefined clients), if not defined by the build system.
- */
-#ifndef CHPP_MAX_REGISTERED_CLIENTS
-#define CHPP_MAX_REGISTERED_CLIENTS 1
-#endif
-
-/**
- * Maximum number of services that can be discovered by CHPP (not including
- * predefined services), if not defined by the build system.
- */
-#ifndef CHPP_MAX_DISCOVERED_SERVICES
-#define CHPP_MAX_DISCOVERED_SERVICES \
- MAX(CHPP_MAX_REGISTERED_SERVICES, CHPP_MAX_REGISTERED_CLIENTS)
-#endif
-
-/**
- * Default value for reserved fields.
- */
-#define CHPP_RESERVED 0
-
-/**
- * Client index number when there is no matching client
- */
-#define CHPP_CLIENT_INDEX_NONE 0xff
-
-/**
- * App layer command at initialization.
- */
-#define CHPP_APP_COMMAND_NONE 0
-
-/**
- * Handle Numbers in ChppAppHeader
- */
-enum ChppHandleNumber {
- //! Handleless communication
- CHPP_HANDLE_NONE = 0x00,
-
- //! Loopback Service
- CHPP_HANDLE_LOOPBACK = 0x01,
-
- //! Time Service
- CHPP_HANDLE_TIMESYNC = 0x02,
-
- //! Discovery Service
- CHPP_HANDLE_DISCOVERY = 0x0F,
-
- //! Negotiated Services (starting from this offset)
- CHPP_HANDLE_NEGOTIATED_RANGE_START = 0x10,
-};
-
-/**
- * Message Types as used in ChppAppHeader
- */
-#define CHPP_APP_MASK_MESSAGE_TYPE LEAST_SIGNIFICANT_NIBBLE
-#define CHPP_APP_GET_MESSAGE_TYPE(value) \
- ((enum ChppMessageType)( \
- (value)&CHPP_APP_MASK_MESSAGE_TYPE)) // TODO: Consider checking if this
- // maps into a valid enum
-enum ChppMessageType {
- //! Request from client. Needs response from service.
- CHPP_MESSAGE_TYPE_CLIENT_REQUEST = 0,
-
- //! Response from service (with the same Command and Transaction ID as the
- //! client request).
- CHPP_MESSAGE_TYPE_SERVICE_RESPONSE = 1,
-
- //! Notification from client. Service shall not respond.
- CHPP_MESSAGE_TYPE_CLIENT_NOTIFICATION = 2,
-
- //! Notification from service. Client shall not respond.
- CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION = 3,
-};
-
-/**
- * Error codes used by the app layer / clients / services.
- */
-enum ChppAppErrorCode {
- //! Success (no error)
- CHPP_APP_ERROR_NONE = 0,
- //! Invalid command
- CHPP_APP_ERROR_INVALID_COMMAND = 1,
- //! Invalid argument(s)
- CHPP_APP_ERROR_INVALID_ARG = 2,
- //! Busy
- CHPP_APP_ERROR_BUSY = 3,
- //! Out of memory
- CHPP_APP_ERROR_OOM = 4,
- //! Feature not supported
- CHPP_APP_ERROR_UNSUPPORTED = 5,
- //! Timeout
- CHPP_APP_ERROR_TIMEOUT = 6,
- //! Functionality disabled (e.g. per user configuration)
- CHPP_APP_ERROR_DISABLED = 7,
- //! Rate limit exceeded (try again later)
- CHPP_APP_ERROR_RATELIMITED = 8,
- //! Function in use / blocked by another entity (e.g. the AP)
- CHPP_APP_ERROR_BLOCKED = 9,
- //! Invalid length
- CHPP_APP_ERROR_INVALID_LENGTH = 10,
- //! CHPP Not Ready
- CHPP_APP_ERROR_NOT_READY = 11,
- //! Error outside of CHPP (e.g. PAL API)
- CHPP_APP_ERROR_BEYOND_CHPP = 12,
- //! Response not matching a pending request
- CHPP_APP_ERROR_UNEXPECTED_RESPONSE = 13,
- //! Conversion failed
- CHPP_APP_ERROR_CONVERSION_FAILED = 14,
- //! Unspecified failure
- CHPP_APP_ERROR_UNSPECIFIED = 255
-};
-
-/**
- * Open status for clients / services.
- */
-enum ChppOpenState {
- CHPP_OPEN_STATE_CLOSED = 0, // Closed
- CHPP_OPEN_STATE_OPENING = 1, // Enables the open request to pass
- CHPP_OPEN_STATE_WAITING_TO_OPEN = 2, // Waiting for open response
- CHPP_OPEN_STATE_OPENED = 3, // Opened
-};
-
-/**
- * CHPP Application Layer header
- */
-CHPP_PACKED_START
-struct ChppAppHeader {
- //! Service Handle
- uint8_t handle;
-
- //! Most significant nibble (MSN): Reserved
- //! Least significant nibble (LSN): Message Type from enum ChppMessageType
- uint8_t type;
-
- //! Transaction ID
- uint8_t transaction;
-
- //! Error if any, from enum ChppAppErrorCode
- uint8_t error;
-
- //! Command
- uint16_t command;
-
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-//! Minimum length of a header that includes upto the transaction ID
-#define CHPP_APP_MIN_LEN_HEADER_WITH_TRANSACTION (3 * sizeof(uint8_t))
-
-/**
- * Function type that dispatches incoming datagrams for any client or service
- */
-typedef enum ChppAppErrorCode(ChppDispatchFunction)(void *context, uint8_t *buf,
- size_t len);
-
-/**
- * Function type that initializes a client and assigns it its handle number
- */
-typedef bool(ChppClientInitFunction)(void *context, uint8_t handle,
- struct ChppVersion serviceVersion);
-
-/**
- * Function type that deinitializes a client.
- */
-typedef void(ChppClientDeinitFunction)(void *context);
-
-/**
- * Function type that dispatches a reset notification to any client or service
- */
-typedef void(ChppNotifierFunction)(void *context);
-
-/**
- * Length of a service UUID and its human-readable printed form in bytes
- */
-#define CHPP_SERVICE_UUID_LEN 16
-#define CHPP_SERVICE_UUID_STRING_LEN (16 * 2 + 4 + 1)
-
-/**
- * Length of a version number, in bytes (major + minor + revision), per CHPP
- * spec.
- */
-#define CHPP_SERVICE_VERSION_LEN (1 + 1 + 2)
-
-/**
- * Maximum length of a human-readable service name, per CHPP spec.
- * (15 ASCII characters + null)
- */
-#define CHPP_SERVICE_NAME_MAX_LEN (15 + 1)
-
-/**
- * CHPP definition of a service descriptor as sent over the wire.
- */
-CHPP_PACKED_START
-struct ChppServiceDescriptor {
- //! UUID of the service.
- //! Must be generated according to RFC 4122, UUID version 4 (random).
- uint8_t uuid[CHPP_SERVICE_UUID_LEN];
-
- //! Human-readable name of the service for debugging.
- char name[CHPP_SERVICE_NAME_MAX_LEN];
-
- //! Version of the service.
- struct ChppVersion version;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * CHPP definition of a service as supported on a server.
- */
-struct ChppService {
- //! Service Descriptor as sent over the wire.
- struct ChppServiceDescriptor descriptor;
-
- //! Pointer to the function that is used to notify the service if CHPP is
- //! reset.
- ChppNotifierFunction *resetNotifierFunctionPtr;
-
- //! Pointer to the function that dispatches incoming client requests for the
- //! service.
- ChppDispatchFunction *requestDispatchFunctionPtr;
-
- //! Pointer to the function that dispatches incoming client notifications for
- //! the service.
- ChppDispatchFunction *notificationDispatchFunctionPtr;
-
- //! Minimum valid length of datagrams for the service.
- size_t minLength;
-};
-
-/**
- * CHPP definition of a client descriptor.
- */
-struct ChppClientDescriptor {
- //! UUID of the client.
- //! Must be generated according to RFC 4122, UUID version 4 (random).
- uint8_t uuid[CHPP_SERVICE_UUID_LEN];
-
- //! Version of the client.
- struct ChppVersion version;
-};
-
-/**
- * CHPP definition of a client.
- */
-struct ChppClient {
- //! Client descriptor.
- struct ChppClientDescriptor descriptor;
-
- //! Pointer to the function that is used to notify the client if CHPP is
- //! reset.
- ChppNotifierFunction *resetNotifierFunctionPtr;
-
- //! Pointer to the function that is used to notify the client if CHPP is
- //! matched to a service.
- ChppNotifierFunction *matchNotifierFunctionPtr;
-
- //! Pointer to the function that dispatches incoming service responses for the
- //! client.
- //! Service responses are only dispatched to clients that have been opened or
- //! are in the process of being (re)opened. @see ChppOpenState
- ChppDispatchFunction *responseDispatchFunctionPtr;
-
- //! Pointer to the function that dispatches incoming service notifications for
- //! the client.
- //! Service notifications are only dispatched to clients that have been
- //! opened. @see ChppOpenState
- ChppDispatchFunction *notificationDispatchFunctionPtr;
-
- //! Pointer to the function that initializes the client (after it is matched
- //! with a service at discovery) and assigns it its handle number.
- ChppClientInitFunction *initFunctionPtr;
-
- //! Pointer to the function that deinitializes the client.
- ChppClientDeinitFunction *deinitFunctionPtr;
-
- //! Number of request-response states in the rRStates array. This is a
- //! uint16_t to match the uint16_t command in struct ChppAppHeader.
- uint16_t rRStateCount;
-
- //! Minimum valid length of datagrams for the service.
- size_t minLength;
-};
-
-/**
- * Request status for clients.
- */
-enum ChppRequestState {
- CHPP_REQUEST_STATE_NONE = 0, // No request sent ever
- CHPP_REQUEST_STATE_REQUEST_SENT = 1, // Sent but no response yet
- CHPP_REQUEST_STATE_RESPONSE_RCV = 2, // Sent and response received
- CHPP_REQUEST_STATE_RESPONSE_TIMEOUT = 3, // Timeout. Responded as need be
-};
-
-/**
- * Maintains the basic state for each request/response functionality of a
- * client or service.
- * Any number of these may be included in the (context) status variable of a
- * client or service (one per every every request/response functionality).
- */
-struct ChppRequestResponseState {
- uint64_t requestTimeNs; // Time of the last request
- uint64_t
- responseTimeNs; // If requestState is CHPP_REQUEST_STATE_REQUEST_SENT,
- // indicates the timeout time for the request
- // If requestState is CHPP_REQUEST_STATE_RESPONSE_RCV,
- // indicates when the response was received
-
- uint8_t requestState; // From enum ChppRequestState
- uint8_t transaction; // Transaction ID for the last request/response
-};
-
-/**
- * Enabled clients and services.
- */
-struct ChppClientServiceSet {
- bool wifiService : 1;
- bool gnssService : 1;
- bool wwanService : 1;
- bool wifiClient : 1;
- bool gnssClient : 1;
- bool wwanClient : 1;
- bool loopbackClient : 1;
-};
-
-struct ChppLoopbackClientState;
-struct ChppTimesyncClientState;
-
-struct ChppAppState {
- struct ChppTransportState *transportContext; // Pointing to transport context
-
- const struct chrePalSystemApi *systemApi; // Pointing to the PAL system APIs
-
- uint8_t registeredServiceCount; // Number of services currently registered
-
- const struct ChppService *registeredServices[CHPP_MAX_REGISTERED_SERVICES];
-
- void *registeredServiceContexts[CHPP_MAX_REGISTERED_SERVICES];
-
- uint8_t registeredClientCount; // Number of clients currently registered
-
- const struct ChppClient *registeredClients[CHPP_MAX_REGISTERED_CLIENTS];
-
- const struct ChppClientState
- *registeredClientStates[CHPP_MAX_REGISTERED_CLIENTS];
-
- void *registeredClientContexts[CHPP_MAX_REGISTERED_CLIENTS];
-
- uint64_t nextRequestTimeoutNs;
-
- uint8_t
- clientIndexOfServiceIndex[CHPP_MAX_DISCOVERED_SERVICES]; // Lookup table
-
- struct ChppClientServiceSet clientServiceSet; // Enabled client/services
-
- // Pointers to the contexts of basic clients, which are allocated if and when
- // they are initialized
- struct ChppLoopbackClientState *loopbackClientContext;
- struct ChppTimesyncClientState *timesyncClientContext;
-
- // For discovery clients
- bool isDiscoveryClientEverInitialized;
- bool isDiscoveryClientInitialized;
- bool isDiscoveryComplete;
-
- // The number of clients that matched a service during discovery.
- uint8_t matchedClientCount;
-
- // The number of services that were found during discovery.
- uint8_t discoveredServiceCount;
-
- struct ChppMutex discoveryMutex;
- struct ChppConditionVariable discoveryCv;
-};
-
-#define CHPP_SERVICE_INDEX_OF_HANDLE(handle) \
- ((handle)-CHPP_HANDLE_NEGOTIATED_RANGE_START)
-
-#define CHPP_SERVICE_HANDLE_OF_INDEX(index) \
- ((index) + CHPP_HANDLE_NEGOTIATED_RANGE_START)
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Initializes the CHPP app layer state stored in the parameter appContext.
- * It is necessary to initialize state for each app layer instance on
- * every platform.
- *
- * @param appContext Maintains status for each app layer instance.
- * @param transportContext The transport layer status struct associated with
- * this app layer instance.
- */
-void chppAppInit(struct ChppAppState *appContext,
- struct ChppTransportState *transportContext);
-
-/**
- * Same as chppAppInit(), but specifies the client/service endpoints to be
- * enabled.
- *
- * @param appContext Maintains status for each app layer instance.
- * @param transportContext The transport layer status struct associated with
- * this app layer instance.
- * @param clientServiceSet Bitmap specifying the client/service endpoints to be
- * enabled.
- */
-void chppAppInitWithClientServiceSet(
- struct ChppAppState *appContext,
- struct ChppTransportState *transportContext,
- struct ChppClientServiceSet clientServiceSet);
-
-/**
- * Deinitializes the CHPP app layer for e.g. clean shutdown.
- *
- * @param appContext A non-null pointer to ChppAppState initialized previously
- * in chppAppInit().
- */
-void chppAppDeinit(struct ChppAppState *appContext);
-
-/**
- * Processes an Rx Datagram from the transport layer.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-void chppAppProcessRxDatagram(struct ChppAppState *context, uint8_t *buf,
- size_t len);
-
-/**
- * Used by the transport layer to notify the app layer of a reset during
- * operation. This function is called after the transport layer has sent a reset
- * or reset-ack packet.
- * In turn, this function notifies clients and services to allow them to reset
- * or recover state as necessary.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppAppProcessReset(struct ChppAppState *context);
-
-/**
- * Convert UUID to a human-readable, null-terminated string.
- *
- * @param uuid Input UUID
- * @param strOut Output null-terminated string
- */
-void chppUuidToStr(const uint8_t uuid[CHPP_SERVICE_UUID_LEN],
- char strOut[CHPP_SERVICE_UUID_STRING_LEN]);
-
-/**
- * Maps a CHPP app layer error to a CHRE error.
- *
- * @param chppError CHPP app layer error (from enum ChppAppErrorCode).
- *
- * @return CHRE error (from enum chreError).
- */
-uint8_t chppAppErrorToChreError(uint8_t error);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_APP_H_
diff --git a/chpp/include/chpp/clients.h b/chpp/include/chpp/clients.h
deleted file mode 100644
index bf757fa9..00000000
--- a/chpp/include/chpp/clients.h
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_CLIENTS_H_
-#define CHPP_CLIENTS_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/condition_variable.h"
-#include "chpp/macros.h"
-#include "chpp/mutex.h"
-#include "chre_api/chre/common.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/**
- * Uses chppAllocClientRequest() to allocate a client request message of a
- * specific type and its corresponding length.
- *
- * @param clientState State variable of the client.
- * @param type Type of response.
- *
- * @return Pointer to allocated memory
- */
-#define chppAllocClientRequestFixed(clientState, type) \
- (type *)chppAllocClientRequest(clientState, sizeof(type))
-
-/**
- * Uses chppAllocClientRequest() to allocate a variable-length client request
- * message of a specific type.
- *
- * @param clientState State variable of the client.
- * @param type Type of response which includes an arrayed member.
- * @param count number of items in the array of arrayField.
- * @param arrayField The arrayed member field.
- *
- * @return Pointer to allocated memory
- */
-#define chppAllocClientRequestTypedArray(clientState, type, count, arrayField) \
- (type *)chppAllocClientRequest( \
- clientState, sizeof(type) + (count)*sizeof_member(type, arrayField[0]))
-
-/**
- * Maintains the basic state of a client.
- * This is expected to be included once in the (context) status variable of
- * each client.
- */
-struct ChppClientState {
- struct ChppAppState *appContext; // Pointer to app layer context
- struct ChppRequestResponseState
- *rRStates; // Pointer to array of request-response states, if any
- uint8_t index; // Index of this client
- uint8_t handle; // Handle number for this client
- uint8_t transaction; // Next Transaction ID to be used
-
- uint8_t openState; // As defined in enum ChppOpenState
- bool pseudoOpen : 1; // Client to be opened upon a reset
- bool initialized : 1; // Is initialized
- bool everInitialized : 1; // Synchronization primitives initialized
-
- bool responseReady : 1; // For sync. request/responses
- struct ChppMutex responseMutex;
- struct ChppConditionVariable responseCondVar;
-};
-
-#ifdef CHPP_CLIENT_ENABLED_CHRE_WWAN
-#define CHPP_CLIENT_ENABLED_WWAN
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_CHRE_WIFI
-#define CHPP_CLIENT_ENABLED_WIFI
-#endif
-
-#ifdef CHPP_CLIENT_ENABLED_CHRE_GNSS
-#define CHPP_CLIENT_ENABLED_GNSS
-#endif
-
-#if defined(CHPP_CLIENT_ENABLED_LOOPBACK) || \
- defined(CHPP_CLIENT_ENABLED_TIMESYNC) || \
- defined(CHPP_CLIENT_ENABLED_DISCOVERY) || \
- defined(CHPP_CLIENT_ENABLED_WWAN) || defined(CHPP_CLIENT_ENABLED_WIFI) || \
- defined(CHPP_CLIENT_ENABLED_GNSS)
-#define CHPP_CLIENT_ENABLED
-#endif
-
-#define CHPP_CLIENT_REQUEST_TIMEOUT_INFINITE CHPP_TIME_MAX
-
-#ifndef CHPP_CLIENT_REQUEST_TIMEOUT_DEFAULT
-#define CHPP_CLIENT_REQUEST_TIMEOUT_DEFAULT CHRE_ASYNC_RESULT_TIMEOUT_NS
-#endif
-
-// Default timeout for discovery completion.
-#ifndef CHPP_DISCOVERY_DEFAULT_TIMEOUT_MS
-#define CHPP_DISCOVERY_DEFAULT_TIMEOUT_MS UINT64_C(10000) // 10s
-#endif
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Registers common clients with the CHPP app layer. These clients are enabled
- * by CHPP_CLIENT_ENABLED_xxxx definitions. This function is automatically
- * called by chppAppInit().
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppRegisterCommonClients(struct ChppAppState *context);
-
-/**
- * Deregisters common clients with the CHPP app layer. These clients are enabled
- * by CHPP_CLIENT_ENABLED_xxxx definitions. This function is automatically
- * called by chppAppDeinit().
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppDeregisterCommonClients(struct ChppAppState *context);
-
-/**
- * Registers a new client on CHPP. This function is to be called by the
- * platform initialization code for every non-common client available on a
- * server (if any), i.e. except those that are registered through
- * chppRegisterCommonClients().
- *
- * Registered clients are matched with discovered services during discovery.
- * When a match succeeds, the client's initialization function (pointer) is
- * called, assigning them their handle number.
- *
- * Note that the maximum number of clients that can be registered on a platform
- * can specified as CHPP_MAX_REGISTERED_CLIENTS by the initialization code.
- * Otherwise, a default value will be used.
- *
- * @param appContext Maintains status for each app layer instance.
- * @param clientContext Maintains status for each client instance.
- * @param clientState State variable of the client.
- * @param rRStates Pointer to array of request-response states, if any.
- * @param newClient The client to be registered on this platform.
- */
-void chppRegisterClient(struct ChppAppState *appContext, void *clientContext,
- struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRStates,
- const struct ChppClient *newClient);
-
-/**
- * Initializes basic CHPP clients.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppInitBasicClients(struct ChppAppState *context);
-
-/**
- * Initializes a client. This function must be called when a client is matched
- * with a service during discovery to provides its handle number.
- *
- * @param clientState State variable of the client.
- * @param handle Handle number for this client.
- */
-void chppClientInit(struct ChppClientState *clientState, uint8_t handle);
-
-/**
- * Deinitializes a client.
- *
- * @param clientState State variable of the client.
- */
-void chppClientDeinit(struct ChppClientState *clientState);
-
-/**
- * Deinitializes basic clients.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppDeinitBasicClients(struct ChppAppState *context);
-
-/**
- * Deinitializes all matched clients.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppDeinitMatchedClients(struct ChppAppState *context);
-
-/**
- * Allocates a client request message of a specified length, populating the
- * (app layer) client request header, including the sequence ID. The
- * next-sequence ID stored in the client state variable is subsequently
- * incremented.
- *
- * It is expected that for most use cases, the chppAllocClientRequestFixed()
- * or chppAllocClientRequestTypedArray() macros shall be used rather than
- * calling this function directly.
- *
- * @param clientState State variable of the client.
- * @param len Length of the response message (including header) in bytes. Note
- * that the specified length must be at least equal to the lendth of the app
- * layer header.
- *
- * @return Pointer to allocated memory
- */
-struct ChppAppHeader *chppAllocClientRequest(
- struct ChppClientState *clientState, size_t len);
-
-/**
- * Uses chppAllocClientRequest() to allocate a specific client request command
- * without any additional payload.
- *
- * @param clientState State variable of the client.
- * @param command Type of response.
- *
- * @return Pointer to allocated memory
- */
-struct ChppAppHeader *chppAllocClientRequestCommand(
- struct ChppClientState *clientState, uint16_t command);
-
-/**
- * This function shall be called for all outgoing client requests in order to
- * A) Timestamp them, and
- * B) Save their Transaction ID
- * as part of the request/response's ChppRequestResponseState struct.
- *
- * This function prints an error message if a duplicate request is sent
- * while outstanding request is still pending without a response.
- *
- * @param clientState State of the client sending the client request.
- * @param transactionId The transaction ID to use when loading the app.
- * @param rRState Maintains the basic state for each request/response
- * functionality of a client.
- * @param requestHeader Client request header.
- */
-void chppClientTimestampRequest(struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState,
- struct ChppAppHeader *requestHeader,
- uint64_t timeoutNs);
-
-/**
- * This function shall be called for incoming responses to a client request in
- * order to
- * A) Verify the correct transaction ID
- * B) Timestamp them, and
- * C) Mark them as fulfilled
- * D) TODO: check for timeout
- *
- * This function prints an error message if a response is received without an
- * outstanding request.
- *
- * @param clientState State of the client sending the client request.
- * @param rRState Maintains the basic state for each request/response
- * functionality of a client.
- * @param requestHeader Client request header.
- *
- * @return false if there is an error. True otherwise.
- */
-bool chppClientTimestampResponse(struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState,
- const struct ChppAppHeader *responseHeader);
-
-/**
- * Timestamps a client request using chppClientTimestampResponse() and enqueues
- * it using chppEnqueueTxDatagramOrFail().
- *
- * Refer to their respective documentation for details.
- *
- * Note that the ownership of buf is taken from the caller when this method is
- * invoked.
- *
- * @param clientState State of the client sending the client request.
- * @param rRState Maintains the basic state for each request/response
- * functionality of a client.
- * @param buf Datagram payload allocated through chppMalloc. Cannot be null.
- * @param len Datagram length in bytes.
- * @param timeoutNs Time in nanoseconds before a timeout response is generated.
- * Zero means no timeout response.
- *
- * @return True informs the sender that the datagram was successfully enqueued.
- * False informs the sender that the queue was full and the payload discarded.
- */
-bool chppSendTimestampedRequestOrFail(struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState,
- void *buf, size_t len,
- uint64_t timeoutNs);
-
-/**
- * Similar to chppSendTimestampedRequestOrFail() but blocks execution until a
- * response is received. Used for synchronous requests.
- *
- * In order to use this function, clientState->responseNotifier must have been
- * initialized using chppNotifierInit() upon initialization of the client.
- *
- * @param clientState State of the client sending the client request.
- * @param rRState Maintains the basic state for each request/response
- * functionality of a client.
- * @param buf Datagram payload allocated through chppMalloc. Cannot be null.
- * @param len Datagram length in bytes.
- *
- * @return True informs the sender that the datagram was successfully enqueued.
- * False informs the sender that the payload was discarded because either the
- * queue was full, or the request timed out.
- */
-bool chppSendTimestampedRequestAndWait(struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState,
- void *buf, size_t len);
-
-/**
- * Same as chppSendTimestampedRequestAndWait() but with a specified timeout.
- */
-bool chppSendTimestampedRequestAndWaitTimeout(
- struct ChppClientState *clientState,
- struct ChppRequestResponseState *rRState, void *buf, size_t len,
- uint64_t timeoutNs);
-
-/**
- * Markes a closed client as pseudo-open, so that it would be opened upon a
- * reset.
- *
- * @param clientState State variable of the client.
- */
-void chppClientPseudoOpen(struct ChppClientState *clientState);
-
-/**
- * Sends a client request for the open command in a blocking or non-blocking
- * manner.
- * A non-blocking open is used to for reopening a service after a reset or for
- * opening a pseudo-open service.
- *
- * @param clientState State variable of the client.
- * @param openRRState Request/response state for the open command.
- * @param openCommand Open command to be sent.
- * @param blocking Indicates a blocking (vs. non-blocking) open request.
- *
- * @return Indicates success or failure.
- */
-bool chppClientSendOpenRequest(struct ChppClientState *clientState,
- struct ChppRequestResponseState *openRRState,
- uint16_t openCommand, bool blocking);
-
-/**
- * Processes a service response for the open command.
- *
- * @param clientState State variable of the client.
- */
-void chppClientProcessOpenResponse(struct ChppClientState *clientState,
- uint8_t *buf, size_t len);
-
-/**
- * Recalculates the next upcoming client request timeout time.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppClientRecalculateNextTimeout(struct ChppAppState *context);
-
-/**
- * Closes any remaining open requests for a given client by sending a timeout.
- * This function is used when a client is reset.
- *
- * @param clientState State variable of the client.
- * @param client The client for whech to clear out open requests.
- * @param clearOnly If true, indicates that a timeout response shouldn't be
- * sent to the client. This must only be set if the requests are being
- * cleared as part of the client closing.
- */
-void chppClientCloseOpenRequests(struct ChppClientState *clientState,
- const struct ChppClient *client,
- bool clearOnly);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_CLIENTS_H_
diff --git a/chpp/include/chpp/clients/discovery.h b/chpp/include/chpp/clients/discovery.h
deleted file mode 100644
index a47523a5..00000000
--- a/chpp/include/chpp/clients/discovery.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_CLIENT_DISCOVERY_H_
-#define CHPP_CLIENT_DISCOVERY_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * CHPP discovery state initialization that should be called on CHPP startup. It
- * may be called during transient internal resets, but is a no-op.
- */
-void chppDiscoveryInit(struct ChppAppState *context);
-
-/**
- * CHPP discovery state de-initialization that should be called during shutdown.
- */
-void chppDiscoveryDeinit(struct ChppAppState *context);
-
-/**
- * A method that can be invoked to block until the CHPP discovery sequence
- * completes. This can be useful to wait until CHPP client invocations can
- * succeed.
- *
- * @param context The non-null pointer to the ChppAppState of this instance.
- * @param timeoutMs The timeout in milliseconds.
- *
- * @return False if timed out waiting for discovery completion.
- */
-bool chppWaitForDiscoveryComplete(struct ChppAppState *context,
- uint64_t timeoutMs);
-
-/**
- * Dispatches an Rx Datagram from the transport layer that is determined to be
- * for the CHPP Discovery Client.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input (request) datagram. Cannot be null.
- * @param len Length of input data in bytes.
- */
-bool chppDispatchDiscoveryServiceResponse(struct ChppAppState *context,
- const uint8_t *buf, size_t len);
-
-/**
- * Initiates a CHPP service discovery from the client side, in order to send a
- * CHPP_DISCOVERY_COMMAND_DISCOVER_ALL client request to a server. It is
- * expected that this function be called upon initialization, after sending or
- * receiving a reset-ack.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppInitiateDiscovery(struct ChppAppState *context);
-
-/**
- * Checks if all discovery clients have been matched with a remote service.
- *
- * @param context Maintains status for each app layer instance.
- *
- * @return true if all registered clients have been matched by a discovered
- * service.
- */
-bool chppAreAllClientsMatched(struct ChppAppState *context);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_CLIENT_DISCOVERY_H_
diff --git a/chpp/include/chpp/clients/gnss.h b/chpp/include/chpp/clients/gnss.h
deleted file mode 100644
index 74f5022d..00000000
--- a/chpp/include/chpp/clients/gnss.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_GNSS_CLIENT_H_
-#define CHPP_GNSS_CLIENT_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Called by the App layer to register the GNSS (location) common client.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppRegisterGnssClient(struct ChppAppState *appContext);
-
-/**
- * Called by the App layer to deregister the GNSS (location) common client.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppDeregisterGnssClient(struct ChppAppState *appContext);
-
-/**
- * @return The ChppClientState pointer to the GNSS client.
- */
-struct ChppClientState *getChppGnssClientState(void);
-
-#ifndef CHPP_CLIENT_ENABLED_CHRE_GNSS
-/**
- * Alternative to chrePalGnssGetApi() to avoid conflicting with CHPP service.
- */
-const struct chrePalGnssApi *chppPalGnssGetApi(uint32_t requestedApiVersion);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_GNSS_CLIENT_H_
diff --git a/chpp/include/chpp/clients/loopback.h b/chpp/include/chpp/clients/loopback.h
deleted file mode 100644
index 6f74a7ee..00000000
--- a/chpp/include/chpp/clients/loopback.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_CLIENT_LOOPBACK_H_
-#define CHPP_CLIENT_LOOPBACK_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Loopback Test Results.
- */
-struct ChppLoopbackTestResult {
- enum ChppAppErrorCode error; // Indicates success or error type
- size_t requestLen; // Length of the loopback request datagram, including app
- // header
- size_t responseLen; // Length of the loopback response datagram, including
- // app header
- size_t firstError; // Location of the first incorrect byte in the response
- // datagram
- size_t byteErrors; // Number of incorrect bytes in the response datagram
- uint64_t rttNs; // Round trip time
-};
-
-/**
- * Minimum header length for a loopback packet. Everything afterwards is
- * considered a payload and is looped back.
- */
-#define CHPP_LOOPBACK_HEADER_LEN 2
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Initializes the client.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppLoopbackClientInit(struct ChppAppState *context);
-
-/**
- * Deinitializes the client.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppLoopbackClientDeinit(struct ChppAppState *context);
-
-/**
- * Dispatches an Rx Datagram from the transport layer that is determined to
- * be for the CHPP Loopback Client.
- *
- * @param context Maintains status for each app layer instance.
- * @param response Input (response) datagram. Cannot be null.
- * @param len Length of input data in bytes.
- */
-bool chppDispatchLoopbackServiceResponse(struct ChppAppState *context,
- const uint8_t *response, size_t len);
-
-/**
- * Initiates a CHPP service loopback from the client side.
- * Note that only one loopback test may be run at any time on each client.
- *
- * @param context Maintains status for each app layer instance.
- */
-struct ChppLoopbackTestResult chppRunLoopbackTest(struct ChppAppState *context,
- const uint8_t *buf,
- size_t len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_CLIENT_LOOPBACK_H_
diff --git a/chpp/include/chpp/clients/timesync.h b/chpp/include/chpp/clients/timesync.h
deleted file mode 100644
index a905057d..00000000
--- a/chpp/include/chpp/clients/timesync.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_CLIENT_TIMESYNC_H_
-#define CHPP_CLIENT_TIMESYNC_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-#include "chpp/common/timesync.h"
-#include "chpp/macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Maximum timesync step change at each measurement
- */
-#ifndef CHPP_CLIENT_TIMESYNC_MAX_CHANGE_NS
-#define CHPP_CLIENT_TIMESYNC_MAX_CHANGE_NS (100 * CHPP_NSEC_PER_MSEC)
-#endif
-
-/**
- * Default maximum age of a time offset measurement
- */
-#ifndef CHPP_TIMESYNC_DEFAULT_MAX_AGE_NS
-#define CHPP_TIMESYNC_DEFAULT_MAX_AGE_NS (24 * CHPP_NSEC_PER_HOUR)
-#endif
-
-/**
- * Timesync Results.
- */
-struct ChppTimesyncResult {
- enum ChppAppErrorCode error; // Indicates success or error type
- int64_t offsetNs; // Time offset of service (service - client)
- uint64_t rttNs; // RTT
- uint64_t measurementTimeNs; // Time of last measurement
-};
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Initializes the client.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppTimesyncClientInit(struct ChppAppState *context);
-
-/**
- * Deinitializes the client.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppTimesyncClientDeinit(struct ChppAppState *context);
-
-/**
- * Resets the client.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppTimesyncClientReset(struct ChppAppState *context);
-
-/**
- * Dispatches an Rx Datagram from the transport layer that is determined to
- * be for the CHPP Timesync Client.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input (response) datagram. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates success or failure.
- */
-bool chppDispatchTimesyncServiceResponse(struct ChppAppState *context,
- const uint8_t *buf, size_t len);
-
-/**
- * Initiates a CHPP timesync to measure time offset of the service.
- *
- * @param context Maintains status for each app layer instance.
- *
- * @return Indicates success or failure.
- */
-bool chppTimesyncMeasureOffset(struct ChppAppState *context);
-
-/**
- * Provides the time offset of the service. If the latest measurement is within
- * maxTimesyncAgeNs, this function reuses the last measurement. Otherwise, it
- * will initiate a new measurement.
- *
- * @param context Maintains status for each app layer instance.
- * @param maxTimesyncAgeNs Maximum acceptable age of measuement.
- *
- * @return Time offset of service vs client (service - client)
- */
-int64_t chppTimesyncGetOffset(struct ChppAppState *context,
- uint64_t maxTimesyncAgeNs);
-
-/**
- * Provides the raw results of the latest timesync measurement.
- *
- * @param context Maintains status for each app layer instance.
- *
- * @return Latest result.
- */
-const struct ChppTimesyncResult *chppTimesyncGetResult(
- struct ChppAppState *context);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_CLIENT_TIMESYNC_H_
diff --git a/chpp/include/chpp/clients/wifi.h b/chpp/include/chpp/clients/wifi.h
deleted file mode 100644
index e0384cd0..00000000
--- a/chpp/include/chpp/clients/wifi.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_WIFI_CLIENT_H_
-#define CHPP_WIFI_CLIENT_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Called by the App layer to register the WiFi common client.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppRegisterWifiClient(struct ChppAppState *appContext);
-
-/**
- * Called by the App layer to deregister the WiFi common client.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppDeregisterWifiClient(struct ChppAppState *appContext);
-
-/**
- * @return The ChppClientState pointer to the WiFi client.
- */
-struct ChppClientState *getChppWifiClientState(void);
-
-#ifndef CHPP_CLIENT_ENABLED_CHRE_WIFI
-/**
- * Alternative to chrePalWifiGetApi() to avoid conflicting with CHPP service.
- */
-const struct chrePalWifiApi *chppPalWifiGetApi(uint32_t requestedApiVersion);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WIFI_CLIENT_H_
diff --git a/chpp/include/chpp/clients/wwan.h b/chpp/include/chpp/clients/wwan.h
deleted file mode 100644
index 3b10f2a4..00000000
--- a/chpp/include/chpp/clients/wwan.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_WWAN_CLIENT_H_
-#define CHPP_WWAN_CLIENT_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Called by the App layer to register the WWAN (cellular) common client.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppRegisterWwanClient(struct ChppAppState *appContext);
-
-/**
- * Called by the App layer to deregister the WWAN (cellular) common client.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppDeregisterWwanClient(struct ChppAppState *appContext);
-
-/**
- * @return The ChppClientState pointer to the WWAN client.
- */
-struct ChppClientState *getChppWwanClientState(void);
-
-#ifndef CHPP_CLIENT_ENABLED_CHRE_WWAN
-/**
- * Alternative to chrePalWwanGetApi() to avoid conflicting with CHPP service.
- */
-const struct chrePalWwanApi *chppPalWwanGetApi(uint32_t requestedApiVersion);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WWAN_CLIENT_H_
diff --git a/chpp/include/chpp/common/common_types.h b/chpp/include/chpp/common/common_types.h
deleted file mode 100644
index d72927b9..00000000
--- a/chpp/include/chpp/common/common_types.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_SERVICES_COMMON_TYPES_H_
-#define CHPP_SERVICES_COMMON_TYPES_H_
-
-#include <stdint.h>
-
-#include "chpp/macros.h"
-
-/**
- * When CHRE API structures are converted to CHPP wire format structures, this
- * type is used to replace a pointer to an array.
- *
- * For example, in the CHRE API we might have something like this:
- * struct chreBar {
- * uint32_t baz;
- * };
- * struct chreFooResult {
- * uint8_t barCount;
- * const struct chreBar *bars;
- * };
- *
- * To serialize this object for CHPP, we replace the pointer with a ChppOffset:
- *
- * struct ChppFooResult { // (packed)
- * uint8_t barCount;
- * struct ChppOffset bars;
- * };
- *
- * Over the wire, this structure would then immediately be followed by barCount
- * instances of chreBar, and bars.offset would be set to sizeof(ChppFooResult)
- * and bars.length set to barCount * sizeof(chreBar).
- *
- * The same applies for things like null-terminated strings (when not defined
- * as a fixed-size nested array) - in that case, "length" includes null
- * termination.
- */
-CHPP_PACKED_START
-struct ChppOffset {
- //! Offset from the start of payload to the array
- uint16_t offset;
-
- //! Size of the array, in bytes
- uint16_t length;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-#endif // CHPP_SERVICES_COMMON_TYPES_H_
diff --git a/chpp/include/chpp/common/discovery.h b/chpp/include/chpp/common/discovery.h
deleted file mode 100644
index bcefd94d..00000000
--- a/chpp/include/chpp/common/discovery.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_COMMON_DISCOVERY_H_
-#define CHPP_COMMON_DISCOVERY_H_
-
-#include "chpp/app.h"
-#include "chpp/macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/**
- * Data structure used by the Discovery Response.
- */
-CHPP_PACKED_START
-struct ChppDiscoveryResponse {
- struct ChppAppHeader header;
- struct ChppServiceDescriptor services[];
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Commands used by the Discovery Service
- */
-enum ChppDiscoveryCommands {
- // Discover all services.
- CHPP_DISCOVERY_COMMAND_DISCOVER_ALL = 0x0001,
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_COMMON_DISCOVERY_H_
diff --git a/chpp/include/chpp/common/gnss.h b/chpp/include/chpp/common/gnss.h
deleted file mode 100644
index 0f557a42..00000000
--- a/chpp/include/chpp/common/gnss.h
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_GNSS_COMMON_H_
-#define CHPP_GNSS_COMMON_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-#define CHPP_PAL_GNSS_API_VERSION CHRE_PAL_GNSS_API_V1_4
-
-/**
- * Data structures for Control Location Session request.
- */
-CHPP_PACKED_START
-struct ChppGnssControlLocationSessionParameters {
- bool enable;
- uint32_t minIntervalMs;
- uint32_t minTimeToNextFixMs;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppGnssControlLocationSessionRequest {
- struct ChppAppHeader header;
- struct ChppGnssControlLocationSessionParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Data structures for Control Measurement Session request.
- */
-CHPP_PACKED_START
-struct ChppGnssControlMeasurementSessionParameters {
- bool enable;
- uint32_t minIntervalMs;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppGnssControlMeasurementSessionRequest {
- struct ChppAppHeader header;
- struct ChppGnssControlMeasurementSessionParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Data structures for Configure Passive Listener request.
- */
-CHPP_PACKED_START
-struct ChppGnssConfigurePassiveLocationListenerParameters {
- bool enable;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppGnssConfigurePassiveLocationListenerRequest {
- struct ChppAppHeader header;
- struct ChppGnssConfigurePassiveLocationListenerParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Data structures used by the Get Capabilities response.
- */
-CHPP_PACKED_START
-struct ChppGnssGetCapabilitiesParameters {
- uint32_t capabilities;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppGnssGetCapabilitiesResponse {
- struct ChppAppHeader header;
- struct ChppGnssGetCapabilitiesParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Data structure used by the Control Location Session response.
- */
-CHPP_PACKED_START struct ChppGnssControlLocationSessionResponse {
- struct ChppAppHeader header;
- bool enabled;
- uint8_t errorCode;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Data structure used by the Control Measurement Session response.
- */
-CHPP_PACKED_START struct ChppGnssControlMeasurementSessionResponse {
- struct ChppAppHeader header;
- bool enabled;
- uint8_t errorCode;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Commands used by the GNSS (GPS) Service.
- */
-enum ChppGnssCommands {
- //! Initializes the service.
- CHPP_GNSS_OPEN = 0x0000,
-
- //! Deinitializes the service.
- CHPP_GNSS_CLOSE = 0x0001,
-
- //! Retrieves a set of flags indicating supported features.
- CHPP_GNSS_GET_CAPABILITIES = 0x0002,
-
- //! Start/stop/modify the GNSS location session.
- CHPP_GNSS_CONTROL_LOCATION_SESSION = 0x0003,
-
- //! Start/stop/modify the raw GNSS measurement session.
- CHPP_GNSS_CONTROL_MEASUREMENT_SESSION = 0x0004,
-
- //! Configures opportunistic reporting of location fixes produced for other
- //! GNSS clients.
- CHPP_GNSS_CONFIGURE_PASSIVE_LOCATION_LISTENER = 0x0005,
-
- //! Notification to request that the core CHRE system re-send requests for any
- //! active sessions and its current passive location listener setting.
- CHPP_GNSS_REQUEST_STATE_RESYNC_NOTIFICATION = 0x0006,
-
- //! Notification with GNSS location results.
- CHPP_GNSS_LOCATION_RESULT_NOTIFICATION = 0x0007,
-
- //! Notification with raw GNSS measurement results.
- CHPP_GNSS_MEASUREMENT_RESULT_NOTIFICATION = 0x0008,
-};
-#define CHPP_GNSS_CLIENT_REQUEST_MAX \
- CHPP_GNSS_CONFIGURE_PASSIVE_LOCATION_LISTENER
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_GNSS_COMMON_H_
diff --git a/chpp/include/chpp/common/gnss_types.h b/chpp/include/chpp/common/gnss_types.h
deleted file mode 100644
index 1f5f6534..00000000
--- a/chpp/include/chpp/common/gnss_types.h
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_GNSS_TYPES_H_
-#define CHPP_GNSS_TYPES_H_
-
-// This file was automatically generated by chre_api_to_chpp.py
-// Date: 2021-05-24 15:46:26 UTC
-// Source: chre_api/include/chre_api/chre/gnss.h @ commit 833a6241
-
-// DO NOT modify this file directly, as those changes will be lost the next
-// time the script is executed
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/common/common_types.h"
-#include "chpp/macros.h"
-#include "chre_api/chre/gnss.h"
-#include "chre_api/chre/version.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-CHPP_PACKED_START
-
-//! See {@link chreGnssClock} for details
-struct ChppGnssClock {
- int64_t time_ns;
- int64_t full_bias_ns;
- float bias_ns;
- float drift_nsps;
- float bias_uncertainty_ns;
- float drift_uncertainty_nsps;
- uint32_t hw_clock_discontinuity_count;
- uint16_t flags;
- uint8_t reserved[2]; // Input ignored; always set to 0
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreGnssMeasurement} for details
-struct ChppGnssMeasurement {
- int64_t time_offset_ns;
- int64_t accumulated_delta_range_um;
- int64_t received_sv_time_in_ns;
- int64_t received_sv_time_uncertainty_in_ns;
- float pseudorange_rate_mps;
- float pseudorange_rate_uncertainty_mps;
- float accumulated_delta_range_uncertainty_m;
- float c_n0_dbhz;
- float snr_db;
- uint16_t state;
- uint16_t accumulated_delta_range_state;
- int16_t svid;
- uint8_t constellation;
- uint8_t multipath_indicator;
- float carrier_frequency_hz;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreGnssDataEvent} for details
-struct ChppGnssDataEvent {
- uint8_t version; // Input ignored; always set to CHRE_GNSS_DATA_EVENT_VERSION
- uint8_t measurement_count;
- uint8_t reserved[6]; // Input ignored; always set to 0
- struct ChppGnssClock clock;
- struct ChppOffset measurements; // References measurement_count instances of
- // struct ChppOffset
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreGnssLocationEvent} for details
-struct ChppGnssLocationEvent {
- uint64_t timestamp;
- int32_t latitude_deg_e7;
- int32_t longitude_deg_e7;
- float altitude;
- float speed;
- float bearing;
- float accuracy;
- uint16_t flags;
- uint8_t reserved[2]; // Input ignored; always set to 0
- float altitude_accuracy;
- float speed_accuracy;
- float bearing_accuracy;
-} CHPP_PACKED_ATTR;
-
-//! CHPP app header plus struct ChppGnssDataEventWithHeader
-struct ChppGnssDataEventWithHeader {
- struct ChppAppHeader header;
- struct ChppGnssDataEvent payload;
-} CHPP_PACKED_ATTR;
-
-//! CHPP app header plus struct ChppGnssLocationEventWithHeader
-struct ChppGnssLocationEventWithHeader {
- struct ChppAppHeader header;
- struct ChppGnssLocationEvent payload;
-} CHPP_PACKED_ATTR;
-
-CHPP_PACKED_END
-
-// Encoding functions (CHRE --> CHPP)
-
-/**
- * Converts from given CHRE structure to serialized CHPP type.
- *
- * @param in Fully-formed CHRE structure.
- * @param out Upon success, will point to a buffer allocated with chppMalloc().
- * It is the responsibility of the caller to set the values of the CHPP app
- * layer header, and to free the buffer when it is no longer needed via
- * chppFree() or CHPP_FREE_AND_NULLIFY().
- * @param outSize Upon success, will be set to the size of the output buffer, in
- * bytes.
- *
- * @return true on success, false if memory allocation failed.
- */
-bool chppGnssDataEventFromChre(const struct chreGnssDataEvent *in,
- struct ChppGnssDataEventWithHeader **out,
- size_t *outSize);
-
-/**
- * Converts from given CHRE structure to serialized CHPP type.
- *
- * @param in Fully-formed CHRE structure.
- * @param out Upon success, will point to a buffer allocated with chppMalloc().
- * It is the responsibility of the caller to set the values of the CHPP app
- * layer header, and to free the buffer when it is no longer needed via
- * chppFree() or CHPP_FREE_AND_NULLIFY().
- * @param outSize Upon success, will be set to the size of the output buffer, in
- * bytes.
- *
- * @return true on success, false if memory allocation failed.
- */
-bool chppGnssLocationEventFromChre(const struct chreGnssLocationEvent *in,
- struct ChppGnssLocationEventWithHeader **out,
- size_t *outSize);
-
-// Decoding functions (CHPP --> CHRE)
-
-/**
- * Converts from serialized CHPP structure to a CHRE type.
- *
- * @param in Fully-formed CHPP structure.
- * @param in Size of the CHPP structure in bytes.
- *
- * @return If successful, a pointer to a CHRE structure allocated with
- * chppMalloc(). If unsuccessful, null. It is the responsibility of the caller
- * to free the buffer when it is no longer needed via chppFree() or
- * CHPP_FREE_AND_NULLIFY().
- */
-struct chreGnssDataEvent *chppGnssDataEventToChre(
- const struct ChppGnssDataEvent *in, size_t inSize);
-
-/**
- * Converts from serialized CHPP structure to a CHRE type.
- *
- * @param in Fully-formed CHPP structure.
- * @param in Size of the CHPP structure in bytes.
- *
- * @return If successful, a pointer to a CHRE structure allocated with
- * chppMalloc(). If unsuccessful, null. It is the responsibility of the caller
- * to free the buffer when it is no longer needed via chppFree() or
- * CHPP_FREE_AND_NULLIFY().
- */
-struct chreGnssLocationEvent *chppGnssLocationEventToChre(
- const struct ChppGnssLocationEvent *in, size_t inSize);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_GNSS_TYPES_H_
diff --git a/chpp/include/chpp/common/standard_uuids.h b/chpp/include/chpp/common/standard_uuids.h
deleted file mode 100644
index d66061bc..00000000
--- a/chpp/include/chpp/common/standard_uuids.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_STANDARD_UUIDS_H_
-#define CHPP_STANDARD_UUIDS_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Client / Service UUID v4 Definitions
- ***********************************************/
-
-/**
- * Standard WWAN UUID
- */
-#define CHPP_UUID_WWAN_STANDARD \
- { \
- 0x1f, 0x56, 0x3d, 0xf2, 0x5d, 0x07, 0x49, 0x87, 0xba, 0x2b, 0xb3, 0x0e, \
- 0xf2, 0x3d, 0x11, 0x28 \
- }
-
-/**
- * Standard WiFi UUID
- */
-#define CHPP_UUID_WIFI_STANDARD \
- { \
- 0x24, 0x2c, 0x25, 0xaa, 0xc8, 0x2b, 0x40, 0xf1, 0xb8, 0x42, 0x6b, 0xdc, \
- 0x8c, 0x46, 0xa1, 0xb6 \
- }
-
-/**
- * Standard GNSS UUID
- */
-#define CHPP_UUID_GNSS_STANDARD \
- { \
- 0x3a, 0x64, 0x11, 0xa2, 0x50, 0x5b, 0x44, 0x42, 0xaf, 0xdb, 0x41, 0x8e, \
- 0x3a, 0x74, 0xfa, 0xf4 \
- }
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_STANDARD_UUIDS_H_
diff --git a/chpp/include/chpp/common/timesync.h b/chpp/include/chpp/common/timesync.h
deleted file mode 100644
index 3f0ff37f..00000000
--- a/chpp/include/chpp/common/timesync.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_COMMON_TIMESYNC_H_
-#define CHPP_COMMON_TIMESYNC_H_
-
-#include "chpp/app.h"
-#include "chpp/macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/**
- * Data structure used by the Discovery Response.
- */
-CHPP_PACKED_START
-struct ChppTimesyncResponse {
- struct ChppAppHeader header;
- uint64_t timeNs;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Commands used by the Discovery Service
- */
-enum ChppTimesyncCommands {
- // Get time. This should be the same clock used to timestamp any data /
- // samples provided to CHPP.
- CHPP_TIMESYNC_COMMAND_GETTIME = 0x0001,
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_COMMON_TIMESYNC_H_
diff --git a/chpp/include/chpp/common/wifi.h b/chpp/include/chpp/common/wifi.h
deleted file mode 100644
index 59c4a43e..00000000
--- a/chpp/include/chpp/common/wifi.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_WIFI_COMMON_H_
-#define CHPP_WIFI_COMMON_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-#define CHPP_PAL_WIFI_API_VERSION CHRE_PAL_WIFI_API_V1_5
-
-/**
- * Data structures used by the Configure Scan Monitor request.
- */
-CHPP_PACKED_START
-struct ChppWifiConfigureScanMonitorAsyncRequestParameters {
- bool enable;
- const void *cookie;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppWifiConfigureScanMonitorAsyncRequest {
- struct ChppAppHeader header;
- struct ChppWifiConfigureScanMonitorAsyncRequestParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Data structures used by the Get Capabilities Response.
- */
-CHPP_PACKED_START
-struct ChppWifiGetCapabilitiesParameters {
- uint32_t capabilities;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppWifiGetCapabilitiesResponse {
- struct ChppAppHeader header;
- struct ChppWifiGetCapabilitiesParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Data structures used by the Configure Scan Monitor Async Response.
- */
-CHPP_PACKED_START
-struct ChppWifiConfigureScanMonitorAsyncResponseParameters {
- bool enabled;
- uint8_t errorCode;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppWifiConfigureScanMonitorAsyncResponse {
- struct ChppAppHeader header;
- struct ChppWifiConfigureScanMonitorAsyncResponseParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Data structure used by the Request Scan Response.
- */
-CHPP_PACKED_START
-struct ChppWifiRequestScanResponseParameters {
- bool pending;
- uint8_t errorCode;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppWifiRequestScanResponse {
- struct ChppAppHeader header;
- struct ChppWifiRequestScanResponseParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Commands used by the WiFi (WLAN) Service.
- */
-enum ChppWifiCommands {
- //! Initializes the service.
- CHPP_WIFI_OPEN = 0x0000,
-
- //! Deinitializes the service.
- CHPP_WIFI_CLOSE = 0x0001,
-
- //! Retrieves a set of flags indicating supported features.
- CHPP_WIFI_GET_CAPABILITIES = 0x0002,
-
- //! Configures whether scanEventCallback receives unsolicited scan results.
- CHPP_WIFI_CONFIGURE_SCAN_MONITOR_ASYNC = 0x0003,
-
- //! Request that the WiFi chipset perform a scan, or deliver cached results.
- CHPP_WIFI_REQUEST_SCAN_ASYNC = 0x0004,
-
- //! Request that the WiFi chipset perform RTT ranging.
- CHPP_WIFI_REQUEST_RANGING_ASYNC = 0x0005,
-};
-#define CHPP_WIFI_CLIENT_REQUEST_MAX CHPP_WIFI_REQUEST_RANGING_ASYNC
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WIFI_COMMON_H_
diff --git a/chpp/include/chpp/common/wifi_types.h b/chpp/include/chpp/common/wifi_types.h
deleted file mode 100644
index ce94329f..00000000
--- a/chpp/include/chpp/common/wifi_types.h
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_WIFI_TYPES_H_
-#define CHPP_WIFI_TYPES_H_
-
-// This file was automatically generated by chre_api_to_chpp.py
-// Date: 2021-05-24 15:46:25 UTC
-// Source: chre_api/include/chre_api/chre/wifi.h @ commit 833a6241
-
-// DO NOT modify this file directly, as those changes will be lost the next
-// time the script is executed
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/common/common_types.h"
-#include "chpp/macros.h"
-#include "chre_api/chre/version.h"
-#include "chre_api/chre/wifi.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-CHPP_PACKED_START
-
-//! See {@link chreWifiLci} for details
-struct ChppWifiLci {
- int64_t latitude;
- int64_t longitude;
- int32_t altitude;
- uint8_t latitudeUncertainty;
- uint8_t longitudeUncertainty;
- uint8_t altitudeType;
- uint8_t altitudeUncertainty;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWifiRangingResult} for details
-struct ChppWifiRangingResult {
- uint64_t timestamp;
- uint8_t macAddress[6];
- uint8_t status;
- int8_t rssi;
- uint32_t distance;
- uint32_t distanceStdDev;
- struct ChppWifiLci lci;
- uint8_t flags;
- uint8_t reserved[7]; // Input ignored; always set to 0
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWifiRangingEvent} for details
-struct ChppWifiRangingEvent {
- uint8_t
- version; // Input ignored; always set to CHRE_WIFI_RANGING_EVENT_VERSION
- uint8_t resultCount;
- uint8_t reserved[2]; // Input ignored; always set to 0
- struct ChppOffset
- results; // References resultCount instances of struct ChppOffset
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWifiRangingTarget} for details
-struct ChppWifiRangingTarget {
- uint8_t macAddress[6];
- uint32_t primaryChannel;
- uint32_t centerFreqPrimary;
- uint32_t centerFreqSecondary;
- uint8_t channelWidth;
- uint8_t reserved[3]; // Input ignored; always set to 0
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWifiRangingParams} for details
-struct ChppWifiRangingParams {
- uint8_t targetListLen;
- struct ChppOffset
- targetList; // References targetListLen instances of struct ChppOffset
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWifiScanResult} for details
-struct ChppWifiScanResult {
- uint32_t ageMs;
- uint16_t capabilityInfo;
- uint8_t ssidLen;
- uint8_t ssid[32];
- uint8_t bssid[6];
- uint8_t flags;
- int8_t rssi;
- uint8_t band;
- uint32_t primaryChannel;
- uint32_t centerFreqPrimary;
- uint32_t centerFreqSecondary;
- uint8_t channelWidth;
- uint8_t securityMode;
- uint8_t radioChain;
- int8_t rssiChain0;
- int8_t rssiChain1;
- uint8_t reserved[7]; // Input ignored; always set to 0
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWifiScanEvent} for details
-struct ChppWifiScanEvent {
- uint8_t version; // Input ignored; always set to CHRE_WIFI_SCAN_EVENT_VERSION
- uint8_t resultCount;
- uint8_t resultTotal;
- uint8_t eventIndex;
- uint8_t scanType;
- uint8_t ssidSetSize;
- uint16_t scannedFreqListLen;
- uint64_t referenceTime;
- struct ChppOffset scannedFreqList; // References scannedFreqListLen instances
- // of struct ChppOffset
- struct ChppOffset
- results; // References resultCount instances of struct ChppOffset
- uint8_t radioChainPref;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWifiSsidListItem} for details
-struct ChppWifiSsidListItem {
- uint8_t ssidLen;
- uint8_t ssid[32];
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWifiScanParams} for details
-struct ChppWifiScanParams {
- uint8_t scanType;
- uint32_t maxScanAgeMs;
- uint16_t frequencyListLen;
- struct ChppOffset frequencyList; // References frequencyListLen instances of
- // struct ChppOffset
- uint8_t ssidListLen;
- struct ChppOffset
- ssidList; // References ssidListLen instances of struct ChppOffset
- uint8_t radioChainPref;
- uint8_t channelSet;
-} CHPP_PACKED_ATTR;
-
-//! CHPP app header plus struct ChppWifiScanEventWithHeader
-struct ChppWifiScanEventWithHeader {
- struct ChppAppHeader header;
- struct ChppWifiScanEvent payload;
-} CHPP_PACKED_ATTR;
-
-//! CHPP app header plus struct ChppWifiScanParamsWithHeader
-struct ChppWifiScanParamsWithHeader {
- struct ChppAppHeader header;
- struct ChppWifiScanParams payload;
-} CHPP_PACKED_ATTR;
-
-//! CHPP app header plus struct ChppWifiRangingEventWithHeader
-struct ChppWifiRangingEventWithHeader {
- struct ChppAppHeader header;
- struct ChppWifiRangingEvent payload;
-} CHPP_PACKED_ATTR;
-
-//! CHPP app header plus struct ChppWifiRangingParamsWithHeader
-struct ChppWifiRangingParamsWithHeader {
- struct ChppAppHeader header;
- struct ChppWifiRangingParams payload;
-} CHPP_PACKED_ATTR;
-
-CHPP_PACKED_END
-
-// Encoding functions (CHRE --> CHPP)
-
-/**
- * Converts from given CHRE structure to serialized CHPP type.
- *
- * @param in Fully-formed CHRE structure.
- * @param out Upon success, will point to a buffer allocated with chppMalloc().
- * It is the responsibility of the caller to set the values of the CHPP app
- * layer header, and to free the buffer when it is no longer needed via
- * chppFree() or CHPP_FREE_AND_NULLIFY().
- * @param outSize Upon success, will be set to the size of the output buffer, in
- * bytes.
- *
- * @return true on success, false if memory allocation failed.
- */
-bool chppWifiScanEventFromChre(const struct chreWifiScanEvent *in,
- struct ChppWifiScanEventWithHeader **out,
- size_t *outSize);
-
-/**
- * Converts from given CHRE structure to serialized CHPP type.
- *
- * @param in Fully-formed CHRE structure.
- * @param out Upon success, will point to a buffer allocated with chppMalloc().
- * It is the responsibility of the caller to set the values of the CHPP app
- * layer header, and to free the buffer when it is no longer needed via
- * chppFree() or CHPP_FREE_AND_NULLIFY().
- * @param outSize Upon success, will be set to the size of the output buffer, in
- * bytes.
- *
- * @return true on success, false if memory allocation failed.
- */
-bool chppWifiScanParamsFromChre(const struct chreWifiScanParams *in,
- struct ChppWifiScanParamsWithHeader **out,
- size_t *outSize);
-
-/**
- * Converts from given CHRE structure to serialized CHPP type.
- *
- * @param in Fully-formed CHRE structure.
- * @param out Upon success, will point to a buffer allocated with chppMalloc().
- * It is the responsibility of the caller to set the values of the CHPP app
- * layer header, and to free the buffer when it is no longer needed via
- * chppFree() or CHPP_FREE_AND_NULLIFY().
- * @param outSize Upon success, will be set to the size of the output buffer, in
- * bytes.
- *
- * @return true on success, false if memory allocation failed.
- */
-bool chppWifiRangingEventFromChre(const struct chreWifiRangingEvent *in,
- struct ChppWifiRangingEventWithHeader **out,
- size_t *outSize);
-
-/**
- * Converts from given CHRE structure to serialized CHPP type.
- *
- * @param in Fully-formed CHRE structure.
- * @param out Upon success, will point to a buffer allocated with chppMalloc().
- * It is the responsibility of the caller to set the values of the CHPP app
- * layer header, and to free the buffer when it is no longer needed via
- * chppFree() or CHPP_FREE_AND_NULLIFY().
- * @param outSize Upon success, will be set to the size of the output buffer, in
- * bytes.
- *
- * @return true on success, false if memory allocation failed.
- */
-bool chppWifiRangingParamsFromChre(const struct chreWifiRangingParams *in,
- struct ChppWifiRangingParamsWithHeader **out,
- size_t *outSize);
-
-// Decoding functions (CHPP --> CHRE)
-
-/**
- * Converts from serialized CHPP structure to a CHRE type.
- *
- * @param in Fully-formed CHPP structure.
- * @param in Size of the CHPP structure in bytes.
- *
- * @return If successful, a pointer to a CHRE structure allocated with
- * chppMalloc(). If unsuccessful, null. It is the responsibility of the caller
- * to free the buffer when it is no longer needed via chppFree() or
- * CHPP_FREE_AND_NULLIFY().
- */
-struct chreWifiScanEvent *chppWifiScanEventToChre(
- const struct ChppWifiScanEvent *in, size_t inSize);
-
-/**
- * Converts from serialized CHPP structure to a CHRE type.
- *
- * @param in Fully-formed CHPP structure.
- * @param in Size of the CHPP structure in bytes.
- *
- * @return If successful, a pointer to a CHRE structure allocated with
- * chppMalloc(). If unsuccessful, null. It is the responsibility of the caller
- * to free the buffer when it is no longer needed via chppFree() or
- * CHPP_FREE_AND_NULLIFY().
- */
-struct chreWifiScanParams *chppWifiScanParamsToChre(
- const struct ChppWifiScanParams *in, size_t inSize);
-
-/**
- * Converts from serialized CHPP structure to a CHRE type.
- *
- * @param in Fully-formed CHPP structure.
- * @param in Size of the CHPP structure in bytes.
- *
- * @return If successful, a pointer to a CHRE structure allocated with
- * chppMalloc(). If unsuccessful, null. It is the responsibility of the caller
- * to free the buffer when it is no longer needed via chppFree() or
- * CHPP_FREE_AND_NULLIFY().
- */
-struct chreWifiRangingEvent *chppWifiRangingEventToChre(
- const struct ChppWifiRangingEvent *in, size_t inSize);
-
-/**
- * Converts from serialized CHPP structure to a CHRE type.
- *
- * @param in Fully-formed CHPP structure.
- * @param in Size of the CHPP structure in bytes.
- *
- * @return If successful, a pointer to a CHRE structure allocated with
- * chppMalloc(). If unsuccessful, null. It is the responsibility of the caller
- * to free the buffer when it is no longer needed via chppFree() or
- * CHPP_FREE_AND_NULLIFY().
- */
-struct chreWifiRangingParams *chppWifiRangingParamsToChre(
- const struct ChppWifiRangingParams *in, size_t inSize);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WIFI_TYPES_H_
diff --git a/chpp/include/chpp/common/wifi_utils.h b/chpp/include/chpp/common/wifi_utils.h
deleted file mode 100644
index 24a10194..00000000
--- a/chpp/include/chpp/common/wifi_utils.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 CHPP_WIFI_UTILS_H_
-#define CHPP_WIFI_UTILS_H_
-
-#include <stdbool.h>
-
-#include "chre_api/chre/wifi.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Resets the internal state to use chppCheckWifiScanEventNotification(). Should
- * be used whenever the CHPP WiFi link resets.
- */
-void chppCheckWifiScanEventNotificationReset(void);
-
-/**
- * Helper function to validate incoming WiFi scan events. This method will
- * retain history of the previous invocations to verify if the sequence
- * of WiFi scan events are valid.
- *
- * @param chre A non-null pointer to the event.
- *
- * @return false if the check failed.
- */
-bool chppCheckWifiScanEventNotification(const struct chreWifiScanEvent *chre);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WIFI_UTILS_H_
diff --git a/chpp/include/chpp/common/wwan.h b/chpp/include/chpp/common/wwan.h
deleted file mode 100644
index 9c066226..00000000
--- a/chpp/include/chpp/common/wwan.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_WWAN_COMMON_H_
-#define CHPP_WWAN_COMMON_H_
-
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-#define CHPP_PAL_WWAN_API_VERSION CHRE_PAL_WWAN_API_V1_4
-
-/**
- * Data structures used by the Get Capabilities Response.
- */
-CHPP_PACKED_START
-struct ChppWwanGetCapabilitiesParameters {
- uint32_t capabilities;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-CHPP_PACKED_START
-struct ChppWwanGetCapabilitiesResponse {
- struct ChppAppHeader header;
- struct ChppWwanGetCapabilitiesParameters params;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Commands used by the WWAN (cellular) Service.
- */
-enum ChppWwanCommands {
- //! Initializes the service.
- CHPP_WWAN_OPEN = 0x0000,
-
- //! Deinitializes the service.
- CHPP_WWAN_CLOSE = 0x0001,
-
- //! Retrieves a set of flags indicating supported features.
- CHPP_WWAN_GET_CAPABILITIES = 0x0002,
-
- //! Query information about the current serving cell and its neighbors.
- CHPP_WWAN_GET_CELLINFO_ASYNC = 0x0003,
-};
-#define CHPP_WWAN_CLIENT_REQUEST_MAX CHPP_WWAN_GET_CELLINFO_ASYNC
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WWAN_COMMON_H_
diff --git a/chpp/include/chpp/common/wwan_types.h b/chpp/include/chpp/common/wwan_types.h
deleted file mode 100644
index 853963ff..00000000
--- a/chpp/include/chpp/common/wwan_types.h
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_WWAN_TYPES_H_
-#define CHPP_WWAN_TYPES_H_
-
-// This file was automatically generated by chre_api_to_chpp.py
-// Date: 2021-05-24 15:46:25 UTC
-// Source: chre_api/include/chre_api/chre/wwan.h @ commit 833a6241
-
-// DO NOT modify this file directly, as those changes will be lost the next
-// time the script is executed
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/common/common_types.h"
-#include "chpp/macros.h"
-#include "chre_api/chre/version.h"
-#include "chre_api/chre/wwan.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-CHPP_PACKED_START
-
-//! See {@link chreWwanCellIdentityCdma} for details
-struct ChppWwanCellIdentityCdma {
- int32_t networkId;
- int32_t systemId;
- int32_t basestationId;
- int32_t longitude;
- int32_t latitude;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanSignalStrengthCdma} for details
-struct ChppWwanSignalStrengthCdma {
- int32_t dbm;
- int32_t ecio;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanSignalStrengthEvdo} for details
-struct ChppWwanSignalStrengthEvdo {
- int32_t dbm;
- int32_t ecio;
- int32_t signalNoiseRatio;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfoCdma} for details
-struct ChppWwanCellInfoCdma {
- struct ChppWwanCellIdentityCdma cellIdentityCdma;
- struct ChppWwanSignalStrengthCdma signalStrengthCdma;
- struct ChppWwanSignalStrengthEvdo signalStrengthEvdo;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellIdentityGsm} for details
-struct ChppWwanCellIdentityGsm {
- int32_t mcc;
- int32_t mnc;
- int32_t lac;
- int32_t cid;
- int32_t arfcn;
- uint8_t bsic;
- uint8_t reserved[3]; // Input ignored; always set to 0
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanSignalStrengthGsm} for details
-struct ChppWwanSignalStrengthGsm {
- int32_t signalStrength;
- int32_t bitErrorRate;
- int32_t timingAdvance;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfoGsm} for details
-struct ChppWwanCellInfoGsm {
- struct ChppWwanCellIdentityGsm cellIdentityGsm;
- struct ChppWwanSignalStrengthGsm signalStrengthGsm;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellIdentityLte} for details
-struct ChppWwanCellIdentityLte {
- int32_t mcc;
- int32_t mnc;
- int32_t ci;
- int32_t pci;
- int32_t tac;
- int32_t earfcn;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanSignalStrengthLte} for details
-struct ChppWwanSignalStrengthLte {
- int32_t signalStrength;
- int32_t rsrp;
- int32_t rsrq;
- int32_t rssnr;
- int32_t cqi;
- int32_t timingAdvance;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfoLte} for details
-struct ChppWwanCellInfoLte {
- struct ChppWwanCellIdentityLte cellIdentityLte;
- struct ChppWwanSignalStrengthLte signalStrengthLte;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellIdentityNr} for details
-struct ChppWwanCellIdentityNr {
- int32_t mcc;
- int32_t mnc;
- uint32_t nci0;
- uint32_t nci1;
- int32_t pci;
- int32_t tac;
- int32_t nrarfcn;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanSignalStrengthNr} for details
-struct ChppWwanSignalStrengthNr {
- int32_t ssRsrp;
- int32_t ssRsrq;
- int32_t ssSinr;
- int32_t csiRsrp;
- int32_t csiRsrq;
- int32_t csiSinr;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfoNr} for details
-struct ChppWwanCellInfoNr {
- struct ChppWwanCellIdentityNr cellIdentityNr;
- struct ChppWwanSignalStrengthNr signalStrengthNr;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellIdentityTdscdma} for details
-struct ChppWwanCellIdentityTdscdma {
- int32_t mcc;
- int32_t mnc;
- int32_t lac;
- int32_t cid;
- int32_t cpid;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanSignalStrengthTdscdma} for details
-struct ChppWwanSignalStrengthTdscdma {
- int32_t rscp;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfoTdscdma} for details
-struct ChppWwanCellInfoTdscdma {
- struct ChppWwanCellIdentityTdscdma cellIdentityTdscdma;
- struct ChppWwanSignalStrengthTdscdma signalStrengthTdscdma;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellIdentityWcdma} for details
-struct ChppWwanCellIdentityWcdma {
- int32_t mcc;
- int32_t mnc;
- int32_t lac;
- int32_t cid;
- int32_t psc;
- int32_t uarfcn;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanSignalStrengthWcdma} for details
-struct ChppWwanSignalStrengthWcdma {
- int32_t signalStrength;
- int32_t bitErrorRate;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfoWcdma} for details
-struct ChppWwanCellInfoWcdma {
- struct ChppWwanCellIdentityWcdma cellIdentityWcdma;
- struct ChppWwanSignalStrengthWcdma signalStrengthWcdma;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfoPerRat} for details
-union ChppWwanCellInfoPerRat {
- struct ChppWwanCellInfoGsm gsm;
- struct ChppWwanCellInfoCdma cdma;
- struct ChppWwanCellInfoLte lte;
- struct ChppWwanCellInfoWcdma wcdma;
- struct ChppWwanCellInfoTdscdma tdscdma;
- struct ChppWwanCellInfoNr nr;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfo} for details
-struct ChppWwanCellInfo {
- uint64_t timeStamp;
- uint8_t cellInfoType;
- uint8_t timeStampType;
- uint8_t registered;
- uint8_t reserved; // Input ignored; always set to 0
- union ChppWwanCellInfoPerRat CellInfo;
-} CHPP_PACKED_ATTR;
-
-//! See {@link chreWwanCellInfoResult} for details
-struct ChppWwanCellInfoResult {
- uint8_t version; // Input ignored; always set to
- // CHRE_WWAN_CELL_INFO_RESULT_VERSION
- uint8_t errorCode;
- uint8_t cellInfoCount;
- uint8_t reserved; // Input ignored; always set to 0
- uint32_t cookie; // Input ignored; always set to 0
- struct ChppOffset
- cells; // References cellInfoCount instances of struct ChppOffset
-} CHPP_PACKED_ATTR;
-
-//! CHPP app header plus struct ChppWwanCellInfoResultWithHeader
-struct ChppWwanCellInfoResultWithHeader {
- struct ChppAppHeader header;
- struct ChppWwanCellInfoResult payload;
-} CHPP_PACKED_ATTR;
-
-CHPP_PACKED_END
-
-// Encoding functions (CHRE --> CHPP)
-
-/**
- * Converts from given CHRE structure to serialized CHPP type.
- *
- * @param in Fully-formed CHRE structure.
- * @param out Upon success, will point to a buffer allocated with chppMalloc().
- * It is the responsibility of the caller to set the values of the CHPP app
- * layer header, and to free the buffer when it is no longer needed via
- * chppFree() or CHPP_FREE_AND_NULLIFY().
- * @param outSize Upon success, will be set to the size of the output buffer, in
- * bytes.
- *
- * @return true on success, false if memory allocation failed.
- */
-bool chppWwanCellInfoResultFromChre(
- const struct chreWwanCellInfoResult *in,
- struct ChppWwanCellInfoResultWithHeader **out, size_t *outSize);
-
-// Decoding functions (CHPP --> CHRE)
-
-/**
- * Converts from serialized CHPP structure to a CHRE type.
- *
- * @param in Fully-formed CHPP structure.
- * @param in Size of the CHPP structure in bytes.
- *
- * @return If successful, a pointer to a CHRE structure allocated with
- * chppMalloc(). If unsuccessful, null. It is the responsibility of the caller
- * to free the buffer when it is no longer needed via chppFree() or
- * CHPP_FREE_AND_NULLIFY().
- */
-struct chreWwanCellInfoResult *chppWwanCellInfoResultToChre(
- const struct ChppWwanCellInfoResult *in, size_t inSize);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WWAN_TYPES_H_
diff --git a/chpp/include/chpp/condition_variable.h b/chpp/include/chpp/condition_variable.h
deleted file mode 100644
index 8e80031d..00000000
--- a/chpp/include/chpp/condition_variable.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-/*
- * Implementation Notes
- * Each platform must supply a platform-specific platform_condition_variable.h
- * to provide definitions and a platform-specific condition_variable.c to
- * provide the implementation for the definitions in this file.
- */
-
-#ifndef CHPP_CONDITION_VARIABLE_H_
-#define CHPP_CONDITION_VARIABLE_H_
-
-#include <inttypes.h>
-#include <stdbool.h>
-
-#include "chpp/mutex.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Platform-specific condition variable struct defined in the platform's
- * platform_condition_variable.h that enables the funcions defined here.
- */
-struct ChppConditionVariable;
-
-/**
- * Initializes the platform-specific ChppConditionVariable.
- */
-static void chppConditionVariableInit(struct ChppConditionVariable *cv);
-
-/**
- * Deinitializes the platform-specific ChppConditionVariable.
- */
-static void chppConditionVariableDeinit(struct ChppConditionVariable *cv);
-
-/**
- * Waits until signaled through chppConditionVariableSignal(). Only one entity
- * may be waiting on a condition variable at one time.
- *
- * It is expected that the provided mutex is locked before the function is
- * invoked, and otherwise results in undefined behavior.
- *
- * @param cv The pointer to the condition variable.
- * @param mutex The mutex to use with this condition variable.
- *
- * @return True if the wait succeeded.
- */
-static bool chppConditionVariableWait(struct ChppConditionVariable *cv,
- struct ChppMutex *mutex);
-
-/**
- * Same as chppConditionVariableWait(), but with a specified timeout.
- *
- * @param cv The pointer to the condition variable.
- * @param mutex The mutex to use with this condition variable.
- * @param timeoutNs The timeout in nanoseconds.
- *
- * @return True if the wait succeeded.
- */
-static bool chppConditionVariableTimedWait(struct ChppConditionVariable *cv,
- struct ChppMutex *mutex,
- uint64_t timeoutNs);
-
-/**
- * Signals on an entity waiting on the condition variable through
- * chppConditionVariableWait().
- *
- * @param cv The pointer to the condition variable.
- */
-static void chppConditionVariableSignal(struct ChppConditionVariable *cv);
-
-#ifdef __cplusplus
-}
-#endif
-
-#include "chpp/platform/platform_condition_variable.h"
-
-#endif // CHPP_CONDITION_VARIABLE_H_
diff --git a/chpp/include/chpp/crc.h b/chpp/include/chpp/crc.h
deleted file mode 100644
index 4a9fb3f2..00000000
--- a/chpp/include/chpp/crc.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_CRC_H_
-#define CHPP_CRC_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Calculates IEEE CRC-32, initialized to (~crc), on an input data buffer.
- *
- * It is expected that the implementation be optimized based on individual
- * platforms, e.g. by reusing HW/SW optimized CRC functionality.
- *
- * @param crc CRC initialization value. This may be used to calculate a CRC on
- * daisy-chained input data. Otherwise, it can be set to zero to initialize to
- * 0xFFFFFFFF.
- * @param buf Input data.
- * @param len Input data length in bytes.
- *
- * @return Calculated CRC-32.
- */
-uint32_t chppCrc32(uint32_t crc, const uint8_t *buf, size_t len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_CRC_H_
diff --git a/chpp/include/chpp/link.h b/chpp/include/chpp/link.h
deleted file mode 100644
index 9a35f473..00000000
--- a/chpp/include/chpp/link.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-/*
- * Implementation Notes:
- * Each platform must supply a platform-specific platform_link.h to provide the
- * definitions and a platform-specific link.c to provide the implementation for
- * the definitions in this file.
- * The platform must also initialize the ChppPlatformLinkParameters for each
- * link (context.linkParams).
- */
-
-#ifndef CHPP_LINK_H_
-#define CHPP_LINK_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Error codes used by the link layer.
- */
-enum ChppLinkErrorCode {
- //! No error - data queued to be sent asynchronously
- CHPP_LINK_ERROR_NONE_QUEUED = 0,
-
- //! No error - data successfully sent
- CHPP_LINK_ERROR_NONE_SENT = 1,
-
- //! Timeout
- CHPP_LINK_ERROR_TIMEOUT = 2,
-
- //! Busy
- CHPP_LINK_ERROR_BUSY = 3,
-
- //! Out of memory
- CHPP_LINK_ERROR_OOM = 4,
-
- //! Link not established
- CHPP_LINK_ERROR_NO_LINK = 5,
-
- //! Unspecified failure
- CHPP_LINK_ERROR_UNSPECIFIED = 255
-};
-
-/*
- * Platform-specific struct with link details / parameters.
- */
-struct ChppPlatformLinkParameters;
-
-/**
- * Platform-specific function to initialize the link layer.
- *
- * @param params Platform-specific struct with link details / parameters.
- */
-void chppPlatformLinkInit(struct ChppPlatformLinkParameters *params);
-
-/**
- * Platform-specific function to deinitialize the link layer (e.g. clean exit).
- *
- * @param params Platform-specific struct with link details / parameters.
- */
-void chppPlatformLinkDeinit(struct ChppPlatformLinkParameters *params);
-
-/*
- * Platform-specific function to send Tx data over to the link layer.
- *
- * @param params Platform-specific struct with link details / parameters.
- * @param buf Data to be sent.
- * @param len Length of the data to be sent in bytes.
- *
- * @return CHPP_LINK_ERROR_NONE_SENT if the platform implementation for this
- * function is synchronous, i.e. it is done with buf and len once the function
- * returns. A return value of CHPP_LINK_ERROR_NONE_QUEUED indicates that this
- * function is implemented asynchronously. In this case, it is up to the
- * platform implementation to call chppLinkSendDoneCb() after processing the
- * contents of buf and len. Otherwise, an error code is returned per enum
- * ChppLinkErrorCode.
- */
-enum ChppLinkErrorCode chppPlatformLinkSend(
- struct ChppPlatformLinkParameters *params, uint8_t *buf, size_t len);
-
-/**
- * Platform-specific function to perform a task from the main CHPP transport
- * work thread. The task can be specified by the signal argument, which is
- * triggered by previous call[s] to chppWorkThreadSignalFromLink(). An example
- * of the type of work that can be performed is processing RX data from the
- * physical layer.
- *
- * @param params Platform-specific struct with link details / parameters.
- * @param signal The signal that describes the work to be performed. Only bits
- * specified by CHPP_TRANSPORT_SIGNAL_PLATFORM_MASK can be set.
- */
-void chppPlatformLinkDoWork(struct ChppPlatformLinkParameters *params,
- uint32_t signal);
-
-/*
- * Platform-specific function to reset a non-synchronous link, where the link
- * implementation is responsible for calling chppLinkSendDoneCb() after
- * processing the contents of buf and len. For such links, a reset called before
- * chppLinkSendDoneCb() indicates to the link to abort sending out buf, and that
- * the contents of buf and len will become invalid.
- *
- * @param params Platform-specific struct with link details / parameters.
- */
-void chppPlatformLinkReset(struct ChppPlatformLinkParameters *params);
-
-#ifdef __cplusplus
-}
-#endif
-
-#include "chpp/platform/platform_link.h"
-
-#endif // CHPP_LINK_H_
diff --git a/chpp/include/chpp/log.h b/chpp/include/chpp/log.h
deleted file mode 100644
index 285dfd38..00000000
--- a/chpp/include/chpp/log.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_LOG_H_
-#define CHPP_LOG_H_
-
-// Defines CHRE macros that are necessary to compile CHPP (for compilers other
-// than GCC / clang)
-#ifndef IS_CHPP_BUILD
-#define IS_CHPP_BUILD
-#endif
-
-#include "chpp/platform/platform_log.h"
-#include "chre/util/log_common.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Log errors if the platform does not supply logging macros.
- */
-
-#ifndef CHPP_LOGE
-#error "CHPP_LOGE must be defined"
-#endif // CHPP_LOGE
-
-#ifndef CHPP_LOGW
-#error "CHPP_LOGW must be defined"
-#endif // CHPP_LOGW
-
-#ifndef CHPP_LOGI
-#error "CHPP_LOGI must be defined"
-#endif // CHPP_LOGI
-
-#ifndef CHPP_LOGD
-#error "CHPP_LOGD must be defined"
-#endif // CHPP_LOGD
-
-#ifndef CHPP_MINIMUM_LOG_LEVEL
-#define CHPP_MINIMUM_LOG_LEVEL CHRE_LOG_LEVEL_DEBUG
-#endif // CHPP_MINIMUM_LOG_LEVEL
-
-#if CHPP_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_ERROR
-#undef CHPP_LOGE
-#define CHPP_LOGE(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
-#endif
-
-#if CHPP_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_WARN
-#undef CHPP_LOGW
-#define CHPP_LOGW(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
-#endif
-
-#if CHPP_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_INFO
-#undef CHPP_LOGI
-#define CHPP_LOGI(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
-#endif
-
-#if CHPP_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_DEBUG
-#undef CHPP_LOGD
-#define CHPP_LOGD(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
-#endif
-
-/**
- * Logs an out of memory error with file and line number.
- */
-#define CHPP_LOG_OOM() CHPP_LOGE("OOM at %s:%d", __FILE__, __LINE__)
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_LOG_H_
diff --git a/chpp/include/chpp/macros.h b/chpp/include/chpp/macros.h
index b2948130..0c9cc4ad 100644
--- a/chpp/include/chpp/macros.h
+++ b/chpp/include/chpp/macros.h
@@ -17,122 +17,33 @@
#ifndef CHPP_MACROS_H_
#define CHPP_MACROS_H_
-#include <assert.h>
-#include <inttypes.h>
-#include <stddef.h>
#include <stdlib.h>
-#include "chpp/memory.h"
-
#ifdef __cplusplus
extern "C" {
#endif
-#define MOST_SIGNIFICANT_NIBBLE 0xf0
-#define LEAST_SIGNIFICANT_NIBBLE 0x0f
-
#ifndef UNUSED_VAR
#define UNUSED_VAR(var) ((void)(var))
#endif
#ifndef MIN
-#define MIN(a, b) ((a) < (b) ? (a) : (b))
+#define MIN(a, b) ((a) < (b)) ? (a) : (b)
#endif
#ifndef MAX
-#define MAX(a, b) ((a) > (b) ? (a) : (b))
-#endif
-
-#ifndef ARRAY_SIZE
-#define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
+#define MAX(a, b) ((a) > (b)) ? (a) : (b)
#endif
#ifndef CHPP_ASSERT
#define CHPP_ASSERT(var) assert(var)
#endif
-#ifndef CHPP_ASSERT_LOG
-#define CHPP_ASSERT_LOG(var, fmt, ...) \
- do { \
- if (!(var)) { \
- CHPP_LOGE(fmt, ##__VA_ARGS__); \
- CHPP_ASSERT(false); \
- } \
- } while (0)
-#endif
-
#ifndef CHPP_NOT_NULL
#define CHPP_NOT_NULL(var) CHPP_ASSERT((var) != NULL)
#endif
/**
- * Debug assertions that are not intended to be enabled for production software.
- */
-#ifndef CHPP_DEBUG_ASSERT
-#ifdef CHPP_DEBUG_ASSERT_ENABLED
-#define CHPP_DEBUG_ASSERT(var) CHPP_ASSERT(var)
-#else
-#define CHPP_DEBUG_ASSERT(var) UNUSED_VAR(var)
-#endif // CHPP_DEBUG_ASSERT_ENABLED
-#endif // CHPP_DEBUG_ASSERT
-
-#ifndef CHPP_DEBUG_ASSERT_LOG
-#define CHPP_DEBUG_ASSERT_LOG(var, fmt, ...) \
- do { \
- if (!(var)) { \
- CHPP_LOGE(fmt, ##__VA_ARGS__); \
- CHPP_DEBUG_ASSERT(false); \
- } \
- } while (0)
-#endif
-
-#ifndef PRIu64 // Pre-C99 lacks PRIu64 support. Note that the correct
- // definition on pre-C99 systems would be compiler-dependent.
-#define PRIu64 "llu"
-#endif
-
-#if defined(__GNUC__) && (__STDC_VERSION__ >= 201112L)
-#define CHPP_C11_OR_NEWER
-#endif
-
-#ifdef CHPP_C11_OR_NEWER
-#define CHPP_STATIC_ASSERT _Static_assert
-
-#else
-#define CHPP_STATIC_ASSERT4(cond, var) typedef char var[(!!(cond)) * 2 - 1]
-#define CHPP_STATIC_ASSERT3(cond, line) \
- CHPP_STATIC_ASSERT4(cond, static_assertion_at_line_##line)
-#define CHPP_STATIC_ASSERT2(cond, line) CHPP_STATIC_ASSERT3(cond, line)
-#define CHPP_STATIC_ASSERT(cond, msg) CHPP_STATIC_ASSERT2(cond, __LINE__)
-
-#endif // CHPP_C11_OR_NEWER
-
-// Time-related macros
-#define CHPP_TIME_NONE 0
-#define CHPP_TIME_MAX UINT64_MAX
-#define CHPP_MSEC_PER_SEC UINT64_C(1000)
-#define CHPP_USEC_PER_MSEC UINT64_C(1000)
-#define CHPP_NSEC_PER_USEC UINT64_C(1000)
-#define CHPP_USEC_PER_SEC (CHPP_USEC_PER_MSEC * CHPP_MSEC_PER_SEC)
-#define CHPP_NSEC_PER_MSEC (CHPP_NSEC_PER_USEC * CHPP_USEC_PER_MSEC)
-#define CHPP_NSEC_PER_SEC \
- (CHPP_NSEC_PER_USEC * CHPP_USEC_PER_MSEC * CHPP_MSEC_PER_SEC)
-#define CHPP_NSEC_PER_MINUTE (CHPP_NSEC_PER_SEC * 60)
-#define CHPP_NSEC_PER_HOUR (CHPP_NSEC_PER_MINUTE * 60)
-
-#if defined(__GNUC__) || defined(__clang__)
-#define check_types_match(t1, t2) ((__typeof__(t1) *)0 != (__typeof__(t2) *)0)
-#else
-#define check_types_match(t1, t2) 0
-#endif
-
-#define container_of(ptr, type, member) \
- ((type *)(void *)((char *)(ptr)-offsetof(type, member)) + \
- check_types_match(*(ptr), ((type *)0)->member))
-
-#define sizeof_member(type, member) (sizeof(((type *)0)->member))
-
-/**
* Macros for defining (compiler dependent) packed structures
*/
#if defined(__GNUC__) || defined(__clang__)
@@ -140,34 +51,16 @@ extern "C" {
#define CHPP_PACKED_START
#define CHPP_PACKED_END
#define CHPP_PACKED_ATTR __attribute__((packed))
-
#elif defined(__ICCARM__) || defined(__CC_ARM)
// For IAR ARM and Keil MDK-ARM compilers
#define CHPP_PACKED_START _Pragma("pack(push, 1)")
#define CHPP_PACKED_END _Pragma("pack(pop)")
#define CHPP_PACKED_ATTR
-
-#elif defined(_MSC_VER)
-// For Microsoft Visual Studio
-#define CHPP_PACKED_START __pragma(pack(push, 1))
-#define CHPP_PACKED_END __pragma(pack(pop))
-#define CHPP_PACKED_ATTR
-
#else
// Unknown compiler
#error Unrecognized compiler
#endif
-#define CHPP_FREE_AND_NULLIFY(p) \
- do { \
- chppFree(p); \
- (p) = NULL; \
- } while (0)
-
-//! Cast a const pointer to a non-const. This is necessary for removing const
-//! with the -Wcast-qual compiler flag.
-#define CHPP_CONST_CAST_POINTER(p) (void *)(intptr_t)(p)
-
#ifdef __cplusplus
}
#endif
diff --git a/chpp/include/chpp/memory.h b/chpp/include/chpp/memory.h
index 51fdb6b3..d19cda41 100644
--- a/chpp/include/chpp/memory.h
+++ b/chpp/include/chpp/memory.h
@@ -17,7 +17,7 @@
#ifndef CHPP_MEMORY_H_
#define CHPP_MEMORY_H_
-#include <stddef.h>
+#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
@@ -29,10 +29,7 @@ extern "C" {
void *chppMalloc(const size_t size);
/**
- * Free memory.
- * Note that is is expected that CHPP_FREE_AND_NULLIFY() is used exclusively
- * instead of calling chppFree directly. This would ensure that buf is set to
- * NULL afterwards.
+ * Free memory
*/
void chppFree(void *ptr);
diff --git a/chpp/include/chpp/mutex.h b/chpp/include/chpp/mutex.h
index 27aa1a82..b48e02cd 100644
--- a/chpp/include/chpp/mutex.h
+++ b/chpp/include/chpp/mutex.h
@@ -29,8 +29,7 @@ extern "C" {
#endif
/*
- * Platform-specific mutex struct, defined in the platform's platform_mutex.h
- * file.
+ * Platform-specific mutex struct, including the member "lock"
*/
struct ChppMutex;
@@ -42,13 +41,6 @@ struct ChppMutex;
static void chppMutexInit(struct ChppMutex *mutex);
/*
- * Deinitializes a specified platform-specific mutex.
- *
- * @param mutex points to the ChppMutex mutex struct.
- */
-static void chppMutexDeinit(struct ChppMutex *mutex);
-
-/*
* Locks a specified platform-specific mutex.
*
* @param mutex points to the ChppMutex mutex struct.
diff --git a/chpp/include/chpp/notifier.h b/chpp/include/chpp/notifier.h
deleted file mode 100644
index 2624b476..00000000
--- a/chpp/include/chpp/notifier.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-/*
- * Implementation Notes
- * Each platform must supply a platform-specific platform_notifier.h to provide
- * definitions and a platform-specific notifier.c to provide the implementation
- * for the definitions in this file.
- */
-
-#ifndef CHPP_SYNC_H_
-#define CHPP_SYNC_H_
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Platform-specific condition variable struct defined in the platform's
- * platform_notifier.h that enables the funcions defined here.
- */
-struct ChppNotifier;
-
-/**
- * Initializes the platform-specific ChppNotifier.
- * Will be called before notifier is used anywhere else.
- *
- * @param notifier Points to the ChppNotifier being initialized.
- */
-static void chppNotifierInit(struct ChppNotifier *notifier);
-
-/**
- * Deinitializes the platform-specific ChppNotifier.
- *
- * @param notifier Points to the ChppNotifier being deinitialized.
- */
-static void chppNotifierDeinit(struct ChppNotifier *notifier);
-
-/**
- * Returns the signal value in chppNotifierSignal(), if any. Resets the signal
- * value afterwards.
- *
- * @param notifier Points to the ChppNotifier being used.
- *
- * @return The signal value indicated in chppNotifierSignal().
- */
-static uint32_t chppNotifierGetSignal(struct ChppNotifier *notifier);
-
-/**
- * Waits on a platform-specific notifier until it is signaled through
- * chppNotifierSignal(). Similar to chppNotifierTimedWait(), but without the
- * timeout.
- *
- * @param notifier Points to the ChppNotifier being used.
- *
- * @return The signal value indicated in chppNotifierSignal().
- */
-static uint32_t chppNotifierWait(struct ChppNotifier *notifier);
-
-/**
- * Waits on a platform-specific notifier until it is signaled through
- * chppNotifierSignal() or until the specified timeout.
- *
- * Note that while the timeout is specified as a uint64_t, in practice, CHPP
- * would only use values up to CHPP_TRANSPORT_TX_TIMEOUT_NS.
- *
- * @param notifier Points to the ChppNotifier being used.
- * @param timeoutNs Timeout in nanoseconds.
- *
- * @return The signal value indicated in chppNotifierSignal().
- */
-static uint32_t chppNotifierTimedWait(struct ChppNotifier *notifier,
- uint64_t timeoutNs);
-
-/**
- * Signals chppNotifierTimedWait() with the specified signal value.
- *
- * The signal values can be defined by the user of this class. Note that it is
- * expected for different signals to be bitwise exclusive, i.e. each bit in the
- * uint32_t should indicate a specific type of signal event. This allows for
- * multiple events to be handled simultaneously in chppNotifierTimedWait().
- *
- * @param notifier Points to the ChppNotifier being used.
- */
-static void chppNotifierSignal(struct ChppNotifier *notifier, uint32_t signal);
-
-#ifdef __cplusplus
-}
-#endif
-
-#include "chpp/platform/platform_notifier.h"
-
-#endif // CHPP_SYNC_H_
diff --git a/chpp/include/chpp/pal_api.h b/chpp/include/chpp/pal_api.h
deleted file mode 100644
index 14930d8a..00000000
--- a/chpp/include/chpp/pal_api.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_PAL_API_H_
-#define CHPP_PAL_API_H_
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Called by the App layer to initialize the PAL system APIs.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppPalSystemApiInit(struct ChppAppState *context);
-
-/**
- * Called by the App layer to deinitialize the PAL system APIs.
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppPalSystemApiDeinit(struct ChppAppState *context);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_LOG_H_
diff --git a/chpp/include/chpp/services.h b/chpp/include/chpp/services.h
deleted file mode 100644
index ad75e9bf..00000000
--- a/chpp/include/chpp/services.h
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_SERVICES_H_
-#define CHPP_SERVICES_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-#if defined(CHPP_SERVICE_ENABLED_WWAN) || \
- defined(CHPP_SERVICE_ENABLED_WIFI) || defined(CHPP_SERVICE_ENABLED_GNSS)
-#define CHPP_SERVICE_ENABLED
-#endif
-
-/**
- * Uses chppAllocServiceNotification() to allocate a variable-length response
- * message of a specific type.
- *
- * @param type Type of notification which includes an arrayed member.
- * @param count number of items in the array of arrayField.
- * @param arrayField The arrayed member field.
- *
- * @return Pointer to allocated memory
- */
-#define chppAllocServiceNotificationTypedArray(type, count, arrayField) \
- (type *)chppAllocServiceNotification( \
- sizeof(type) + (count)*sizeof_member(type, arrayField[0]))
-
-/**
- * Uses chppAllocServiceNotification() to allocate a response message of a
- * specific type and its corresponding length.
- *
- * @param type Type of notification.
- *
- * @return Pointer to allocated memory
- */
-#define chppAllocServiceNotificationFixed(type) \
- (type *)chppAllocServiceNotification(sizeof(type))
-
-/**
- * Uses chppAllocServiceResponse() to allocate a variable-length response
- * message of a specific type.
- *
- * @param requestHeader client request header, as per
- * chppAllocServiceResponse().
- * @param type Type of response which includes an arrayed member.
- * @param count number of items in the array of arrayField.
- * @param arrayField The arrayed member field.
- *
- * @return Pointer to allocated memory
- */
-#define chppAllocServiceResponseTypedArray(requestHeader, type, count, \
- arrayField) \
- (type *)chppAllocServiceResponse( \
- requestHeader, \
- sizeof(type) + (count)*sizeof_member(type, arrayField[0]))
-
-/**
- * Uses chppAllocServiceResponse() to allocate a response message of a specific
- * type and its corresponding length.
- *
- * @param requestHeader client request header, as per
- * chppAllocServiceResponse().
- * @param type Type of response.
- *
- * @return Pointer to allocated memory
- */
-#define chppAllocServiceResponseFixed(requestHeader, type) \
- (type *)chppAllocServiceResponse(requestHeader, sizeof(type))
-
-/**
- * Maintains the basic state of a service.
- * This is expected to be included once in the (context) status variable of each
- * service.
- */
-struct ChppServiceState {
- struct ChppAppState *appContext; // Pointer to app layer context
- uint8_t handle; // Handle number for this service
-
- uint8_t openState; // As defined in enum ChppOpenState
-};
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Registers common services with the CHPP app layer. These services are enabled
- * by CHPP_SERVICE_ENABLED_xxxx definitions. This function is automatically
- * called by chppAppInit().
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppRegisterCommonServices(struct ChppAppState *context);
-
-/**
- * Deregisters common services with the CHPP app layer. These services are
- * enabled by CHPP_SERVICE_ENABLED_xxxx definitions. This function is
- * automatically called by chppAppInit().
- *
- * @param context Maintains status for each app layer instance.
- */
-void chppDeregisterCommonServices(struct ChppAppState *context);
-
-/**
- * Registers a new service on CHPP. This function is to be called by the
- * platform initialization code for every non-common service available on a
- * server (if any), i.e. except those that are registered through
- * chppRegisterCommonServices().
- *
- * Note that the maximum number of services that can be registered on a platform
- * can specified as CHPP_MAX_REGISTERED_SERVICES by the initialization code.
- * Otherwise, a default value will be used.
- *
- * @param appContext Maintains status for each app layer instance.
- * @param serviceContext Maintains status for each service instance.
- * @param newService The service to be registered on this platform.
- *
- * @return Handle number of the registered service.
- */
-uint8_t chppRegisterService(struct ChppAppState *appContext,
- void *serviceContext,
- const struct ChppService *newService);
-
-/**
- * Allocates a service notification of a specified length.
- *
- * It is expected that for most use cases, the
- * chppAllocServiceNotificationFixed() or
- * chppAllocServiceNotificationTypedArray() macros shall be used rather than
- * calling this function directly.
- *
- * @param len Length of the notification (including header) in bytes. Note
- * that the specified length must be at least equal to the lendth of the app
- * layer header.
- *
- * @return Pointer to allocated memory
- */
-struct ChppAppHeader *chppAllocServiceNotification(size_t len);
-
-/**
- * Allocates a service response message of a specified length, populating the
- * (app layer) service response header accorging to the provided client request
- * (app layer) header.
- *
- * It is expected that for most use cases, the chppAllocServiceResponseFixed()
- * or chppAllocServiceResponseTypedArray() macros shall be used rather than
- * calling this function directly.
- *
- * @param requestHeader Client request header.
- * @param len Length of the response message (including header) in bytes. Note
- * that the specified length must be at least equal to the lendth of the app
- * layer header.
- *
- * @return Pointer to allocated memory
- */
-struct ChppAppHeader *chppAllocServiceResponse(
- const struct ChppAppHeader *requestHeader, size_t len);
-
-/**
- * This function shall be called for all incoming client requests in order to
- * A) Timestamp them, and
- * B) Save their Transaction ID
- * as part of the request/response's ChppRequestResponseState struct.
- *
- * This function prints an error message if a duplicate request is received
- * while outstanding request is still pending without a response.
- *
- * @param rRState Maintains the basic state for each request/response
- * functionality of a service.
- * @param requestHeader Client request header.
- */
-void chppServiceTimestampRequest(struct ChppRequestResponseState *rRState,
- struct ChppAppHeader *requestHeader);
-
-/**
- * This function shall be called for the final service response to a client
- * request in order to
- * A) Timestamp them, and
- * B) Mark them as fulfilled
- * part of the request/response's ChppRequestResponseState struct.
- *
- * This function prints an error message if a response is attempted without an
- * outstanding request.
- *
- * For most responses, it is expected that chppSendTimestampedResponseOrFail()
- * shall be used to both timestamp and send the response in one shot.
- *
- * @param rRState Maintains the basic state for each request/response
- * functionality of a service.
- */
-void chppServiceTimestampResponse(struct ChppRequestResponseState *rRState);
-
-/**
- * Timestamps a service response using chppServiceTimestampResponse() and
- * enqueues it using chppEnqueueTxDatagramOrFail().
- *
- * Refer to their respective documentation for details.
- *
- * @param serviceState State of the service sending the response service.
- * @param rRState Maintains the basic state for each request/response
- * functionality of a service.
- * @param buf Datagram payload allocated through chppMalloc. Cannot be null.
- * @param len Datagram length in bytes.
- *
- * @return True informs the sender that the datagram was successfully enqueued.
- * False informs the sender that the queue was full and the payload discarded.
- */
-bool chppSendTimestampedResponseOrFail(struct ChppServiceState *serviceState,
- struct ChppRequestResponseState *rRState,
- void *buf, size_t len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_SERVICES_H_
diff --git a/chpp/include/chpp/services/discovery.h b/chpp/include/chpp/services/discovery.h
deleted file mode 100644
index 5c0dadd2..00000000
--- a/chpp/include/chpp/services/discovery.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_SERVICE_DISCOVERY_H_
-#define CHPP_SERVICE_DISCOVERY_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/*
- * Dispatches a client request that is determined to be for the CHPP Discovery
- * Service.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input (request) datagram. Cannot be null.
- * @param len Length of input data in bytes.
- */
-bool chppDispatchDiscoveryClientRequest(struct ChppAppState *context,
- const uint8_t *buf, size_t len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_SERVICE_DISCOVERY_H_
diff --git a/chpp/include/chpp/services/gnss.h b/chpp/include/chpp/services/gnss.h
deleted file mode 100644
index 4422b79f..00000000
--- a/chpp/include/chpp/services/gnss.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_GNSS_SERVICE_H_
-#define CHPP_GNSS_SERVICE_H_
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Called by the App layer to register the GNSS (GPS) common service.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppRegisterGnssService(struct ChppAppState *appContext);
-
-/**
- * Called by the App layer to deregister the GNSS (GPS) common service.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppDeregisterGnssService(struct ChppAppState *appContext);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_GNSS_SERVICE_H_
diff --git a/chpp/include/chpp/services/loopback.h b/chpp/include/chpp/services/loopback.h
deleted file mode 100644
index 1a0ee7fd..00000000
--- a/chpp/include/chpp/services/loopback.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_LOOPBACK_H_
-#define CHPP_LOOPBACK_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/*
- * Processes an client request Rx datagram from the transport layer that is
- * determined to be for the CHPP Loopback Service.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-bool chppDispatchLoopbackClientRequest(struct ChppAppState *context,
- uint8_t *buf, size_t len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_LOOPBACK_H_
diff --git a/chpp/include/chpp/services/nonhandle.h b/chpp/include/chpp/services/nonhandle.h
deleted file mode 100644
index f0568f2f..00000000
--- a/chpp/include/chpp/services/nonhandle.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_NONHANDLE_H_
-#define CHPP_NONHANDLE_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/*
- * Dispatches an Rx Datagram from the transport layer for systems that are using
- * the optional handleless CHPP communication service. Does not need to be
- * implemented on systems that are not using handleless communication.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-void chppDispatchNonHandle(struct ChppAppState *context, uint8_t *buf,
- size_t len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_NONHANDLE_H_
diff --git a/chpp/include/chpp/services/timesync.h b/chpp/include/chpp/services/timesync.h
deleted file mode 100644
index 6439370c..00000000
--- a/chpp/include/chpp/services/timesync.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_SERVICE_TIMESYNC_H_
-#define CHPP_SERVICE_TIMESYNC_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Dispatches a client request that is determined to be for the CHPP Timesync
- * Service.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input (request) datagram. Cannot be null.
- * @param len Length of input data in bytes.
- */
-bool chppDispatchTimesyncClientRequest(struct ChppAppState *context,
- const uint8_t *buf, size_t len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_SERVICE_TIMESYNC_H_
diff --git a/chpp/include/chpp/services/wifi.h b/chpp/include/chpp/services/wifi.h
deleted file mode 100644
index f4e435d9..00000000
--- a/chpp/include/chpp/services/wifi.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_WIFI_SERVICE_H_
-#define CHPP_WIFI_SERVICE_H_
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Called by the App layer to register the WiFi (WLAN) common service.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppRegisterWifiService(struct ChppAppState *appContext);
-
-/**
- * Called by the App layer to deregister the WiFi (WLAN) common service.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppDeregisterWifiService(struct ChppAppState *appContext);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WIFI_SERVICE_H_
diff --git a/chpp/include/chpp/services/wwan.h b/chpp/include/chpp/services/wwan.h
deleted file mode 100644
index 2ff92427..00000000
--- a/chpp/include/chpp/services/wwan.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_WWAN_SERVICE_H_
-#define CHPP_WWAN_SERVICE_H_
-
-#include "chpp/app.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Public Definitions
- ***********************************************/
-
-/************************************************
- * Public functions
- ***********************************************/
-
-/**
- * Called by the App layer to register the WWAN (cellular) common service.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppRegisterWwanService(struct ChppAppState *appContext);
-
-/**
- * Called by the App layer to deregister the WWAN (cellular) common service.
- *
- * @param appContext Maintains status for each app layer instance.
- */
-void chppDeregisterWwanService(struct ChppAppState *appContext);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_WWAN_SERVICE_H_
diff --git a/chpp/include/chpp/time.h b/chpp/include/chpp/time.h
deleted file mode 100644
index 55140dc3..00000000
--- a/chpp/include/chpp/time.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-/*
- * Implementation Notes
- * Each platform must supply chpp/platform/platform_time.h which provides the
- * platform-specific definitions (and implementation as necessary) for the
- * definitions in this file.
- */
-
-#ifndef CHPP_TIME_H_
-#define CHPP_TIME_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * @return The current time in nanoseconds.
- */
-static uint64_t chppGetCurrentTimeNs(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#include "chpp/platform/platform_time.h"
-
-#endif // CHPP_TIME_H_
diff --git a/chpp/include/chpp/transport.h b/chpp/include/chpp/transport.h
index f9431ea4..13791bc6 100644
--- a/chpp/include/chpp/transport.h
+++ b/chpp/include/chpp/transport.h
@@ -17,16 +17,16 @@
#ifndef CHPP_TRANSPORT_H_
#define CHPP_TRANSPORT_H_
+#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
+#include <string.h>
-#include "chpp/condition_variable.h"
-#include "chpp/link.h"
#include "chpp/macros.h"
+#include "chpp/memory.h"
#include "chpp/mutex.h"
-#include "chpp/notifier.h"
-#include "chpp/transport_signals.h"
+#include "chpp/platform/log.h"
#ifdef __cplusplus
extern "C" {
@@ -37,53 +37,6 @@ extern "C" {
***********************************************/
/**
- * CHPP Transport layer reset timeout in ns. The transport layer will attempt
- * another reset if the previous reset is not acked in time.
- */
-#ifndef CHPP_TRANSPORT_RESET_TIMEOUT_NS
-#define CHPP_TRANSPORT_RESET_TIMEOUT_NS \
- (UINT64_C(1500) * CHPP_NSEC_PER_MSEC) // 1500 ms
-#endif
-
-/**
- * CHPP Transport layer timeout for tx packets.
- */
-#ifndef CHPP_TRANSPORT_TX_TIMEOUT_NS
-#define CHPP_TRANSPORT_TX_TIMEOUT_NS \
- (UINT64_C(100) * CHPP_NSEC_PER_MSEC) // 100 ms
-#endif
-
-/**
- * CHPP Transport layer timeout for rx packets.
- */
-#ifndef CHPP_TRANSPORT_RX_TIMEOUT_NS
-#define CHPP_TRANSPORT_RX_TIMEOUT_NS \
- (UINT64_C(80) * CHPP_NSEC_PER_MSEC) // 80 ms
-#endif
-
-/**
- * CHPP Transport layer maximum retransmission attempts, after which a reset is
- * attempted. Setting this to zero disables retransmissions.
- */
-#ifndef CHPP_TRANSPORT_MAX_RETX
-#define CHPP_TRANSPORT_MAX_RETX UINT16_C(4)
-#endif
-
-/**
- * CHPP Transport layer maximum reset attempts. Current functional values are 1
- * or higher (setting to 0 currently functions identically to 1).
- */
-#ifndef CHPP_TRANSPORT_MAX_RESET
-#define CHPP_TRANSPORT_MAX_RESET UINT16_C(3)
-#endif
-
-/**
- * CHPP Transport layer predefined timeout values.
- */
-#define CHPP_TRANSPORT_TIMEOUT_INFINITE UINT64_MAX
-#define CHPP_TRANSPORT_TIMEOUT_IMMEDIATE 0
-
-/**
* CHPP Transport header flags bitmap
*
* @defgroup CHPP_TRANSPORT_FLAG
@@ -93,12 +46,14 @@ extern "C" {
#define CHPP_TRANSPORT_FLAG_FINISHED_DATAGRAM 0x00
// Set if packet is part of a fragmented datagram, except for the last fragment
#define CHPP_TRANSPORT_FLAG_UNFINISHED_DATAGRAM 0x01
+// Set for first packet after bootup or to reset after irrecoverable error
+#define CHPP_TRANSPORT_FLAG_RESET 0x02
// Reserved for future use
-#define CHPP_TRANSPORT_FLAG_RESERVED 0xfe
+#define CHPP_TRANSPORT_FLAG_RESERVED 0xfc
/** @} */
/**
- * Preamble (i.e. packet start delimiter) for this version of CHPP is "Ch".
+ * Preamble (i.e. packet start delimiter).
* Any future backwards-incompatible versions of CHPP Transport will use a
* different preamble.
*
@@ -110,135 +65,76 @@ extern "C" {
/** @} */
/**
- * Macros for a specific byte in the CHPP_PREAMBLE.
- * Using the CHPP_PREAMBLE_BYTE_... macros are preferred due to a reduced risk
- * of mistakes.
- */
-#define chppPreambleByte(loc) \
- ((CHPP_PREAMBLE_DATA >> (8 * (CHPP_PREAMBLE_LEN_BYTES - (loc)-1))) & 0xff)
-#define CHPP_PREAMBLE_BYTE_FIRST chppPreambleByte(0)
-#define CHPP_PREAMBLE_BYTE_SECOND chppPreambleByte(1)
-
-/**
* Maximum number of datagrams in the Tx queue.
* CHPP will return an error if it is provided with a new Tx datagram when this
* queue is full.
* To be safe, this should be less than half of the maximum uint8_t value.
* Otherwise, ChppTxDatagramQueue should be updated accordingly.
*/
-#define CHPP_TX_DATAGRAM_QUEUE_LEN ((uint8_t)16)
+#define CHPP_TX_DATAGRAM_QUEUE_LEN 16
/**
* Maximum payload of packets at the link layer.
- * TODO: Negotiate or advertise MTU. In the mean time, set default as to achieve
- * transport TX MTU of 1024.
+ * TODO: Negotiate or advertise MTU
*/
-#define CHPP_LINK_TX_MTU_BYTES \
- ((uint16_t)MIN( \
- CHPP_PLATFORM_LINK_TX_MTU_BYTES, \
- (1024 + CHPP_PREAMBLE_LEN_BYTES + sizeof(struct ChppTransportHeader) + \
- sizeof(struct ChppTransportFooter))))
+#define CHPP_LINK_MTU_BYTES \
+ (1024 + CHPP_PREAMBLE_LEN_BYTES + sizeof(struct ChppTransportHeader) + \
+ sizeof(struct ChppTransportFooter))
/**
* Maximum payload of packets at the transport layer.
*/
-#define CHPP_TRANSPORT_TX_MTU_BYTES \
- ((uint16_t)(CHPP_LINK_TX_MTU_BYTES - CHPP_PREAMBLE_LEN_BYTES - \
- sizeof(struct ChppTransportHeader) - \
- sizeof(struct ChppTransportFooter)))
-
-/**
- * Maximum payload of packets at the transport layer.
- */
-#define CHPP_TRANSPORT_RX_MTU_BYTES \
- ((uint16_t)(CHPP_PLATFORM_LINK_RX_MTU_BYTES - CHPP_PREAMBLE_LEN_BYTES - \
- sizeof(struct ChppTransportHeader) - \
- sizeof(struct ChppTransportFooter)))
+#define CHPP_TRANSPORT_MTU_BYTES \
+ (CHPP_LINK_MTU_BYTES - CHPP_PREAMBLE_LEN_BYTES - \
+ sizeof(struct ChppTransportHeader) - sizeof(struct ChppTransportFooter))
/************************************************
* Status variables to store context in lieu of global variables (this)
***********************************************/
/**
- * Error codes optionally reported in ChppTransportHeader (Least significant
- * nibble of int8_t packetCode).
- */
-#define CHPP_TRANSPORT_ERROR_MASK LEAST_SIGNIFICANT_NIBBLE
-#define CHPP_TRANSPORT_GET_ERROR(value) \
- ((enum ChppTransportErrorCode)( \
- (value)&CHPP_TRANSPORT_ERROR_MASK)) // TODO: Consider checking if this
- // maps into a valid enum
-enum ChppTransportErrorCode {
- //! No error reported (either ACK or implicit NACK)
- CHPP_TRANSPORT_ERROR_NONE = 0,
- //! Checksum failure
- CHPP_TRANSPORT_ERROR_CHECKSUM = 1,
- //! Out of memory
- CHPP_TRANSPORT_ERROR_OOM = 2,
- //! Busy
- CHPP_TRANSPORT_ERROR_BUSY = 3,
- //! Invalid header
- CHPP_TRANSPORT_ERROR_HEADER = 4,
- //! Out of order
- CHPP_TRANSPORT_ERROR_ORDER = 5,
- //! Timeout
- CHPP_TRANSPORT_ERROR_TIMEOUT = 6,
- //! Too many retries
- CHPP_TRANSPORT_ERROR_MAX_RETRIES = 7,
- //! Message incomprehensible at App Layer
- CHPP_TRANSPORT_ERROR_APPLAYER = 0xF,
-};
-
-/**
- * Packet attributes in ChppTransportHeader (Most significant nibble (MSN) of
- * int8_t packetCode).
- */
-#define CHPP_TRANSPORT_ATTR_VALUE(value) (((value)&0x0f) << 4)
-#define CHPP_TRANSPORT_ATTR_MASK MOST_SIGNIFICANT_NIBBLE
-#define CHPP_TRANSPORT_GET_ATTR(value) \
- ((enum ChppTransportPacketAttributes)( \
- (value)&CHPP_TRANSPORT_ATTR_MASK)) // TODO: Consider checking if this
- // maps into a valid enum
-
-enum ChppTransportPacketAttributes {
- //! None
- CHPP_TRANSPORT_ATTR_NONE = CHPP_TRANSPORT_ATTR_VALUE(0),
- //! Reset
- CHPP_TRANSPORT_ATTR_RESET = CHPP_TRANSPORT_ATTR_VALUE(1),
- //! Reset Ack
- CHPP_TRANSPORT_ATTR_RESET_ACK = CHPP_TRANSPORT_ATTR_VALUE(2),
- //! Transport-Layer Loopback Request
- CHPP_TRANSPORT_ATTR_LOOPBACK_REQUEST = CHPP_TRANSPORT_ATTR_VALUE(3),
- //! Transport-Layer Loopback Response
- CHPP_TRANSPORT_ATTR_LOOPBACK_RESPONSE = CHPP_TRANSPORT_ATTR_VALUE(4),
+ * Error codes optionally reported in ChppTransportHeader
+ */
+enum ChppErrorCode {
+ // No error reported (either ACK or implicit NACK)
+ CHPP_ERROR_NONE = 0,
+ // Checksum failure
+ CHPP_ERROR_CHECKSUM = 1,
+ // Out of memory
+ CHPP_ERROR_OOM = 2,
+ // Busy
+ CHPP_ERROR_BUSY = 3,
+ // Invalid header
+ CHPP_ERROR_HEADER = 4,
+ // Out of order
+ CHPP_ERROR_ORDER = 5,
+ // Timeout (implicit, deduced and used internally only)
+ CHPP_ERROR_TIMEOUT = 0xF,
};
-#define CHPP_ATTR_AND_ERROR_TO_PACKET_CODE(attr, error) \
- ((uint8_t)(attr & CHPP_TRANSPORT_ATTR_MASK) | \
- (uint8_t)(error & CHPP_TRANSPORT_ERROR_MASK))
-
/**
* CHPP Transport Layer header (not including the preamble)
*/
CHPP_PACKED_START
struct ChppTransportHeader {
- //! Flags bitmap, defined as CHPP_TRANSPORT_FLAG_...
+ // Flags bitmap, defined as CHPP_TRANSPORT_FLAG_...
uint8_t flags;
- //! LS Nibble: Defined in enum ChppTransportErrorCode
- //! MS Nibble: Defined in enum ChppTransportPacketAttributes
- uint8_t packetCode;
+ // Error info (2 nibbles)
+ // LS Nibble: Defined in ChppErrorCode enum
+ // MS Nibble: Reserved
+ uint8_t errorCode;
- //! Next expected sequence number for a payload-bearing packet
+ // Next expected sequence number for a payload-bearing packet
uint8_t ackSeq;
- //! Sequence number
+ // Sequence number
uint8_t seq;
- //! Payload length in bytes (not including header / footer)
+ // Payload length in bytes (not including header / footer)
uint16_t length;
- //! Reserved
+ // Reserved? TBD
uint16_t reserved;
} CHPP_PACKED_ATTR;
CHPP_PACKED_END
@@ -248,154 +144,86 @@ CHPP_PACKED_END
*/
CHPP_PACKED_START
struct ChppTransportFooter {
- uint32_t checksum; // IEEE CRC-32 initialized to 0xFFFFFFFF
+ // Checksum algo TBD. Maybe IEEE CRC-32?
+ uint32_t checksum;
} CHPP_PACKED_ATTR;
CHPP_PACKED_END
enum ChppRxState {
- //! Waiting for, or processing, the preamble (i.e. packet start delimiter)
- //! Moves to CHPP_STATE_HEADER as soon as it has seen a complete preamble.
+ // Waiting for, or processing, the preamble (i.e. packet start delimiter)
+ // Moves to CHPP_STATE_HEADER as soon as it has seen a complete preamble.
CHPP_STATE_PREAMBLE = 0,
- //! Processing the packet header. Moves to CHPP_STATE_PAYLOAD after processing
- //! the expected length of the header.
+ // Processing the packet header. Moves to CHPP_STATE_PAYLOAD after processing
+ // the expected length of the header.
CHPP_STATE_HEADER = 1,
- //! Copying the packet payload. The payload length is determined by the
- //! header.
- //! Moves to CHPP_STATE_FOOTER afterwards.
+ // Copying the packet payload. The payload length is determined by the header.
+ // Moves to CHPP_STATE_FOOTER afterwards.
CHPP_STATE_PAYLOAD = 2,
- //! Processing the packet footer (checksum) and responding accordingly. Moves
- //! to CHPP_STATE_PREAMBLE afterwards.
+ // Processing the packet footer (checksum) and responding accordingly. Moves
+ // to CHPP_STATE_PREAMBLE afterwards.
CHPP_STATE_FOOTER = 3,
};
-enum ChppResetState {
- CHPP_RESET_STATE_RESETTING = 0, //! Reset in progress
- CHPP_RESET_STATE_NONE = 1, //! Not in the middle of a reset
- CHPP_RESET_STATE_PERMANENT_FAILURE = 2, //! Failed, will not retry
-};
-
-/**
- * Semantic Versioning system of CHRE.
- */
-CHPP_PACKED_START
-struct ChppVersion {
- //! Major version of (breaking changes).
- uint8_t major;
-
- //! Minor version (backwards compatible changes).
- uint8_t minor;
-
- //! Patch version (bug fixes).
- uint16_t patch;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
-/**
- * Payload that is sent along reset and reset-ack packets. This may be used to
- * advertise the configuration parameters of this CHPP instance, and/or set the
- * configuration parameters of the remote side (TODO).
- */
-CHPP_PACKED_START
-struct ChppTransportConfiguration {
- //! CHPP transport version.
- struct ChppVersion version;
-
- //! Receive MTU size.
- uint16_t rxMtu;
-
- //! Max outstanding packet window size (1 for current implementation).
- uint16_t windowSize;
-
- //! Transport layer timeout in milliseconds (i.e. to receive ACK).
- uint16_t timeoutInMs;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
struct ChppRxStatus {
- //! Current receiving state, as described in ChppRxState.
+ // Current receiving state, as described in ChppRxState.
enum ChppRxState state;
- //! Location counter in bytes within each state. Must always be reinitialized
- //! to 0 when switching states.
+ // Location counter in bytes within each state. Must always be reinitialized
+ // to 0 when switching states.
size_t locInState;
- //! Next expected sequence number (for a payload-bearing packet)
+ // Next expected sequence number (for a payload-bearing packet)
uint8_t expectedSeq;
- //! Packet (error) code, if any, of the last received packet
- uint8_t receivedPacketCode;
-
- //! Last received ACK sequence number (i.e. next expected sequence number for
- //! an outgoing payload-bearing packet)
- uint8_t receivedAckSeq;
+ // Error code, if any, of the last received packet
+ enum ChppErrorCode receivedErrorCode;
- //! Time when starting to receive the current packet (i.e. after preamble).
- uint64_t packetStartTimeNs;
-
- //! Location counter in bytes within the current Rx datagram.
+ // Location counter in bytes within the current Rx datagram.
size_t locInDatagram;
-
- //! The total number of data received in chppRxDataCb.
- size_t numTotalDataBytes;
-
- //! The timestamp when the transport received any data through chppRxDataCb.
- uint32_t lastDataTimeMs;
-
- //! The timestamp when the transport received a good RX packet.
- uint32_t lastGoodPacketTimeMs;
};
struct ChppTxStatus {
- //! Last sent ACK sequence number (i.e. next expected sequence number for
- //! an incoming payload-bearing packet)
- uint8_t sentAckSeq;
+ // Last received ACK sequence number (i.e. next expected sequence number for
+ // an outgoing payload-bearing packet)
+ uint8_t ackedSeq;
- //! Last sent sequence number (irrespective of whether it has been received /
- //! ACKed or not)
+ // Last sent sequence number (irrespective of whether it has been received /
+ // ACKed or not)
uint8_t sentSeq;
- //! Does the transport layer have any packets (with or without payload) it
- //! needs to send out?
+ // Does the transport layer have any packets (with or without payload) it
+ // needs to send out?
bool hasPacketsToSend;
- //! Error code, if any, of the next packet the transport layer will send out.
- uint8_t packetCodeToSend;
+ // Error code, if any, of the next packet the transport layer will send out.
+ enum ChppErrorCode errorCodeToSend;
- //! How many times the last sent sequence number has been (re-)sent.
- size_t txAttempts;
-
- //! Time when the last packet was sent to the link layer.
- uint64_t lastTxTimeNs;
-
- //! How many bytes of the front-of-queue datagram has been sent out
+ // How many bytes of the front-of-queue datagram has been sent out
size_t sentLocInDatagram;
- //! Note: For a future ACK window >1, sentLocInDatagram doesn't always apply
- //! to the front-of-queue datagram. Instead, we need to track the queue
- //! position the datagram being sent as well (relative to the front-of-queue).
- //! e.g. uint8_t datagramBeingSent
+ // Note: For a future ACK window >1, sentLocInDatagram doesn't always apply to
+ // the front-of-queue datagram. Instead, we need to track the queue position
+ // the datagram being sent as well (relative to the front-of-queue). e.g.
+ // uint8_t datagramBeingSent
- //! How many bytes of the front-of-queue datagram has been acked
+ // How many bytes of the front-of-queue datagram has been acked
size_t ackedLocInDatagram;
-
- //! Whether the link layer is still processing pendingTxPacket
- bool linkBusy;
};
-struct PendingTxPacket {
- //! Length of outgoing packet to the Link Layer
+struct PacketToSend {
+ // Length of outgoing packet to the Link Layer
size_t length;
- //! Payload of outgoing packet to the Link Layer
- uint8_t payload[CHPP_LINK_TX_MTU_BYTES];
+ // Payload of outgoing packet to the Link Layer
+ uint8_t payload[CHPP_LINK_MTU_BYTES];
};
struct ChppDatagram {
- //! Length of datagram payload in bytes (A datagram can be constituted from
- //! one or more packets)
+ // Length of datagram payload in bytes (A datagram can be constituted from one
+ // or more packets)
size_t length;
// Datagram payload
@@ -403,52 +231,33 @@ struct ChppDatagram {
};
struct ChppTxDatagramQueue {
- //! Number of pending datagrams in the queue.
+ // Number of pending datagrams in the queue.
uint8_t pending;
- //! Index of the datagram at the front of the queue.
+ // Index of the datagram at the front of the queue.
uint8_t front;
- //! Location counter within the front datagram (i.e. the datagram at the front
- //! of the queue), showing how many bytes of this datagram have already been
- //! packetized and processed.
+ // Location counter within the front datagram (i.e. the datagram at the front
+ // of the queue), showing how many bytes of this datagram have already been
+ // packetized and processed.
size_t loc;
- //! Array of datagrams
+ // Array of datagrams
struct ChppDatagram datagram[CHPP_TX_DATAGRAM_QUEUE_LEN];
};
struct ChppTransportState {
- struct ChppAppState *appContext; // Pointer to app layer context
-
struct ChppRxStatus rxStatus; // Rx state and location within
struct ChppTransportHeader rxHeader; // Rx packet header
struct ChppTransportFooter rxFooter; // Rx packet footer (checksum)
struct ChppDatagram rxDatagram; // Rx datagram
- uint8_t loopbackResult; // Last transport-layer loopback test result as an
- // enum ChppAppErrorCode
struct ChppTxStatus txStatus; // Tx state
struct ChppTxDatagramQueue txDatagramQueue; // Queue of datagrams to be Tx
- struct PendingTxPacket pendingTxPacket; // Outgoing packet to Link Layer
- struct ChppDatagram transportLoopbackData; // Transport-layer loopback
- // request data, if any
+ struct PacketToSend packetToSend; // Outgoing packet to Link Layer
- struct ChppMutex mutex; // Lock for transport state (i.e. context)
- struct ChppNotifier notifier; // Notifier for main thread
- bool initialized; // Has been initialized
- enum ChppResetState resetState; // Maintains state of a reset
- uint16_t resetCount; // (Unsuccessful) reset attempts
- uint64_t resetTimeNs; // Time of last reset
-
- struct ChppConditionVariable
- resetCondVar; // Condvar specifically to wait for resetState
-
- //! This MUST be the last field in the ChppTransportState structure, otherwise
- //! chppResetTransportContext() will not work properly.
- struct ChppPlatformLinkParameters linkParams; // For corresponding link layer
-
- // !!! DO NOT ADD ANY NEW FIELDS HERE - ADD THEM BEFORE linkParams !!!
+ struct ChppMutex mutex; // Lock for transport state (i.e. context)
+ struct ChppMutex linkLayerMutex; // Lock for the link layer
};
/************************************************
@@ -456,45 +265,12 @@ struct ChppTransportState {
***********************************************/
/**
- * Initializes the CHPP transport layer state stored in the parameter
- * transportContext.
- * It is necessary to initialize state for each transport layer instance on
- * every platform.
- * Each transport layer instance is associated with a single application layer
- * instance. appContext points to the application layer status struct associated
- * with this transport layer instance.
- *
- * Note: It is necessary to initialize the platform-specific values of
- * transportContext.linkParams (prior to the call, if needed in the link layer
- * APIs, such as chppPlatformLinkInit()).
- *
- * @param transportContext Maintains status for each transport layer instance.
- * @param appContext The app layer status struct associated with this transport
- * layer instance.
- */
-void chppTransportInit(struct ChppTransportState *transportContext,
- struct ChppAppState *appContext);
-
-/**
- * Deinitializes the CHPP transport layer and does necessary clean-ups for
- * e.g. clean shutdown.
- *
- * @param transportContext A non-null pointer to ChppTransportState
- * initialized previously in chppTransportInit().
- */
-void chppTransportDeinit(struct ChppTransportState *transportContext);
-
-/**
- * Blocking call until CHPP has finished resetting.
- *
- * @param transportContext, A non-null pointer to ChppTransportState
- * initialized previously in chppTransportDeinit().
- * @param timeoutMs The timeout in milliseconds.
+ * Initializes the CHPP transport layer state stored in the parameter context.
*
- * @return False if timed out.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
*/
-bool chppTransportWaitForResetComplete(
- struct ChppTransportState *transportContext, uint64_t timeoutMs);
+void chppTransportInit(struct ChppTransportState *context);
/**
* Processes all incoming data on the serial port based on the Rx state.
@@ -506,7 +282,8 @@ bool chppTransportWaitForResetComplete(
*
* TODO: Add sufficient outward facing documentation
*
- * @param context Maintains status for each transport layer instance.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
* @param buf Input data. Cannot be null.
* @param len Length of input data in bytes.
*
@@ -518,207 +295,30 @@ bool chppRxDataCb(struct ChppTransportState *context, const uint8_t *buf,
size_t len);
/**
- * Optional callback function for the link layer to indicate the end of a
- * packet. The availability of this information depends on the link layer
- * implementation.
+ * Callback function for the timer that detects timeouts during transmit
*
- * @param context Maintains status for each transport layer instance.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
*/
-void chppRxPacketCompleteCb(struct ChppTransportState *context);
+void chppTxTimeoutTimerCb(struct ChppTransportState *context);
/**
- * Enqueues an outgoing datagram of a specified length and frees the payload
- * asynchronously after it is sent. The payload must have been allocated by the
- * caller using chppMalloc.
+ * Enqueues an outgoing datagram of a specified length. The payload must have
+ * been allocated by the caller using chppMalloc. If enqueueing is successful,
+ * the payload shall be freed only by the transport layer (once it has been sent
+ * out). If enqueueing is unsuccessful, it is up to the sender to decide whether
+ * to free the payload and/or resend it later.
*
- * If enqueueing a datagram is unsuccessful, the payload is freed (discarded)
- * and an error message printed.
- *
- * Note that the ownership of buf is taken from the caller when this method is
- * invoked.
- *
- * @param context Maintains status for each transport layer instance.
- * @param buf Datagram payload allocated through chppMalloc. Cannot be null.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
* @param len Datagram length in bytes.
- *
+ * @param buf Datagram payload allocated through chppMalloc. Cannot be null.
* @return True informs the sender that the datagram was successfully enqueued.
- * False informs the sender that the queue was full and the payload discarded.
- */
-bool chppEnqueueTxDatagramOrFail(struct ChppTransportState *context, void *buf,
- size_t len);
-
-/**
- * Enables the App Layer to enqueue an outgoing error datagram, for example for
- * an OOM situation over the wire.
- *
- * @param context Maintains status for each transport layer instance.
- * @param errorCode Error code to be sent.
- */
-void chppEnqueueTxErrorDatagram(struct ChppTransportState *context,
- enum ChppTransportErrorCode errorCode);
-
-/**
- * Provides systems that do not use chppWorkThreadStart() and its associated
- * timeout mechanisms (that relies on chppNotifierTimedWait()) how long they
- * should wait until they run chppTransportDoWork() again, in nanoseconds.
- *
- * For these implementations, chppTransportDoWork() should be run at or slightly
- * after the wait time returned by this function.
- *
- * A return value of CHPP_TRANSPORT_TIMEOUT_INFINITE indicates that there is no
- * need to run chppTransportDoWork() based on a timeout (i.e. CHPP is not
- * waiting on an ACK).
- *
- * A return value of CHPP_TRANSPORT_TIMEOUT_IMMEDIATE indicates that
- * chppTransportDoWork() should be run immediately.
- *
- * @param context Maintains status for each transport layer instance.
- *
- * @return Time until chppTransportDoWork() must be called in nanoseconds.
- */
-uint64_t chppTransportGetTimeUntilNextDoWorkNs(
- struct ChppTransportState *context);
-
-/**
- * Starts the main thread for CHPP's Transport Layer. This thread needs to be
- * started after the Transport Layer is initialized through chppTransportInit().
- * Note that a platform may implement this as a new thread or as part of an
- * existing thread.
- *
- * If needed (e.g. for testing and debugging), this thread can be stopped by
- * calling chppWorkThreadStop().
- *
- * If a system does not support multi-threading, the system MUST replicate the
- * high-level behavior of chppWorkThreadStart(). More details in the
- * documentation of chppWorkThreadHandleSignal(). For such systems,
- * chppTransportGetTimeUntilNextDoWorkNs() can be used to replicate the
- * functionality of chppNotifierTimedWait().
- *
- * @param context Maintains status for each transport layer instance.
- */
-void chppWorkThreadStart(struct ChppTransportState *context);
-
-/**
- * Handles signals set for the CHPP transport instance. This method should be
- * invoked externally if chppWorkThreadStart() cannot be directly used, for
- * example if the system does not support thread signaling and needs explicit
- * control of the CHPP work thread from an outer control loop. By "outer control
- * loop," we mean the code path triggering work on the CHPP transport layer.
- *
- * Note that if a platform uses this method, the outer control loop MUST
- * replicate the behavior in the chppWorkThreadStart() method exactly. All
- * pending signals MUST be handled prior to the suspension of the outer control
- * loop, and any initialization sequence MUST be replicated.
- *
- * @param context Maintains status for each transport layer instance.
- * @param signals The signals to process. Should be obtained via
- * chppNotifierTimedWait() for the given transport context's notifier.
- *
- * @return true if the CHPP work thread should exit.
- */
-bool chppWorkThreadHandleSignal(struct ChppTransportState *context,
- uint32_t signals);
-
-/**
- * Signals the main thread for CHPP's Transport Layer to perform some work. This
- * method should only be called from the link layer.
- *
- * Note that this method must be safe to call from an interrupt context, as the
- * platform link layer implementation may send a signal from one (e.g. handling
- * an interrupt from the physical layer or inputs from the remote endpoint).
- *
- * @param params Platform-specific struct with link details / parameters.
- * @param signal The signal that describes the work to be performed. Only bits
- * specified by CHPP_TRANSPORT_SIGNAL_PLATFORM_MASK can be set.
- */
-static inline void chppWorkThreadSignalFromLink(
- struct ChppPlatformLinkParameters *params, uint32_t signal) {
- struct ChppTransportState *context =
- container_of(params, struct ChppTransportState, linkParams);
-
- CHPP_ASSERT((signal & ~(CHPP_TRANSPORT_SIGNAL_PLATFORM_MASK)) == 0);
- chppNotifierSignal(&context->notifier,
- signal & CHPP_TRANSPORT_SIGNAL_PLATFORM_MASK);
-}
-
-/**
- * Stops the main thread for CHPP's Transport Layer that has been started by
- * calling chppWorkThreadStart(). Stopping this thread may be necessary for
- * testing and debugging purposes.
- *
- * @param context Maintains status for each transport layer instance.
- */
-void chppWorkThreadStop(struct ChppTransportState *context);
-
-/**
- * Notifies the transport layer that the link layer is done sending the previous
- * payload (as provided to platformLinkSend() through buf and len) and can
- * accept more data.
- *
- * On systems that implement the link layer Tx asynchronously, where
- * platformLinkSend() returns False before consuming the payload provided to it
- * (i.e. buf and len), the platform implementation must call this function after
- * platformLinkSend() is done with the payload (i.e. buf and len).
- *
- * @param params Platform-specific struct with link details / parameters.
- * @param error Indicates success or failure type.
+ * False informs the sender that the queue was full.
*/
-void chppLinkSendDoneCb(struct ChppPlatformLinkParameters *params,
- enum ChppLinkErrorCode error);
+bool chppEnqueueTxDatagram(struct ChppTransportState *context, size_t len,
+ uint8_t *buf);
-/**
- * Notifies the transport layer that the app layer is done with the previous
- * payload (as provided to chppAppProcessRxDatagram() through buf and len), so
- * it is freed appropriately etc.
- *
- * TODO: Look into automatically doing this when a response is sent back by a
- * service.
- *
- * @param context Maintains status for each transport layer instance.
- * @param buf Pointer to the buf given to chppAppProcessRxDatagram. Cannot be
- * null.
- */
-void chppDatagramProcessDoneCb(struct ChppTransportState *context,
- uint8_t *buf);
-
-/**
- * Sends out transport-layer loopback data. Note that in most situations, an
- * application-layer loopback test is pprefrable as it is more thorough and
- * provides statistics regarding the correctness of the loopbacked data.
- *
- * The result will be available later, asynchronously, as a ChppAppErrorCode
- * enum in context->loopbackResult.
- *
- * @param context Maintains status for each transport layer instance.
- * @param buf Pointer to the loopback data to be sent. Cannot be null.
- * @param len Length of the loopback data.
- *
- * @return A ChppLinkErrorCode enum indicating if the transport-layer-loopback
- * request was accepted. Note that the actual test result will be available
- * later, asynchronously, in context->loopbackResult.
- */
-uint8_t chppRunTransportLoopback(struct ChppTransportState *context,
- uint8_t *buf, size_t len);
-
-/**
- * Sends a reset or reset-ack packet over the link in order to reset the remote
- * side or inform the counterpart of a reset, respectively. The transport
- * layer's configuration is sent as the payload of the reset packet.
- *
- * This function is typically used only internally, either immediately after
- * initialization via chppWorkThreadStart() or for subsequent resets or
- * reset-acks via chppReset(). However, implementations that do not rely on
- * chppWorkThreadStart() would require to call this function after initializing
- * CHPP.
- *
- * @param transportContext Maintains status for each transport layer instance.
- * @param resetType Distinguishes a reset from a reset-ack, as defined in the
- * ChppTransportPacketAttributes struct.
- * @param error Provides the error that led to the reset.
- */
-void chppTransportSendReset(struct ChppTransportState *context,
- enum ChppTransportPacketAttributes resetType,
- enum ChppTransportErrorCode error);
#ifdef __cplusplus
}
diff --git a/chpp/include/chpp/transport_signals.h b/chpp/include/chpp/transport_signals.h
deleted file mode 100644
index 95a3d445..00000000
--- a/chpp/include/chpp/transport_signals.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_TRANSPORT_SIGNALS_H_
-#define CHPP_TRANSPORT_SIGNALS_H_
-
-#include <stdint.h>
-
-#include "macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-//! Signals to use in ChppNotifier in the CHPP transport work thread
-//! (ran in chppWorkThreadStart()).
-#define CHPP_TRANSPORT_SIGNAL_EXIT UINT32_C(1 << 0)
-#define CHPP_TRANSPORT_SIGNAL_EVENT UINT32_C(1 << 1)
-#define CHPP_TRANSPORT_SIGNAL_TIMEOUT \
- UINT32_C(1 << 15) // Usage is optional and platform-dependent
-
-//! These bits are reserved for platform use (e.g. in the platform-specific
-//! link layer implementation).
-#define CHPP_TRANSPORT_SIGNAL_PLATFORM_MASK UINT32_C(0xFFFF0000)
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_TRANSPORT_SIGNALS_H_
diff --git a/chpp/platform/linux/include/chpp/platform/log.h b/chpp/platform/linux/include/chpp/platform/log.h
new file mode 100644
index 00000000..d14ac8ed
--- /dev/null
+++ b/chpp/platform/linux/include/chpp/platform/log.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * 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 CHPP_LOG_H_
+#define CHPP_LOG_H_
+
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef __FILENAME__
+#define __FILENAME__ __FILE__
+#endif
+
+// TODO: consider switching to a PAL interface to assist platform adaptation
+#define CHPP_LINUX_LOG(level, color, fmt, ...) \
+ printf("\e[" color "m%s %s:%d\t" fmt "\e[0m\n", level, __FILENAME__, \
+ __LINE__, ##__VA_ARGS__)
+
+#define LOGE(fmt, ...) CHPP_LINUX_LOG("E", "91", fmt, ##__VA_ARGS__)
+#define LOGW(fmt, ...) CHPP_LINUX_LOG("W", "93", fmt, ##__VA_ARGS__)
+#define LOGI(fmt, ...) CHPP_LINUX_LOG("I", "96", fmt, ##__VA_ARGS__)
+#define LOGD(fmt, ...) CHPP_LINUX_LOG("D", "97", fmt, ##__VA_ARGS__)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // CHPP_LOG_H_
diff --git a/chpp/platform/linux/include/chpp/platform/platform_condition_variable.h b/chpp/platform/linux/include/chpp/platform/platform_condition_variable.h
deleted file mode 100644
index ac3f4cf7..00000000
--- a/chpp/platform/linux/include/chpp/platform/platform_condition_variable.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_PLATFORM_CONDITION_VARIABLE_H_
-#define CHPP_PLATFORM_CONDITION_VARIABLE_H_
-
-#include <pthread.h>
-#include <stdbool.h>
-
-#include "chpp/macros.h"
-#include "chpp/mutex.h"
-#include "time.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct ChppConditionVariable {
- pthread_cond_t cond; // Condition variable
-};
-
-static inline void chppConditionVariableInit(struct ChppConditionVariable *cv) {
- pthread_cond_init(&cv->cond, NULL);
-}
-
-static inline void chppConditionVariableDeinit(
- struct ChppConditionVariable *cv) {
- pthread_cond_destroy(&cv->cond);
-}
-
-static inline bool chppConditionVariableWait(struct ChppConditionVariable *cv,
- struct ChppMutex *mutex) {
- return pthread_cond_wait(&cv->cond, &mutex->lock) == 0;
-}
-
-static inline bool chppConditionVariableTimedWait(
- struct ChppConditionVariable *cv, struct ChppMutex *mutex,
- uint64_t timeoutNs) {
- uint64_t timeoutS = timeoutNs / CHPP_NSEC_PER_SEC;
- timeoutNs = timeoutNs % CHPP_NSEC_PER_SEC;
-
- struct timespec now;
- clock_gettime(CLOCK_REALTIME, &now);
- now.tv_sec += timeoutS;
- now.tv_nsec += timeoutNs;
- return pthread_cond_timedwait(&cv->cond, &mutex->lock, &now) == 0;
-}
-
-static inline void chppConditionVariableSignal(
- struct ChppConditionVariable *cv) {
- pthread_cond_signal(&cv->cond);
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_PLATFORM_CONDITION_VARIABLE_H_
diff --git a/chpp/platform/linux/include/chpp/platform/platform_link.h b/chpp/platform/linux/include/chpp/platform/platform_link.h
deleted file mode 100644
index 22590082..00000000
--- a/chpp/platform/linux/include/chpp/platform/platform_link.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_PLATFORM_LINK_H_
-#define CHPP_PLATFORM_LINK_H_
-
-#include <pthread.h>
-#include <stdbool.h>
-#include <stddef.h>
-
-#include "chpp/mutex.h"
-#include "chpp/notifier.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define CHPP_PLATFORM_LINK_TX_MTU_BYTES 1280
-#define CHPP_PLATFORM_LINK_RX_MTU_BYTES 1280
-
-#define CHPP_PLATFORM_TRANSPORT_TIMEOUT_MS 1000
-
-// Forward declaration
-struct ChppTransportState;
-
-struct ChppPlatformLinkParameters {
- //! Indicates that the link to the remote endpoint has been established.
- //! This simulates the establishment of the physical link, so
- //! chppPlatformLinkSend() will fail if this field is set to false.
- bool linkEstablished;
-
- //! A pointer to the transport context of the remote endpoint.
- struct ChppTransportState *remoteTransportContext;
-
- //! A thread to use when sending data to the remote endpoint asynchronously.
- pthread_t linkSendThread;
-
- //! The notifier for linkSendThread.
- struct ChppNotifier notifier;
-
- //! The mutex to protect buf/bufLen.
- struct ChppMutex mutex;
-
- //! The temporary buffer to use to send data to the remote endpoint.
- uint8_t buf[CHPP_PLATFORM_LINK_TX_MTU_BYTES];
- size_t bufLen;
-
- //! The string name of the linkSendThread.
- const char *linkThreadName;
-
- //! The string name of the CHPP work thread.
- const char *workThreadName;
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_PLATFORM_LINK_H_
diff --git a/chpp/platform/linux/include/chpp/platform/platform_log.h b/chpp/platform/linux/include/chpp/platform/platform_log.h
deleted file mode 100644
index e2918a02..00000000
--- a/chpp/platform/linux/include/chpp/platform/platform_log.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 CHPP_PLATFORM_LOG_H_
-#define CHPP_PLATFORM_LOG_H_
-
-#include <inttypes.h>
-#include <pthread.h>
-#include <stdio.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef __FILENAME__
-#define __FILENAME__ __FILE__
-#endif
-
-#ifndef PRIuSIZE
-#define PRIuSIZE "zu"
-#endif
-
-// TODO: Should use PRIu8 etc. from inttypes.h instead of %d, etc. (add -Wall
-// and -Werror to cflags to catch these)
-#define CHPP_LINUX_LOG(level, color, fmt, ...) \
- { \
- char name[16]; \
- pthread_getname_np(pthread_self(), name, 16); \
- printf("\e[" color "m%s %s:%d\t (%s) " fmt "\e[0m\n", level, __FILENAME__, \
- __LINE__, name, ##__VA_ARGS__); \
- }
-
-#define CHPP_LOGE(fmt, ...) CHPP_LINUX_LOG("E", "91", fmt, ##__VA_ARGS__)
-#define CHPP_LOGW(fmt, ...) CHPP_LINUX_LOG("W", "93", fmt, ##__VA_ARGS__)
-#define CHPP_LOGI(fmt, ...) CHPP_LINUX_LOG("I", "96", fmt, ##__VA_ARGS__)
-#define CHPP_LOGD(fmt, ...) CHPP_LINUX_LOG("D", "97", fmt, ##__VA_ARGS__)
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_PLATFORM_LOG_H_
diff --git a/chpp/platform/linux/include/chpp/platform/platform_mutex.h b/chpp/platform/linux/include/chpp/platform/platform_mutex.h
index 8a1fded5..ad2fff11 100644
--- a/chpp/platform/linux/include/chpp/platform/platform_mutex.h
+++ b/chpp/platform/linux/include/chpp/platform/platform_mutex.h
@@ -31,10 +31,6 @@ static inline void chppMutexInit(struct ChppMutex *mutex) {
pthread_mutex_init(&mutex->lock, NULL);
}
-static inline void chppMutexDeinit(struct ChppMutex *mutex) {
- pthread_mutex_destroy(&mutex->lock);
-}
-
static inline void chppMutexLock(struct ChppMutex *mutex) {
pthread_mutex_lock(&mutex->lock);
}
diff --git a/chpp/platform/linux/include/chpp/platform/platform_notifier.h b/chpp/platform/linux/include/chpp/platform/platform_notifier.h
deleted file mode 100644
index 0b0b429d..00000000
--- a/chpp/platform/linux/include/chpp/platform/platform_notifier.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_PLATFORM_SYNC_H_
-#define CHPP_PLATFORM_SYNC_H_
-
-#include <pthread.h>
-#include <stdint.h>
-
-#include "chpp/mutex.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct ChppNotifier {
- pthread_cond_t cond; // Condition variable
- struct ChppMutex mutex; // Platform-specific mutex
- uint32_t signal;
-};
-
-/**
- * Platform implementation of chppNotifierInit()
- */
-void chppPlatformNotifierInit(struct ChppNotifier *notifier);
-
-/**
- * Platform implementation of chppNotifierDeinit()
- */
-void chppPlatformNotifierDeinit(struct ChppNotifier *notifier);
-
-/**
- * Platform implementation of chppNotifierGetSignal()
- */
-uint32_t chppPlatformNotifierGetSignal(struct ChppNotifier *notifier);
-
-/**
- * Platform implementation of chppNotifierWait()
- */
-uint32_t chppPlatformNotifierWait(struct ChppNotifier *notifier);
-
-/**
- * Platform implementation of chppNotifierTimedWait()
- */
-uint32_t chppPlatformNotifierTimedWait(struct ChppNotifier *notifier,
- uint64_t timeoutNs);
-
-/**
- * Platform implementation of chppNotifierSignal()
- */
-void chppPlatformNotifierSignal(struct ChppNotifier *notifier, uint32_t signal);
-
-static inline void chppNotifierInit(struct ChppNotifier *notifier) {
- chppPlatformNotifierInit(notifier);
-}
-
-static inline void chppNotifierDeinit(struct ChppNotifier *notifier) {
- chppPlatformNotifierDeinit(notifier);
-}
-
-static inline uint32_t chppNotifierGetSignal(struct ChppNotifier *notifier) {
- return chppPlatformNotifierGetSignal(notifier);
-}
-
-static inline uint32_t chppNotifierWait(struct ChppNotifier *notifier) {
- return chppPlatformNotifierWait(notifier);
-}
-
-static inline uint32_t chppNotifierTimedWait(struct ChppNotifier *notifier,
- uint64_t timeoutNs) {
- return chppPlatformNotifierTimedWait(notifier, timeoutNs);
-}
-
-static inline void chppNotifierSignal(struct ChppNotifier *notifier,
- uint32_t signal) {
- chppPlatformNotifierSignal(notifier, signal);
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_PLATFORM_SYNC_H_
diff --git a/chpp/platform/linux/include/chpp/platform/platform_time.h b/chpp/platform/linux/include/chpp/platform/platform_time.h
deleted file mode 100644
index faa617dc..00000000
--- a/chpp/platform/linux/include/chpp/platform/platform_time.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHPP_PLATFORM_TIME_H_
-#define CHPP_PLATFORM_TIME_H_
-
-#include <stdint.h>
-
-#include "chpp/macros.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define CHPP_TIMESPEC_TO_NS(time) \
- ((uint64_t)time.tv_sec * CHPP_NSEC_PER_SEC + (uint64_t)time.tv_nsec)
-
-static inline uint64_t chppGetCurrentTimeNs(void) {
- struct timespec now;
- clock_gettime(CLOCK_REALTIME, &now);
- return CHPP_TIMESPEC_TO_NS(now);
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_PLATFORM_TIME_H_
diff --git a/chpp/platform/linux/include/chpp/platform/utils.h b/chpp/platform/linux/include/chpp/platform/utils.h
deleted file mode 100644
index c28d0fb4..00000000
--- a/chpp/platform/linux/include/chpp/platform/utils.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 CHPP_PLATFORM_UTILS_H_
-#define CHPP_PLATFORM_UTILS_H_
-
-#include <stddef.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Clears the amount of memory allocation tracked by chppGetTotalAllocBytes().
- */
-void chppClearTotalAllocBytes(void);
-
-/**
- * @return The total amount of memory allocated by CHPP.
- */
-size_t chppGetTotalAllocBytes(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_PLATFORM_UTILS_H_
diff --git a/chpp/platform/linux/link.c b/chpp/platform/linux/link.c
deleted file mode 100644
index 8594a8d6..00000000
--- a/chpp/platform/linux/link.c
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/link.h"
-
-#include <inttypes.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/transport.h"
-
-// The set of signals to use for the linkSendThread.
-#define SIGNAL_EXIT UINT32_C(1 << 0)
-#define SIGNAL_DATA UINT32_C(1 << 1)
-
-/**
- * This thread is used to "send" TX data to the remote endpoint. The remote
- * endpoint is defined by the ChppTransportState pointer, so a loopback link
- * with a single CHPP instance can be supported.
- */
-static void *linkSendThread(void *arg) {
- struct ChppPlatformLinkParameters *params =
- (struct ChppPlatformLinkParameters *)arg;
- while (true) {
- uint32_t signal = chppNotifierTimedWait(&params->notifier, CHPP_TIME_MAX);
-
- if (signal & SIGNAL_EXIT) {
- break;
- }
- if (signal & SIGNAL_DATA) {
- enum ChppLinkErrorCode error;
-
- chppMutexLock(&params->mutex);
-
- if (params->remoteTransportContext == NULL) {
- CHPP_LOGW("remoteTransportContext is NULL");
- error = CHPP_LINK_ERROR_NONE_SENT;
-
- } else if (!params->linkEstablished) {
- CHPP_LOGE("No (fake) link");
- error = CHPP_LINK_ERROR_NO_LINK;
-
- } else if (!chppRxDataCb(params->remoteTransportContext, params->buf,
- params->bufLen)) {
- CHPP_LOGW("chppRxDataCb return state!=preamble (packet incomplete)");
- error = CHPP_LINK_ERROR_NONE_SENT;
-
- } else {
- error = CHPP_LINK_ERROR_NONE_SENT;
- }
-
- params->bufLen = 0;
- chppLinkSendDoneCb(params, error);
-
- chppMutexUnlock(&params->mutex);
- }
- }
-
- return NULL;
-}
-
-void chppPlatformLinkInit(struct ChppPlatformLinkParameters *params) {
- params->bufLen = 0;
- chppMutexInit(&params->mutex);
- chppNotifierInit(&params->notifier);
- pthread_create(&params->linkSendThread, NULL /* attr */, linkSendThread,
- params);
- if (params->linkThreadName != NULL) {
- pthread_setname_np(params->linkSendThread, params->linkThreadName);
- }
-}
-
-void chppPlatformLinkDeinit(struct ChppPlatformLinkParameters *params) {
- params->bufLen = 0;
- chppNotifierSignal(&params->notifier, SIGNAL_EXIT);
- pthread_join(params->linkSendThread, NULL /* retval */);
- chppNotifierDeinit(&params->notifier);
- chppMutexDeinit(&params->mutex);
-}
-
-enum ChppLinkErrorCode chppPlatformLinkSend(
- struct ChppPlatformLinkParameters *params, uint8_t *buf, size_t len) {
- bool success = false;
- chppMutexLock(&params->mutex);
- if (params->bufLen != 0) {
- CHPP_LOGE("Failed to send data - link layer busy");
- } else {
- success = true;
- memcpy(params->buf, buf, len);
- params->bufLen = len;
- }
- chppMutexUnlock(&params->mutex);
-
- if (success) {
- chppNotifierSignal(&params->notifier, SIGNAL_DATA);
- }
-
- return success ? CHPP_LINK_ERROR_NONE_QUEUED : CHPP_LINK_ERROR_BUSY;
-}
-
-void chppPlatformLinkDoWork(struct ChppPlatformLinkParameters *params,
- uint32_t signal) {
- UNUSED_VAR(params);
- UNUSED_VAR(signal);
-}
-
-void chppPlatformLinkReset(struct ChppPlatformLinkParameters *params) {
- chppPlatformLinkDeinit(params);
- chppPlatformLinkInit(params);
-}
diff --git a/chpp/platform/linux/memory.c b/chpp/platform/linux/memory.c
index dc07a215..99b9753b 100644
--- a/chpp/platform/linux/memory.c
+++ b/chpp/platform/linux/memory.c
@@ -15,98 +15,17 @@
*/
#include "chpp/memory.h"
-
-#include <stdatomic.h>
-#include <stddef.h>
-#include <stdlib.h>
-
-#ifdef CHPP_LINUX_MEMORY_DEBUG
-#include "chpp/log.h"
-#endif // CHPP_LINUX_MEMORY_DEBUG
#include "chpp/macros.h"
-#include "chpp/platform/utils.h"
-
-//! A header used to track the amount of allocated memory.
-struct ChppAllocHeader {
- size_t bytes;
-};
-
-static atomic_size_t gTotalAllocBytes = 0;
void *chppMalloc(const size_t size) {
- void *ptr = NULL;
- if (size != 0) {
- ptr = malloc(sizeof(struct ChppAllocHeader) + size);
-
- if (ptr != NULL) {
- struct ChppAllocHeader *header = (struct ChppAllocHeader *)ptr;
- header->bytes = size;
- header++;
- ptr = header;
-
- gTotalAllocBytes += size;
- }
- }
-
-#ifdef CHPP_LINUX_MEMORY_DEBUG
- CHPP_LOGI("%s: size %zu total (after malloc) %zu", __func__, size,
- gTotalAllocBytes);
-#endif // CHPP_LINUX_MEMORY_DEBUG
-
- return ptr;
+ return malloc(size);
}
void chppFree(void *ptr) {
- if (ptr != NULL) {
- struct ChppAllocHeader *header = (struct ChppAllocHeader *)ptr;
- header--;
- size_t size = header->bytes;
- gTotalAllocBytes -= size;
-
-#ifdef CHPP_LINUX_MEMORY_DEBUG
- CHPP_LOGI("%s: size %zu total (after free) %zu", __func__, size,
- gTotalAllocBytes);
-#endif // CHPP_LINUX_MEMORY_DEBUG
-
- free(header);
- }
+ free(ptr);
}
void *chppRealloc(void *oldPtr, const size_t newSize, const size_t oldSize) {
UNUSED_VAR(oldSize);
- void *ptr = NULL;
- if (newSize != oldSize) {
- struct ChppAllocHeader *oldHeader = (struct ChppAllocHeader *)oldPtr;
- oldHeader--;
-
- void *reallocPtr =
- realloc(oldHeader, newSize + sizeof(struct ChppAllocHeader));
- if (reallocPtr != NULL) {
- struct ChppAllocHeader *newHeader = (struct ChppAllocHeader *)reallocPtr;
- newHeader->bytes = newSize;
- newHeader++;
- ptr = newHeader;
-
- if (newSize > oldSize) {
- gTotalAllocBytes += (newSize - oldSize);
- } else {
- gTotalAllocBytes -= (oldSize - newSize);
- }
- }
- }
-
-#ifdef CHPP_LINUX_MEMORY_DEBUG
- CHPP_LOGI("%s: size %zu total (after realloc) %zu", __func__, newSize,
- gTotalAllocBytes);
-#endif // CHPP_LINUX_MEMORY_DEBUG
-
- return ptr;
-}
-
-void chppClearTotalAllocBytes() {
- gTotalAllocBytes = 0;
-}
-
-size_t chppGetTotalAllocBytes() {
- return gTotalAllocBytes;
+ return realloc(oldPtr, newSize);
}
diff --git a/chpp/platform/linux/notifier.c b/chpp/platform/linux/notifier.c
deleted file mode 100644
index eac77016..00000000
--- a/chpp/platform/linux/notifier.c
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/platform/platform_notifier.h"
-
-#include <pthread.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/macros.h"
-#include "chpp/mutex.h"
-#include "chpp/platform/platform_time.h"
-#include "chpp/transport.h"
-#include "chpp/transport_signals.h"
-#include "time.h"
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppPlatformNotifierInit(struct ChppNotifier *notifier) {
- chppMutexInit(&notifier->mutex);
- pthread_cond_init(&notifier->cond, NULL);
-}
-
-void chppPlatformNotifierDeinit(struct ChppNotifier *notifier) {
- pthread_cond_destroy(&notifier->cond);
- chppMutexDeinit(&notifier->mutex);
-}
-
-uint32_t chppPlatformNotifierGetSignal(struct ChppNotifier *notifier) {
- chppMutexLock(&notifier->mutex);
-
- uint32_t signal = notifier->signal;
- notifier->signal = 0;
-
- chppMutexUnlock(&notifier->mutex);
- return signal;
-}
-
-uint32_t chppPlatformNotifierWait(struct ChppNotifier *notifier) {
- chppMutexLock(&notifier->mutex);
-
- while (notifier->signal == 0) {
- pthread_cond_wait(&notifier->cond, &notifier->mutex.lock);
- }
- uint32_t signal = notifier->signal;
- notifier->signal = 0;
-
- chppMutexUnlock(&notifier->mutex);
- return signal;
-}
-uint32_t chppPlatformNotifierTimedWait(struct ChppNotifier *notifier,
- uint64_t timeoutNs) {
- if (timeoutNs == CHPP_TRANSPORT_TIMEOUT_INFINITE) {
- return chppPlatformNotifierWait(notifier);
-
- } else {
- struct timespec timeout;
- struct timespec absTime;
- uint64_t timeoutS = timeoutNs / CHPP_NSEC_PER_SEC;
- timeoutNs = timeoutNs % CHPP_NSEC_PER_SEC;
-
- chppMutexLock(&notifier->mutex);
-
- clock_gettime(CLOCK_REALTIME, &absTime);
- timeout = absTime;
- timeout.tv_sec += timeoutS;
- timeout.tv_nsec += timeoutNs;
-
- while ((notifier->signal == 0) &&
- (CHPP_TIMESPEC_TO_NS(absTime) < CHPP_TIMESPEC_TO_NS(timeout))) {
- pthread_cond_timedwait(&notifier->cond, &notifier->mutex.lock, &absTime);
- clock_gettime(CLOCK_REALTIME, &absTime);
- }
- uint32_t signal = notifier->signal;
- notifier->signal = 0;
-
- chppMutexUnlock(&notifier->mutex);
- return signal;
- }
-}
-
-void chppPlatformNotifierSignal(struct ChppNotifier *notifier,
- uint32_t signal) {
- chppMutexLock(&notifier->mutex);
-
- notifier->signal |= signal;
- pthread_cond_signal(&notifier->cond);
-
- chppMutexUnlock(&notifier->mutex);
-}
diff --git a/chpp/platform/linux/services/platform_gnss.c b/chpp/platform/linux/services/platform_gnss.c
deleted file mode 100644
index caecf64c..00000000
--- a/chpp/platform/linux/services/platform_gnss.c
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <stdbool.h>
-#include <stdint.h>
-
-#include "chpp/common/gnss.h"
-#include "chpp/macros.h"
-#include "chre/pal/gnss.h"
-
-static const struct chrePalSystemApi *gSystemApi;
-static const struct chrePalGnssCallbacks *gCallbacks;
-
-static bool gnssPalOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalGnssCallbacks *callbacks) {
- gSystemApi = systemApi;
- gCallbacks = callbacks;
-
- return true;
-}
-
-static void gnssPalClose(void) {}
-
-static uint32_t gnssPalGetCapabilities(void) {
- return CHRE_GNSS_CAPABILITIES_LOCATION | CHRE_GNSS_CAPABILITIES_MEASUREMENTS |
- CHRE_GNSS_CAPABILITIES_GNSS_ENGINE_BASED_PASSIVE_LISTENER;
-}
-
-static bool gnssPalControlLocationSession(bool enable, uint32_t minIntervalMs,
- uint32_t minTimeToNextFixMs) {
- // TODO
- UNUSED_VAR(enable);
- UNUSED_VAR(minIntervalMs);
- UNUSED_VAR(minTimeToNextFixMs);
-
- return true; // If successful
-}
-
-static void gnssPalReleaseLocationEvent(struct chreGnssLocationEvent *event) {
- gSystemApi->memoryFree(event);
-}
-
-static bool gnssPalControlMeasurementSessiont(bool enable,
- uint32_t minIntervalMs) {
- // TODO
- UNUSED_VAR(enable);
- UNUSED_VAR(minIntervalMs);
-
- return true; // If successful
-}
-
-static void gnssPalReleaseMeasurementDataEvent(
- struct chreGnssDataEvent *event) {
- gSystemApi->memoryFree(CHPP_CONST_CAST_POINTER(event->measurements));
- gSystemApi->memoryFree(event);
-}
-
-static bool gnssPalConfigurePassiveLocationListener(bool enable) {
- // TODO
- UNUSED_VAR(enable);
-
- return true; // If successful
-}
-
-#ifdef CHPP_SERVICE_ENABLED_GNSS
-const struct chrePalGnssApi *chrePalGnssGetApi(uint32_t requestedApiVersion) {
- static const struct chrePalGnssApi api = {
- .moduleVersion = CHPP_PAL_GNSS_API_VERSION,
- .open = gnssPalOpen,
- .close = gnssPalClose,
- .getCapabilities = gnssPalGetCapabilities,
- .controlLocationSession = gnssPalControlLocationSession,
- .releaseLocationEvent = gnssPalReleaseLocationEvent,
- .controlMeasurementSession = gnssPalControlMeasurementSessiont,
- .releaseMeasurementDataEvent = gnssPalReleaseMeasurementDataEvent,
- .configurePassiveLocationListener =
- gnssPalConfigurePassiveLocationListener,
- };
-
- CHPP_STATIC_ASSERT(
- CHRE_PAL_GNSS_API_CURRENT_VERSION == CHPP_PAL_GNSS_API_VERSION,
- "A newer CHRE PAL API version is available. Please update.");
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(api.moduleVersion,
- requestedApiVersion)) {
- return NULL;
- } else {
- return &api;
- }
-}
-#endif
diff --git a/chpp/platform/linux/services/platform_wifi.c b/chpp/platform/linux/services/platform_wifi.c
deleted file mode 100644
index fe4347d4..00000000
--- a/chpp/platform/linux/services/platform_wifi.c
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <stdbool.h>
-#include <stdint.h>
-
-#include "chpp/common/wifi.h"
-#include "chpp/macros.h"
-#include "chpp/services/wifi.h"
-#include "chre/pal/wifi.h"
-
-static const struct chrePalSystemApi *gSystemApi;
-static const struct chrePalWifiCallbacks *gCallbacks;
-
-static bool wifiPalOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalWifiCallbacks *callbacks) {
- gSystemApi = systemApi;
- gCallbacks = callbacks;
-
- return true;
-}
-
-static void wifiPalClose(void) {}
-
-static uint32_t wifiPalGetCapabilities(void) {
- return CHRE_WIFI_CAPABILITIES_SCAN_MONITORING |
- CHRE_WIFI_CAPABILITIES_ON_DEMAND_SCAN;
-}
-
-static bool wifiPalConfigureScanMonitor(bool enable) {
- // TODO
- UNUSED_VAR(enable);
- return true; // If successful
-}
-
-static bool wifiPalRequestScan(const struct chreWifiScanParams *params) {
- // TODO
- UNUSED_VAR(params);
- return true; // If successful
-}
-
-static void wifiPalReleaseScanEvent(struct chreWifiScanEvent *event) {
- gSystemApi->memoryFree(CHPP_CONST_CAST_POINTER(event->results));
- gSystemApi->memoryFree(event);
-}
-
-static bool wifiPalRequestRanging(const struct chreWifiRangingParams *params) {
- // TODO
- UNUSED_VAR(params);
- return true; // If successful
-}
-
-static void wifiPalReleaseRangingEvent(struct chreWifiRangingEvent *event) {
- gSystemApi->memoryFree(CHPP_CONST_CAST_POINTER(event->scannedFreqList));
- gSystemApi->memoryFree(CHPP_CONST_CAST_POINTER(event->results));
- gSystemApi->memoryFree(event);
-}
-
-#ifdef CHPP_SERVICE_ENABLED_WIFI
-const struct chrePalWifiApi *chrePalWifiGetApi(uint32_t requestedApiVersion) {
- static const struct chrePalWifiApi api = {
- .moduleVersion = CHPP_PAL_WIFI_API_VERSION,
- .open = wifiPalOpen,
- .close = wifiPalClose,
- .getCapabilities = wifiPalGetCapabilities,
- .configureScanMonitor = wifiPalConfigureScanMonitor,
- .requestScan = wifiPalRequestScan,
- .releaseScanEvent = wifiPalReleaseScanEvent,
- .requestRanging = wifiPalRequestRanging,
- .releaseRangingEvent = wifiPalReleaseRangingEvent,
- };
-
- CHPP_STATIC_ASSERT(
- CHRE_PAL_WIFI_API_CURRENT_VERSION == CHPP_PAL_WIFI_API_VERSION,
- "A newer CHRE PAL API version is available. Please update.");
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(api.moduleVersion,
- requestedApiVersion)) {
- return NULL;
- } else {
- return &api;
- }
-}
-#endif
diff --git a/chpp/platform/linux/services/platform_wwan.c b/chpp/platform/linux/services/platform_wwan.c
deleted file mode 100644
index 78f7f5a8..00000000
--- a/chpp/platform/linux/services/platform_wwan.c
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <stdbool.h>
-#include <stdint.h>
-
-#include "chpp/common/wwan.h"
-#include "chpp/services/wwan.h"
-#include "chre/pal/wwan.h"
-
-static const struct chrePalSystemApi *gSystemApi;
-static const struct chrePalWwanCallbacks *gCallbacks;
-
-static bool wwanPalOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalWwanCallbacks *callbacks) {
- gSystemApi = systemApi;
- gCallbacks = callbacks;
-
- return true;
-}
-
-static void wwanPalClose(void) {}
-
-static uint32_t wwanPalGetCapabilities(void) {
- return CHRE_WWAN_GET_CELL_INFO;
-}
-
-static bool wwanPalRequestCellInfo(void) {
- struct chreWwanCellInfoResult *result =
- gSystemApi->memoryAlloc(sizeof(struct chreWwanCellInfoResult));
- CHPP_NOT_NULL(result);
-
- // TODO: <populate result>
-
- if (result->cellInfoCount > 0) {
- result->cells = gSystemApi->memoryAlloc(result->cellInfoCount *
- sizeof(struct chreWwanCellInfo));
- CHPP_NOT_NULL(cells);
- }
-
- // TODO: <populate cells>
-
- gCallbacks->cellInfoResultCallback(result);
-
- return true; // If successful
-}
-
-static void wwanPalReleaseCellInfoResult(
- struct chreWwanCellInfoResult *result) {
- gSystemApi->memoryFree(CHPP_CONST_CAST_POINTER(result->cells));
- gSystemApi->memoryFree(result);
-}
-
-#ifdef CHPP_SERVICE_ENABLED_WWAN
-const struct chrePalWwanApi *chrePalWwanGetApi(uint32_t requestedApiVersion) {
- static const struct chrePalWwanApi api = {
- .moduleVersion = CHPP_PAL_WWAN_API_VERSION,
- .open = wwanPalOpen,
- .close = wwanPalClose,
- .getCapabilities = wwanPalGetCapabilities,
- .requestCellInfo = wwanPalRequestCellInfo,
- .releaseCellInfoResult = wwanPalReleaseCellInfoResult,
- };
-
- CHPP_STATIC_ASSERT(
- CHRE_PAL_WWAN_API_CURRENT_VERSION == CHPP_PAL_WWAN_API_VERSION,
- "A newer CHRE PAL API version is available. Please update.");
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(api.moduleVersion,
- requestedApiVersion)) {
- return NULL;
- } else {
- return &api;
- }
-}
-#endif
diff --git a/chpp/platform/pal_api.c b/chpp/platform/pal_api.c
deleted file mode 100644
index b8584b7b..00000000
--- a/chpp/platform/pal_api.c
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * 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 "chpp/pal_api.h"
-
-#include <stdarg.h>
-#include <stdio.h>
-
-#include "chpp/app.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chpp/time.h"
-#include "chre/pal/system.h"
-#include "chre_api/chre/re.h"
-
-//! Define a format string for PAL logs. This is defined as a macro so that it
-//! can be used as a string literal by platform implementations of the logging
-//! macros.
-#define PAL_LOG_FORMAT_STR "PAL: %s"
-
-static uint64_t palSystemApiGetCurrentTime(void) {
- return chppGetCurrentTimeNs();
-}
-
-static void palSystemApiLog(enum chreLogLevel level, const char *formatStr,
- ...) {
- char logBuf[512];
- va_list args;
-
- va_start(args, formatStr);
- vsnprintf(logBuf, sizeof(logBuf), formatStr, args);
- // TODO: not sure if vsnprintf will be well-supported on partner platforms (on
- // the CHRE side, we know it's the case for SLPI but even then it's not
- // supported in micro-image). We may instead want to expose a va_list version
- // of the platform log functionality, so we can just forward directly to the
- // underlying platform log functionality without handling format string
- // expansion in common code.
- va_end(args);
-
- switch (level) {
- case CHRE_LOG_ERROR:
- CHPP_LOGE(PAL_LOG_FORMAT_STR, logBuf);
- break;
- case CHRE_LOG_WARN:
- CHPP_LOGW(PAL_LOG_FORMAT_STR, logBuf);
- break;
- case CHRE_LOG_INFO:
- CHPP_LOGI(PAL_LOG_FORMAT_STR, logBuf);
- break;
- case CHRE_LOG_DEBUG:
- default:
- CHPP_LOGD(PAL_LOG_FORMAT_STR, logBuf);
- }
-}
-
-void chppPalSystemApiInit(struct ChppAppState *context) {
- // Initialize the CHRE System API with function implementations provided
- // above.
- static const struct chrePalSystemApi chrePalSystemApi = {
- .version = CHRE_PAL_SYSTEM_API_CURRENT_VERSION,
- .getCurrentTime = palSystemApiGetCurrentTime,
- .log = palSystemApiLog,
- .memoryAlloc = chppMalloc,
- .memoryFree = chppFree,
- };
-
- context->systemApi = &chrePalSystemApi;
-}
-
-void chppPalSystemApiDeinit(struct ChppAppState *context) {
- UNUSED_VAR(context);
-}
diff --git a/chpp/platform/shared/crc.c b/chpp/platform/shared/crc.c
deleted file mode 100644
index 7c63515c..00000000
--- a/chpp/platform/shared/crc.c
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 "chpp/crc.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-uint32_t chppCrc32(uint32_t crc, const uint8_t *buf, size_t len) {
- // This lookup table (LUT) consumes 16 * 4 = 64 bytes. Other implementations
- // exist with a larger LUT, with a LUT calculated on the fly, or without using
- // a LUT altogether.
- static const uint32_t crc32LookupTable[] = {
- 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
- 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
- 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
-
- crc = ~crc;
- for (size_t i = 0; i < len; i++) {
- crc = crc32LookupTable[(crc ^ buf[i]) & 0x0F] ^ (crc >> 4);
- crc = crc32LookupTable[(crc ^ (buf[i] >> 4)) & 0x0F] ^ (crc >> 4);
- }
- crc = ~crc;
-
- return crc;
-}
diff --git a/chpp/services.c b/chpp/services.c
deleted file mode 100644
index dd087115..00000000
--- a/chpp/services.c
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/services.h"
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/log.h"
-#include "chpp/memory.h"
-#ifdef CHPP_SERVICE_ENABLED_GNSS
-#include "chpp/services/gnss.h"
-#endif
-#ifdef CHPP_SERVICE_ENABLED_WIFI
-#include "chpp/services/wifi.h"
-#endif
-#ifdef CHPP_SERVICE_ENABLED_WWAN
-#include "chpp/services/wwan.h"
-#endif
-#include "chpp/time.h"
-#include "chpp/transport.h"
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppRegisterCommonServices(struct ChppAppState *context) {
- UNUSED_VAR(context);
-
-#ifdef CHPP_SERVICE_ENABLED_WWAN
- if (context->clientServiceSet.wwanService) {
- chppRegisterWwanService(context);
- }
-#endif
-
-#ifdef CHPP_SERVICE_ENABLED_WIFI
- if (context->clientServiceSet.wifiService) {
- chppRegisterWifiService(context);
- }
-#endif
-
-#ifdef CHPP_SERVICE_ENABLED_GNSS
- if (context->clientServiceSet.gnssService) {
- chppRegisterGnssService(context);
- }
-#endif
-}
-
-void chppDeregisterCommonServices(struct ChppAppState *context) {
- UNUSED_VAR(context);
-
-#ifdef CHPP_SERVICE_ENABLED_WWAN
- if (context->clientServiceSet.wwanService) {
- chppDeregisterWwanService(context);
- }
-#endif
-
-#ifdef CHPP_SERVICE_ENABLED_WIFI
- if (context->clientServiceSet.wifiService) {
- chppDeregisterWifiService(context);
- }
-#endif
-
-#ifdef CHPP_SERVICE_ENABLED_GNSS
- if (context->clientServiceSet.gnssService) {
- chppDeregisterGnssService(context);
- }
-#endif
-}
-
-uint8_t chppRegisterService(struct ChppAppState *appContext,
- void *serviceContext,
- const struct ChppService *newService) {
- CHPP_NOT_NULL(newService);
-
- if (appContext->registeredServiceCount >= CHPP_MAX_REGISTERED_SERVICES) {
- CHPP_LOGE("Max services registered: # %" PRIu8,
- appContext->registeredServiceCount);
- return CHPP_HANDLE_NONE;
-
- } else {
- appContext->registeredServices[appContext->registeredServiceCount] =
- newService;
- appContext->registeredServiceContexts[appContext->registeredServiceCount] =
- serviceContext;
-
- char uuidText[CHPP_SERVICE_UUID_STRING_LEN];
- chppUuidToStr(newService->descriptor.uuid, uuidText);
- CHPP_LOGD("Registered service # %" PRIu8
- " on handle %d"
- " with name=%s, UUID=%s, version=%" PRIu8 ".%" PRIu8 ".%" PRIu16
- ", min_len=%" PRIuSIZE " ",
- appContext->registeredServiceCount,
- CHPP_SERVICE_HANDLE_OF_INDEX(appContext->registeredServiceCount),
- newService->descriptor.name, uuidText,
- newService->descriptor.version.major,
- newService->descriptor.version.minor,
- newService->descriptor.version.patch, newService->minLength);
-
- return CHPP_SERVICE_HANDLE_OF_INDEX(appContext->registeredServiceCount++);
- }
-}
-
-struct ChppAppHeader *chppAllocServiceNotification(size_t len) {
- CHPP_ASSERT(len >= sizeof(struct ChppAppHeader));
-
- struct ChppAppHeader *result = chppMalloc(len);
- if (result) {
- result->handle = CHPP_HANDLE_NONE;
- result->type = CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION;
- result->transaction = 0;
- result->error = CHPP_APP_ERROR_NONE;
- result->command = CHPP_APP_COMMAND_NONE;
- }
- return result;
-}
-
-struct ChppAppHeader *chppAllocServiceResponse(
- const struct ChppAppHeader *requestHeader, size_t len) {
- CHPP_ASSERT(len >= sizeof(struct ChppAppHeader));
-
- struct ChppAppHeader *result = chppMalloc(len);
- if (result) {
- *result = *requestHeader;
- result->type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
- result->error = CHPP_APP_ERROR_NONE;
- }
- return result;
-}
-
-void chppServiceTimestampRequest(struct ChppRequestResponseState *rRState,
- struct ChppAppHeader *requestHeader) {
- if (rRState->responseTimeNs == CHPP_TIME_NONE &&
- rRState->requestTimeNs != CHPP_TIME_NONE) {
- CHPP_LOGE("Duplicate request rx at t=%" PRIu64,
- rRState->requestTimeNs / CHPP_NSEC_PER_MSEC);
- }
- rRState->requestTimeNs = chppGetCurrentTimeNs();
- rRState->responseTimeNs = CHPP_TIME_NONE;
- rRState->transaction = requestHeader->transaction;
-}
-
-void chppServiceTimestampResponse(struct ChppRequestResponseState *rRState) {
- uint64_t previousResponseTime = rRState->responseTimeNs;
- rRState->responseTimeNs = chppGetCurrentTimeNs();
-
- if (rRState->requestTimeNs == CHPP_TIME_NONE) {
- CHPP_LOGE("Tx response w/ no req t=%" PRIu64,
- rRState->responseTimeNs / CHPP_NSEC_PER_MSEC);
-
- } else if (previousResponseTime != CHPP_TIME_NONE) {
- CHPP_LOGW("Resend response t=%" PRIu64 " for request at t=%" PRIu64,
- rRState->responseTimeNs / CHPP_NSEC_PER_MSEC,
- rRState->responseTimeNs / CHPP_NSEC_PER_MSEC);
-
- } else {
- CHPP_LOGD("Sending initial response at t=%" PRIu64
- " for request at t=%" PRIu64 " (RTT=%" PRIu64 ")",
- rRState->responseTimeNs / CHPP_NSEC_PER_MSEC,
- rRState->responseTimeNs / CHPP_NSEC_PER_MSEC,
- (rRState->responseTimeNs - rRState->requestTimeNs) /
- CHPP_NSEC_PER_MSEC);
- }
-}
-
-bool chppSendTimestampedResponseOrFail(struct ChppServiceState *serviceState,
- struct ChppRequestResponseState *rRState,
- void *buf, size_t len) {
- chppServiceTimestampResponse(rRState);
- return chppEnqueueTxDatagramOrFail(serviceState->appContext->transportContext,
- buf, len);
-}
diff --git a/chpp/services/discovery.c b/chpp/services/discovery.c
deleted file mode 100644
index 4ed54913..00000000
--- a/chpp/services/discovery.c
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/services/discovery.h"
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/common/discovery.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/services.h"
-#include "chpp/transport.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static void chppDiscoveryDiscoverAll(struct ChppAppState *context,
- const struct ChppAppHeader *rxHeader);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Processes the Discover All Services (0x0001) request.
- *
- * @param context Maintains status for each app layer instance.
- * @param requestHeader Request datagram header. Cannot be null.
- */
-static void chppDiscoveryDiscoverAll(
- struct ChppAppState *context, const struct ChppAppHeader *requestHeader) {
- // Allocate response
- size_t responseLen =
- sizeof(struct ChppAppHeader) +
- context->registeredServiceCount * sizeof(struct ChppServiceDescriptor);
-
- struct ChppDiscoveryResponse *response = chppAllocServiceResponseTypedArray(
- requestHeader, struct ChppDiscoveryResponse,
- context->registeredServiceCount, services);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- CHPP_ASSERT(false);
-
- } else {
- CHPP_LOGI("Discovery resp count=%" PRIu8, context->registeredServiceCount);
-
- response->header.error = CHPP_APP_ERROR_NONE;
-
- // Populate list of services
- for (size_t i = 0; i < context->registeredServiceCount; i++) {
- response->services[i] = context->registeredServices[i]->descriptor;
- }
-
- // Send out response datagram
- chppEnqueueTxDatagramOrFail(context->transportContext, response,
- responseLen);
- }
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-bool chppDispatchDiscoveryClientRequest(struct ChppAppState *context,
- const uint8_t *buf, size_t len) {
- UNUSED_VAR(len);
- const struct ChppAppHeader *rxHeader = (const struct ChppAppHeader *)buf;
- bool success = true;
-
- switch (rxHeader->command) {
- case CHPP_DISCOVERY_COMMAND_DISCOVER_ALL: {
- // Send back a list of services supported by this platform.
- chppDiscoveryDiscoverAll(context, rxHeader);
- break;
- }
- default: {
- success = false;
- }
- }
- return success;
-}
diff --git a/chpp/services/gnss.c b/chpp/services/gnss.c
deleted file mode 100644
index 184000ff..00000000
--- a/chpp/services/gnss.c
+++ /dev/null
@@ -1,687 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/services/gnss.h"
-
-#include <inttypes.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/common/gnss.h"
-#include "chpp/common/gnss_types.h"
-#include "chpp/common/standard_uuids.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/services.h"
-#include "chre/pal/gnss.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppDispatchGnssRequest(void *serviceContext,
- uint8_t *buf, size_t len);
-static void chppGnssServiceNotifyReset(void *serviceContext);
-
-/************************************************
- * Private Definitions
- ***********************************************/
-
-/**
- * Configuration parameters for this service
- */
-static const struct ChppService kGnssServiceConfig = {
- .descriptor.uuid = CHPP_UUID_GNSS_STANDARD,
-
- // Human-readable name
- .descriptor.name = "GNSS",
-
- // Version
- .descriptor.version.major = 1,
- .descriptor.version.minor = 0,
- .descriptor.version.patch = 0,
-
- // Notifies service if CHPP is reset
- .resetNotifierFunctionPtr = &chppGnssServiceNotifyReset,
-
- // Client request dispatch function pointer
- .requestDispatchFunctionPtr = &chppDispatchGnssRequest,
-
- // Client notification dispatch function pointer
- .notificationDispatchFunctionPtr = NULL, // Not supported
-
- // Min length is the entire header
- .minLength = sizeof(struct ChppAppHeader),
-};
-
-/**
- * Structure to maintain state for the GNSS service and its Request/Response
- * (RR) functionality.
- */
-struct ChppGnssServiceState {
- struct ChppServiceState service; // GNSS service state
- const struct chrePalGnssApi *api; // GNSS PAL API
-
- // Based on chre/pal/gnss.h and chrePalGnssApi
- struct ChppRequestResponseState open; // Service init state
- struct ChppRequestResponseState close; // Service deinit state
- struct ChppRequestResponseState getCapabilities; // Get Capabilities state
- struct ChppRequestResponseState
- controlLocationSession; // Control Location measurement state
- struct ChppRequestResponseState
- controlMeasurementSession; // Control Raw GNSS measurement state
- struct ChppRequestResponseState
- configurePassiveLocationListener; // Configure Passive location receiving
- // state
-};
-
-// Note: The CHRE PAL API only allows for one definition - see comment in WWAN
-// service for details.
-// Note: There is no notion of a cookie in the CHRE GNSS API so we need to use
-// the global service state (gGnssServiceContext) directly in all callbacks.
-struct ChppGnssServiceState gGnssServiceContext;
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppGnssServiceOpen(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppGnssServiceClose(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppGnssServiceGetCapabilities(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppGnssServiceControlLocationSession(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len);
-static enum ChppAppErrorCode chppGnssServiceControlMeasurementSession(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len);
-static enum ChppAppErrorCode chppGnssServiceConfigurePassiveLocationListener(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len);
-
-static void chppGnssServiceRequestStateResyncCallback(void);
-static void chppGnssServiceLocationStatusChangeCallback(bool enabled,
- uint8_t errorCode);
-static void chppGnssServiceLocationEventCallback(
- struct chreGnssLocationEvent *event);
-static void chppGnssServiceMeasurementStatusChangeCallback(bool enabled,
- uint8_t errorCode);
-static void chppGnssServiceMeasurementEventCallback(
- struct chreGnssDataEvent *event);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Dispatches a client request from the transport layer that is determined to be
- * for the GNSS service. If the result of the dispatch is an error, this
- * function responds to the client with the same error.
- *
- * This function is called from the app layer using its function pointer given
- * during service registration.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppDispatchGnssRequest(void *serviceContext,
- uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- buf += sizeof(struct ChppAppHeader);
- len -= sizeof(struct ChppAppHeader);
-
- struct ChppGnssServiceState *gnssServiceContext =
- (struct ChppGnssServiceState *)serviceContext;
- struct ChppRequestResponseState *rRState = NULL;
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
- bool dispatched = true;
-
- switch (rxHeader->command) {
- case CHPP_GNSS_OPEN: {
- rRState = &gnssServiceContext->open;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppGnssServiceOpen(gnssServiceContext, rxHeader);
- break;
- }
-
- case CHPP_GNSS_CLOSE: {
- rRState = &gnssServiceContext->close;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppGnssServiceClose(gnssServiceContext, rxHeader);
- break;
- }
-
- case CHPP_GNSS_GET_CAPABILITIES: {
- rRState = &gnssServiceContext->getCapabilities;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppGnssServiceGetCapabilities(gnssServiceContext, rxHeader);
- break;
- }
-
- case CHPP_GNSS_CONTROL_LOCATION_SESSION: {
- rRState = &gnssServiceContext->controlLocationSession;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppGnssServiceControlLocationSession(gnssServiceContext,
- rxHeader, buf, len);
- break;
- }
-
- case CHPP_GNSS_CONTROL_MEASUREMENT_SESSION: {
- rRState = &gnssServiceContext->controlMeasurementSession;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppGnssServiceControlMeasurementSession(gnssServiceContext,
- rxHeader, buf, len);
- break;
- }
-
- case CHPP_GNSS_CONFIGURE_PASSIVE_LOCATION_LISTENER: {
- rRState = &gnssServiceContext->configurePassiveLocationListener;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppGnssServiceConfigurePassiveLocationListener(
- gnssServiceContext, rxHeader, buf, len);
- break;
- }
-
- default: {
- dispatched = false;
- error = CHPP_APP_ERROR_INVALID_COMMAND;
- break;
- }
- }
-
- if (dispatched == true && error != CHPP_APP_ERROR_NONE) {
- // Request was dispatched but an error was returned. Close out
- // chppServiceTimestampRequest()
- chppServiceTimestampResponse(rRState);
- }
-
- return error;
-}
-
-/**
- * Initializes the GNSS service upon an open request from the client and
- * responds to the client with the result.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppGnssServiceOpen(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader) {
- static const struct chrePalGnssCallbacks palCallbacks = {
- .requestStateResync = chppGnssServiceRequestStateResyncCallback,
- .locationStatusChangeCallback =
- chppGnssServiceLocationStatusChangeCallback,
- .locationEventCallback = chppGnssServiceLocationEventCallback,
- .measurementStatusChangeCallback =
- chppGnssServiceMeasurementStatusChangeCallback,
- .measurementEventCallback = chppGnssServiceMeasurementEventCallback,
- };
-
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (gnssServiceContext->service.openState == CHPP_OPEN_STATE_OPENED) {
- CHPP_LOGE("GNSS service already open");
- CHPP_DEBUG_ASSERT(false);
- error = CHPP_APP_ERROR_INVALID_COMMAND;
-
- } else if (!gnssServiceContext->api->open(
- gnssServiceContext->service.appContext->systemApi,
- &palCallbacks)) {
- CHPP_LOGE("GNSS PAL open failed");
- CHPP_DEBUG_ASSERT(false);
- error = CHPP_APP_ERROR_BEYOND_CHPP;
-
- } else {
- CHPP_LOGI("GNSS service opened");
- gnssServiceContext->service.openState = CHPP_OPEN_STATE_OPENED;
-
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppAppHeader);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- chppSendTimestampedResponseOrFail(&gnssServiceContext->service,
- &gnssServiceContext->open, response,
- responseLen);
- }
- }
-
- return error;
-}
-
-/**
- * Deinitializes the GNSS service.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppGnssServiceClose(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader) {
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- gnssServiceContext->api->close();
- gnssServiceContext->service.openState = CHPP_OPEN_STATE_CLOSED;
-
- CHPP_LOGI("GNSS service closed");
-
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppAppHeader);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- chppSendTimestampedResponseOrFail(&gnssServiceContext->service,
- &gnssServiceContext->close, response,
- responseLen);
- }
-
- return error;
-}
-
-/**
- * Notifies the service of an incoming reset.
- *
- * @param serviceContext Maintains status for each service instance.
- */
-static void chppGnssServiceNotifyReset(void *serviceContext) {
- struct ChppGnssServiceState *gnssServiceContext =
- (struct ChppGnssServiceState *)serviceContext;
-
- if (gnssServiceContext->service.openState != CHPP_OPEN_STATE_OPENED) {
- CHPP_LOGW("GNSS service reset but wasn't open");
- } else {
- CHPP_LOGI("GNSS service reset. Closing");
- gnssServiceContext->service.openState = CHPP_OPEN_STATE_CLOSED;
- gnssServiceContext->api->close();
- }
-}
-
-/**
- * Retrieves a set of flags indicating the GNSS features supported by the
- * current implementation.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppGnssServiceGetCapabilities(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader) {
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- struct ChppGnssGetCapabilitiesResponse *response =
- chppAllocServiceResponseFixed(requestHeader,
- struct ChppGnssGetCapabilitiesResponse);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- response->params.capabilities = gnssServiceContext->api->getCapabilities();
-
- CHPP_LOGD("chppGnssServiceGetCapabilities returning 0x%" PRIx32
- ", %" PRIuSIZE " bytes",
- response->params.capabilities, responseLen);
- chppSendTimestampedResponseOrFail(&gnssServiceContext->service,
- &gnssServiceContext->getCapabilities,
- response, responseLen);
- }
-
- return error;
-}
-
-/**
- * Start/stop/modify the GNSS location session.
- *
- * This function returns an error code synchronously.
- * A subsequent call to chppGnssServiceLocationStatusChangeCallback() will be
- * used to communicate the result of this request (as a service response).
- * A subsequent call to chppGnssServiceLocationEventCallback() will be used to
- * communicate the location fixes (as service notifications).
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppGnssServiceControlLocationSession(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len) {
- UNUSED_VAR(requestHeader);
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (len < sizeof(struct ChppGnssControlLocationSessionParameters)) {
- error = CHPP_APP_ERROR_INVALID_ARG;
-
- } else {
- struct ChppGnssControlLocationSessionParameters *parameters =
- (struct ChppGnssControlLocationSessionParameters *)buf;
-
- if (!gnssServiceContext->api->controlLocationSession(
- parameters->enable, parameters->minIntervalMs,
- parameters->minTimeToNextFixMs)) {
- error = CHPP_APP_ERROR_UNSPECIFIED;
- }
- }
-
- return error;
-}
-
-/**
- * Start/stop/modify the raw GNSS measurement session.
- *
- * This function returns an error code synchronously.
- * A subsequent call to chppGnssServiceMeasurementStatusChangeCallback() will be
- * used to communicate the result of this request (as a service response).
- * A subsequent call to chppGnssServiceMeasurementEventCallback() will be used
- * to communicate the measurements (as service notifications).
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppGnssServiceControlMeasurementSession(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len) {
- UNUSED_VAR(requestHeader);
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (len < sizeof(struct ChppGnssControlMeasurementSessionParameters)) {
- error = CHPP_APP_ERROR_INVALID_ARG;
-
- } else {
- struct ChppGnssControlMeasurementSessionParameters *parameters =
- (struct ChppGnssControlMeasurementSessionParameters *)buf;
-
- if (!gnssServiceContext->api->controlMeasurementSession(
- parameters->enable, parameters->minIntervalMs)) {
- error = CHPP_APP_ERROR_UNSPECIFIED;
- }
- }
-
- return error;
-}
-
-/**
- * Configures whether to opportunistically deliver any location fixes produced
- * for other clients of the GNSS engine.
- *
- * This function returns an error code synchronously.
- * A subsequent call to chppGnssServiceLocationEventCallback() will be used to
- * communicate the location fixes (as service notifications).
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppGnssServiceConfigurePassiveLocationListener(
- struct ChppGnssServiceState *gnssServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len) {
- UNUSED_VAR(requestHeader);
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (len < sizeof(struct ChppGnssConfigurePassiveLocationListenerParameters)) {
- error = CHPP_APP_ERROR_INVALID_ARG;
- } else {
- struct ChppGnssConfigurePassiveLocationListenerParameters *parameters =
- (struct ChppGnssConfigurePassiveLocationListenerParameters *)buf;
-
- if (!gnssServiceContext->api->configurePassiveLocationListener(
- parameters->enable)) {
- error = CHPP_APP_ERROR_UNSPECIFIED;
-
- } else {
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppAppHeader);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- chppSendTimestampedResponseOrFail(
- &gnssServiceContext->service,
- &gnssServiceContext->configurePassiveLocationListener, response,
- responseLen);
- }
- }
- }
-
- return error;
-}
-
-/**
- * GNSS PAL callback to request that the core CHRE system re-send requests for
- * any active sessions and its current passive location listener setting.
- */
-static void chppGnssServiceRequestStateResyncCallback(void) {
- struct ChppAppHeader *notification =
- chppAllocServiceNotificationFixed(struct ChppAppHeader);
- size_t notificationLen = sizeof(*notification);
-
- if (notification == NULL) {
- CHPP_LOG_OOM();
- CHPP_ASSERT(false);
-
- } else {
- notification->handle = gGnssServiceContext.service.handle;
- notification->command = CHPP_GNSS_REQUEST_STATE_RESYNC_NOTIFICATION;
-
- chppEnqueueTxDatagramOrFail(
- gGnssServiceContext.service.appContext->transportContext, notification,
- notificationLen);
- }
-}
-
-/**
- * GNSS PAL callback to inform the CHRE of the result of changes to the location
- * session status.
- */
-static void chppGnssServiceLocationStatusChangeCallback(bool enabled,
- uint8_t errorCode) {
- // Recreate request header
- struct ChppAppHeader requestHeader = {
- .handle = gGnssServiceContext.service.handle,
- .transaction = gGnssServiceContext.controlLocationSession.transaction,
- .command = CHPP_GNSS_CONTROL_LOCATION_SESSION,
- };
-
- struct ChppGnssControlLocationSessionResponse *response =
- chppAllocServiceResponseFixed(
- &requestHeader, struct ChppGnssControlLocationSessionResponse);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- CHPP_ASSERT(false);
-
- } else {
- response->enabled = enabled;
- response->errorCode = errorCode;
-
- chppSendTimestampedResponseOrFail(
- &gGnssServiceContext.service,
- &gGnssServiceContext.controlLocationSession, response, responseLen);
- }
-}
-
-/**
- * GNSS PAL callback to pass GNSS location fixes to the core CHRE system.
- */
-static void chppGnssServiceLocationEventCallback(
- struct chreGnssLocationEvent *event) {
- // Craft response per parser script
- struct ChppGnssLocationEventWithHeader *notification = NULL;
- size_t notificationLen = 0;
-
- if (!chppGnssLocationEventFromChre(event, &notification, &notificationLen)) {
- CHPP_LOGE("LocationEvent conversion failed (OOM?)");
-
- notification = chppMalloc(sizeof(struct ChppAppHeader));
- if (notification == NULL) {
- CHPP_LOG_OOM();
- } else {
- notificationLen = sizeof(struct ChppAppHeader);
- }
- }
-
- if (notification != NULL) {
- notification->header.handle = gGnssServiceContext.service.handle;
- notification->header.type = CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION;
- notification->header.transaction =
- 0; // Because we don't know this is in response to a Location Session
- // or Passive Location Listener
- notification->header.error =
- (notificationLen > sizeof(struct ChppAppHeader))
- ? CHPP_APP_ERROR_NONE
- : CHPP_APP_ERROR_CONVERSION_FAILED;
- notification->header.command = CHPP_GNSS_LOCATION_RESULT_NOTIFICATION;
-
- chppEnqueueTxDatagramOrFail(
- gGnssServiceContext.service.appContext->transportContext, notification,
- notificationLen);
- }
-
- gGnssServiceContext.api->releaseLocationEvent(event);
-}
-
-/**
- * GNSS PAL callback to inform the CHRE of the result of changes to the raw GNSS
- * measurement session status.
- */
-static void chppGnssServiceMeasurementStatusChangeCallback(bool enabled,
- uint8_t errorCode) {
- // Recreate request header
- struct ChppAppHeader requestHeader = {
- .handle = gGnssServiceContext.service.handle,
- .transaction = gGnssServiceContext.controlMeasurementSession.transaction,
- .command = CHPP_GNSS_CONTROL_MEASUREMENT_SESSION,
- };
-
- struct ChppGnssControlMeasurementSessionResponse *response =
- chppAllocServiceResponseFixed(
- &requestHeader, struct ChppGnssControlMeasurementSessionResponse);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- CHPP_ASSERT(false);
-
- } else {
- response->enabled = enabled;
- response->errorCode = errorCode;
-
- chppSendTimestampedResponseOrFail(
- &gGnssServiceContext.service,
- &gGnssServiceContext.controlMeasurementSession, response, responseLen);
- }
-}
-
-/**
- * GNSS PAL callback to pass raw GNSS measurement data to the core CHRE system.
- */
-static void chppGnssServiceMeasurementEventCallback(
- struct chreGnssDataEvent *event) {
- // Craft response per parser script
- struct ChppGnssDataEventWithHeader *notification = NULL;
- size_t notificationLen = 0;
-
- if (!chppGnssDataEventFromChre(event, &notification, &notificationLen)) {
- CHPP_LOGE("DataEvent conversion failed (OOM?) ID=%" PRIu8,
- gGnssServiceContext.controlMeasurementSession.transaction);
-
- notification = chppMalloc(sizeof(struct ChppAppHeader));
- if (notification == NULL) {
- CHPP_LOG_OOM();
- } else {
- notificationLen = sizeof(struct ChppAppHeader);
- }
- }
-
- if (notification != NULL) {
- notification->header.handle = gGnssServiceContext.service.handle;
- notification->header.type = CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION;
- notification->header.transaction =
- gGnssServiceContext.controlMeasurementSession.transaction;
- notification->header.error =
- (notificationLen > sizeof(struct ChppAppHeader))
- ? CHPP_APP_ERROR_NONE
- : CHPP_APP_ERROR_CONVERSION_FAILED;
- notification->header.command = CHPP_GNSS_MEASUREMENT_RESULT_NOTIFICATION;
-
- chppEnqueueTxDatagramOrFail(
- gGnssServiceContext.service.appContext->transportContext, notification,
- notificationLen);
- }
-
- gGnssServiceContext.api->releaseMeasurementDataEvent(event);
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppRegisterGnssService(struct ChppAppState *appContext) {
- gGnssServiceContext.api = chrePalGnssGetApi(CHPP_PAL_GNSS_API_VERSION);
-
- if (gGnssServiceContext.api == NULL) {
- CHPP_LOGE(
- "GNSS PAL API version not compatible with CHPP. Cannot register GNSS "
- "service");
- CHPP_DEBUG_ASSERT(false);
-
- } else {
- gGnssServiceContext.service.appContext = appContext;
- gGnssServiceContext.service.handle = chppRegisterService(
- appContext, (void *)&gGnssServiceContext, &kGnssServiceConfig);
- CHPP_DEBUG_ASSERT(gGnssServiceContext.service.handle);
- }
-}
-
-void chppDeregisterGnssService(struct ChppAppState *appContext) {
- // TODO
-
- UNUSED_VAR(appContext);
-}
diff --git a/chpp/services/loopback.c b/chpp/services/loopback.c
deleted file mode 100644
index 2173fab7..00000000
--- a/chpp/services/loopback.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/services/loopback.h"
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "chpp/app.h"
-#include "chpp/log.h"
-#include "chpp/memory.h"
-#include "chpp/transport.h"
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-bool chppDispatchLoopbackClientRequest(struct ChppAppState *context,
- uint8_t *buf, size_t len) {
- uint8_t *response = chppMalloc(len);
- if (response == NULL) {
- CHPP_LOG_OOM();
- chppEnqueueTxErrorDatagram(context->transportContext,
- CHPP_TRANSPORT_ERROR_OOM);
-
- } else {
- CHPP_LOGI("Looping back len=%" PRIuSIZE, len);
-
- // Copy received datagram
- memcpy(response, buf, len);
-
- // Modify response message type per loopback spec.
- struct ChppAppHeader *responseHeader = (struct ChppAppHeader *)response;
- responseHeader->type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
-
- // Send out response datagram
- chppEnqueueTxDatagramOrFail(context->transportContext, response, len);
- }
-
- return true;
-}
diff --git a/chpp/services/nonhandle.c b/chpp/services/nonhandle.c
deleted file mode 100644
index ab5bd391..00000000
--- a/chpp/services/nonhandle.c
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/services/nonhandle.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/macros.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppDispatchNonHandle(struct ChppAppState *context, uint8_t *buf,
- size_t len) {
- UNUSED_VAR(context);
- UNUSED_VAR(buf);
- UNUSED_VAR(len);
-}
diff --git a/chpp/services/timesync.c b/chpp/services/timesync.c
deleted file mode 100644
index e66b5129..00000000
--- a/chpp/services/timesync.c
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/services/timesync.h"
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/common/timesync.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/services.h"
-#include "chpp/time.h"
-#include "chpp/transport.h"
-
-/**
- * Processes the GetTime (0x0001) request and responds with the time as on the
- * service. This should be the same clock used to timestamp any data samples
- * provided to CHPP.
- *
- * @param context Maintains status for each app layer instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- */
-static void chppTimesyncGetTime(struct ChppAppState *context,
- const uint8_t *buf, size_t len) {
- UNUSED_VAR(len);
- const struct ChppAppHeader *requestHeader = (const struct ChppAppHeader *)buf;
-
- struct ChppTimesyncResponse *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppTimesyncResponse);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- CHPP_DEBUG_ASSERT(false);
-
- } else {
- response->timeNs = chppGetCurrentTimeNs();
- CHPP_LOGD("chppTimesyncGetTime returning %" PRIuSIZE
- " bytes at time=%" PRIu64,
- responseLen, response->timeNs / CHPP_NSEC_PER_MSEC);
-
- chppEnqueueTxDatagramOrFail(context->transportContext, response,
- responseLen);
- }
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-bool chppDispatchTimesyncClientRequest(struct ChppAppState *context,
- const uint8_t *buf, size_t len) {
- UNUSED_VAR(len);
- const struct ChppAppHeader *rxHeader = (const struct ChppAppHeader *)buf;
- bool success = true;
-
- switch (rxHeader->command) {
- case CHPP_TIMESYNC_COMMAND_GETTIME: {
- chppTimesyncGetTime(context, buf, len);
- break;
- }
- default: {
- success = false;
- }
- }
- return success;
-}
diff --git a/chpp/services/wifi.c b/chpp/services/wifi.c
deleted file mode 100644
index eef5b2c5..00000000
--- a/chpp/services/wifi.c
+++ /dev/null
@@ -1,690 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/services/wifi.h"
-
-#include <inttypes.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/common/standard_uuids.h"
-#include "chpp/common/wifi.h"
-#include "chpp/common/wifi_types.h"
-#include "chpp/common/wifi_utils.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/services.h"
-#include "chre/pal/wifi.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppDispatchWifiRequest(void *serviceContext,
- uint8_t *buf, size_t len);
-static void chppWifiServiceNotifyReset(void *serviceContext);
-
-/************************************************
- * Private Definitions
- ***********************************************/
-
-/**
- * Configuration parameters for this service
- */
-static const struct ChppService kWifiServiceConfig = {
- .descriptor.uuid = CHPP_UUID_WIFI_STANDARD,
-
- // Human-readable name
- .descriptor.name = "WiFi",
-
- // Version
- .descriptor.version.major = 1,
- .descriptor.version.minor = 0,
- .descriptor.version.patch = 0,
-
- // Notifies service if CHPP is reset
- .resetNotifierFunctionPtr = &chppWifiServiceNotifyReset,
-
- // Client request dispatch function pointer
- .requestDispatchFunctionPtr = &chppDispatchWifiRequest,
-
- // Client notification dispatch function pointer
- .notificationDispatchFunctionPtr = NULL, // Not supported
-
- // Min length is the entire header
- .minLength = sizeof(struct ChppAppHeader),
-};
-
-/**
- * Structure to maintain state for the WiFi service and its Request/Response
- * (RR) functionality.
- */
-struct ChppWifiServiceState {
- struct ChppServiceState service; // WiFi service state
- const struct chrePalWifiApi *api; // WiFi PAL API
-
- // Based on chre/pal/wifi.h and chrePalWifiApi
- struct ChppRequestResponseState open; // Service init state
- struct ChppRequestResponseState close; // Service deinit state
- struct ChppRequestResponseState getCapabilities; // Get Capabilities state
- struct ChppRequestResponseState
- configureScanMonitorAsync; // Configure scan monitor state
- struct ChppRequestResponseState requestScanAsync; // Request scan state
- struct ChppRequestResponseState requestRangingAsync; // Request ranging state
-};
-
-// Note: The CHRE PAL API only allows for one definition - see comment in WWAN
-// service for details.
-// Note: There is no notion of a cookie in the CHRE WiFi API so we need to use
-// the global service state (gWifiServiceContext) directly in all callbacks.
-struct ChppWifiServiceState gWifiServiceContext;
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppWifiServiceOpen(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppWifiServiceClose(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppWifiServiceGetCapabilities(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppWifiServiceConfigureScanMonitorAsync(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len);
-static enum ChppAppErrorCode chppWifiServiceRequestScanAsync(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len);
-static enum ChppAppErrorCode chppWifiServiceRequestRangingAsync(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len);
-
-static void chppWifiServiceScanMonitorStatusChangeCallback(bool enabled,
- uint8_t errorCode);
-static void chppWifiServiceScanResponseCallback(bool pending,
- uint8_t errorCode);
-static void chppWifiServiceScanEventCallback(struct chreWifiScanEvent *event);
-static void chppWifiServiceRangingEventCallback(
- uint8_t errorCode, struct chreWifiRangingEvent *event);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Dispatches a client request from the transport layer that is determined to be
- * for the WiFi service. If the result of the dispatch is an error, this
- * function responds to the client with the same error.
- *
- * This function is called from the app layer using its function pointer given
- * during service registration.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppDispatchWifiRequest(void *serviceContext,
- uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- buf += sizeof(struct ChppAppHeader);
- len -= sizeof(struct ChppAppHeader);
-
- struct ChppWifiServiceState *wifiServiceContext =
- (struct ChppWifiServiceState *)serviceContext;
- struct ChppRequestResponseState *rRState = NULL;
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
- bool dispatched = true;
-
- switch (rxHeader->command) {
- case CHPP_WIFI_OPEN: {
- rRState = &wifiServiceContext->open;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWifiServiceOpen(wifiServiceContext, rxHeader);
- break;
- }
-
- case CHPP_WIFI_CLOSE: {
- rRState = &wifiServiceContext->close;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWifiServiceClose(wifiServiceContext, rxHeader);
- break;
- }
-
- case CHPP_WIFI_GET_CAPABILITIES: {
- rRState = &wifiServiceContext->getCapabilities;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWifiServiceGetCapabilities(wifiServiceContext, rxHeader);
- break;
- }
-
- case CHPP_WIFI_CONFIGURE_SCAN_MONITOR_ASYNC: {
- rRState = &wifiServiceContext->configureScanMonitorAsync;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWifiServiceConfigureScanMonitorAsync(wifiServiceContext,
- rxHeader, buf, len);
- break;
- }
-
- case CHPP_WIFI_REQUEST_SCAN_ASYNC: {
- rRState = &wifiServiceContext->requestScanAsync;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWifiServiceRequestScanAsync(wifiServiceContext, rxHeader, buf,
- len);
- break;
- }
-
- case CHPP_WIFI_REQUEST_RANGING_ASYNC: {
- rRState = &wifiServiceContext->requestRangingAsync;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWifiServiceRequestRangingAsync(wifiServiceContext, rxHeader,
- buf, len);
- break;
- }
-
- default: {
- dispatched = false;
- error = CHPP_APP_ERROR_INVALID_COMMAND;
- break;
- }
- }
-
- if (dispatched == true && error != CHPP_APP_ERROR_NONE) {
- // Request was dispatched but an error was returned. Close out
- // chppServiceTimestampRequest()
- chppServiceTimestampResponse(rRState);
- }
-
- return error;
-}
-
-/**
- * Initializes the WiFi service upon an open request from the client and
- * responds to the client with the result.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWifiServiceOpen(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader) {
- static const struct chrePalWifiCallbacks palCallbacks = {
- .scanMonitorStatusChangeCallback =
- chppWifiServiceScanMonitorStatusChangeCallback,
- .scanResponseCallback = chppWifiServiceScanResponseCallback,
- .scanEventCallback = chppWifiServiceScanEventCallback,
- .rangingEventCallback = chppWifiServiceRangingEventCallback,
- };
-
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (wifiServiceContext->service.openState == CHPP_OPEN_STATE_OPENED) {
- CHPP_LOGE("WiFi service already open");
- CHPP_DEBUG_ASSERT(false);
- error = CHPP_APP_ERROR_INVALID_COMMAND;
-
- } else if (!wifiServiceContext->api->open(
- wifiServiceContext->service.appContext->systemApi,
- &palCallbacks)) {
- CHPP_LOGE("WiFi PAL open failed");
- CHPP_DEBUG_ASSERT(false);
- error = CHPP_APP_ERROR_BEYOND_CHPP;
-
- } else {
- CHPP_LOGI("WiFi service opened");
- wifiServiceContext->service.openState = CHPP_OPEN_STATE_OPENED;
-
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppAppHeader);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- chppSendTimestampedResponseOrFail(&wifiServiceContext->service,
- &wifiServiceContext->open, response,
- responseLen);
- }
- }
-
- return error;
-}
-
-/**
- * Deinitializes the WiFi service.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWifiServiceClose(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader) {
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- wifiServiceContext->api->close();
- wifiServiceContext->service.openState = CHPP_OPEN_STATE_CLOSED;
-
- CHPP_LOGI("WiFi service closed");
-
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppAppHeader);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- chppSendTimestampedResponseOrFail(&wifiServiceContext->service,
- &wifiServiceContext->close, response,
- responseLen);
- }
- return error;
-}
-
-/**
- * Notifies the service of an incoming reset.
- *
- * @param serviceContext Maintains status for each service instance.
- */
-static void chppWifiServiceNotifyReset(void *serviceContext) {
- struct ChppWifiServiceState *wifiServiceContext =
- (struct ChppWifiServiceState *)serviceContext;
-
- if (wifiServiceContext->service.openState != CHPP_OPEN_STATE_OPENED) {
- CHPP_LOGW("WiFi service reset but wasn't open");
- } else {
- CHPP_LOGI("WiFi service reset. Closing");
- wifiServiceContext->service.openState = CHPP_OPEN_STATE_CLOSED;
- wifiServiceContext->api->close();
- }
-}
-
-/**
- * Retrieves a set of flags indicating the WiFi features supported by the
- * current implementation.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWifiServiceGetCapabilities(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader) {
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- struct ChppWifiGetCapabilitiesResponse *response =
- chppAllocServiceResponseFixed(requestHeader,
- struct ChppWifiGetCapabilitiesResponse);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- response->params.capabilities = wifiServiceContext->api->getCapabilities();
-
- CHPP_LOGD("chppWifiServiceGetCapabilities returning 0x%" PRIx32
- ", %" PRIuSIZE " bytes",
- response->params.capabilities, responseLen);
- chppSendTimestampedResponseOrFail(&wifiServiceContext->service,
- &wifiServiceContext->getCapabilities,
- response, responseLen);
- }
-
- return error;
-}
-
-/**
- * Configures whether scanEventCallback receives unsolicited scan results, i.e.
- * the results of scans not performed at the request of CHRE.
- *
- * This function returns an error code synchronously.
- * A subsequent call to chppWifiServiceScanMonitorStatusChangeCallback() will be
- * used to communicate the result of this request (as a service response).
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWifiServiceConfigureScanMonitorAsync(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len) {
- UNUSED_VAR(requestHeader);
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (len < sizeof(bool)) {
- error = CHPP_APP_ERROR_INVALID_ARG;
- } else {
- bool *enable = (bool *)buf;
- if (!wifiServiceContext->api->configureScanMonitor(*enable)) {
- error = CHPP_APP_ERROR_UNSPECIFIED;
- }
- }
-
- return error;
-}
-
-/**
- * Request that the WiFi chipset perform a scan, or deliver results from its
- * cache if the parameters allow for it.
- *
- * This function returns an error code synchronously.
- * A subsequent call to chppWifiServiceScanResponseCallback() will be used to
- * communicate the result of this request (as a service response).
- * A subsequent call to chppWifiServiceScanEventCallback() will be used to
- * communicate the scan results (as a service notification).
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWifiServiceRequestScanAsync(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len) {
- UNUSED_VAR(requestHeader);
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- struct chreWifiScanParams *chre =
- chppWifiScanParamsToChre((struct ChppWifiScanParams *)buf, len);
-
- if (chre == NULL) {
- CHPP_LOGE(
- "WifiServiceRequestScanAsync CHPP -> CHRE conversion failed. Input "
- "len=%" PRIuSIZE,
- len);
- error = CHPP_APP_ERROR_INVALID_ARG;
-
- } else {
- if (!wifiServiceContext->api->requestScan(chre)) {
- error = CHPP_APP_ERROR_UNSPECIFIED;
- }
-
- if (chre->frequencyListLen > 0) {
- void *frequencyList = CHPP_CONST_CAST_POINTER(chre->frequencyList);
- CHPP_FREE_AND_NULLIFY(frequencyList);
- }
- if (chre->ssidListLen > 0) {
- void *ssidList = CHPP_CONST_CAST_POINTER(chre->ssidList);
- CHPP_FREE_AND_NULLIFY(ssidList);
- }
- CHPP_FREE_AND_NULLIFY(chre);
- }
-
- return error;
-}
-
-/**
- * Request that the WiFi chipset perform RTT ranging against a set of access
- * points specified in params.
- *
- * This function returns an error code synchronously.
- * A subsequent call to chppWifiServiceRangingEventCallback() will be used to
- * communicate the ranging results (as a service notification).
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWifiServiceRequestRangingAsync(
- struct ChppWifiServiceState *wifiServiceContext,
- struct ChppAppHeader *requestHeader, uint8_t *buf, size_t len) {
- UNUSED_VAR(requestHeader);
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- struct chreWifiRangingParams *chre =
- chppWifiRangingParamsToChre((struct ChppWifiRangingParams *)buf, len);
-
- if (chre == NULL) {
- CHPP_LOGE(
- "WifiServiceRequestRangingAsync CHPP -> CHRE conversion failed. Input "
- "len=%" PRIuSIZE,
- len);
- error = CHPP_APP_ERROR_INVALID_ARG;
-
- } else {
- if (!wifiServiceContext->api->requestRanging(chre)) {
- error = CHPP_APP_ERROR_UNSPECIFIED;
-
- } else {
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppAppHeader);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- chppSendTimestampedResponseOrFail(
- &wifiServiceContext->service,
- &wifiServiceContext->requestRangingAsync, response, responseLen);
- }
- }
-
- if (chre->targetListLen > 0) {
- void *targetList = CHPP_CONST_CAST_POINTER(chre->targetList);
- CHPP_FREE_AND_NULLIFY(targetList);
- }
- CHPP_FREE_AND_NULLIFY(chre);
- }
-
- return error;
-}
-
-/**
- * PAL callback with the result of changes to the scan monitor registration
- * status requested via configureScanMonitor.
- *
- * @param enabled true if the scan monitor is currently active
- * @param errorCode An error code from enum chreError
- */
-static void chppWifiServiceScanMonitorStatusChangeCallback(bool enabled,
- uint8_t errorCode) {
- // Recreate request header
- struct ChppAppHeader requestHeader = {
- .handle = gWifiServiceContext.service.handle,
- .transaction = gWifiServiceContext.configureScanMonitorAsync.transaction,
- .command = CHPP_WIFI_CONFIGURE_SCAN_MONITOR_ASYNC,
- };
-
- struct ChppWifiConfigureScanMonitorAsyncResponse *response =
- chppAllocServiceResponseFixed(
- &requestHeader, struct ChppWifiConfigureScanMonitorAsyncResponse);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- CHPP_ASSERT(false);
-
- } else {
- response->params.enabled = enabled;
- response->params.errorCode = errorCode;
-
- chppSendTimestampedResponseOrFail(
- &gWifiServiceContext.service,
- &gWifiServiceContext.configureScanMonitorAsync, response, responseLen);
- }
-}
-
-/**
- * PAL callback with the result of a requestScan.
- *
- * @param pending true if the request was successful.
- * @param errorCode An error code from enum chreError.
- */
-static void chppWifiServiceScanResponseCallback(bool pending,
- uint8_t errorCode) {
- // Recreate request header
- struct ChppAppHeader requestHeader = {
- .handle = gWifiServiceContext.service.handle,
- .transaction = gWifiServiceContext.requestScanAsync.transaction,
- .command = CHPP_WIFI_REQUEST_SCAN_ASYNC,
- };
-
- struct ChppWifiRequestScanResponse *response = chppAllocServiceResponseFixed(
- &requestHeader, struct ChppWifiRequestScanResponse);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- CHPP_ASSERT(false);
-
- } else {
- response->params.pending = pending;
- response->params.errorCode = errorCode;
-
- chppSendTimestampedResponseOrFail(&gWifiServiceContext.service,
- &gWifiServiceContext.requestScanAsync,
- response, responseLen);
- }
-}
-
-/**
- * PAL callback with WiFi scan results.
- *
- * @param event Scan result data.
- */
-static void chppWifiServiceScanEventCallback(struct chreWifiScanEvent *event) {
- // Craft response per parser script
- struct ChppWifiScanEventWithHeader *notification = NULL;
- size_t notificationLen = 0;
-
- CHPP_DEBUG_ASSERT(chppCheckWifiScanEventNotification(event));
-
- if (!chppWifiScanEventFromChre(event, &notification, &notificationLen)) {
- CHPP_LOGE("ScanEvent conversion failed (OOM?). ID=%" PRIu8,
- gWifiServiceContext.requestScanAsync.transaction);
-
- notification = chppMalloc(sizeof(struct ChppAppHeader));
- if (notification == NULL) {
- CHPP_LOG_OOM();
- } else {
- notificationLen = sizeof(struct ChppAppHeader);
- }
- }
-
- if (notification != NULL) {
- notification->header.handle = gWifiServiceContext.service.handle;
- notification->header.type = CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION;
- notification->header.transaction =
- gWifiServiceContext.requestScanAsync.transaction;
- notification->header.error =
- (notificationLen > sizeof(struct ChppAppHeader))
- ? CHPP_APP_ERROR_NONE
- : CHPP_APP_ERROR_CONVERSION_FAILED;
- notification->header.command = CHPP_WIFI_REQUEST_SCAN_ASYNC;
-
- chppEnqueueTxDatagramOrFail(
- gWifiServiceContext.service.appContext->transportContext, notification,
- notificationLen);
- }
-
- gWifiServiceContext.api->releaseScanEvent(event);
-}
-
-/**
- * PAL callback with RTT ranging results from the WiFi module.
- *
- * @param errorCode An error code from enum chreError.
- * @param event Ranging data.
- */
-static void chppWifiServiceRangingEventCallback(
- uint8_t errorCode, struct chreWifiRangingEvent *event) {
- struct ChppWifiRangingEventWithHeader *notification = NULL;
- size_t notificationLen = 0;
-
- if (!chppWifiRangingEventFromChre(event, &notification, &notificationLen)) {
- CHPP_LOGE("RangingEvent conversion failed (OOM?) ID=%" PRIu8,
- gWifiServiceContext.requestRangingAsync.transaction);
-
- notification = chppMalloc(sizeof(struct ChppAppHeader));
- if (notification == NULL) {
- CHPP_LOG_OOM();
- } else {
- notificationLen = sizeof(struct ChppAppHeader);
- }
- }
-
- if (notification != NULL) {
- notification->header.handle = gWifiServiceContext.service.handle;
- notification->header.type = CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION;
- notification->header.transaction =
- gWifiServiceContext.requestRangingAsync.transaction;
- notification->header.error =
- (notificationLen > sizeof(struct ChppAppHeader))
- ? CHPP_APP_ERROR_NONE
- : CHPP_APP_ERROR_CONVERSION_FAILED;
- notification->header.command = CHPP_WIFI_REQUEST_RANGING_ASYNC;
-
- if (errorCode != CHRE_ERROR_NONE) {
- notification->header.error = CHPP_APP_ERROR_BEYOND_CHPP;
- notificationLen = MIN(notificationLen, sizeof(struct ChppAppHeader));
- }
-
- chppEnqueueTxDatagramOrFail(
- gWifiServiceContext.service.appContext->transportContext, notification,
- notificationLen);
- }
-
- gWifiServiceContext.api->releaseRangingEvent(event);
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppRegisterWifiService(struct ChppAppState *appContext) {
- gWifiServiceContext.api = chrePalWifiGetApi(CHRE_PAL_WIFI_API_V1_2);
-
- chppCheckWifiScanEventNotificationReset();
-
- if (gWifiServiceContext.api == NULL) {
- CHPP_LOGE(
- "WiFi PAL API version not compatible with CHPP. Cannot register WiFi "
- "service");
- CHPP_DEBUG_ASSERT(false);
-
- } else {
- gWifiServiceContext.service.appContext = appContext;
- gWifiServiceContext.service.handle = chppRegisterService(
- appContext, (void *)&gWifiServiceContext, &kWifiServiceConfig);
- CHPP_DEBUG_ASSERT(gWifiServiceContext.service.handle);
- }
-}
-
-void chppDeregisterWifiService(struct ChppAppState *appContext) {
- // TODO
-
- UNUSED_VAR(appContext);
-}
diff --git a/chpp/services/wwan.c b/chpp/services/wwan.c
deleted file mode 100644
index 90a48efe..00000000
--- a/chpp/services/wwan.c
+++ /dev/null
@@ -1,432 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chpp/services/wwan.h"
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/common/standard_uuids.h"
-#include "chpp/common/wwan.h"
-#include "chpp/common/wwan_types.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chpp/services.h"
-#include "chre/pal/wwan.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppDispatchWwanRequest(void *serviceContext,
- uint8_t *buf, size_t len);
-static void chppWwanServiceNotifyReset(void *serviceContext);
-
-/************************************************
- * Private Definitions
- ***********************************************/
-
-/**
- * Configuration parameters for this service
- */
-static const struct ChppService kWwanServiceConfig = {
- .descriptor.uuid = CHPP_UUID_WWAN_STANDARD,
-
- // Human-readable name
- .descriptor.name = "WWAN",
-
- // Version
- .descriptor.version.major = 1,
- .descriptor.version.minor = 0,
- .descriptor.version.patch = 0,
-
- // Notifies service if CHPP is reset
- .resetNotifierFunctionPtr = &chppWwanServiceNotifyReset,
-
- // Client request dispatch function pointer
- .requestDispatchFunctionPtr = &chppDispatchWwanRequest,
-
- // Client notification dispatch function pointer
- .notificationDispatchFunctionPtr = NULL, // Not supported
-
- // Min length is the entire header
- .minLength = sizeof(struct ChppAppHeader),
-};
-
-/**
- * Structure to maintain state for the WWAN service and its Request/Response
- * (RR) functionality.
- */
-struct ChppWwanServiceState {
- struct ChppServiceState service; // WWAN service state
- const struct chrePalWwanApi *api; // WWAN PAL API
-
- struct ChppRequestResponseState open; // Service init state
- struct ChppRequestResponseState close; // Service deinit state
- struct ChppRequestResponseState getCapabilities; // Get Capabilities state
- struct ChppRequestResponseState getCellInfoAsync; // Get CellInfo Async state
-};
-
-// Note: This global definition of gWwanServiceContext supports only one
-// instance of the CHPP WWAN service at a time. This limitation is primarily due
-// to the PAL API.
-// It would be possible to generate different API and callback pointers to
-// support multiple instances of the service or modify the PAL API to pass a
-// void* for context, but this is not necessary in the current version of CHPP.
-// In such case, wwanServiceContext would be allocated dynamically as part of
-// chppRegisterWwanService(), e.g.
-// struct ChppWwanServiceState *wwanServiceContext = chppMalloc(...);
-// instead of globally here.
-struct ChppWwanServiceState gWwanServiceContext;
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-static enum ChppAppErrorCode chppWwanServiceOpen(
- struct ChppWwanServiceState *wwanServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppWwanServiceClose(
- struct ChppWwanServiceState *wwanServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppWwanServiceGetCapabilities(
- struct ChppWwanServiceState *wwanServiceContext,
- struct ChppAppHeader *requestHeader);
-static enum ChppAppErrorCode chppWwanServiceGetCellInfoAsync(
- struct ChppWwanServiceState *wwanServiceContext,
- struct ChppAppHeader *requestHeader);
-
-static void chppWwanServiceCellInfoResultCallback(
- struct chreWwanCellInfoResult *result);
-
-/************************************************
- * Private Functions
- ***********************************************/
-
-/**
- * Dispatches a client request from the transport layer that is determined to be
- * for the WWAN service. If the result of the dispatch is an error, this
- * function responds to the client with the same error.
- *
- * This function is called from the app layer using its function pointer given
- * during service registration.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param buf Input data. Cannot be null.
- * @param len Length of input data in bytes.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppDispatchWwanRequest(void *serviceContext,
- uint8_t *buf, size_t len) {
- struct ChppAppHeader *rxHeader = (struct ChppAppHeader *)buf;
- struct ChppWwanServiceState *wwanServiceContext =
- (struct ChppWwanServiceState *)serviceContext;
- struct ChppRequestResponseState *rRState = NULL;
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
- bool dispatched = true;
-
- UNUSED_VAR(len);
-
- switch (rxHeader->command) {
- case CHPP_WWAN_OPEN: {
- rRState = &wwanServiceContext->open;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWwanServiceOpen(wwanServiceContext, rxHeader);
- break;
- }
-
- case CHPP_WWAN_CLOSE: {
- rRState = &wwanServiceContext->close;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWwanServiceClose(wwanServiceContext, rxHeader);
- break;
- }
-
- case CHPP_WWAN_GET_CAPABILITIES: {
- rRState = &wwanServiceContext->getCapabilities;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWwanServiceGetCapabilities(wwanServiceContext, rxHeader);
- break;
- }
-
- case CHPP_WWAN_GET_CELLINFO_ASYNC: {
- rRState = &wwanServiceContext->getCellInfoAsync;
- chppServiceTimestampRequest(rRState, rxHeader);
- error = chppWwanServiceGetCellInfoAsync(wwanServiceContext, rxHeader);
- break;
- }
-
- default: {
- dispatched = false;
- error = CHPP_APP_ERROR_INVALID_COMMAND;
- break;
- }
- }
-
- if (dispatched == true && error != CHPP_APP_ERROR_NONE) {
- // Request was dispatched but an error was returned. Close out
- // chppServiceTimestampRequest()
- chppServiceTimestampResponse(rRState);
- }
-
- return error;
-}
-
-/**
- * Initializes the WWAN service upon an open request from the client and
- * responds to the client with the result.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWwanServiceOpen(
- struct ChppWwanServiceState *wwanServiceContext,
- struct ChppAppHeader *requestHeader) {
- static const struct chrePalWwanCallbacks palCallbacks = {
- .cellInfoResultCallback = chppWwanServiceCellInfoResultCallback,
- };
-
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (wwanServiceContext->service.openState == CHPP_OPEN_STATE_OPENED) {
- CHPP_LOGE("WWAN service already open");
- CHPP_DEBUG_ASSERT(false);
- error = CHPP_APP_ERROR_INVALID_COMMAND;
-
- } else if (!wwanServiceContext->api->open(
- wwanServiceContext->service.appContext->systemApi,
- &palCallbacks)) {
- CHPP_LOGE("WWAN PAL open failed");
- CHPP_DEBUG_ASSERT(false);
- error = CHPP_APP_ERROR_BEYOND_CHPP;
-
- } else {
- CHPP_LOGI("WWAN service opened");
- wwanServiceContext->service.openState = CHPP_OPEN_STATE_OPENED;
-
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppAppHeader);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- chppSendTimestampedResponseOrFail(&wwanServiceContext->service,
- &wwanServiceContext->open, response,
- responseLen);
- }
- }
-
- return error;
-}
-
-/**
- * Deinitializes the WWAN service.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWwanServiceClose(
- struct ChppWwanServiceState *wwanServiceContext,
- struct ChppAppHeader *requestHeader) {
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- wwanServiceContext->api->close();
- wwanServiceContext->service.openState = CHPP_OPEN_STATE_CLOSED;
-
- CHPP_LOGI("WWAN service closed");
-
- struct ChppAppHeader *response =
- chppAllocServiceResponseFixed(requestHeader, struct ChppAppHeader);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- chppSendTimestampedResponseOrFail(&wwanServiceContext->service,
- &wwanServiceContext->close, response,
- responseLen);
- }
-
- return error;
-}
-
-/**
- * Notifies the service of an incoming reset.
- *
- * @param serviceContext Maintains status for each service instance.
- */
-static void chppWwanServiceNotifyReset(void *serviceContext) {
- struct ChppWwanServiceState *wwanServiceContext =
- (struct ChppWwanServiceState *)serviceContext;
-
- if (wwanServiceContext->service.openState != CHPP_OPEN_STATE_OPENED) {
- CHPP_LOGW("WWAN service reset but wasn't open");
- } else {
- CHPP_LOGI("WWAN service reset. Closing");
- wwanServiceContext->service.openState = CHPP_OPEN_STATE_CLOSED;
- wwanServiceContext->api->close();
- }
-}
-
-/**
- * Retrieves a set of flags indicating the WWAN features supported by the
- * current implementation.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWwanServiceGetCapabilities(
- struct ChppWwanServiceState *wwanServiceContext,
- struct ChppAppHeader *requestHeader) {
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- struct ChppWwanGetCapabilitiesResponse *response =
- chppAllocServiceResponseFixed(requestHeader,
- struct ChppWwanGetCapabilitiesResponse);
- size_t responseLen = sizeof(*response);
-
- if (response == NULL) {
- CHPP_LOG_OOM();
- error = CHPP_APP_ERROR_OOM;
- } else {
- response->params.capabilities = wwanServiceContext->api->getCapabilities();
-
- CHPP_LOGD("chppWwanServiceGetCapabilities returning 0x%" PRIx32
- ", %" PRIuSIZE " bytes",
- response->params.capabilities, responseLen);
- chppSendTimestampedResponseOrFail(&wwanServiceContext->service,
- &wwanServiceContext->getCapabilities,
- response, responseLen);
- }
-
- return error;
-}
-
-/**
- * Query information about the current serving cell and its neighbors in
- * response to a client request. This does not perform a network scan, but
- * should return state from the current network registration data stored in the
- * cellular modem.
- *
- * This function returns an error code synchronously. The requested cellular
- * information shall be returned asynchronously to the client via the
- * chppPlatformWwanCellInfoResultEvent() service response.
- *
- * @param serviceContext Maintains status for each service instance.
- * @param requestHeader App layer header of the request.
- *
- * @return Indicates the result of this function call.
- */
-static enum ChppAppErrorCode chppWwanServiceGetCellInfoAsync(
- struct ChppWwanServiceState *wwanServiceContext,
- struct ChppAppHeader *requestHeader) {
- UNUSED_VAR(requestHeader);
-
- enum ChppAppErrorCode error = CHPP_APP_ERROR_NONE;
-
- if (!wwanServiceContext->api->requestCellInfo()) {
- CHPP_LOGE(
- "WWAN requestCellInfo PAL API failed. Unable to register for callback");
- error = CHPP_APP_ERROR_UNSPECIFIED;
- }
-
- return error;
-}
-
-/**
- * PAL callback to provide the result of a prior Request Cell Info
- * (cellInfoResultCallback).
- *
- * @param result Scan results.
- */
-static void chppWwanServiceCellInfoResultCallback(
- struct chreWwanCellInfoResult *result) {
- // Recover state
- struct ChppRequestResponseState *rRState =
- &gWwanServiceContext.getCellInfoAsync;
- struct ChppWwanServiceState *wwanServiceContext =
- container_of(rRState, struct ChppWwanServiceState, getCellInfoAsync);
-
- // Craft response per parser script
- struct ChppWwanCellInfoResultWithHeader *response = NULL;
- size_t responseLen = 0;
- if (!chppWwanCellInfoResultFromChre(result, &response, &responseLen)) {
- CHPP_LOGE("CellInfo conversion failed (OOM?) ID=%" PRIu8,
- rRState->transaction);
-
- response = chppMalloc(sizeof(struct ChppAppHeader));
- if (response == NULL) {
- CHPP_LOG_OOM();
- } else {
- responseLen = sizeof(struct ChppAppHeader);
- }
- }
-
- if (response != NULL) {
- response->header.handle = wwanServiceContext->service.handle;
- response->header.type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
- response->header.transaction = rRState->transaction;
- response->header.error = (responseLen > sizeof(struct ChppAppHeader))
- ? CHPP_APP_ERROR_NONE
- : CHPP_APP_ERROR_CONVERSION_FAILED;
- response->header.command = CHPP_WWAN_GET_CELLINFO_ASYNC;
-
- chppSendTimestampedResponseOrFail(&wwanServiceContext->service, rRState,
- response, responseLen);
- }
-
- gWwanServiceContext.api->releaseCellInfoResult(result);
-}
-
-/************************************************
- * Public Functions
- ***********************************************/
-
-void chppRegisterWwanService(struct ChppAppState *appContext) {
- gWwanServiceContext.api = chrePalWwanGetApi(CHPP_PAL_WWAN_API_VERSION);
-
- if (gWwanServiceContext.api == NULL) {
- CHPP_LOGE(
- "WWAN PAL API version not compatible with CHPP. Cannot register WWAN "
- "service");
- CHPP_DEBUG_ASSERT(false);
-
- } else {
- gWwanServiceContext.service.appContext = appContext;
- gWwanServiceContext.service.handle = chppRegisterService(
- appContext, (void *)&gWwanServiceContext, &kWwanServiceConfig);
- CHPP_DEBUG_ASSERT(gWwanServiceContext.service.handle);
- }
-}
-
-void chppDeregisterWwanService(struct ChppAppState *appContext) {
- // TODO
-
- UNUSED_VAR(appContext);
-}
diff --git a/chpp/test/app_test.cpp b/chpp/test/app_test.cpp
deleted file mode 100644
index 248688c6..00000000
--- a/chpp/test/app_test.cpp
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <gtest/gtest.h>
-
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-#include <thread>
-
-#include "app_test_base.h"
-#include "chpp/app.h"
-#include "chpp/clients/discovery.h"
-#include "chpp/clients/loopback.h"
-#include "chpp/clients/timesync.h"
-#include "chpp/log.h"
-#include "chpp/transport.h"
-
-/*
- * Test suite for the CHPP Loopback client/service
- */
-namespace chpp {
-namespace {
-
-TEST_F(AppTestBase, SimpleStartStop) {
- // Simple test to make sure start/stop work threads work without crashing
- ASSERT_TRUE(mClientTransportContext.linkParams.linkEstablished);
- ASSERT_TRUE(mServiceTransportContext.linkParams.linkEstablished);
-}
-
-TEST_F(AppTestBase, TransportLayerLoopback) {
- // This tests the more limited transport-layer-looopback. In contrast,
- // the regular application-layer loopback test provides a more thorough test
- // and test results.
- constexpr size_t kTestLen = CHPP_TRANSPORT_TX_MTU_BYTES;
- uint8_t buf[kTestLen];
- for (size_t i = 0; i < kTestLen; i++) {
- buf[i] = (uint8_t)(i + 100);
- }
-
- std::this_thread::sleep_for(std::chrono::milliseconds(2000));
- CHPP_LOGI("Starting transport-layer loopback test (max buffer = %zu)...",
- kTestLen);
-
- EXPECT_EQ(CHPP_APP_ERROR_NONE,
- chppRunTransportLoopback(mClientAppContext.transportContext, buf,
- kTestLen));
- std::this_thread::sleep_for(std::chrono::milliseconds(300));
- EXPECT_EQ(CHPP_APP_ERROR_NONE,
- mClientAppContext.transportContext->loopbackResult);
-
- EXPECT_EQ(
- CHPP_APP_ERROR_NONE,
- chppRunTransportLoopback(mClientAppContext.transportContext, buf, 100));
- std::this_thread::sleep_for(std::chrono::milliseconds(300));
- EXPECT_EQ(CHPP_APP_ERROR_NONE,
- mClientAppContext.transportContext->loopbackResult);
-
- EXPECT_EQ(
- CHPP_APP_ERROR_NONE,
- chppRunTransportLoopback(mClientAppContext.transportContext, buf, 1));
- std::this_thread::sleep_for(std::chrono::milliseconds(300));
- EXPECT_EQ(CHPP_APP_ERROR_NONE,
- mClientAppContext.transportContext->loopbackResult);
-
- EXPECT_EQ(
- CHPP_APP_ERROR_INVALID_LENGTH,
- chppRunTransportLoopback(mClientAppContext.transportContext, buf, 0));
- std::this_thread::sleep_for(std::chrono::milliseconds(300));
- EXPECT_EQ(CHPP_APP_ERROR_INVALID_LENGTH,
- mClientAppContext.transportContext->loopbackResult);
-}
-
-TEST_F(AppTestBase, SimpleLoopback) {
- constexpr size_t kTestLen =
- CHPP_TRANSPORT_TX_MTU_BYTES - CHPP_LOOPBACK_HEADER_LEN;
- uint8_t buf[kTestLen];
- for (size_t i = 0; i < kTestLen; i++) {
- buf[i] = (uint8_t)(i + 100);
- }
-
- CHPP_LOGI(
- "Starting loopback test without fragmentation (max buffer = %zu)...",
- kTestLen);
-
- struct ChppLoopbackTestResult result;
-
- result = chppRunLoopbackTest(&mClientAppContext, buf, kTestLen);
- EXPECT_EQ(result.error, CHPP_APP_ERROR_NONE);
-
- result = chppRunLoopbackTest(&mClientAppContext, buf, 10);
- EXPECT_EQ(result.error, CHPP_APP_ERROR_NONE);
-
- result = chppRunLoopbackTest(&mClientAppContext, buf, 1);
- EXPECT_EQ(result.error, CHPP_APP_ERROR_NONE);
-
- result = chppRunLoopbackTest(&mClientAppContext, buf, 0);
- EXPECT_EQ(result.error, CHPP_APP_ERROR_INVALID_LENGTH);
-}
-
-TEST_F(AppTestBase, FragmentedLoopback) {
- constexpr size_t kTestLen = UINT16_MAX;
- uint8_t buf[kTestLen];
- for (size_t i = 0; i < kTestLen; i++) {
- buf[i] = (uint8_t)(
- (i % 251) + 64); // Arbitrary data. A modulus of 251, a prime number,
- // reduces the chance of alignment with the MTU.
- }
-
- CHPP_LOGI("Starting loopback test with fragmentation (max buffer = %zu)...",
- kTestLen);
-
- struct ChppLoopbackTestResult result;
-
- result = chppRunLoopbackTest(&mClientAppContext, buf, kTestLen);
- EXPECT_EQ(result.error, CHPP_APP_ERROR_NONE);
-
- result = chppRunLoopbackTest(&mClientAppContext, buf, 50000);
- EXPECT_EQ(result.error, CHPP_APP_ERROR_NONE);
-
- result = chppRunLoopbackTest(
- &mClientAppContext, buf,
- CHPP_TRANSPORT_TX_MTU_BYTES - CHPP_LOOPBACK_HEADER_LEN + 1);
- EXPECT_EQ(result.error, CHPP_APP_ERROR_NONE);
-}
-
-TEST_F(AppTestBase, Timesync) {
- constexpr uint64_t kMaxRtt = 2 * CHPP_NSEC_PER_MSEC; // in ms
- constexpr int64_t kMaxOffset = 1 * CHPP_NSEC_PER_MSEC; // in ms
-
- CHPP_LOGI("Starting timesync test...");
-
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
- EXPECT_TRUE(chppTimesyncMeasureOffset(&mClientAppContext));
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
-
- EXPECT_EQ(chppTimesyncGetResult(&mClientAppContext)->error,
- CHPP_APP_ERROR_NONE);
-
- EXPECT_LT(chppTimesyncGetResult(&mClientAppContext)->rttNs, kMaxRtt);
- EXPECT_NE(chppTimesyncGetResult(&mClientAppContext)->rttNs, 0);
-
- EXPECT_LT(chppTimesyncGetResult(&mClientAppContext)->offsetNs, kMaxOffset);
- EXPECT_GT(chppTimesyncGetResult(&mClientAppContext)->offsetNs, -kMaxOffset);
- EXPECT_NE(chppTimesyncGetResult(&mClientAppContext)->offsetNs, 0);
-}
-
-TEST_F(AppTestBase, DiscoveryMatched) {
- constexpr uint64_t kTimeoutMs = 5000;
- EXPECT_TRUE(chppWaitForDiscoveryComplete(&mClientAppContext, kTimeoutMs));
- EXPECT_TRUE(chppAreAllClientsMatched(&mClientAppContext));
-}
-
-} // namespace
-} // namespace chpp
diff --git a/chpp/test/app_test_base.cpp b/chpp/test/app_test_base.cpp
deleted file mode 100644
index 3c4ed83f..00000000
--- a/chpp/test/app_test_base.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "app_test_base.h"
-
-#include <gtest/gtest.h>
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-#include <thread>
-
-#include "chpp/app.h"
-#include "chpp/clients/discovery.h"
-#include "chpp/macros.h"
-#include "chpp/platform/utils.h"
-#include "chpp/transport.h"
-
-namespace chpp {
-namespace {
-
-void *workThread(void *arg) {
- ChppTransportState *context = static_cast<ChppTransportState *>(arg);
- pthread_setname_np(pthread_self(), context->linkParams.workThreadName);
-
- chppWorkThreadStart(context);
-
- return nullptr;
-}
-
-} // anonymous namespace
-
-void AppTestBase::SetUp() {
- chppClearTotalAllocBytes();
- memset(&mClientTransportContext.linkParams, 0,
- sizeof(mClientTransportContext.linkParams));
- memset(&mServiceTransportContext.linkParams, 0,
- sizeof(mServiceTransportContext.linkParams));
- // The linkSendThread in the link layer is a link "to" the remote end.
- mServiceTransportContext.linkParams.linkThreadName = "Link to client";
- mServiceTransportContext.linkParams.workThreadName = "Service work";
- mClientTransportContext.linkParams.linkThreadName = "Link to service";
- mClientTransportContext.linkParams.workThreadName = "Client work";
-
- mClientTransportContext.linkParams.remoteTransportContext =
- &mServiceTransportContext;
- mServiceTransportContext.linkParams.remoteTransportContext =
- &mClientTransportContext;
-
- struct ChppClientServiceSet set;
- memset(&set, 0, sizeof(set));
- set.wifiClient = 1;
- set.gnssClient = 1;
- set.wwanClient = 1;
- set.loopbackClient = 1;
-
- chppTransportInit(&mClientTransportContext, &mClientAppContext);
- chppAppInitWithClientServiceSet(&mClientAppContext, &mClientTransportContext,
- set);
- pthread_create(&mClientWorkThread, NULL, workThread,
- &mClientTransportContext);
-
- // Wait a bit to emulate the scenario where the remote is not yet up
- std::this_thread::sleep_for(std::chrono::milliseconds(450));
-
- memset(&set, 0, sizeof(set));
- set.wifiService = 1;
- set.gnssService = 1;
- set.wwanService = 1;
-
- chppTransportInit(&mServiceTransportContext, &mServiceAppContext);
- chppAppInitWithClientServiceSet(&mServiceAppContext,
- &mServiceTransportContext, set);
- pthread_create(&mServiceWorkThread, NULL, workThread,
- &mServiceTransportContext);
-
- mClientTransportContext.linkParams.linkEstablished = true;
- mServiceTransportContext.linkParams.linkEstablished = true;
-
- constexpr uint64_t kResetWaitTimeMs = 1500;
- chppTransportWaitForResetComplete(&mClientTransportContext, kResetWaitTimeMs);
-
- constexpr uint64_t kDiscoveryWaitTimeMs = 5000;
- chppWaitForDiscoveryComplete(&mClientAppContext, kDiscoveryWaitTimeMs);
-}
-
-void AppTestBase::TearDown() {
- // Stop the work threads first to avoid any transient activity.
- chppWorkThreadStop(&mClientTransportContext);
- chppWorkThreadStop(&mServiceTransportContext);
- pthread_join(mClientWorkThread, NULL);
- pthread_join(mServiceWorkThread, NULL);
-
- chppAppDeinit(&mClientAppContext);
- chppTransportDeinit(&mClientTransportContext);
-
- chppAppDeinit(&mServiceAppContext);
- chppTransportDeinit(&mServiceTransportContext);
-
- EXPECT_EQ(chppGetTotalAllocBytes(), 0);
-}
-
-} // namespace chpp
diff --git a/chpp/test/app_test_base.h b/chpp/test/app_test_base.h
deleted file mode 100644
index a3b63e64..00000000
--- a/chpp/test/app_test_base.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <gtest/gtest.h>
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-#include <thread>
-
-#include "chpp/app.h"
-#include "chpp/clients/loopback.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/transport.h"
-
-namespace chpp {
-
-/*
- * A base class for all CHPP app level tests.
- */
-class AppTestBase : public testing::Test {
- protected:
- void SetUp() override;
- void TearDown() override;
-
- ChppTransportState mClientTransportContext = {};
- ChppAppState mClientAppContext = {};
-
- ChppTransportState mServiceTransportContext = {};
- ChppAppState mServiceAppContext = {};
-
- pthread_t mClientWorkThread;
- pthread_t mServiceWorkThread;
-};
-
-} // namespace chpp
diff --git a/chpp/test/clients_test.cpp b/chpp/test/clients_test.cpp
deleted file mode 100644
index cd6a0487..00000000
--- a/chpp/test/clients_test.cpp
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 "clients_test.h"
-
-#include <gtest/gtest.h>
-
-#include <string.h>
-#include <thread>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chpp/platform/utils.h"
-#include "chpp/services.h"
-#include "chpp/time.h"
-#include "chpp/transport.h"
-#include "chre/pal/wwan.h"
-
-class ClientsTest : public testing::Test {
- protected:
- void SetUp() override {
- chppClearTotalAllocBytes();
- memset(&mTransportContext.linkParams, 0,
- sizeof(mTransportContext.linkParams));
- mTransportContext.linkParams.linkEstablished = true;
- chppTransportInit(&mTransportContext, &mAppContext);
- chppAppInit(&mAppContext, &mTransportContext);
- mClientState =
- (struct ChppClientState *)mAppContext.registeredClientContexts[0];
- chppClientInit(mClientState, CHPP_HANDLE_NEGOTIATED_RANGE_START);
-
- mTransportContext.resetState = CHPP_RESET_STATE_NONE;
- }
-
- void TearDown() override {
- chppAppDeinit(&mAppContext);
- chppTransportDeinit(&mTransportContext);
-
- EXPECT_EQ(chppGetTotalAllocBytes(), 0);
- }
-
- struct ChppTransportState mTransportContext;
- struct ChppAppState mAppContext;
- struct ChppClient mClient;
- struct ChppClientState *mClientState;
- struct ChppRequestResponseState mRRState;
-};
-
-void getClientRRStateInputCheck(struct ChppClientState *clientState,
- struct ChppAppHeader *header) {
- ASSERT_TRUE(clientState != NULL);
- uint8_t clientIdx = clientState->index;
-
- ASSERT_TRUE(clientState->appContext != NULL);
- ASSERT_TRUE(clientState->appContext->registeredClients != NULL);
- ASSERT_TRUE(clientState->appContext->registeredClients[clientIdx] != NULL);
- ASSERT_TRUE(
- clientState->appContext->registeredClientStates[clientIdx]->rRStates !=
- NULL);
- ASSERT_LT(
- header->command,
- clientState->appContext->registeredClients[clientIdx]->rRStateCount);
-}
-
-struct ChppRequestResponseState *getClientRRState(
- struct ChppClientState *clientState, struct ChppAppHeader *header) {
- getClientRRStateInputCheck(clientState, header);
-
- uint8_t clientIdx = clientState->index;
- return &(clientState->appContext->registeredClientStates[clientIdx]
- ->rRStates[header->command]);
-}
-
-void isTimeoutAsExpected(uint64_t timeoutTimeNs, uint64_t expectedTimeNs) {
- uint64_t kJitterNs = 10 * CHPP_NSEC_PER_MSEC;
-
- if (expectedTimeNs == CHPP_TIME_MAX) {
- EXPECT_EQ(timeoutTimeNs, expectedTimeNs);
- } else {
- EXPECT_GE(timeoutTimeNs, expectedTimeNs);
- EXPECT_LE(timeoutTimeNs, expectedTimeNs + kJitterNs);
- }
-}
-
-void registerAndValidateRequestForTimeout(struct ChppClientState *clientState,
- struct ChppAppHeader *header,
- uint64_t timeoutNs,
- uint64_t expectedTimeNs) {
- struct ChppRequestResponseState *rRState =
- getClientRRState(clientState, header);
- chppClientTimestampRequest(clientState, rRState, header, timeoutNs);
-
- isTimeoutAsExpected(clientState->appContext->nextRequestTimeoutNs,
- expectedTimeNs);
-}
-
-void registerAndValidateResponseForTimeout(struct ChppClientState *clientState,
- const struct ChppAppHeader *header,
- uint64_t expectedTimeNs) {
- ASSERT_FALSE(clientState == NULL);
- uint8_t clientIdx = clientState->index;
-
- ASSERT_FALSE(clientState->appContext == NULL);
- ASSERT_FALSE(clientState->appContext->registeredClients == NULL);
- ASSERT_FALSE(clientState->appContext->registeredClients[clientIdx] == NULL);
- ASSERT_FALSE(
- clientState->appContext->registeredClientStates[clientIdx]->rRStates ==
- NULL);
- ASSERT_LT(
- header->command,
- clientState->appContext->registeredClients[clientIdx]->rRStateCount);
-
- struct ChppRequestResponseState *rRState =
- &(clientState->appContext->registeredClientStates[clientIdx]
- ->rRStates[header->command]);
- chppClientTimestampResponse(clientState, rRState, header);
-
- isTimeoutAsExpected(clientState->appContext->nextRequestTimeoutNs,
- expectedTimeNs);
-}
-
-void validateTimeoutResponse(const struct ChppAppHeader *request,
- const struct ChppAppHeader *response) {
- ASSERT_TRUE(request != NULL);
- ASSERT_TRUE(response != NULL);
-
- EXPECT_EQ(response->handle, request->handle);
- EXPECT_EQ(response->type, CHPP_MESSAGE_TYPE_SERVICE_RESPONSE);
- EXPECT_EQ(response->transaction, request->transaction);
- EXPECT_EQ(response->error, CHPP_APP_ERROR_TIMEOUT);
- EXPECT_EQ(response->command, request->command);
-}
-
-TEST_F(ClientsTest, RequestResponseTimestampValid) {
- struct ChppAppHeader *reqHeader =
- chppAllocClientRequestCommand(mClientState, 0 /* command */);
- chppClientTimestampRequest(mClientState, &mRRState, reqHeader,
- CHPP_CLIENT_REQUEST_TIMEOUT_INFINITE);
-
- struct ChppAppHeader *respHeader =
- chppAllocServiceResponse(reqHeader, sizeof(*reqHeader));
- ASSERT_TRUE(chppClientTimestampResponse(mClientState, &mRRState, respHeader));
-
- chppFree(reqHeader);
- chppFree(respHeader);
-}
-
-TEST_F(ClientsTest, RequestResponseTimestampDuplicate) {
- struct ChppAppHeader *reqHeader =
- chppAllocClientRequestCommand(mClientState, 0 /* command */);
- chppClientTimestampRequest(mClientState, &mRRState, reqHeader,
- CHPP_CLIENT_REQUEST_TIMEOUT_INFINITE);
-
- struct ChppAppHeader *respHeader =
- chppAllocServiceResponse(reqHeader, sizeof(*reqHeader));
- ASSERT_TRUE(chppClientTimestampResponse(mClientState, &mRRState, respHeader));
- ASSERT_FALSE(
- chppClientTimestampResponse(mClientState, &mRRState, respHeader));
-
- chppFree(reqHeader);
- chppFree(respHeader);
-}
-
-TEST_F(ClientsTest, RequestResponseTimestampInvalidId) {
- struct ChppAppHeader *reqHeader =
- chppAllocClientRequestCommand(mClientState, 0 /* command */);
- chppClientTimestampRequest(mClientState, &mRRState, reqHeader,
- CHPP_CLIENT_REQUEST_TIMEOUT_INFINITE);
-
- struct ChppAppHeader *newReqHeader =
- chppAllocClientRequestCommand(mClientState, 0 /* command */);
- struct ChppAppHeader *respHeader =
- chppAllocServiceResponse(newReqHeader, sizeof(*reqHeader));
- ASSERT_FALSE(
- chppClientTimestampResponse(mClientState, &mRRState, respHeader));
-
- chppFree(reqHeader);
- chppFree(newReqHeader);
- chppFree(respHeader);
-}
-
-TEST_F(ClientsTest, RequestTimeoutAddRemoveSingle) {
- EXPECT_EQ(mAppContext.nextRequestTimeoutNs, CHPP_TIME_MAX);
-
- struct ChppAppHeader *reqHeader =
- chppAllocClientRequestCommand(mClientState, 1 /* command */);
-
- uint64_t time = chppGetCurrentTimeNs();
- uint64_t timeout = 1000 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader, timeout,
- time + timeout);
-
- EXPECT_TRUE(
- chppTransportGetClientRequestTimeoutResponse(&mTransportContext) == NULL);
-
- registerAndValidateResponseForTimeout(mClientState, reqHeader, CHPP_TIME_MAX);
-
- chppFree(reqHeader);
-}
-
-TEST_F(ClientsTest, RequestTimeoutAddRemoveMultiple) {
- struct ChppAppHeader *reqHeader1 =
- chppAllocClientRequestCommand(mClientState, 0 /* command */);
- struct ChppAppHeader *reqHeader2 =
- chppAllocClientRequestCommand(mClientState, 1 /* command */);
- struct ChppAppHeader *reqHeader3 =
- chppAllocClientRequestCommand(mClientState, 2 /* command */);
-
- EXPECT_EQ(mAppContext.nextRequestTimeoutNs, CHPP_TIME_MAX);
-
- uint64_t time1 = chppGetCurrentTimeNs();
- uint64_t timeout1 = 2000 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader1, timeout1,
- time1 + timeout1);
-
- uint64_t time2 = chppGetCurrentTimeNs();
- uint64_t timeout2 = 4000 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader2, timeout2,
- time1 + timeout1);
-
- uint64_t time3 = chppGetCurrentTimeNs();
- uint64_t timeout3 = 3000 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader3, timeout3,
- time1 + timeout1);
-
- registerAndValidateResponseForTimeout(mClientState, reqHeader1,
- time3 + timeout3);
-
- EXPECT_TRUE(
- chppTransportGetClientRequestTimeoutResponse(&mTransportContext) == NULL);
-
- uint64_t time4 = chppGetCurrentTimeNs();
- uint64_t timeout4 = 1000 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader1, timeout4,
- time4 + timeout4);
-
- registerAndValidateResponseForTimeout(mClientState, reqHeader1,
- time3 + timeout3);
-
- registerAndValidateResponseForTimeout(mClientState, reqHeader3,
- time2 + timeout2);
-
- registerAndValidateResponseForTimeout(mClientState, reqHeader2,
- CHPP_TIME_MAX);
-
- EXPECT_TRUE(
- chppTransportGetClientRequestTimeoutResponse(&mTransportContext) == NULL);
-
- chppFree(reqHeader1);
- chppFree(reqHeader2);
- chppFree(reqHeader3);
-}
-
-TEST_F(ClientsTest, DuplicateRequestTimeoutResponse) {
- EXPECT_EQ(mAppContext.nextRequestTimeoutNs, CHPP_TIME_MAX);
-
- struct ChppAppHeader *reqHeader =
- chppAllocClientRequestCommand(mClientState, 1 /* command */);
-
- uint64_t time1 = chppGetCurrentTimeNs();
- uint64_t timeout1 = 200 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader, timeout1,
- time1 + timeout1);
-
- std::this_thread::sleep_for(std::chrono::nanoseconds(timeout1 / 2));
-
- uint64_t time2 = chppGetCurrentTimeNs();
- uint64_t timeout2 = 200 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader, timeout2,
- time2 + timeout2);
-
- std::this_thread::sleep_for(
- std::chrono::nanoseconds(timeout1 + time1 - chppGetCurrentTimeNs()));
- // First request would have timed out but superseded by second request
- ASSERT_GT(mAppContext.nextRequestTimeoutNs, chppGetCurrentTimeNs());
-
- std::this_thread::sleep_for(
- std::chrono::nanoseconds(timeout2 + time2 - chppGetCurrentTimeNs()));
- // Second request should have timed out
- ASSERT_LT(mAppContext.nextRequestTimeoutNs, chppGetCurrentTimeNs());
-
- struct ChppAppHeader *response =
- chppTransportGetClientRequestTimeoutResponse(&mTransportContext);
- validateTimeoutResponse(reqHeader, response);
- if (response != NULL) {
- chppFree(response);
- }
-
- registerAndValidateResponseForTimeout(mClientState, reqHeader, CHPP_TIME_MAX);
- EXPECT_TRUE(
- chppTransportGetClientRequestTimeoutResponse(&mTransportContext) == NULL);
-
- chppFree(reqHeader);
-}
-
-TEST_F(ClientsTest, RequestTimeoutResponse) {
- EXPECT_EQ(mAppContext.nextRequestTimeoutNs, CHPP_TIME_MAX);
-
- struct ChppAppHeader *reqHeader1 =
- chppAllocClientRequestCommand(mClientState, 1 /* command */);
- struct ChppAppHeader *reqHeader2 =
- chppAllocClientRequestCommand(mClientState, 2 /* command */);
-
- uint64_t time1 = chppGetCurrentTimeNs();
- uint64_t timeout1 = 200 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader1, timeout1,
- time1 + timeout1);
-
- std::this_thread::sleep_for(std::chrono::nanoseconds(timeout1));
- ASSERT_LT(mAppContext.nextRequestTimeoutNs, chppGetCurrentTimeNs());
-
- struct ChppAppHeader *response =
- chppTransportGetClientRequestTimeoutResponse(&mTransportContext);
- validateTimeoutResponse(reqHeader1, response);
- if (response != NULL) {
- chppFree(response);
- }
-
- registerAndValidateResponseForTimeout(mClientState, reqHeader1,
- CHPP_TIME_MAX);
- EXPECT_TRUE(
- chppTransportGetClientRequestTimeoutResponse(&mTransportContext) == NULL);
-
- uint64_t time2 = chppGetCurrentTimeNs();
- uint64_t timeout2 = 200 * CHPP_NSEC_PER_MSEC;
- registerAndValidateRequestForTimeout(mClientState, reqHeader2, timeout2,
- time2 + timeout2);
-
- std::this_thread::sleep_for(std::chrono::nanoseconds(timeout2));
- ASSERT_LT(mAppContext.nextRequestTimeoutNs, chppGetCurrentTimeNs());
-
- response = chppTransportGetClientRequestTimeoutResponse(&mTransportContext);
- validateTimeoutResponse(reqHeader2, response);
- if (response != NULL) {
- chppFree(response);
- }
-
- chppFree(reqHeader1);
- chppFree(reqHeader2);
-}
diff --git a/chpp/test/clients_test.h b/chpp/test/clients_test.h
deleted file mode 100644
index d7caa321..00000000
--- a/chpp/test/clients_test.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 CHPP_CLIENTS_TEST_H_
-#define CHPP_CLIENTS_TEST_H_
-
-#include "chpp/app.h"
-#include "chpp/transport.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/************************************************
- * Functions necessary for unit testing
- ***********************************************/
-
-struct ChppAppHeader *chppTransportGetClientRequestTimeoutResponse(
- struct ChppTransportState *context);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHPP_CLIENTS_TEST_H_
diff --git a/chpp/test/transport_test.cpp b/chpp/test/transport_test.cpp
index 8eb8ddee..1fcf7035 100644
--- a/chpp/test/transport_test.cpp
+++ b/chpp/test/transport_test.cpp
@@ -14,39 +14,15 @@
* limitations under the License.
*/
-#include "transport_test.h"
-
#include <gtest/gtest.h>
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
+#include <stdio.h>
#include <string.h>
-#include <thread>
-#include "chpp/app.h"
-#include "chpp/common/discovery.h"
-#include "chpp/common/gnss.h"
-#include "chpp/common/gnss_types.h"
-#include "chpp/common/standard_uuids.h"
-#include "chpp/common/wifi.h"
-#include "chpp/common/wifi_types.h"
-#include "chpp/common/wwan.h"
-#include "chpp/crc.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chpp/platform/utils.h"
-#include "chpp/services/discovery.h"
-#include "chpp/services/loopback.h"
#include "chpp/transport.h"
-#include "chre/pal/wwan.h"
+#include "transport_test.h"
namespace {
-// Preamble as separate bytes for testing
-constexpr uint8_t kChppPreamble0 = 0x68;
-constexpr uint8_t kChppPreamble1 = 0x43;
-
// Max size of payload sent to chppRxDataCb (bytes)
constexpr size_t kMaxChunkSize = 20000;
@@ -55,10 +31,22 @@ constexpr size_t kMaxPacketSize = kMaxChunkSize + CHPP_PREAMBLE_LEN_BYTES +
sizeof(ChppTransportFooter);
// Input sizes to test the entire range of sizes with a few tests
-constexpr int kChunkSizes[] = {0, 1, 2, 3, 4, 21, 100, 1000, 10001, 20000};
+constexpr int kChunkSizes[] = {0, 1, 2, 3, 4, 5, 6,
+ 7, 8, 10, 16, 20, 30, 40,
+ 51, 100, 201, 1000, 10001, 20000};
-// Number of services
-constexpr int kServiceCount = 3;
+/**
+ * Adds a CHPP preamble to the specified location of buf
+ *
+ * @param buf The CHPP preamble will be added to buf
+ * @param loc Location of buf where the CHPP preamble will be added
+ */
+void chppAddPreamble(uint8_t *buf, size_t loc) {
+ for (size_t i = 0; i < CHPP_PREAMBLE_LEN_BYTES; i++) {
+ buf[loc + i] = static_cast<uint8_t>(
+ CHPP_PREAMBLE_DATA >> (CHPP_PREAMBLE_LEN_BYTES - 1 - i) & 0xff);
+ }
+}
/*
* Test suite for the CHPP Transport Layer
@@ -66,304 +54,21 @@ constexpr int kServiceCount = 3;
class TransportTests : public testing::TestWithParam<int> {
protected:
void SetUp() override {
- chppClearTotalAllocBytes();
- memset(&mTransportContext.linkParams, 0,
- sizeof(mTransportContext.linkParams));
- mTransportContext.linkParams.linkEstablished = true;
- chppTransportInit(&mTransportContext, &mAppContext);
- chppAppInit(&mAppContext, &mTransportContext);
-
- mTransportContext.resetState = CHPP_RESET_STATE_NONE;
-
- // Make sure CHPP has a correct count of the number of registered services
- // on this platform, (in this case, 1,) as registered in the function
- // chppRegisterCommonServices().
- ASSERT_EQ(mAppContext.registeredServiceCount, kServiceCount);
+ chppTransportInit(&context);
}
- void TearDown() override {
- chppAppDeinit(&mAppContext);
- chppTransportDeinit(&mTransportContext);
-
- EXPECT_EQ(chppGetTotalAllocBytes(), 0);
- }
-
- ChppTransportState mTransportContext = {};
- ChppAppState mAppContext = {};
- uint8_t mBuf[kMaxPacketSize] = {};
+ ChppTransportState context = {};
+ uint8_t buf[kMaxPacketSize] = {};
};
/**
- * Wait for chppTransportDoWork() to finish after it is notified by
- * chppEnqueueTxPacket to run.
- *
- * TODO: (b/177616847) Improve test robustness / synchronization without adding
- * overhead to CHPP
- */
-void WaitForTransport(struct ChppTransportState *transportContext) {
- // Wait for linkParams.notifier.signal to be triggered and processed
- volatile uint32_t k = 1;
- while (transportContext->linkParams.notifier.signal == 0 && k > 0) {
- k++;
- }
- while (transportContext->linkParams.notifier.signal != 0 && k > 0) {
- k++;
- }
- ASSERT_FALSE(k == 0);
- while (k < UINT16_MAX) {
- k++;
- }
- while (k > 0) {
- k--;
- }
-
- // Should have reset loc and length for next packet / datagram
- EXPECT_EQ(transportContext->rxStatus.locInDatagram, 0);
- EXPECT_EQ(transportContext->rxDatagram.length, 0);
-}
-
-/**
- * Validates a ChppTestResponse. Since the error field within the
- * ChppAppHeader struct is optional (and not used for common services), this
- * function returns the error field to be checked if desired, depending on the
- * service.
- *
- * @param buf Buffer containing response.
- * @param ackSeq Ack sequence to be verified.
- * @param handle Handle number to be verified
- * @param transactionID Transaction ID to be verified.
- *
- * @return The error field within the ChppAppHeader struct that is used by some
- * but not all services.
- */
-uint8_t validateChppTestResponse(void *buf, uint8_t ackSeq, uint8_t handle,
- uint8_t transactionID) {
- struct ChppTestResponse *response = (ChppTestResponse *)buf;
-
- // Check preamble
- EXPECT_EQ(response->preamble0, kChppPreamble0);
- EXPECT_EQ(response->preamble1, kChppPreamble1);
-
- // Check response transport headers
- EXPECT_EQ(response->transportHeader.packetCode, CHPP_TRANSPORT_ERROR_NONE);
- EXPECT_EQ(response->transportHeader.ackSeq, ackSeq);
-
- // Check response app headers
- EXPECT_EQ(response->appHeader.handle, handle);
- EXPECT_EQ(response->appHeader.type, CHPP_MESSAGE_TYPE_SERVICE_RESPONSE);
- EXPECT_EQ(response->appHeader.transaction, transactionID);
-
- // Return optional response error to be checked if desired
- return response->appHeader.error;
-}
-
-/**
- * Aborts a packet and validates state.
- *
- * @param transportcontext Maintains status for each transport layer instance.
- */
-void endAndValidatePacket(struct ChppTransportState *transportContext) {
- chppRxPacketCompleteCb(transportContext);
- EXPECT_EQ(transportContext->rxStatus.state, CHPP_STATE_PREAMBLE);
- EXPECT_EQ(transportContext->rxStatus.locInDatagram, 0);
- EXPECT_EQ(transportContext->rxDatagram.length, 0);
-}
-
-/**
- * Adds a preamble to a certain location in a buffer, and increases the location
- * accordingly, to account for the length of the added preamble.
- *
- * @param buf Buffer.
- * @param location Location to add the preamble, which its value will be
- * increased accordingly.
- */
-void addPreambleToBuf(uint8_t *buf, size_t *location) {
- buf[(*location)++] = kChppPreamble0;
- buf[(*location)++] = kChppPreamble1;
-}
-
-/**
- * Adds a transport header (with default values) to a certain location in a
- * buffer, and increases the location accordingly, to account for the length of
- * the added transport header.
- *
- * @param buf Buffer.
- * @param location Location to add the transport header, which its value will be
- * increased accordingly.
- *
- * @return Pointer to the added transport header (e.g. to modify its fields).
- */
-ChppTransportHeader *addTransportHeaderToBuf(uint8_t *buf, size_t *location) {
- size_t oldLoc = *location;
-
- // Default values for initial, minimum size request packet
- ChppTransportHeader transHeader = {};
- transHeader.flags = CHPP_TRANSPORT_FLAG_FINISHED_DATAGRAM;
- transHeader.packetCode = CHPP_TRANSPORT_ERROR_NONE;
- transHeader.ackSeq = 1;
- transHeader.seq = 0;
- transHeader.length = sizeof(ChppAppHeader);
- transHeader.reserved = 0;
-
- memcpy(&buf[*location], &transHeader, sizeof(transHeader));
- *location += sizeof(transHeader);
-
- return (ChppTransportHeader *)&buf[oldLoc];
-}
-
-/**
- * Adds an app header (with default values) to a certain location in a buffer,
- * and increases the location accordingly, to account for the length of the
- * added app header.
- *
- * @param buf Buffer.
- * @param location Location to add the app header, which its value will be
- * increased accordingly.
- *
- * @return Pointer to the added app header (e.g. to modify its fields).
- */
-ChppAppHeader *addAppHeaderToBuf(uint8_t *buf, size_t *location) {
- size_t oldLoc = *location;
-
- // Default values - to be updated later as necessary
- ChppAppHeader appHeader = {};
- appHeader.handle = CHPP_HANDLE_NEGOTIATED_RANGE_START;
- appHeader.type = CHPP_MESSAGE_TYPE_CLIENT_REQUEST;
- appHeader.transaction = 0;
- appHeader.error = CHPP_APP_ERROR_NONE;
- appHeader.command = 0;
-
- memcpy(&buf[*location], &appHeader, sizeof(appHeader));
- *location += sizeof(appHeader);
-
- return (ChppAppHeader *)&buf[oldLoc];
-}
-
-/**
- * Adds a transport footer to a certain location in a buffer, and increases the
- * location accordingly, to account for the length of the added preamble.
- *
- * @param buf Buffer.
- * @param location Location to add the footer. The value of location will be
- * increased accordingly.
- *
- */
-void addTransportFooterToBuf(uint8_t *buf, size_t *location) {
- uint32_t *checksum = (uint32_t *)&buf[*location];
-
- *checksum = chppCrc32(0, &buf[CHPP_PREAMBLE_LEN_BYTES],
- *location - CHPP_PREAMBLE_LEN_BYTES);
-
- *location += sizeof(ChppTransportFooter);
-}
-
-/**
- * Opens a service and checks to make sure it was opened correctly.
- *
- * @param transportContext Transport layer context.
- * @param buf Buffer.
- * @param ackSeq Ack sequence of the packet to be sent out
- * @param seq Sequence number of the packet to be sent out.
- * @param handle Handle of the service to be opened.
- * @param transactionID Transaction ID for the open request.
- * @param command Open command.
- */
-void openService(ChppTransportState *transportContext, uint8_t *buf,
- uint8_t ackSeq, uint8_t seq, uint8_t handle,
- uint8_t transactionID, uint16_t command) {
- size_t len = 0;
-
- addPreambleToBuf(buf, &len);
-
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(buf, &len);
- transHeader->ackSeq = ackSeq;
- transHeader->seq = seq;
-
- ChppAppHeader *appHeader = addAppHeaderToBuf(buf, &len);
- appHeader->handle = handle;
- appHeader->transaction = transactionID;
- appHeader->command = command;
-
- addTransportFooterToBuf(buf, &len);
-
- // Send header + payload (if any) + footer
- EXPECT_TRUE(chppRxDataCb(transportContext, buf, len));
-
- // Check for correct state
- uint8_t nextSeq = transHeader->seq + 1;
- EXPECT_EQ(transportContext->rxStatus.expectedSeq, nextSeq);
- EXPECT_EQ(transportContext->rxStatus.state, CHPP_STATE_PREAMBLE);
-
- // Wait for response
- WaitForTransport(transportContext);
-
- // Validate common response fields
- EXPECT_EQ(validateChppTestResponse(transportContext->pendingTxPacket.payload,
- nextSeq, handle, transactionID),
- CHPP_APP_ERROR_NONE);
-
- // Check response length
- EXPECT_EQ(sizeof(ChppTestResponse), CHPP_PREAMBLE_LEN_BYTES +
- sizeof(ChppTransportHeader) +
- sizeof(ChppAppHeader));
- EXPECT_EQ(transportContext->pendingTxPacket.length,
- sizeof(ChppTestResponse) + sizeof(ChppTransportFooter));
-}
-
-/**
- * Sends a command to a service and checks for errors.
- *
- * @param transportContext Transport layer context.
- * @param buf Buffer.
- * @param ackSeq Ack sequence of the packet to be sent out
- * @param seq Sequence number of the packet to be sent out.
- * @param handle Handle of the service to be opened.
- * @param transactionID Transaction ID for the open request.
- * @param command Command to be sent.
- */
-void sendCommandToService(ChppTransportState *transportContext, uint8_t *buf,
- uint8_t ackSeq, uint8_t seq, uint8_t handle,
- uint8_t transactionID, uint16_t command) {
- size_t len = 0;
-
- addPreambleToBuf(buf, &len);
-
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(buf, &len);
- transHeader->ackSeq = ackSeq;
- transHeader->seq = seq;
-
- ChppAppHeader *appHeader = addAppHeaderToBuf(buf, &len);
- appHeader->handle = handle;
- appHeader->transaction = transactionID;
- appHeader->command = command;
-
- addTransportFooterToBuf(buf, &len);
-
- // Send header + payload (if any) + footer
- EXPECT_TRUE(chppRxDataCb(transportContext, buf, len));
-
- // Check for correct state
- uint8_t nextSeq = transHeader->seq + 1;
- EXPECT_EQ(transportContext->rxStatus.expectedSeq, nextSeq);
- EXPECT_EQ(transportContext->rxStatus.state, CHPP_STATE_PREAMBLE);
-
- // Wait for response
- WaitForTransport(transportContext);
-
- // Validate common response fields
- EXPECT_EQ(validateChppTestResponse(transportContext->pendingTxPacket.payload,
- nextSeq, handle, transactionID),
- CHPP_APP_ERROR_NONE);
-}
-
-/**
* A series of zeros shouldn't change state from CHPP_STATE_PREAMBLE
*/
TEST_P(TransportTests, ZeroNoPreambleInput) {
size_t len = static_cast<size_t>(GetParam());
if (len <= kMaxChunkSize) {
- EXPECT_TRUE(chppRxDataCb(&mTransportContext, mBuf, len));
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_PREAMBLE);
+ EXPECT_TRUE(chppRxDataCb(&context, buf, len));
+ EXPECT_EQ(context.rxStatus.state, CHPP_STATE_PREAMBLE);
}
}
@@ -375,18 +80,15 @@ TEST_P(TransportTests, ZeroThenPreambleInput) {
size_t len = static_cast<size_t>(GetParam());
if (len <= kMaxChunkSize) {
- // Add preamble at the end of mBuf, as individual bytes instead of using
- // chppAddPreamble(&mBuf[preambleLoc])
- size_t preambleLoc = MAX(0, len - CHPP_PREAMBLE_LEN_BYTES);
- mBuf[preambleLoc] = kChppPreamble0;
- mBuf[preambleLoc + 1] = kChppPreamble1;
+ // Add preamble at the end of buf
+ chppAddPreamble(buf, MAX(0, len - CHPP_PREAMBLE_LEN_BYTES));
if (len >= CHPP_PREAMBLE_LEN_BYTES) {
- EXPECT_FALSE(chppRxDataCb(&mTransportContext, mBuf, len));
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_HEADER);
+ EXPECT_FALSE(chppRxDataCb(&context, buf, len));
+ EXPECT_EQ(context.rxStatus.state, CHPP_STATE_HEADER);
} else {
- EXPECT_TRUE(chppRxDataCb(&mTransportContext, mBuf, len));
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_PREAMBLE);
+ EXPECT_TRUE(chppRxDataCb(&context, buf, len));
+ EXPECT_EQ(context.rxStatus.state, CHPP_STATE_PREAMBLE);
}
}
}
@@ -395,229 +97,84 @@ TEST_P(TransportTests, ZeroThenPreambleInput) {
* Rx Testing with various length payloads of zeros
*/
TEST_P(TransportTests, RxPayloadOfZeros) {
- mTransportContext.rxStatus.state = CHPP_STATE_PREAMBLE;
+ context.rxStatus.state = CHPP_STATE_HEADER;
size_t len = static_cast<size_t>(GetParam());
- bool validLen = (len <= CHPP_TRANSPORT_RX_MTU_BYTES);
-
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
if (len <= kMaxChunkSize) {
- size_t loc = 0;
- addPreambleToBuf(mBuf, &loc);
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(mBuf, &loc);
+ ChppTransportHeader header{};
+ header.flags = 0;
+ header.errorCode = 0;
+ header.ackSeq = 1;
+ header.seq = 0;
+ header.length = len;
- transHeader->length = static_cast<uint16_t>(len);
- loc += len;
-
- addTransportFooterToBuf(mBuf, &loc);
+ memcpy(buf, &header, sizeof(header));
// Send header and check for correct state
- EXPECT_EQ(
- chppRxDataCb(&mTransportContext, mBuf,
- CHPP_PREAMBLE_LEN_BYTES + sizeof(ChppTransportHeader)),
- !validLen);
-
- if (!validLen) {
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_PREAMBLE);
- } else if (len > 0) {
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_PAYLOAD);
+ EXPECT_FALSE(chppRxDataCb(&context, buf, sizeof(ChppTransportHeader)));
+ if (len > 0) {
+ EXPECT_EQ(context.rxStatus.state, CHPP_STATE_PAYLOAD);
} else {
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_FOOTER);
+ EXPECT_EQ(context.rxStatus.state, CHPP_STATE_FOOTER);
}
// Correct decoding of packet length
- EXPECT_EQ(mTransportContext.rxHeader.length, len);
- EXPECT_EQ(mTransportContext.rxStatus.locInDatagram, 0);
- EXPECT_EQ(mTransportContext.rxDatagram.length, validLen ? len : 0);
+ EXPECT_EQ(context.rxHeader.length, len);
+ EXPECT_EQ(context.rxStatus.locInDatagram, 0);
+ EXPECT_EQ(context.rxDatagram.length, len);
// Send payload if any and check for correct state
if (len > 0) {
- EXPECT_EQ(
- chppRxDataCb(
- &mTransportContext,
- &mBuf[CHPP_PREAMBLE_LEN_BYTES + sizeof(ChppTransportHeader)],
- len),
- !validLen);
- EXPECT_EQ(mTransportContext.rxStatus.state,
- validLen ? CHPP_STATE_FOOTER : CHPP_STATE_PREAMBLE);
+ EXPECT_FALSE(
+ chppRxDataCb(&context, &buf[sizeof(ChppTransportHeader)], len));
+ EXPECT_EQ(context.rxStatus.state, CHPP_STATE_FOOTER);
}
// Should have complete packet payload by now
- EXPECT_EQ(mTransportContext.rxStatus.locInDatagram, validLen ? len : 0);
+ EXPECT_EQ(context.rxStatus.locInDatagram, len);
// But no ACK yet
- EXPECT_EQ(mTransportContext.rxStatus.expectedSeq, transHeader->seq);
+ EXPECT_FALSE(context.txStatus.hasPacketsToSend);
+ EXPECT_EQ(context.txStatus.errorCodeToSend, CHPP_ERROR_NONE);
+ EXPECT_EQ(context.rxStatus.expectedSeq, header.seq);
+
+ // Send footer and check for correct state
+ EXPECT_TRUE(chppRxDataCb(&context, &buf[sizeof(ChppTransportHeader) + len],
+ sizeof(ChppTransportFooter)));
+ EXPECT_EQ(context.rxStatus.state, CHPP_STATE_PREAMBLE);
- // Send footer
- EXPECT_TRUE(chppRxDataCb(
- &mTransportContext,
- &mBuf[CHPP_PREAMBLE_LEN_BYTES + sizeof(ChppTransportHeader) + len],
- sizeof(ChppTransportFooter)));
+ // Should have reset loc and length for next packet / datagram
+ EXPECT_EQ(context.rxStatus.locInDatagram, 0);
+ EXPECT_EQ(context.rxDatagram.length, 0);
- // The next expected packet sequence # should incremented only if the
- // received packet is payload-bearing.
- uint8_t nextSeq = transHeader->seq + ((validLen && len > 0) ? 1 : 0);
- EXPECT_EQ(mTransportContext.rxStatus.expectedSeq, nextSeq);
+ // If payload packet, expect next packet with incremented sequence #
+ // Otherwise, should keep previous sequence #
+ uint8_t nextSeq = header.seq + ((len > 0) ? 1 : 0);
+ EXPECT_EQ(context.rxStatus.expectedSeq, nextSeq);
- // Check for correct ACK crafting if applicable (i.e. if the received packet
- // is payload-bearing).
- if (validLen && len > 0) {
- // TODO: Remove later as can cause flaky tests
- // These are expected to change shortly afterwards, as chppTransportDoWork
- // is run
- // EXPECT_TRUE(mTransportContext.txStatus.hasPacketsToSend);
- EXPECT_EQ(mTransportContext.txStatus.packetCodeToSend,
- CHPP_TRANSPORT_ERROR_NONE);
- EXPECT_EQ(mTransportContext.txDatagramQueue.pending, 0);
+ // Check for correct ACK crafting if applicable
+ // TODO: This will need updating once signalling goes in
+ if (len > 0) {
+ EXPECT_TRUE(context.txStatus.hasPacketsToSend);
+ EXPECT_EQ(context.txStatus.errorCodeToSend, CHPP_ERROR_NONE);
+ EXPECT_EQ(context.txDatagramQueue.pending, 0);
- WaitForTransport(&mTransportContext);
+ chppTransportDoWork(&context);
- // Check response packet fields
struct ChppTransportHeader *txHeader =
- (struct ChppTransportHeader *)&mTransportContext.pendingTxPacket
+ (struct ChppTransportHeader *)&context.packetToSend
.payload[CHPP_PREAMBLE_LEN_BYTES];
+
EXPECT_EQ(txHeader->flags, CHPP_TRANSPORT_FLAG_FINISHED_DATAGRAM);
- EXPECT_EQ(txHeader->packetCode, CHPP_TRANSPORT_ERROR_NONE);
+ EXPECT_EQ(txHeader->errorCode, CHPP_ERROR_NONE);
EXPECT_EQ(txHeader->ackSeq, nextSeq);
EXPECT_EQ(txHeader->length, 0);
- // Check outgoing packet length
- EXPECT_EQ(mTransportContext.pendingTxPacket.length,
+ EXPECT_EQ(context.packetToSend.length,
CHPP_PREAMBLE_LEN_BYTES + sizeof(struct ChppTransportHeader) +
sizeof(struct ChppTransportFooter));
}
-
- // Check for correct state
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_PREAMBLE);
-
- // Should have reset loc and length for next packet / datagram
- EXPECT_EQ(mTransportContext.rxStatus.locInDatagram, 0);
- EXPECT_EQ(mTransportContext.rxDatagram.length, 0);
}
-
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-}
-
-/**
- * End of Packet Link Notification during preamble
- */
-TEST_F(TransportTests, LinkSendDonePreamble) {
- size_t payloadLen = 1000;
- size_t partLenPreamble = CHPP_PREAMBLE_LEN_BYTES - 1;
-
- mTransportContext.rxStatus.state = CHPP_STATE_PREAMBLE;
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- size_t loc = 0;
- addPreambleToBuf(mBuf, &loc);
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(mBuf, &loc);
- transHeader->length = static_cast<uint16_t>(payloadLen);
- loc += payloadLen;
- addTransportFooterToBuf(mBuf, &loc);
-
- EXPECT_FALSE(chppRxDataCb(&mTransportContext, mBuf, partLenPreamble));
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_PREAMBLE);
- endAndValidatePacket(&mTransportContext);
-
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-}
-
-/**
- * End of Packet Link Notification during header
- */
-TEST_F(TransportTests, LinkSendDoneHeader) {
- size_t payloadLen = 1000;
- size_t partLenHeader =
- CHPP_PREAMBLE_LEN_BYTES + sizeof(ChppTransportHeader) - 1;
-
- mTransportContext.rxStatus.state = CHPP_STATE_PREAMBLE;
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- size_t loc = 0;
- addPreambleToBuf(mBuf, &loc);
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(mBuf, &loc);
- transHeader->length = static_cast<uint16_t>(payloadLen);
- loc += payloadLen;
- addTransportFooterToBuf(mBuf, &loc);
-
- EXPECT_FALSE(chppRxDataCb(&mTransportContext, mBuf, partLenHeader));
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_HEADER);
- EXPECT_EQ(mTransportContext.rxHeader.length, payloadLen);
- endAndValidatePacket(&mTransportContext);
-
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-}
-
-/**
- * End of Packet Link Notification during payload
- */
-TEST_F(TransportTests, LinkSendDonePayload) {
- size_t payloadLen = 1000;
- size_t partLenPayload = 500;
-
- mTransportContext.rxStatus.state = CHPP_STATE_PREAMBLE;
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- size_t loc = 0;
- addPreambleToBuf(mBuf, &loc);
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(mBuf, &loc);
- transHeader->length = static_cast<uint16_t>(payloadLen);
- loc += payloadLen;
- addTransportFooterToBuf(mBuf, &loc);
-
- EXPECT_FALSE(chppRxDataCb(&mTransportContext, mBuf, partLenPayload));
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_PAYLOAD);
- EXPECT_EQ(mTransportContext.rxHeader.length, payloadLen);
- EXPECT_EQ(
- mTransportContext.rxStatus.locInDatagram,
- partLenPayload - CHPP_PREAMBLE_LEN_BYTES - sizeof(ChppTransportHeader));
- EXPECT_EQ(mTransportContext.rxDatagram.length, payloadLen);
- endAndValidatePacket(&mTransportContext);
-
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-}
-
-/**
- * End of Packet Link Notification during footer
- */
-TEST_F(TransportTests, LinkSendDoneFooter) {
- size_t payloadLen = 1000;
- size_t partLenFooter = CHPP_PREAMBLE_LEN_BYTES + sizeof(ChppTransportHeader) +
- payloadLen + sizeof(ChppTransportFooter) - 1;
-
- mTransportContext.rxStatus.state = CHPP_STATE_PREAMBLE;
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- size_t loc = 0;
- addPreambleToBuf(mBuf, &loc);
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(mBuf, &loc);
- transHeader->length = static_cast<uint16_t>(payloadLen);
- loc += payloadLen;
- addTransportFooterToBuf(mBuf, &loc);
-
- EXPECT_FALSE(chppRxDataCb(&mTransportContext, mBuf, partLenFooter));
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_FOOTER);
- EXPECT_EQ(mTransportContext.rxHeader.length, payloadLen);
- EXPECT_EQ(mTransportContext.rxStatus.locInDatagram, payloadLen);
- EXPECT_EQ(mTransportContext.rxDatagram.length, payloadLen);
- endAndValidatePacket(&mTransportContext);
-
- chppWorkThreadStop(&mTransportContext);
- t1.join();
}
TEST_P(TransportTests, EnqueueDatagrams) {
@@ -630,514 +187,42 @@ TEST_P(TransportTests, EnqueueDatagrams) {
for (int j = 0; j == CHPP_TX_DATAGRAM_QUEUE_LEN; j++) {
for (size_t i = 1; i <= len; i++) {
- uint8_t *mBuf = (uint8_t *)chppMalloc(i + 100);
- EXPECT_TRUE(
- chppEnqueueTxDatagramOrFail(&mTransportContext, mBuf, i + 100));
+ uint8_t *buf = (uint8_t *)chppMalloc(i + 100);
+ EXPECT_TRUE(chppEnqueueTxDatagram(&context, i + 100, buf));
- EXPECT_EQ(mTransportContext.txDatagramQueue.pending, i);
- EXPECT_EQ(mTransportContext.txDatagramQueue.front, fr);
- EXPECT_EQ(mTransportContext.txDatagramQueue
+ EXPECT_EQ(context.txDatagramQueue.pending, i);
+ EXPECT_EQ(context.txDatagramQueue.front, fr);
+ EXPECT_EQ(context.txDatagramQueue
.datagram[(i - 1 + fr) % CHPP_TX_DATAGRAM_QUEUE_LEN]
.length,
i + 100);
}
- if (mTransportContext.txDatagramQueue.pending ==
- CHPP_TX_DATAGRAM_QUEUE_LEN) {
- uint8_t *mBuf = (uint8_t *)chppMalloc(100);
- EXPECT_FALSE(
- chppEnqueueTxDatagramOrFail(&mTransportContext, mBuf, 100));
- CHPP_FREE_AND_NULLIFY(mBuf);
+ if (context.txDatagramQueue.pending == CHPP_TX_DATAGRAM_QUEUE_LEN) {
+ uint8_t *buf = (uint8_t *)chppMalloc(100);
+ EXPECT_FALSE(chppEnqueueTxDatagram(&context, 100, buf));
+ chppFree(buf);
}
for (size_t i = len; i > 0; i--) {
fr++;
fr %= CHPP_TX_DATAGRAM_QUEUE_LEN;
- EXPECT_TRUE(chppDequeueTxDatagram(&mTransportContext));
+ EXPECT_TRUE(chppDequeueTxDatagram(&context));
- EXPECT_EQ(mTransportContext.txDatagramQueue.front, fr);
- EXPECT_EQ(mTransportContext.txDatagramQueue.pending, i - 1);
+ EXPECT_EQ(context.txDatagramQueue.front, fr);
+ EXPECT_EQ(context.txDatagramQueue.pending, i - 1);
}
- EXPECT_FALSE(chppDequeueTxDatagram(&mTransportContext));
-
- EXPECT_EQ(mTransportContext.txDatagramQueue.front, fr);
- EXPECT_EQ(mTransportContext.txDatagramQueue.pending, 0);
- }
- }
-}
-
-/**
- * Loopback testing with various length payloads of zeros
- */
-TEST_P(TransportTests, LoopbackPayloadOfZeros) {
- mTransportContext.rxStatus.state = CHPP_STATE_PREAMBLE;
- size_t len = static_cast<size_t>(GetParam());
-
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-
- if (len > 1 && len <= kMaxChunkSize) {
- // Loopback App header (only 2 fields required)
- mBuf[0] = CHPP_HANDLE_LOOPBACK;
- mBuf[1] = CHPP_MESSAGE_TYPE_CLIENT_REQUEST;
-
- EXPECT_TRUE(chppDispatchLoopbackClientRequest(&mAppContext, mBuf, len));
-
- uint16_t end = (mTransportContext.txDatagramQueue.front +
- mTransportContext.txDatagramQueue.pending - 1) %
- CHPP_TX_DATAGRAM_QUEUE_LEN;
-
- EXPECT_EQ(mTransportContext.txDatagramQueue.datagram[end].length, len);
- EXPECT_EQ(mTransportContext.txDatagramQueue.datagram[end].payload[0],
- CHPP_HANDLE_LOOPBACK);
- EXPECT_EQ(mTransportContext.txDatagramQueue.datagram[end].payload[1],
- CHPP_MESSAGE_TYPE_SERVICE_RESPONSE);
- }
-}
-
-/**
- * Discovery service + Transaction ID
- */
-TEST_P(TransportTests, DiscoveryAndTransactionID) {
- uint8_t transactionID = static_cast<uint8_t>(GetParam());
- size_t len = 0;
-
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-
- ChppAppHeader *appHeader = addAppHeaderToBuf(mBuf, &len);
- appHeader->handle = CHPP_HANDLE_DISCOVERY;
- appHeader->transaction = transactionID;
- appHeader->command = CHPP_DISCOVERY_COMMAND_DISCOVER_ALL;
-
- EXPECT_TRUE(chppDispatchDiscoveryClientRequest(&mAppContext, mBuf, len));
-
- uint16_t end = (mTransportContext.txDatagramQueue.front +
- mTransportContext.txDatagramQueue.pending - 1) %
- CHPP_TX_DATAGRAM_QUEUE_LEN;
-
- struct ChppAppHeader *responseHeader =
- (ChppAppHeader *)mTransportContext.txDatagramQueue.datagram[end].payload;
-
- EXPECT_EQ(responseHeader->handle, CHPP_HANDLE_DISCOVERY);
- EXPECT_EQ(responseHeader->type, CHPP_MESSAGE_TYPE_SERVICE_RESPONSE);
- EXPECT_EQ(responseHeader->transaction, transactionID);
- EXPECT_EQ(responseHeader->error, CHPP_APP_ERROR_NONE);
- EXPECT_EQ(responseHeader->command, CHPP_DISCOVERY_COMMAND_DISCOVER_ALL);
-
- // Decode discovery response
- ChppServiceDescriptor *services =
- (ChppServiceDescriptor *)&mTransportContext.txDatagramQueue.datagram[end]
- .payload[sizeof(ChppAppHeader)];
-
- // Check total length (and implicit service count)
- EXPECT_EQ(
- mTransportContext.txDatagramQueue.datagram[end].length,
- sizeof(ChppAppHeader) + kServiceCount * sizeof(ChppServiceDescriptor));
-
- // Check service configuration response
- ChppServiceDescriptor wwanServiceDescriptor = {};
- static const uint8_t uuid[CHPP_SERVICE_UUID_LEN] = CHPP_UUID_WWAN_STANDARD;
- memcpy(&wwanServiceDescriptor.uuid, &uuid,
- sizeof(wwanServiceDescriptor.uuid));
- static const char name[CHPP_SERVICE_NAME_MAX_LEN] = "WWAN";
- memcpy(&wwanServiceDescriptor.name, &name,
- sizeof(wwanServiceDescriptor.name));
- wwanServiceDescriptor.version.major = 1;
- wwanServiceDescriptor.version.minor = 0;
- wwanServiceDescriptor.version.patch = 0;
-
- EXPECT_EQ(std::memcmp(services[0].uuid, wwanServiceDescriptor.uuid,
- sizeof(wwanServiceDescriptor.uuid)),
- 0);
- EXPECT_EQ(std::memcmp(services[0].name, wwanServiceDescriptor.name,
- sizeof(wwanServiceDescriptor.name)),
- 0);
- EXPECT_EQ(services[0].version.major, wwanServiceDescriptor.version.major);
- EXPECT_EQ(services[0].version.minor, wwanServiceDescriptor.version.minor);
- EXPECT_EQ(services[0].version.patch, wwanServiceDescriptor.version.patch);
-}
-
-/**
- * CRC-32 calculation for several pre-known test vectors.
- */
-TEST_F(TransportTests, CRC32Basic) {
- static const char kTest1Str[] = "Hello World Test!";
- static const uint8_t *kTest1 = (const uint8_t *)kTest1Str;
- EXPECT_EQ(chppCrc32(0, kTest1, 17), 0x613B1D74);
- EXPECT_EQ(chppCrc32(0, kTest1, 16), 0x5F88D7D9);
- EXPECT_EQ(chppCrc32(0, kTest1, 1), 0xAA05262F);
- EXPECT_EQ(chppCrc32(0, kTest1, 0), 0x00000000);
-
- static const uint8_t kTest2[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
- EXPECT_EQ(chppCrc32(0, kTest2, 6), 0x41D9ED00);
- EXPECT_EQ(chppCrc32(0, kTest2, 5), 0xD2FD1072);
- EXPECT_EQ(chppCrc32(0, kTest2, 4), 0xFFFFFFFF);
- EXPECT_EQ(chppCrc32(0, kTest2, 3), 0xFFFFFF00);
- EXPECT_EQ(chppCrc32(0, kTest2, 2), 0xFFFF0000);
- EXPECT_EQ(chppCrc32(0, kTest2, 1), 0xFF000000);
- EXPECT_EQ(chppCrc32(0, kTest2, 0), 0x00000000);
+ EXPECT_FALSE(chppDequeueTxDatagram(&context));
- static const char kTest3Str[] = "123456789";
- static const uint8_t *kTest3 = (const uint8_t *)kTest3Str;
- EXPECT_EQ(chppCrc32(0, kTest3, 9), 0xCBF43926);
-
- static const uint8_t kTest4[] = {0x00, 0x00, 0x00, 0x00};
- EXPECT_EQ(chppCrc32(0, kTest4, sizeof(kTest4)), 0x2144DF1C);
-
- static const uint8_t kTest5[] = {0xF2, 0x01, 0x83};
- EXPECT_EQ(chppCrc32(0, kTest5, sizeof(kTest5)), 0x24AB9D77);
-
- static const uint8_t kTest6[] = {0x0F, 0xAA, 0x00, 0x55};
- EXPECT_EQ(chppCrc32(0, kTest6, sizeof(kTest6)), 0xB6C9B287);
-
- static const uint8_t kTest7[] = {0x00, 0xFF, 0x55, 0x11};
- EXPECT_EQ(chppCrc32(0, kTest7, sizeof(kTest7)), 0x32A06212);
-
- static const uint8_t kTest8[] = {0x33, 0x22, 0x55, 0xAA, 0xBB,
- 0xCC, 0xDD, 0xEE, 0xFF};
- EXPECT_EQ(chppCrc32(0, kTest8, sizeof(kTest8)), 0xB0AE863D);
-
- static const uint8_t kTest9[] = {0x92, 0x6B, 0x55};
- EXPECT_EQ(chppCrc32(0, kTest9, sizeof(kTest9)), 0x9CDEA29B);
-}
-
-/**
- * CRC-32 calculation for daisy-chained input.
- */
-TEST_F(TransportTests, CRC32DaisyChained) {
- static const size_t kMaxLen = 10000;
- uint8_t test[kMaxLen];
- // Populate test with 8-bit LFSR
- // Feedback polynomial is x^8 + x^6 + x^5 + x^4 + 1
- static uint8_t lfsr = 1;
- for (size_t i = 0; i < kMaxLen; i++) {
- test[i] = lfsr;
- lfsr = (lfsr >> 1) |
- (((lfsr << 7) ^ (lfsr << 5) ^ (lfsr << 4) ^ (lfsr << 3)) & 0x80);
- }
-
- for (size_t len = 0; len < kMaxLen; len += 1000) {
- uint32_t fullCRC = chppCrc32(0, &test[0], len);
- for (size_t partition = 0; partition <= len; partition++) {
- uint32_t partialCRC = chppCrc32(0, &test[0], partition);
- EXPECT_EQ(chppCrc32(partialCRC, &test[partition], len - partition),
- fullCRC);
+ EXPECT_EQ(context.txDatagramQueue.front, fr);
+ EXPECT_EQ(context.txDatagramQueue.pending, 0);
}
}
}
-/**
- * WWAN service Open and GetCapabilities.
- */
-TEST_F(TransportTests, WwanOpen) {
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- uint8_t ackSeq = 1;
- uint8_t seq = 0;
- uint8_t handle = CHPP_HANDLE_NEGOTIATED_RANGE_START;
- uint8_t transactionID = 0;
- size_t len = 0;
-
- openService(&mTransportContext, mBuf, ackSeq++, seq++, handle,
- transactionID++, CHPP_WWAN_OPEN);
-
- addPreambleToBuf(mBuf, &len);
-
- uint16_t command = CHPP_WWAN_GET_CAPABILITIES;
- sendCommandToService(&mTransportContext, mBuf, ackSeq++, seq++, handle,
- transactionID++, command);
-
- size_t responseLoc = sizeof(ChppTestResponse);
-
- // Validate capabilities
- uint32_t *capabilities =
- (uint32_t *)&mTransportContext.pendingTxPacket.payload[responseLoc];
- responseLoc += sizeof(uint32_t);
-
- // Cleanup
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-
- uint32_t capabilitySet = CHRE_WWAN_GET_CELL_INFO;
- EXPECT_EQ((*capabilities) & ~(capabilitySet), 0);
-
- // Check total length
- EXPECT_EQ(responseLoc, CHPP_PREAMBLE_LEN_BYTES + sizeof(ChppTransportHeader) +
- sizeof(ChppWwanGetCapabilitiesResponse));
-}
-
-/**
- * WiFi service Open and GetCapabilities.
- */
-TEST_F(TransportTests, WifiOpen) {
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- uint8_t ackSeq = 1;
- uint8_t seq = 0;
- uint8_t handle = CHPP_HANDLE_NEGOTIATED_RANGE_START + 1;
- uint8_t transactionID = 0;
-
- openService(&mTransportContext, mBuf, ackSeq++, seq++, handle,
- transactionID++, CHPP_WIFI_OPEN);
-
- uint16_t command = CHPP_WIFI_GET_CAPABILITIES;
- sendCommandToService(&mTransportContext, mBuf, ackSeq++, seq++, handle,
- transactionID++, command);
-
- size_t responseLoc = sizeof(ChppTestResponse);
-
- // Cleanup
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-
- // Validate capabilities
- uint32_t *capabilities =
- (uint32_t *)&mTransportContext.pendingTxPacket.payload[responseLoc];
- responseLoc += sizeof(uint32_t);
-
- uint32_t capabilitySet = CHRE_WIFI_CAPABILITIES_SCAN_MONITORING |
- CHRE_WIFI_CAPABILITIES_ON_DEMAND_SCAN |
- CHRE_WIFI_CAPABILITIES_RADIO_CHAIN_PREF |
- CHRE_WIFI_CAPABILITIES_RTT_RANGING;
- EXPECT_EQ((*capabilities) & ~(capabilitySet), 0);
-
- // Check total length
- EXPECT_EQ(responseLoc, CHPP_PREAMBLE_LEN_BYTES + sizeof(ChppTransportHeader) +
- sizeof(ChppWwanGetCapabilitiesResponse));
-}
-
-/**
- * GNSS service Open and GetCapabilities.
- */
-TEST_F(TransportTests, GnssOpen) {
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- uint8_t ackSeq = 1;
- uint8_t seq = 0;
- uint8_t handle = CHPP_HANDLE_NEGOTIATED_RANGE_START + 2;
- uint8_t transactionID = 0;
- size_t len = 0;
-
- openService(&mTransportContext, mBuf, ackSeq++, seq++, handle,
- transactionID++, CHPP_GNSS_OPEN);
-
- addPreambleToBuf(mBuf, &len);
-
- uint16_t command = CHPP_GNSS_GET_CAPABILITIES;
- sendCommandToService(&mTransportContext, mBuf, ackSeq++, seq++, handle,
- transactionID++, command);
-
- size_t responseLoc = sizeof(ChppTestResponse);
-
- // Cleanup
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-
- // Validate capabilities
- uint32_t *capabilities =
- (uint32_t *)&mTransportContext.pendingTxPacket.payload[responseLoc];
- responseLoc += sizeof(uint32_t);
-
- uint32_t capabilitySet =
- CHRE_GNSS_CAPABILITIES_LOCATION | CHRE_GNSS_CAPABILITIES_MEASUREMENTS |
- CHRE_GNSS_CAPABILITIES_GNSS_ENGINE_BASED_PASSIVE_LISTENER;
- EXPECT_EQ((*capabilities) & ~(capabilitySet), 0);
-
- // Check total length
- EXPECT_EQ(responseLoc, CHPP_PREAMBLE_LEN_BYTES + sizeof(ChppTransportHeader) +
- sizeof(ChppGnssGetCapabilitiesResponse));
-}
-
-/**
- * Discovery client.
- */
-TEST_F(TransportTests, Discovery) {
- size_t len = 0;
-
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- addPreambleToBuf(mBuf, &len);
-
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(mBuf, &len);
-
- ChppAppHeader *appHeader = addAppHeaderToBuf(mBuf, &len);
- appHeader->handle = CHPP_HANDLE_DISCOVERY;
- appHeader->command = CHPP_DISCOVERY_COMMAND_DISCOVER_ALL;
- appHeader->type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
-
- ChppServiceDescriptor wwanServiceDescriptor = {};
- static const uint8_t uuid[CHPP_SERVICE_UUID_LEN] = CHPP_UUID_WWAN_STANDARD;
- memcpy(&wwanServiceDescriptor.uuid, &uuid,
- sizeof(wwanServiceDescriptor.uuid));
- static const char name[CHPP_SERVICE_NAME_MAX_LEN] = "WWAN";
- memcpy(&wwanServiceDescriptor.name, &name,
- sizeof(wwanServiceDescriptor.name));
- wwanServiceDescriptor.version.major = 1;
- wwanServiceDescriptor.version.minor = 0;
- wwanServiceDescriptor.version.patch = 0;
-
- memcpy(&mBuf[len], &wwanServiceDescriptor, sizeof(ChppServiceDescriptor));
- len += sizeof(ChppServiceDescriptor);
-
- transHeader->length = static_cast<uint16_t>(
- len - sizeof(ChppTransportHeader) - CHPP_PREAMBLE_LEN_BYTES);
-
- addTransportFooterToBuf(mBuf, &len);
-
- // Initialize clientIndexOfServiceIndex[0] to see if it correctly updated
- // upon discovery
- mAppContext.clientIndexOfServiceIndex[0] = CHPP_CLIENT_INDEX_NONE;
-
- // Send header + payload (if any) + footer
- EXPECT_TRUE(chppRxDataCb(&mTransportContext, mBuf, len));
-
- // Cleanup
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-
- // Check for correct state
- EXPECT_EQ(mAppContext.clientIndexOfServiceIndex[0], 0);
- uint8_t nextSeq = transHeader->seq + 1;
- EXPECT_EQ(mTransportContext.rxStatus.expectedSeq, nextSeq);
- EXPECT_EQ(mTransportContext.rxStatus.state, CHPP_STATE_PREAMBLE);
-}
-
-/**
- * Unopened clients should not crash upon an unsolicitated service response.
- */
-TEST_F(TransportTests, UnopenedClient) {
- size_t len = 0;
- uint8_t *buf = (uint8_t *)chppMalloc(100);
-
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-
- ChppAppHeader *appHeader = addAppHeaderToBuf(buf, &len);
- appHeader->handle = CHPP_HANDLE_NEGOTIATED_RANGE_START + 1;
- appHeader->command = CHPP_WIFI_CONFIGURE_SCAN_MONITOR_ASYNC;
- appHeader->type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
- len = sizeof(struct ChppWifiConfigureScanMonitorAsyncResponse);
-
- ASSERT_EQ(mAppContext.registeredServiceCount, kServiceCount);
-
- chppAppProcessRxDatagram(&mAppContext, buf, len);
-
- EXPECT_EQ(mTransportContext.txStatus.packetCodeToSend,
- CHPP_TRANSPORT_ERROR_APPLAYER);
-}
-
-TEST_F(TransportTests, DiscardedPacketTest) {
- mTransportContext.txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, &mTransportContext);
- WaitForTransport(&mTransportContext);
-
- // Send packet to RX thread after manually setting to resetting state.
- // We expect this packet to get dropped, but this test checks for any
- // problematic behavior (e.g. memory leaks).
- mTransportContext.resetState = CHPP_RESET_STATE_RESETTING;
-
- size_t loc = 0;
- addPreambleToBuf(mBuf, &loc);
- ChppTransportHeader *transHeader = addTransportHeaderToBuf(mBuf, &loc);
-
- ChppAppHeader *appHeader = addAppHeaderToBuf(mBuf, &loc);
- appHeader->handle = CHPP_HANDLE_DISCOVERY;
- appHeader->command = CHPP_DISCOVERY_COMMAND_DISCOVER_ALL;
- appHeader->type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
-
- ChppServiceDescriptor wwanServiceDescriptor = {};
- static const uint8_t uuid[CHPP_SERVICE_UUID_LEN] = CHPP_UUID_WWAN_STANDARD;
- memcpy(&wwanServiceDescriptor.uuid, &uuid,
- sizeof(wwanServiceDescriptor.uuid));
- static const char name[CHPP_SERVICE_NAME_MAX_LEN] = "WWAN";
- memcpy(&wwanServiceDescriptor.name, &name,
- sizeof(wwanServiceDescriptor.name));
- wwanServiceDescriptor.version.major = 1;
- wwanServiceDescriptor.version.minor = 0;
- wwanServiceDescriptor.version.patch = 0;
-
- memcpy(&mBuf[loc], &wwanServiceDescriptor, sizeof(ChppServiceDescriptor));
- loc += sizeof(ChppServiceDescriptor);
-
- transHeader->length = static_cast<uint16_t>(
- loc - sizeof(ChppTransportHeader) - CHPP_PREAMBLE_LEN_BYTES);
-
- addTransportFooterToBuf(mBuf, &loc);
-
- mAppContext.clientIndexOfServiceIndex[0] = CHPP_CLIENT_INDEX_NONE;
-
- EXPECT_TRUE(chppRxDataCb(&mTransportContext, mBuf, loc));
-
- chppWorkThreadStop(&mTransportContext);
- t1.join();
-}
-
-/*
- * Correctly handle messages directed to clients / services with an invalid
- * handle number.
- */
-void messageToInvalidHandle(ChppTransportState *transportContext,
- uint8_t type) {
- size_t len = 0;
- uint8_t *buf = (uint8_t *)chppMalloc(100);
-
- transportContext->txStatus.hasPacketsToSend = true;
- std::thread t1(chppWorkThreadStart, transportContext);
- WaitForTransport(transportContext);
- chppWorkThreadStop(transportContext);
- t1.join();
-
- ChppAppHeader *appHeader = addAppHeaderToBuf(buf, &len);
- appHeader->handle =
- CHPP_HANDLE_NEGOTIATED_RANGE_START + CHPP_MAX_REGISTERED_CLIENTS;
- appHeader->type = type;
- len = sizeof(struct ChppAppHeader);
-
- chppAppProcessRxDatagram(transportContext->appContext, buf, len);
-
- EXPECT_EQ(transportContext->txStatus.packetCodeToSend,
- CHPP_TRANSPORT_ERROR_APPLAYER);
-}
-
-TEST_F(TransportTests, RequestToInvalidService) {
- messageToInvalidHandle(&mTransportContext, CHPP_MESSAGE_TYPE_CLIENT_REQUEST);
-}
-
-TEST_F(TransportTests, ResponseToInvalidClient) {
- messageToInvalidHandle(&mTransportContext,
- CHPP_MESSAGE_TYPE_SERVICE_RESPONSE);
-}
-
-TEST_F(TransportTests, NotificationToInvalidService) {
- messageToInvalidHandle(&mTransportContext,
- CHPP_MESSAGE_TYPE_CLIENT_NOTIFICATION);
-}
-
-TEST_F(TransportTests, NotificationToInvalidClient) {
- messageToInvalidHandle(&mTransportContext,
- CHPP_MESSAGE_TYPE_SERVICE_NOTIFICATION);
-}
-
INSTANTIATE_TEST_SUITE_P(TransportTestRange, TransportTests,
testing::ValuesIn(kChunkSizes));
+
} // namespace
diff --git a/chpp/test/transport_test.h b/chpp/test/transport_test.h
index f9b502a8..02b7d5ff 100644
--- a/chpp/test/transport_test.h
+++ b/chpp/test/transport_test.h
@@ -17,32 +17,16 @@
#ifndef CHPP_TRANSPORT_TEST_H_
#define CHPP_TRANSPORT_TEST_H_
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "chpp/app.h"
-#include "chpp/macros.h"
-#include "chpp/transport.h"
-
#ifdef __cplusplus
extern "C" {
#endif
-CHPP_PACKED_START
-struct ChppTestResponse {
- char preamble0;
- char preamble1;
- struct ChppTransportHeader transportHeader;
- struct ChppAppHeader appHeader;
-} CHPP_PACKED_ATTR;
-CHPP_PACKED_END
-
/************************************************
* Functions necessary for unit testing
***********************************************/
-size_t chppDequeueTxDatagram(struct ChppTransportState *context);
+bool chppDequeueTxDatagram(struct ChppTransportState *context);
+void chppTransportDoWork(struct ChppTransportState *context);
#ifdef __cplusplus
}
diff --git a/chpp/test/wifi_convert_test.cpp b/chpp/test/wifi_convert_test.cpp
deleted file mode 100644
index d5df6c1e..00000000
--- a/chpp/test/wifi_convert_test.cpp
+++ /dev/null
@@ -1,550 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <gtest/gtest.h>
-
-#include <stddef.h>
-#include <cstring>
-
-#include "chpp/common/wifi_types.h"
-#include "chpp/memory.h"
-#include "chre/test/common/macros.h"
-
-namespace {
-
-void validateScanResult(const ChppWifiScanResult &chppAp,
- const chreWifiScanResult &chreAp, bool decodeMode) {
- EXPECT_EQ(chppAp.ageMs, chreAp.ageMs);
- EXPECT_EQ(chppAp.capabilityInfo, chreAp.capabilityInfo);
- EXPECT_EQ(chppAp.ssidLen, chreAp.ssidLen);
- EXPECT_EQ(std::memcmp(chppAp.ssid, chreAp.ssid, sizeof(chppAp.ssid)), 0);
- EXPECT_EQ(std::memcmp(chppAp.bssid, chreAp.bssid, sizeof(chppAp.bssid)), 0);
- EXPECT_EQ(chppAp.flags, chreAp.flags);
- EXPECT_EQ(chppAp.rssi, chreAp.rssi);
- EXPECT_EQ(chppAp.band, chreAp.band);
- EXPECT_EQ(chppAp.primaryChannel, chreAp.primaryChannel);
- EXPECT_EQ(chppAp.centerFreqPrimary, chreAp.centerFreqPrimary);
- EXPECT_EQ(chppAp.centerFreqSecondary, chreAp.centerFreqSecondary);
- EXPECT_EQ(chppAp.channelWidth, chreAp.channelWidth);
- EXPECT_EQ(chppAp.securityMode, chreAp.securityMode);
- EXPECT_EQ(chppAp.radioChain, chreAp.radioChain);
- EXPECT_EQ(chppAp.rssiChain0, chreAp.rssiChain0);
- EXPECT_EQ(chppAp.rssiChain1, chreAp.rssiChain1);
-
- for (size_t i = 0;
- i < (decodeMode ? sizeof(chreAp.reserved) : sizeof(chppAp.reserved));
- i++) {
- SCOPED_TRACE(i);
- EXPECT_EQ((decodeMode ? chreAp.reserved[i] : chppAp.reserved[i]), 0);
- }
-}
-
-void validateScanEvent(const chreWifiScanEvent &chreEvent) {
- ChppWifiScanEventWithHeader *chppWithHeader = nullptr;
- size_t outputSize = 999;
-
- // Encode
- bool result =
- chppWifiScanEventFromChre(&chreEvent, &chppWithHeader, &outputSize);
- ASSERT_TRUE(result);
- ASSERT_NE(chppWithHeader, nullptr);
-
- size_t expectedSize = sizeof(ChppWifiScanEventWithHeader) +
- chreEvent.scannedFreqListLen * sizeof(uint32_t) +
- chreEvent.resultCount * sizeof(ChppWifiScanResult);
- EXPECT_EQ(outputSize, expectedSize);
-
- ChppWifiScanEvent *chppEvent = &chppWithHeader->payload;
-
- // Decode
- outputSize -= sizeof(struct ChppAppHeader);
- chreWifiScanEvent *backEvent = chppWifiScanEventToChre(chppEvent, outputSize);
- ASSERT_NE(backEvent, nullptr);
-
- // Compare chreEvent against encoded (chppEvent) and decoded back (backEvent)
-
- EXPECT_EQ(chppEvent->version, CHRE_WIFI_SCAN_EVENT_VERSION);
- EXPECT_EQ(chppEvent->resultCount, chreEvent.resultCount);
- EXPECT_EQ(chppEvent->resultTotal, chreEvent.resultTotal);
- EXPECT_EQ(chppEvent->resultCount, chreEvent.resultCount);
- EXPECT_EQ(chppEvent->eventIndex, chreEvent.eventIndex);
- EXPECT_EQ(chppEvent->scanType, chreEvent.scanType);
- EXPECT_EQ(chppEvent->ssidSetSize, chreEvent.ssidSetSize);
- EXPECT_EQ(chppEvent->scannedFreqListLen, chreEvent.scannedFreqListLen);
- EXPECT_EQ(chppEvent->referenceTime, chreEvent.referenceTime);
- EXPECT_EQ(chppEvent->radioChainPref, chreEvent.radioChainPref);
-
- EXPECT_EQ(backEvent->version, CHRE_WIFI_SCAN_EVENT_VERSION);
- EXPECT_EQ(backEvent->resultCount, chreEvent.resultCount);
- EXPECT_EQ(backEvent->resultTotal, chreEvent.resultTotal);
- EXPECT_EQ(backEvent->resultCount, chreEvent.resultCount);
- EXPECT_EQ(backEvent->eventIndex, chreEvent.eventIndex);
- EXPECT_EQ(backEvent->scanType, chreEvent.scanType);
- EXPECT_EQ(backEvent->ssidSetSize, chreEvent.ssidSetSize);
- EXPECT_EQ(backEvent->scannedFreqListLen, chreEvent.scannedFreqListLen);
- EXPECT_EQ(backEvent->referenceTime, chreEvent.referenceTime);
- EXPECT_EQ(backEvent->radioChainPref, chreEvent.radioChainPref);
-
- uint16_t baseOffset = sizeof(ChppWifiScanEvent);
- if (chreEvent.scannedFreqListLen > 0) {
- EXPECT_EQ(chppEvent->scannedFreqList.offset, baseOffset);
- EXPECT_EQ(chppEvent->scannedFreqList.length,
- chppEvent->scannedFreqListLen * sizeof(uint32_t));
- baseOffset += chppEvent->scannedFreqList.length;
-
- auto *chppScannedFreqList =
- ((const uint8_t *)chppEvent + chppEvent->scannedFreqList.offset);
- for (size_t i = 0; i < chppEvent->scannedFreqListLen; i++) {
- uint32_t currScannedFreq;
- memcpy(&currScannedFreq, chppScannedFreqList + (i * sizeof(uint32_t)),
- sizeof(uint32_t));
- SCOPED_TRACE(i);
- EXPECT_EQ(currScannedFreq, chreEvent.scannedFreqList[i]);
- EXPECT_EQ(currScannedFreq, backEvent->scannedFreqList[i]);
- }
- } else {
- EXPECT_EQ(chppEvent->scannedFreqList.offset, 0);
- EXPECT_EQ(chppEvent->scannedFreqList.length, 0);
- }
-
- if (chreEvent.resultCount > 0) {
- EXPECT_EQ(chppEvent->results.offset, baseOffset);
- EXPECT_EQ(chppEvent->results.length,
- chppEvent->resultCount * sizeof(ChppWifiScanResult));
- baseOffset += chppEvent->results.length;
-
- const ChppWifiScanResult *chppAp =
- (const ChppWifiScanResult *)((const uint8_t *)chppEvent +
- chppEvent->results.offset);
- for (size_t i = 0; i < chppEvent->resultCount; i++) {
- SCOPED_TRACE(::testing::Message() << "Scan result index " << i);
- validateScanResult(chppAp[i], chreEvent.results[i], /*decodeMode=*/false);
- validateScanResult(chppAp[i], backEvent->results[i], /*decodeMode=*/true);
- }
- } else {
- EXPECT_EQ(chppEvent->results.offset, 0);
- EXPECT_EQ(chppEvent->results.length, 0);
- }
-
- // Handling of short input
- chreWifiScanEvent *chreMalformed;
- chreMalformed = chppWifiScanEventToChre(chppEvent, outputSize - 1);
- ASSERT_EQ(chreMalformed, nullptr);
-
- chppFree(chppWithHeader);
- chppFree(backEvent);
-}
-
-void validateScanParams(const chreWifiScanParams &chreParams) {
- ChppWifiScanParamsWithHeader *chppWithHeader = nullptr;
- size_t outputSize = 999;
-
- // Encode
- bool result =
- chppWifiScanParamsFromChre(&chreParams, &chppWithHeader, &outputSize);
- ASSERT_TRUE(result);
- ASSERT_NE(chppWithHeader, nullptr);
-
- size_t expectedSize = sizeof(ChppWifiScanParamsWithHeader) +
- chreParams.frequencyListLen * sizeof(uint32_t) +
- chreParams.ssidListLen * sizeof(ChppWifiSsidListItem);
- EXPECT_EQ(outputSize, expectedSize);
-
- ChppWifiScanParams *chppParams = &chppWithHeader->payload;
-
- // Decode
- outputSize -= sizeof(struct ChppAppHeader);
- chreWifiScanParams *backParams =
- chppWifiScanParamsToChre(chppParams, outputSize);
- ASSERT_NE(backParams, nullptr);
-
- // Compare chreEvent against encoded (chppEvent) and decoded back (backEvent)
-
- EXPECT_EQ(chppParams->scanType, chreParams.scanType);
- EXPECT_EQ(chppParams->maxScanAgeMs, chreParams.maxScanAgeMs);
- EXPECT_EQ(chppParams->frequencyListLen, chreParams.frequencyListLen);
- EXPECT_EQ(chppParams->ssidListLen, chreParams.ssidListLen);
- EXPECT_EQ(chppParams->radioChainPref, chreParams.radioChainPref);
-
- EXPECT_EQ(backParams->scanType, chreParams.scanType);
- EXPECT_EQ(backParams->maxScanAgeMs, chreParams.maxScanAgeMs);
- EXPECT_EQ(backParams->frequencyListLen, chreParams.frequencyListLen);
- EXPECT_EQ(backParams->ssidListLen, chreParams.ssidListLen);
- EXPECT_EQ(backParams->radioChainPref, chreParams.radioChainPref);
-
- uint16_t baseOffset = sizeof(ChppWifiScanParams);
- if (chreParams.frequencyListLen > 0) {
- EXPECT_EQ(chppParams->frequencyList.offset, baseOffset);
- EXPECT_EQ(chppParams->frequencyList.length,
- chppParams->frequencyListLen * sizeof(uint32_t));
- baseOffset += chppParams->frequencyList.length;
-
- auto *chppFrequencyList =
- ((const uint8_t *)chppParams + chppParams->frequencyList.offset);
- for (size_t i = 0; i < chppParams->frequencyListLen; i++) {
- uint32_t currScannedFreq;
- memcpy(&currScannedFreq, chppFrequencyList + (i * sizeof(uint32_t)),
- sizeof(uint32_t));
- SCOPED_TRACE(i);
- EXPECT_EQ(currScannedFreq, chreParams.frequencyList[i]);
- EXPECT_EQ(currScannedFreq, backParams->frequencyList[i]);
- }
- } else {
- EXPECT_EQ(chppParams->frequencyList.offset, 0);
- EXPECT_EQ(chppParams->frequencyList.length, 0);
- }
-
- if (chreParams.ssidListLen > 0) {
- EXPECT_EQ(chppParams->ssidList.offset, baseOffset);
- EXPECT_EQ(chppParams->ssidList.length,
- chppParams->ssidListLen * sizeof(ChppWifiSsidListItem));
- baseOffset += chppParams->ssidList.length;
-
- const ChppWifiSsidListItem *chppSsidList =
- (const ChppWifiSsidListItem *)((const uint8_t *)chppParams +
- chppParams->ssidList.offset);
- for (size_t i = 0; i < chppParams->ssidListLen; i++) {
- SCOPED_TRACE(i);
- EXPECT_EQ(chppSsidList[i].ssidLen, chreParams.ssidList[i].ssidLen);
- EXPECT_EQ(std::memcmp(chppSsidList[i].ssid, chreParams.ssidList[i].ssid,
- sizeof(chppSsidList[i].ssid)),
- 0);
- EXPECT_EQ(chppSsidList[i].ssidLen, backParams->ssidList[i].ssidLen);
- EXPECT_EQ(std::memcmp(chppSsidList[i].ssid, backParams->ssidList[i].ssid,
- sizeof(chppSsidList[i].ssid)),
- 0);
- }
- } else {
- EXPECT_EQ(chppParams->ssidList.offset, 0);
- EXPECT_EQ(chppParams->ssidList.length, 0);
- }
-
- // Handling of short input
- chreWifiScanParams *chreMalformed;
- chreMalformed = chppWifiScanParamsToChre(chppParams, outputSize - 1);
- ASSERT_EQ(chreMalformed, nullptr);
-
- chppFree(chppWithHeader);
- chppFree(backParams);
-}
-
-void validateRangingParams(const chreWifiRangingParams &chreParams) {
- ChppWifiRangingParamsWithHeader *chppWithHeader = nullptr;
- size_t outputSize = 999;
-
- // Encode
- bool result =
- chppWifiRangingParamsFromChre(&chreParams, &chppWithHeader, &outputSize);
- ASSERT_TRUE(result);
- ASSERT_NE(chppWithHeader, nullptr);
-
- size_t expectedSize =
- sizeof(ChppWifiRangingParamsWithHeader) +
- chreParams.targetListLen * sizeof(ChppWifiRangingTarget);
- EXPECT_EQ(outputSize, expectedSize);
-
- ChppWifiRangingParams *chppParams = &chppWithHeader->payload;
-
- // Decode
- outputSize -= sizeof(struct ChppAppHeader);
- chreWifiRangingParams *backParams =
- chppWifiRangingParamsToChre(chppParams, outputSize);
- ASSERT_NE(backParams, nullptr);
-
- // Compare chreEvent against encoded (chppEvent) and decoded back (backEvent)
- EXPECT_EQ(chppParams->targetListLen, chreParams.targetListLen);
- EXPECT_EQ(backParams->targetListLen, chreParams.targetListLen);
-
- uint16_t baseOffset = sizeof(ChppWifiRangingParams);
- if (chreParams.targetListLen > 0) {
- EXPECT_EQ(chppParams->targetList.offset, baseOffset);
- EXPECT_EQ(chppParams->targetList.length,
- chppParams->targetListLen * sizeof(ChppWifiRangingTarget));
- baseOffset += chppParams->targetList.length;
-
- auto *chppRangingList =
- ((const uint8_t *)chppParams + chppParams->targetList.offset);
- for (size_t i = 0; i < chppParams->targetListLen; i++) {
- ChppWifiRangingTarget currentRangingTarget;
- memcpy(&currentRangingTarget,
- chppRangingList + (i * sizeof(ChppWifiRangingTarget)),
- sizeof(ChppWifiRangingTarget));
- SCOPED_TRACE(i);
- EXPECT_EQ(currentRangingTarget.macAddress[0],
- chreParams.targetList[i].macAddress[0]);
- EXPECT_EQ(currentRangingTarget.macAddress[1],
- chreParams.targetList[i].macAddress[1]);
- EXPECT_EQ(currentRangingTarget.macAddress[2],
- chreParams.targetList[i].macAddress[2]);
- EXPECT_EQ(currentRangingTarget.macAddress[3],
- chreParams.targetList[i].macAddress[3]);
- EXPECT_EQ(currentRangingTarget.macAddress[4],
- chreParams.targetList[i].macAddress[4]);
- EXPECT_EQ(currentRangingTarget.macAddress[5],
- chreParams.targetList[i].macAddress[5]);
- EXPECT_EQ(currentRangingTarget.primaryChannel,
- chreParams.targetList[i].primaryChannel);
- EXPECT_EQ(currentRangingTarget.centerFreqPrimary,
- chreParams.targetList[i].centerFreqPrimary);
- EXPECT_EQ(currentRangingTarget.centerFreqSecondary,
- chreParams.targetList[i].centerFreqSecondary);
- EXPECT_EQ(currentRangingTarget.channelWidth,
- chreParams.targetList[i].channelWidth);
-
- EXPECT_EQ(currentRangingTarget.macAddress[0],
- backParams->targetList[i].macAddress[0]);
- EXPECT_EQ(currentRangingTarget.macAddress[1],
- backParams->targetList[i].macAddress[1]);
- EXPECT_EQ(currentRangingTarget.macAddress[2],
- backParams->targetList[i].macAddress[2]);
- EXPECT_EQ(currentRangingTarget.macAddress[3],
- backParams->targetList[i].macAddress[3]);
- EXPECT_EQ(currentRangingTarget.macAddress[4],
- backParams->targetList[i].macAddress[4]);
- EXPECT_EQ(currentRangingTarget.macAddress[5],
- backParams->targetList[i].macAddress[5]);
- EXPECT_EQ(currentRangingTarget.primaryChannel,
- backParams->targetList[i].primaryChannel);
- EXPECT_EQ(currentRangingTarget.centerFreqPrimary,
- backParams->targetList[i].centerFreqPrimary);
- EXPECT_EQ(currentRangingTarget.centerFreqSecondary,
- backParams->targetList[i].centerFreqSecondary);
- EXPECT_EQ(currentRangingTarget.channelWidth,
- backParams->targetList[i].channelWidth);
- }
- } else {
- EXPECT_EQ(chppParams->targetList.offset, 0);
- EXPECT_EQ(chppParams->targetList.length, 0);
- }
-
- // Handling of short input
- chreWifiRangingParams *chreMalformed;
- chreMalformed = chppWifiRangingParamsToChre(chppParams, outputSize - 1);
- ASSERT_EQ(chreMalformed, nullptr);
-
- chppFree(chppWithHeader);
- chppFree(backParams);
-}
-
-} // anonymous namespace
-
-TEST(WifiConvert, EmptyScanResult) {
- const chreWifiScanEvent chreEvent = {
- .version = 200, // ignored
- .resultCount = 0,
- .resultTotal = 0,
- .eventIndex = 0,
- .scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS,
- .ssidSetSize = 2,
- .scannedFreqListLen = 0,
- .referenceTime = 1234,
- .scannedFreqList = nullptr,
- .results = nullptr,
- .radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_HIGH_ACCURACY,
- };
-
- validateScanEvent(chreEvent);
-}
-
-TEST(WifiConvert, SingleResult) {
- // clang-format off
- const chreWifiScanResult chreAp = {
- .ageMs = 11,
- .capabilityInfo = 22,
- .ssidLen = 4,
- .ssid = {'a', 'b', 'c', 'd',},
- .bssid = {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff},
- .flags = CHRE_WIFI_SCAN_RESULT_FLAGS_IS_FTM_RESPONDER,
- .rssi = -37,
- .band = CHRE_WIFI_BAND_2_4_GHZ,
- .primaryChannel = 2437,
- .centerFreqPrimary = 2442,
- .centerFreqSecondary = 2447,
- .channelWidth = CHRE_WIFI_CHANNEL_WIDTH_80_MHZ,
- .securityMode = CHRE_WIFI_SECURITY_MODE_PSK,
- .radioChain = CHRE_WIFI_RADIO_CHAIN_0 | CHRE_WIFI_RADIO_CHAIN_1,
- .rssiChain0 = -37,
- .rssiChain1 = -42,
- };
- const chreWifiScanEvent chreEvent = {
- .version = 200, // ignored
- .resultCount = 1,
- .resultTotal = 5,
- .eventIndex = 2,
- .scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE,
- .ssidSetSize = 0,
- .scannedFreqListLen = 0,
- .referenceTime = 12345,
- .scannedFreqList = nullptr,
- .results = &chreAp,
- .radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT,
- };
- // clang-format on
-
- validateScanEvent(chreEvent);
-}
-
-TEST(WifiConvert, TwoResultsWithFreqList) {
- // clang-format off
- const chreWifiScanResult chreAps[] = {
- {
- .ageMs = 11,
- .capabilityInfo = 22,
- .ssidLen = 4,
- .ssid = {'a', 'b', 'c', 'd',},
- .bssid = {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff},
- .flags = CHRE_WIFI_SCAN_RESULT_FLAGS_IS_FTM_RESPONDER,
- .rssi = -37,
- .band = CHRE_WIFI_BAND_2_4_GHZ,
- .primaryChannel = 2437,
- .centerFreqPrimary = 2442,
- .centerFreqSecondary = 2447,
- .channelWidth = CHRE_WIFI_CHANNEL_WIDTH_80_MHZ,
- .securityMode = CHRE_WIFI_SECURITY_MODE_PSK,
- .radioChain = CHRE_WIFI_RADIO_CHAIN_0 | CHRE_WIFI_RADIO_CHAIN_1,
- .rssiChain0 = -37,
- .rssiChain1 = -42,
- },
- {
- .ageMs = 4325,
- .capabilityInfo = 37,
- .ssidLen = 2,
- .ssid = {'h', 'i',},
- .bssid = {0xab, 0xcd, 0xef, 0x01, 0x23, 0x45},
- .flags = CHRE_WIFI_SCAN_RESULT_FLAGS_VHT_OPS_PRESENT,
- .rssi = -52,
- .band = CHRE_WIFI_BAND_5_GHZ,
- .primaryChannel = 9999,
- .centerFreqPrimary = 8888,
- .centerFreqSecondary = 7777,
- .channelWidth = CHRE_WIFI_CHANNEL_WIDTH_160_MHZ,
- .securityMode = CHRE_WIFI_SECURITY_MODE_SAE,
- .radioChain = CHRE_WIFI_RADIO_CHAIN_0,
- .rssiChain0 = -37,
- .rssiChain1 = 0,
- }};
- const uint32_t freqList[] = {0xdeadbeef, 0xc001cafe, 0xc0a1ba11};
- const chreWifiScanEvent chreEvent = {
- .version = 200, // ignored
- .resultCount = 2,
- .resultTotal = 3,
- .eventIndex = 1,
- .scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE,
- .ssidSetSize = 10,
- .scannedFreqListLen = 3,
- .referenceTime = 56789,
- .scannedFreqList = freqList,
- .results = chreAps,
- .radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_LOW_POWER,
- };
- // clang-format on
-
- validateScanEvent(chreEvent);
-}
-
-TEST(WifiConvert, DefaultScanParams) {
- // From chreWifiRequestScanAsyncDefault
- struct chreWifiScanParams params = {};
- params.scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE;
- params.maxScanAgeMs = 5000; // 5 seconds
- params.frequencyListLen = 0;
- params.ssidListLen = 0;
- params.radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT;
-
- validateScanParams(params);
-}
-
-TEST(WifiConvert, ScanParamsWithFreqList) {
- uint32_t freqList[] = {1234, 3456};
- struct chreWifiScanParams chreParams = {
- .scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS,
- .maxScanAgeMs = 9999,
- .frequencyListLen = 2,
- .frequencyList = freqList,
- .ssidListLen = 0,
- .ssidList = nullptr,
- .radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_LOW_POWER,
- };
-
- validateScanParams(chreParams);
-}
-
-TEST(WifiConvert, ScanParamsWithSsidList) {
- // clang-format off
- chreWifiSsidListItem ssidList[] = {
- {.ssidLen = 4, .ssid = {0xde, 0xad, 0xbe, 0xef}},
- {.ssidLen = 2, .ssid = {':', ')'}}
- };
- // clang-format on
- struct chreWifiScanParams chreParams = {
- .scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS,
- .maxScanAgeMs = 9999,
- .frequencyListLen = 0,
- .frequencyList = nullptr,
- .ssidListLen = 2,
- .ssidList = ssidList,
- .radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_LOW_POWER,
- };
-
- validateScanParams(chreParams);
-}
-
-TEST(WifiConvert, ScanParamsWithBothLists) {
- uint32_t freqList[] = {1234, 3456, 5678};
- // clang-format off
- chreWifiSsidListItem ssidList[] = {
- {.ssidLen = 4, .ssid = {0xde, 0xad, 0xbe, 0xef}},
- {.ssidLen = 3, .ssid = {':', '-', ')'}}
- };
- // clang-format on
- struct chreWifiScanParams chreParams = {
- .scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS,
- .maxScanAgeMs = 9999,
- .frequencyListLen = 3,
- .frequencyList = freqList,
- .ssidListLen = 2,
- .ssidList = ssidList,
- .radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_LOW_POWER,
- };
-
- validateScanParams(chreParams);
-}
-
-TEST(WifiConvert, RangingParamsEmpty) {
- struct chreWifiRangingParams chreParams = {
- .targetListLen = 0,
- .targetList = NULL,
- };
-
- validateRangingParams(chreParams);
-}
-
-TEST(WifiConvert, RangingParamsWithTarget) {
- struct chreWifiRangingTarget target = {
- .macAddress = {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc},
- .primaryChannel = 0xdef02468,
- .centerFreqPrimary = 0xace13579,
- .centerFreqSecondary = 0xbdf369cf,
- .channelWidth = 0x48,
- };
-
- struct chreWifiRangingParams chreParams = {
- .targetListLen = 1,
- .targetList = &target,
- };
-
- validateRangingParams(chreParams);
-}
diff --git a/chpp/test/wwan_convert_test.cpp b/chpp/test/wwan_convert_test.cpp
deleted file mode 100644
index 614269e9..00000000
--- a/chpp/test/wwan_convert_test.cpp
+++ /dev/null
@@ -1,394 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <gtest/gtest.h>
-#include <stddef.h>
-
-#include <string.h>
-
-#include "chpp/common/wwan_types.h"
-#include "chpp/memory.h"
-
-namespace {
-
-// clang-format off
-const chreWwanCellInfo kChreCells[] = {
- {
- .timeStamp = 1234,
- .cellInfoType = CHRE_WWAN_CELL_INFO_TYPE_LTE,
- .timeStampType = CHRE_WWAN_CELL_TIMESTAMP_TYPE_MODEM,
- .registered = 1,
- .reserved = 111, // ignored
- .CellInfo = {
- .lte = {
- .cellIdentityLte = {
- .mcc = 777,
- .mnc = 888,
- .ci = 4321,
- .pci = 333,
- .tac = 9876,
- .earfcn = 5432,
- },
- .signalStrengthLte = {
- .signalStrength = 27,
- .rsrp = 96,
- .rsrq = 18,
- .rssnr = 157,
- .cqi = 13,
- .timingAdvance = INT32_MAX,
- }
- }
- }
- },
- {
- .timeStamp = 1235,
- .cellInfoType = CHRE_WWAN_CELL_INFO_TYPE_WCDMA,
- .timeStampType = CHRE_WWAN_CELL_TIMESTAMP_TYPE_ANTENNA,
- .registered = 0,
- .CellInfo = {
- .wcdma = {
- .cellIdentityWcdma = {
- .mcc = 123,
- .mnc = 456,
- .lac = 789,
- .cid = 012,
- .psc = 345,
- .uarfcn = 678,
- },
- .signalStrengthWcdma = {
- .signalStrength = 99,
- .bitErrorRate = INT32_MAX,
- }
- }
- }
- },
-};
-const chreWwanCellInfoResult kChreResultOneCell = {
- .errorCode = 0,
- .cellInfoCount = 1,
- .cells = kChreCells,
-};
-const chreWwanCellInfoResult kChreResultTwoCell = {
- .errorCode = 0,
- .cellInfoCount = 2,
- .cells = kChreCells,
-};
-// clang-format on
-
-void compareCellInfo(const chreWwanCellInfo *chre,
- const ChppWwanCellInfo *chppIn) {
- // Local variable needed to avoid unaligned memory access.
- ChppWwanCellInfo chppLocal;
- memcpy(&chppLocal, chppIn, sizeof(ChppWwanCellInfo));
- const ChppWwanCellInfo *chpp = &chppLocal;
-
- EXPECT_EQ(chpp->timeStamp, chre->timeStamp);
- EXPECT_EQ(chpp->cellInfoType, chre->cellInfoType);
- EXPECT_EQ(chpp->timeStampType, chre->timeStampType);
- EXPECT_EQ(chpp->registered, chre->registered);
-
- switch (chpp->cellInfoType) {
- case CHRE_WWAN_CELL_INFO_TYPE_LTE:
- EXPECT_EQ(chpp->CellInfo.lte.cellIdentityLte.mcc,
- chre->CellInfo.lte.cellIdentityLte.mcc);
- EXPECT_EQ(chpp->CellInfo.lte.cellIdentityLte.mnc,
- chre->CellInfo.lte.cellIdentityLte.mnc);
- EXPECT_EQ(chpp->CellInfo.lte.cellIdentityLte.ci,
- chre->CellInfo.lte.cellIdentityLte.ci);
- EXPECT_EQ(chpp->CellInfo.lte.cellIdentityLte.pci,
- chre->CellInfo.lte.cellIdentityLte.pci);
- EXPECT_EQ(chpp->CellInfo.lte.cellIdentityLte.tac,
- chre->CellInfo.lte.cellIdentityLte.tac);
- EXPECT_EQ(chpp->CellInfo.lte.cellIdentityLte.earfcn,
- chre->CellInfo.lte.cellIdentityLte.earfcn);
-
- EXPECT_EQ(chpp->CellInfo.lte.signalStrengthLte.signalStrength,
- chre->CellInfo.lte.signalStrengthLte.signalStrength);
- EXPECT_EQ(chpp->CellInfo.lte.signalStrengthLte.rsrp,
- chre->CellInfo.lte.signalStrengthLte.rsrp);
- EXPECT_EQ(chpp->CellInfo.lte.signalStrengthLte.rsrq,
- chre->CellInfo.lte.signalStrengthLte.rsrq);
- EXPECT_EQ(chpp->CellInfo.lte.signalStrengthLte.rssnr,
- chre->CellInfo.lte.signalStrengthLte.rssnr);
- EXPECT_EQ(chpp->CellInfo.lte.signalStrengthLte.cqi,
- chre->CellInfo.lte.signalStrengthLte.cqi);
- EXPECT_EQ(chpp->CellInfo.lte.signalStrengthLte.timingAdvance,
- chre->CellInfo.lte.signalStrengthLte.timingAdvance);
- break;
-
- case CHRE_WWAN_CELL_INFO_TYPE_WCDMA:
- EXPECT_EQ(chpp->CellInfo.wcdma.cellIdentityWcdma.mcc,
- chre->CellInfo.wcdma.cellIdentityWcdma.mcc);
- EXPECT_EQ(chpp->CellInfo.wcdma.cellIdentityWcdma.mnc,
- chre->CellInfo.wcdma.cellIdentityWcdma.mnc);
- EXPECT_EQ(chpp->CellInfo.wcdma.cellIdentityWcdma.lac,
- chre->CellInfo.wcdma.cellIdentityWcdma.lac);
- EXPECT_EQ(chpp->CellInfo.wcdma.cellIdentityWcdma.cid,
- chre->CellInfo.wcdma.cellIdentityWcdma.cid);
- EXPECT_EQ(chpp->CellInfo.wcdma.cellIdentityWcdma.psc,
- chre->CellInfo.wcdma.cellIdentityWcdma.psc);
- EXPECT_EQ(chpp->CellInfo.wcdma.cellIdentityWcdma.uarfcn,
- chre->CellInfo.wcdma.cellIdentityWcdma.uarfcn);
-
- EXPECT_EQ(chpp->CellInfo.wcdma.signalStrengthWcdma.signalStrength,
- chre->CellInfo.wcdma.signalStrengthWcdma.signalStrength);
- EXPECT_EQ(chpp->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate,
- chre->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
- break;
-
- default:
- // Other types not supported yet
- ASSERT_TRUE(false);
- }
-}
-
-//! Test for correct handling of a malformed ChppWwanCellInfoResult (e.g. short
-//! payload, invalid offset/length)
-void testMalformedCellInfoResultDecoding(struct ChppWwanCellInfoResult *chpp,
- size_t inputSize) {
- chreWwanCellInfoResult *chreMalformed;
-
- inputSize--;
- chreMalformed = chppWwanCellInfoResultToChre(chpp, inputSize);
- EXPECT_EQ(chreMalformed, nullptr);
- inputSize++;
-
- chpp->cells.offset++;
- chreMalformed = chppWwanCellInfoResultToChre(chpp, inputSize);
- EXPECT_EQ(chreMalformed, nullptr);
- chpp->cells.offset--;
-
- chpp->cells.length++;
- chreMalformed = chppWwanCellInfoResultToChre(chpp, inputSize);
- EXPECT_EQ(chreMalformed, nullptr);
- chpp->cells.length--;
-
- chpp->cellInfoCount++;
- chreMalformed = chppWwanCellInfoResultToChre(chpp, inputSize);
- EXPECT_EQ(chreMalformed, nullptr);
- chpp->cellInfoCount--;
-
- chpp->cellInfoCount--;
- chreMalformed = chppWwanCellInfoResultToChre(chpp, inputSize);
- EXPECT_EQ(chreMalformed, nullptr);
- chpp->cellInfoCount++;
-}
-
-TEST(WwanConvert, EncodeErrorCode) {
- const chreWwanCellInfoResult chreResult = {
- .version = 200, // ignored
- .errorCode = 2,
- .cellInfoCount = 0,
- .reserved = 3, // ignored
- .cookie = (void *)-1, // ignored
- .cells = nullptr,
- };
-
- ChppWwanCellInfoResultWithHeader *chppWithHeader = nullptr;
- size_t outputSize = 999;
- bool result =
- chppWwanCellInfoResultFromChre(&chreResult, &chppWithHeader, &outputSize);
- ASSERT_TRUE(result);
- ASSERT_NE(chppWithHeader, nullptr);
- EXPECT_EQ(outputSize, sizeof(ChppWwanCellInfoResultWithHeader));
-
- ChppWwanCellInfoResult *chpp = &chppWithHeader->payload;
- EXPECT_EQ(chpp->version, CHRE_WWAN_CELL_INFO_RESULT_VERSION);
- EXPECT_EQ(chpp->errorCode, chreResult.errorCode);
- EXPECT_EQ(chpp->cellInfoCount, chreResult.cellInfoCount);
- EXPECT_EQ(chpp->reserved, 0);
- EXPECT_EQ(chpp->cookie, 0u);
- EXPECT_EQ(chpp->cells.offset, 0);
- EXPECT_EQ(chpp->cells.length, 0);
-
- chppFree(chppWithHeader);
-}
-
-TEST(WwanConvert, DecodeErrorCode) {
- const ChppWwanCellInfoResult chpp = {
- .version = 200, // ignored
- .errorCode = 2,
- .cellInfoCount = 0,
- .reserved = 3, // ignored
- .cookie = 100, // ignored
- .cells.offset = 0,
- .cells.length = 0,
- };
-
- size_t outputSize = sizeof(struct ChppWwanCellInfoResult);
- chreWwanCellInfoResult *chre =
- chppWwanCellInfoResultToChre(&chpp, outputSize);
- ASSERT_NE(chre, nullptr);
-
- EXPECT_EQ(chre->version, CHRE_WWAN_CELL_INFO_RESULT_VERSION);
- EXPECT_EQ(chre->errorCode, chpp.errorCode);
- EXPECT_EQ(chre->cellInfoCount, chpp.cellInfoCount);
- EXPECT_EQ(chre->reserved, 0);
- EXPECT_EQ(chre->cookie, (void *)0);
-
- // Handling of short payload
- chreWwanCellInfoResult *chreShort =
- chppWwanCellInfoResultToChre(&chpp, outputSize - 1);
- ASSERT_EQ(chreShort, nullptr);
-
- chppFree(chre);
-}
-
-TEST(WwanConvert, EncodeOneCell) {
- ChppWwanCellInfoResultWithHeader *chppWithHeader = nullptr;
- size_t outputSize = 999;
- bool result = chppWwanCellInfoResultFromChre(&kChreResultOneCell,
- &chppWithHeader, &outputSize);
- ASSERT_TRUE(result);
- ASSERT_NE(chppWithHeader, nullptr);
- EXPECT_EQ(outputSize, sizeof(ChppWwanCellInfoResultWithHeader) +
- sizeof(ChppWwanCellInfo));
-
- ChppWwanCellInfoResult *chpp = &chppWithHeader->payload;
- EXPECT_EQ(chpp->errorCode, kChreResultOneCell.errorCode);
- EXPECT_EQ(chpp->cellInfoCount, kChreResultOneCell.cellInfoCount);
- EXPECT_EQ(chpp->cells.offset, sizeof(ChppWwanCellInfoResult));
- EXPECT_EQ(chpp->cells.length, sizeof(ChppWwanCellInfo));
-
- ChppWwanCellInfo *chppCell =
- (ChppWwanCellInfo *)((uint8_t *)chpp + chpp->cells.offset);
- EXPECT_EQ(chppCell->reserved, 0);
- compareCellInfo(&kChreCells[0], chppCell);
-
- chppFree(chppWithHeader);
-}
-
-TEST(WwanConvert, EncodeDecodeOneCell) {
- ChppWwanCellInfoResultWithHeader *chppWithHeader;
- size_t outputSize;
- bool result = chppWwanCellInfoResultFromChre(&kChreResultOneCell,
- &chppWithHeader, &outputSize);
- ASSERT_TRUE(result);
- ASSERT_NE(chppWithHeader, nullptr);
-
- ChppWwanCellInfoResult *chpp = &chppWithHeader->payload;
- ChppWwanCellInfo *chppCell =
- (ChppWwanCellInfo *)((uint8_t *)chpp + chpp->cells.offset);
-
- chpp->version = 100; // ignored
- chpp->reserved = 10; // ignored
- chpp->cookie = -10; // ignored
-
- size_t inputSize = outputSize - sizeof(struct ChppAppHeader);
-
- chreWwanCellInfoResult *chre = chppWwanCellInfoResultToChre(chpp, inputSize);
- ASSERT_NE(chre, nullptr);
-
- EXPECT_EQ(chre->version, CHRE_WWAN_CELL_INFO_RESULT_VERSION);
- EXPECT_EQ(chre->reserved, 0);
- EXPECT_EQ(chre->cookie, (void *)0);
-
- EXPECT_EQ(chre->errorCode, chpp->errorCode);
- EXPECT_EQ(chre->errorCode, kChreResultOneCell.errorCode);
- EXPECT_EQ(chre->cellInfoCount, chpp->cellInfoCount);
- EXPECT_EQ(chre->cellInfoCount, kChreResultOneCell.cellInfoCount);
-
- EXPECT_EQ(chre->cells[0].reserved, 0);
- compareCellInfo(&kChreCells[0], chppCell);
- compareCellInfo(&chre->cells[0], chppCell);
-
- testMalformedCellInfoResultDecoding(chpp, inputSize);
-
- chppFree(chppWithHeader);
- chppFree(chre);
-}
-
-TEST(WwanConvert, EncodeTwoCells) {
- ChppWwanCellInfoResultWithHeader *chppWithHeader = nullptr;
- size_t outputSize = 999;
- bool result = chppWwanCellInfoResultFromChre(&kChreResultTwoCell,
- &chppWithHeader, &outputSize);
- ASSERT_TRUE(result);
- ASSERT_NE(chppWithHeader, nullptr);
- EXPECT_EQ(outputSize, sizeof(ChppWwanCellInfoResultWithHeader) +
- 2 * sizeof(ChppWwanCellInfo));
-
- ChppWwanCellInfoResult *chpp = &chppWithHeader->payload;
- EXPECT_EQ(chpp->errorCode, kChreResultTwoCell.errorCode);
- EXPECT_EQ(chpp->cellInfoCount, kChreResultTwoCell.cellInfoCount);
- EXPECT_EQ(chpp->cells.offset, sizeof(ChppWwanCellInfoResult));
- EXPECT_EQ(chpp->cells.length, 2 * sizeof(ChppWwanCellInfo));
-
- ChppWwanCellInfo *chppCells =
- (ChppWwanCellInfo *)((uint8_t *)chpp + chpp->cells.offset);
- EXPECT_EQ(chppCells[0].reserved, 0);
- EXPECT_EQ(chppCells[1].reserved, 0);
- compareCellInfo(&kChreCells[0], &chppCells[0]);
- compareCellInfo(&kChreCells[1], &chppCells[1]);
-
- // Ensure unused bytes in the union are zeroed out
- uint8_t *pastEnd =
- (uint8_t *)&chppCells[1].CellInfo.wcdma.signalStrengthWcdma.bitErrorRate +
- sizeof(chppCells[1].CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
- size_t sizePastEnd = sizeof(chreWwanCellInfo::chreWwanCellInfoPerRat) -
- sizeof(chreWwanCellInfoWcdma);
- uint8_t zeros[sizePastEnd];
- memset(zeros, 0, sizePastEnd);
- EXPECT_EQ(memcmp(pastEnd, zeros, sizeof(zeros)), 0);
-
- chppFree(chppWithHeader);
-}
-
-TEST(WwanConvert, EncodeDecodeTwoCells) {
- ChppWwanCellInfoResultWithHeader *chppWithHeader;
- size_t outputSize;
- bool result = chppWwanCellInfoResultFromChre(&kChreResultTwoCell,
- &chppWithHeader, &outputSize);
- ASSERT_TRUE(result);
- ASSERT_NE(chppWithHeader, nullptr);
-
- ChppWwanCellInfoResult *chpp = &chppWithHeader->payload;
- ChppWwanCellInfo *chppCells =
- (ChppWwanCellInfo *)((uint8_t *)chpp + chpp->cells.offset);
-
- chpp->version = 100; // ignored
- chpp->reserved = 10; // ignored
- chpp->cookie = -10; // ignored
-
- size_t inputSize = outputSize - sizeof(struct ChppAppHeader);
-
- chreWwanCellInfoResult *chre = chppWwanCellInfoResultToChre(chpp, inputSize);
- ASSERT_NE(chre, nullptr);
-
- EXPECT_EQ(chre->version, CHRE_WWAN_CELL_INFO_RESULT_VERSION);
- EXPECT_EQ(chre->reserved, 0);
- EXPECT_EQ(chre->cookie, (void *)0);
-
- EXPECT_EQ(chre->errorCode, chpp->errorCode);
- EXPECT_EQ(chpp->errorCode, kChreResultTwoCell.errorCode);
- EXPECT_EQ(chre->cellInfoCount, chpp->cellInfoCount);
- EXPECT_EQ(chpp->cellInfoCount, kChreResultTwoCell.cellInfoCount);
-
- EXPECT_EQ(chre->cells[0].reserved, 0);
- compareCellInfo(&kChreCells[0], &chppCells[0]);
- compareCellInfo(&chre->cells[0], &chppCells[0]);
-
- EXPECT_EQ(chre->cells[1].reserved, 0);
- compareCellInfo(&kChreCells[1], &chppCells[1]);
- compareCellInfo(&chre->cells[1], &chppCells[1]);
-
- testMalformedCellInfoResultDecoding(chpp, inputSize);
-
- chppFree(chppWithHeader);
- chppFree(chre);
-}
-
-} // namespace
diff --git a/chpp/tools/uuid_gen.py b/chpp/tools/uuid_gen.py
deleted file mode 100644
index 0fdd9fdc..00000000
--- a/chpp/tools/uuid_gen.py
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/usr/bin/python3
-#
-# Copyright (C) 2020 The Android Open Source Project
-#
-# 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.
-#
-
-#
-# This scripts prints a version 4 (random) UUID as a series of comma-separated
-# bytes in braces, so it can be easily used when developing a new CHPP client /
-# service.
-#
-
-import uuid
-
-u = uuid.uuid4().hex
-print("Generated version 4 (random) UUID is " + u)
-
-print("{", end="")
-loc = 0
-while loc < len(u) - 2: # loop through UUID bytes except last byte
- print("0x" + u[loc:loc+2] + ", ", end="")
- loc += 2
-print("0x" + u[loc:loc+2] + "}")
diff --git a/chpp/transport.c b/chpp/transport.c
index f3f76517..c9afeec7 100644
--- a/chpp/transport.c
+++ b/chpp/transport.c
@@ -16,22 +16,6 @@
#include "chpp/transport.h"
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#include "chpp/app.h"
-#include "chpp/clients.h"
-#include "chpp/clients/discovery.h"
-#include "chpp/crc.h"
-#include "chpp/link.h"
-#include "chpp/log.h"
-#include "chpp/macros.h"
-#include "chpp/memory.h"
-#include "chpp/platform/platform_link.h"
-#include "chpp/time.h"
/************************************************
* Prototypes
@@ -47,51 +31,18 @@ static size_t chppConsumePayload(struct ChppTransportState *context,
const uint8_t *buf, size_t len);
static size_t chppConsumeFooter(struct ChppTransportState *context,
const uint8_t *buf, size_t len);
-static void chppAbortRxPacket(struct ChppTransportState *context);
-#ifdef CHPP_SERVICE_ENABLED_TRANSPORT_LOOPBACK
-static void chppProcessTransportLoopbackRequest(
- struct ChppTransportState *context);
-#endif
-#ifdef CHPP_CLIENT_ENABLED_TRANSPORT_LOOPBACK
-static void chppProcessTransportLoopbackResponse(
- struct ChppTransportState *context);
-#endif
-static void chppSetResetComplete(struct ChppTransportState *context);
-static void chppProcessResetAck(struct ChppTransportState *context);
-static void chppProcessRxPacket(struct ChppTransportState *context);
static void chppProcessRxPayload(struct ChppTransportState *context);
-static void chppClearRxDatagram(struct ChppTransportState *context);
static bool chppRxChecksumIsOk(const struct ChppTransportState *context);
-static enum ChppTransportErrorCode chppRxHeaderCheck(
+static enum ChppErrorCode chppRxHeaderCheck(
const struct ChppTransportState *context);
static void chppRegisterRxAck(struct ChppTransportState *context);
static void chppEnqueueTxPacket(struct ChppTransportState *context,
- uint8_t packetCode);
+ enum ChppErrorCode errorCode);
static size_t chppAddPreamble(uint8_t *buf);
-static struct ChppTransportHeader *chppAddHeader(
- struct ChppTransportState *context);
-static void chppAddPayload(struct ChppTransportState *context);
-static void chppAddFooter(struct PendingTxPacket *packet);
-size_t chppDequeueTxDatagram(struct ChppTransportState *context);
-static void chppClearTxDatagramQueue(struct ChppTransportState *context);
-static void chppTransportDoWork(struct ChppTransportState *context);
-static void chppAppendToPendingTxPacket(struct PendingTxPacket *packet,
- const uint8_t *buf, size_t len);
-static const char *chppGetPacketAttrStr(uint8_t packetCode);
-static bool chppEnqueueTxDatagram(struct ChppTransportState *context,
- uint8_t packetCode, void *buf, size_t len);
-enum ChppLinkErrorCode chppSendPendingPacket(
- struct ChppTransportState *context);
-
-static void chppResetTransportContext(struct ChppTransportState *context);
-static void chppReset(struct ChppTransportState *context,
- enum ChppTransportPacketAttributes resetType,
- enum ChppTransportErrorCode error);
-#ifdef CHPP_CLIENT_ENABLED
-struct ChppAppHeader *chppTransportGetClientRequestTimeoutResponse(
- struct ChppTransportState *context);
-#endif
+static uint32_t chppCalculateChecksum(uint8_t *buf, size_t len);
+bool chppDequeueTxDatagram(struct ChppTransportState *context);
+void chppTransportDoWork(struct ChppTransportState *context);
/************************************************
* Private Functions
@@ -102,14 +53,13 @@ struct ChppAppHeader *chppTransportGetClientRequestTimeoutResponse(
* counter among that state (rxStatus.locInState) is also reset at the same
* time.
*
- * @param context Maintains status for each transport layer instance.
- * @param newState Next Rx state.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
+ * @param newState Next Rx state
*/
static void chppSetRxState(struct ChppTransportState *context,
enum ChppRxState newState) {
- CHPP_LOGD("Changing RX transport state from %" PRIu8 " to %" PRIu8
- " after %" PRIuSIZE " bytes",
- context->rxStatus.state, newState, context->rxStatus.locInState);
+ LOGD("Changing state from %d to %d", context->rxStatus.state, newState);
context->rxStatus.locInState = 0;
context->rxStatus.state = newState;
}
@@ -122,11 +72,12 @@ static void chppSetRxState(struct ChppTransportState *context,
* Any future backwards-incompatible versions of CHPP Transport will use a
* different preamble.
*
- * @param context Maintains status for each transport layer instance.
- * @param buf Input data.
- * @param len Length of input data in bytes.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
+ * @param buf Input data
+ * @param len Length of input data in bytes
*
- * @return Length of consumed data in bytes.
+ * @return Length of consumed data in bytes
*/
static size_t chppConsumePreamble(struct ChppTransportState *context,
const uint8_t *buf, size_t len) {
@@ -136,16 +87,16 @@ static size_t chppConsumePreamble(struct ChppTransportState *context,
// serial port calling chppRxDataCb does not implement zero filter
while (consumed < len &&
context->rxStatus.locInState < CHPP_PREAMBLE_LEN_BYTES) {
- size_t offset = context->rxStatus.locInState;
- if ((offset == 0 && buf[consumed] == CHPP_PREAMBLE_BYTE_FIRST) ||
- (offset == 1 && buf[consumed] == CHPP_PREAMBLE_BYTE_SECOND)) {
+ if (buf[consumed] ==
+ ((CHPP_PREAMBLE_DATA >>
+ (CHPP_PREAMBLE_LEN_BYTES - context->rxStatus.locInState - 1)) &
+ 0xff)) {
// Correct byte of preamble observed
context->rxStatus.locInState++;
-
- } else if (buf[consumed] == CHPP_PREAMBLE_BYTE_FIRST) {
+ } else if (buf[consumed] ==
+ ((CHPP_PREAMBLE_DATA >> (CHPP_PREAMBLE_LEN_BYTES - 1)) & 0xff)) {
// Previous search failed but first byte of another preamble observed
context->rxStatus.locInState = 1;
-
} else {
// Continue search for a valid preamble from the start
context->rxStatus.locInState = 0;
@@ -157,7 +108,6 @@ static size_t chppConsumePreamble(struct ChppTransportState *context,
// Let's see why we exited the above loop
if (context->rxStatus.locInState == CHPP_PREAMBLE_LEN_BYTES) {
// Complete preamble observed, move on to next state
- context->rxStatus.packetStartTimeNs = chppGetCurrentTimeNs();
chppSetRxState(context, CHPP_STATE_HEADER);
}
@@ -169,11 +119,12 @@ static size_t chppConsumePreamble(struct ChppTransportState *context,
* stream.
* Moves the Rx state to CHPP_STATE_PAYLOAD afterwards.
*
- * @param context Maintains status for each transport layer instance.
- * @param buf Input data.
- * @param len Length of input data in bytes.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
+ * @param buf Input data
+ * @param len Length of input data in bytes
*
- * @return Length of consumed data in bytes.
+ * @return Length of consumed data in bytes
*/
static size_t chppConsumeHeader(struct ChppTransportState *context,
const uint8_t *buf, size_t len) {
@@ -181,48 +132,54 @@ static size_t chppConsumeHeader(struct ChppTransportState *context,
sizeof(struct ChppTransportHeader));
size_t bytesToCopy = MIN(
len, (sizeof(struct ChppTransportHeader) - context->rxStatus.locInState));
+
+ LOGD("Copying %zu bytes of header", bytesToCopy);
memcpy(((uint8_t *)&context->rxHeader) + context->rxStatus.locInState, buf,
bytesToCopy);
- context->rxStatus.locInState += bytesToCopy;
+ context->rxStatus.locInState += bytesToCopy;
if (context->rxStatus.locInState == sizeof(struct ChppTransportHeader)) {
// Header fully copied. Move on
- enum ChppTransportErrorCode headerCheckResult = chppRxHeaderCheck(context);
- if (headerCheckResult != CHPP_TRANSPORT_ERROR_NONE) {
- // Header fails consistency check. NACK and return to preamble state
- chppEnqueueTxPacket(
- context, CHPP_ATTR_AND_ERROR_TO_PACKET_CODE(CHPP_TRANSPORT_ATTR_NONE,
- headerCheckResult));
+ enum ChppErrorCode headerSanity = chppRxHeaderCheck(context);
+ if (headerSanity != CHPP_ERROR_NONE) {
+ // Header fails sanity check. NACK and return to preamble state
+ chppEnqueueTxPacket(context, headerSanity);
chppSetRxState(context, CHPP_STATE_PREAMBLE);
- } else if (context->rxHeader.length == 0) {
- // Non-payload packet
- chppSetRxState(context, CHPP_STATE_FOOTER);
-
} else {
- // Payload bearing packet
- uint8_t *tempPayload;
+ // Header passes sanity check
- if (context->rxDatagram.length == 0) {
- // Packet is a new datagram
- tempPayload = chppMalloc(context->rxHeader.length);
- } else {
- // Packet is a continuation of a fragmented datagram
- tempPayload =
- chppRealloc(context->rxDatagram.payload,
- context->rxDatagram.length + context->rxHeader.length,
- context->rxDatagram.length);
- }
+ if (context->rxHeader.length == 0) {
+ // Non-payload packet
+ chppSetRxState(context, CHPP_STATE_FOOTER);
- if (tempPayload == NULL) {
- CHPP_LOG_OOM();
- chppEnqueueTxPacket(context, CHPP_TRANSPORT_ERROR_OOM);
- chppSetRxState(context, CHPP_STATE_PREAMBLE);
} else {
- context->rxDatagram.payload = tempPayload;
- context->rxDatagram.length += context->rxHeader.length;
- chppSetRxState(context, CHPP_STATE_PAYLOAD);
+ // Payload bearing packet
+ uint8_t *tempPayload;
+
+ if (context->rxDatagram.length == 0) {
+ // Packet is a new datagram
+ tempPayload = chppMalloc(context->rxHeader.length);
+ } else {
+ // Packet is a continuation of a fragmented datagram
+ tempPayload =
+ chppRealloc(context->rxDatagram.payload,
+ context->rxDatagram.length + context->rxHeader.length,
+ context->rxDatagram.length);
+ }
+
+ if (tempPayload == NULL) {
+ LOGE("OOM for packet# %d, len=%u. Previous fragment(s) total len=%zu",
+ context->rxHeader.seq, context->rxHeader.length,
+ context->rxDatagram.length);
+ chppEnqueueTxPacket(context, CHPP_ERROR_OOM);
+ chppSetRxState(context, CHPP_STATE_PREAMBLE);
+ } else {
+ context->rxDatagram.payload = tempPayload;
+ context->rxDatagram.length += context->rxHeader.length;
+ chppSetRxState(context, CHPP_STATE_PAYLOAD);
+ }
}
}
}
@@ -235,7 +192,8 @@ static size_t chppConsumeHeader(struct ChppTransportState *context,
* by the header, from the incoming data stream.
* Moves the Rx state to CHPP_STATE_FOOTER afterwards.
*
- * @param context Maintains status for each transport layer instance.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
* @param buf Input data
* @param len Length of input data in bytes
*
@@ -246,13 +204,17 @@ static size_t chppConsumePayload(struct ChppTransportState *context,
CHPP_ASSERT(context->rxStatus.locInState < context->rxHeader.length);
size_t bytesToCopy =
MIN(len, (context->rxHeader.length - context->rxStatus.locInState));
+
+ LOGD("Copying %zu bytes of payload", bytesToCopy);
+
memcpy(context->rxDatagram.payload + context->rxStatus.locInDatagram, buf,
bytesToCopy);
context->rxStatus.locInDatagram += bytesToCopy;
- context->rxStatus.locInState += bytesToCopy;
+ context->rxStatus.locInState += bytesToCopy;
if (context->rxStatus.locInState == context->rxHeader.length) {
- // Entire packet payload copied. Move on
+ // Payload copied. Move on
+
chppSetRxState(context, CHPP_STATE_FOOTER);
}
@@ -264,11 +226,12 @@ static size_t chppConsumePayload(struct ChppTransportState *context,
* stream. Checks checksum, triggering the correct response (ACK / NACK).
* Moves the Rx state to CHPP_STATE_PREAMBLE afterwards.
*
- * @param context Maintains status for each transport layer instance.
- * @param buf Input data.
- * @param len Length of input data in bytes.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
+ * @param buf Input data
+ * @param len Length of input data in bytes
*
- * @return Length of consumed data in bytes.
+ * @return Length of consumed data in bytes
*/
static size_t chppConsumeFooter(struct ChppTransportState *context,
const uint8_t *buf, size_t len) {
@@ -276,6 +239,8 @@ static size_t chppConsumeFooter(struct ChppTransportState *context,
sizeof(struct ChppTransportFooter));
size_t bytesToCopy = MIN(
len, (sizeof(struct ChppTransportFooter) - context->rxStatus.locInState));
+
+ LOGD("Copying %zu bytes of footer (checksum)", bytesToCopy);
memcpy(((uint8_t *)&context->rxFooter) + context->rxStatus.locInState, buf,
bytesToCopy);
@@ -283,442 +248,140 @@ static size_t chppConsumeFooter(struct ChppTransportState *context,
if (context->rxStatus.locInState == sizeof(struct ChppTransportFooter)) {
// Footer copied. Move on
- if (CHPP_TRANSPORT_GET_ERROR(context->rxHeader.packetCode) !=
- CHPP_TRANSPORT_ERROR_NONE) {
- CHPP_LOGE("RX packet len=%" PRIu16 " seq=%" PRIu8 " ackSeq=%" PRIu8
- " attr=0x%" PRIx8 " ERR=%" PRIu8 " flags=0x%" PRIx8,
- context->rxHeader.length, context->rxHeader.seq,
- context->rxHeader.ackSeq,
- (uint8_t)CHPP_TRANSPORT_GET_ATTR(context->rxHeader.packetCode),
- (uint8_t)CHPP_TRANSPORT_GET_ERROR(context->rxHeader.packetCode),
- context->rxHeader.flags);
- } else {
- CHPP_LOGD("RX packet len=%" PRIu16 " seq=%" PRIu8 " ackSeq=%" PRIu8
- " attr=0x%" PRIx8 " err=%" PRIu8 " flags=0x%" PRIx8,
- context->rxHeader.length, context->rxHeader.seq,
- context->rxHeader.ackSeq,
- (uint8_t)CHPP_TRANSPORT_GET_ATTR(context->rxHeader.packetCode),
- (uint8_t)CHPP_TRANSPORT_GET_ERROR(context->rxHeader.packetCode),
- context->rxHeader.flags);
- }
+ bool hasPayload = (context->rxHeader.length > 0);
+
+ if (!chppRxChecksumIsOk(context)) {
+ // Packet is bad. Discard bad payload data (if any) and NACK
+ LOGE("Discarding CHPP packet# %d len=%u because of bad checksum",
+ context->rxHeader.seq, context->rxHeader.length);
+
+ if (hasPayload) {
+ context->rxDatagram.length -= context->rxHeader.length;
+ context->rxStatus.locInDatagram -= context->rxHeader.length;
+
+ if (context->rxDatagram.length == 0) {
+ // Discarding this packet == discarding entire datagram
+ chppFree(context->rxDatagram.payload);
+ context->rxDatagram.payload = NULL;
+
+ } else {
+ // Discarding this packet == discarding part of datagram
+ uint8_t *tempPayload = chppRealloc(
+ context->rxDatagram.payload, context->rxDatagram.length,
+ context->rxDatagram.length + context->rxHeader.length);
+ if (tempPayload == NULL) {
+ LOGE(
+ "OOM discarding bad continuation packet# %d len=%u. Previous "
+ "fragment(s) total len=%zu",
+ context->rxHeader.seq, context->rxHeader.length,
+ context->rxDatagram.length);
+ } else {
+ context->rxDatagram.payload = tempPayload;
+ }
+ }
+ }
- if (CHPP_TRANSPORT_GET_ATTR(context->rxHeader.packetCode) ==
- CHPP_TRANSPORT_ATTR_LOOPBACK_REQUEST) {
-#ifdef CHPP_SERVICE_ENABLED_TRANSPORT_LOOPBACK
- chppProcessTransportLoopbackRequest(context);
-#endif
-
- } else if (CHPP_TRANSPORT_GET_ATTR(context->rxHeader.packetCode) ==
- CHPP_TRANSPORT_ATTR_LOOPBACK_RESPONSE) {
-#ifdef CHPP_CLIENT_ENABLED_TRANSPORT_LOOPBACK
- chppProcessTransportLoopbackResponse(context);
-#endif
-
- } else if (!chppRxChecksumIsOk(context)) {
- CHPP_LOGE("Bad checksum. seq=%" PRIu8 " len=%" PRIu16,
- context->rxHeader.seq, context->rxHeader.length);
- chppAbortRxPacket(context);
- chppEnqueueTxPacket(context, CHPP_TRANSPORT_ERROR_CHECKSUM); // NACK
-
- } else if (CHPP_TRANSPORT_GET_ATTR(context->rxHeader.packetCode) ==
- CHPP_TRANSPORT_ATTR_RESET) {
- CHPP_LOGI("RX RESET packet seq=%" PRIu8 " err=%" PRIu8,
- context->rxHeader.seq,
- CHPP_TRANSPORT_GET_ERROR(context->rxHeader.packetCode));
- chppMutexUnlock(&context->mutex);
- chppReset(context, CHPP_TRANSPORT_ATTR_RESET_ACK,
- CHPP_TRANSPORT_ERROR_NONE);
- chppMutexLock(&context->mutex);
-
- } else if (context->resetState == CHPP_RESET_STATE_PERMANENT_FAILURE) {
- // Only a reset is accepted in this state
- CHPP_LOGE("RX discarded in perm fail. seq=%" PRIu8 " len=%" PRIu16,
- context->rxHeader.seq, context->rxHeader.length);
- chppAbortRxPacket(context);
-
- } else if (CHPP_TRANSPORT_GET_ATTR(context->rxHeader.packetCode) ==
- CHPP_TRANSPORT_ATTR_RESET_ACK) {
- CHPP_LOGI("RX RESET-ACK packet. seq=%" PRIu8, context->rxHeader.seq);
- chppProcessResetAck(context);
-
- } else if (context->resetState == CHPP_RESET_STATE_RESETTING) {
- CHPP_LOGE("RX discarded in reset. seq=%" PRIu8 " len=%" PRIu16,
- context->rxHeader.seq, context->rxHeader.length);
- chppAbortRxPacket(context);
+ chppEnqueueTxPacket(context, CHPP_ERROR_CHECKSUM);
} else {
- chppProcessRxPacket(context);
- }
-
- // Done with this packet. Wait for next packet
- chppSetRxState(context, CHPP_STATE_PREAMBLE);
- }
-
- return bytesToCopy;
-}
-
-/**
- * Discards of an incomplete Rx packet during receive (e.g. due to a timeout or
- * bad checksum).
- *
- * @param context Maintains status for each transport layer instance.
- */
-static void chppAbortRxPacket(struct ChppTransportState *context) {
- size_t undoLen = 0;
- size_t undoLoc = 0;
-
- switch (context->rxStatus.state) {
- case (CHPP_STATE_PREAMBLE):
- case (CHPP_STATE_HEADER): {
- break;
- }
-
- case (CHPP_STATE_PAYLOAD): {
- undoLen = context->rxHeader.length;
- undoLoc = context->rxStatus.locInState;
- break;
- }
+ // Packet is good. Save received ACK info and process payload if any
- case (CHPP_STATE_FOOTER): {
- undoLen = context->rxHeader.length;
- undoLoc = context->rxHeader.length;
- break;
- }
+ context->rxStatus.receivedErrorCode = context->rxHeader.errorCode;
- default: {
- CHPP_DEBUG_ASSERT(false);
- }
- }
+ chppRegisterRxAck(context);
- if (undoLen > 0) {
- // Packet has a payload we need to discard of
-
- CHPP_ASSERT(context->rxDatagram.length >= undoLen);
- CHPP_ASSERT(context->rxStatus.locInDatagram >= undoLoc);
- context->rxDatagram.length -= undoLen;
- context->rxStatus.locInDatagram -= undoLoc;
-
- if (context->rxDatagram.length == 0) {
- // Discarding this packet == discarding entire datagram
- CHPP_FREE_AND_NULLIFY(context->rxDatagram.payload);
-
- } else {
- // Discarding this packet == discarding part of datagram
- uint8_t *tempPayload =
- chppRealloc(context->rxDatagram.payload, context->rxDatagram.length,
- context->rxDatagram.length + undoLen);
-
- if (tempPayload == NULL) {
- CHPP_LOG_OOM();
- } else {
- context->rxDatagram.payload = tempPayload;
+ if (context->txDatagramQueue.pending > 0) {
+ // There are packets to send out (could be new or retx)
+ chppEnqueueTxPacket(context, CHPP_ERROR_NONE);
}
- }
- }
-
- chppSetRxState(context, CHPP_STATE_PREAMBLE);
-}
-
-/**
- * Processes a request that is determined to be for a transport-layer loopback.
- *
- * @param context Maintains status for each transport layer instance.
- */
-#ifdef CHPP_SERVICE_ENABLED_TRANSPORT_LOOPBACK
-static void chppProcessTransportLoopbackRequest(
- struct ChppTransportState *context) {
- if (context->txStatus.linkBusy) {
- CHPP_LOGE("Link busy; transport-loopback dropped");
-
- } else {
- context->txStatus.linkBusy = true;
- context->pendingTxPacket.length = 0;
- context->pendingTxPacket.length +=
- chppAddPreamble(&context->pendingTxPacket.payload[0]);
-
- struct ChppTransportHeader *txHeader =
- (struct ChppTransportHeader *)&context->pendingTxPacket
- .payload[context->pendingTxPacket.length];
- context->pendingTxPacket.length += sizeof(*txHeader);
- *txHeader = context->rxHeader;
- txHeader->packetCode = CHPP_ATTR_AND_ERROR_TO_PACKET_CODE(
- CHPP_TRANSPORT_ATTR_LOOPBACK_RESPONSE, txHeader->packetCode);
-
- size_t payloadLen =
- MIN(context->rxDatagram.length, CHPP_TRANSPORT_TX_MTU_BYTES);
- chppAppendToPendingTxPacket(&context->pendingTxPacket,
- context->rxDatagram.payload, payloadLen);
- CHPP_FREE_AND_NULLIFY(context->rxDatagram.payload);
- chppClearRxDatagram(context);
-
- chppAddFooter(&context->pendingTxPacket);
-
- CHPP_LOGI("Trans-looping back len=%" PRIu16 " RX len=%" PRIuSIZE,
- txHeader->length, context->rxDatagram.length);
- enum ChppLinkErrorCode error = chppSendPendingPacket(context);
-
- if (error != CHPP_LINK_ERROR_NONE_QUEUED) {
- chppLinkSendDoneCb(&context->linkParams, error);
+ if (hasPayload) {
+ chppProcessRxPayload(context);
+ }
}
- }
-}
-#endif
-
-/**
- * Processes a response that is determined to be for a transport-layer loopback.
- *
- * @param context Maintains status for each transport layer instance.
- */
-#ifdef CHPP_CLIENT_ENABLED_TRANSPORT_LOOPBACK
-static void chppProcessTransportLoopbackResponse(
- struct ChppTransportState *context) {
- if (context->transportLoopbackData.length != context->rxDatagram.length) {
- CHPP_LOGE("rx len=%" PRIuSIZE " != tx len=%" PRIuSIZE,
- context->rxDatagram.length,
- context->transportLoopbackData.length - CHPP_PREAMBLE_LEN_BYTES -
- sizeof(struct ChppTransportHeader) -
- sizeof(struct ChppTransportFooter));
- context->loopbackResult = CHPP_APP_ERROR_INVALID_LENGTH;
-
- } else if (memcmp(context->rxDatagram.payload,
- context->transportLoopbackData.payload,
- context->rxDatagram.length) != 0) {
- CHPP_LOGE("rx & tx data don't match: len=%" PRIuSIZE,
- context->rxDatagram.length);
- context->loopbackResult = CHPP_APP_ERROR_INVALID_ARG;
-
- } else {
- context->loopbackResult = CHPP_APP_ERROR_NONE;
-
- CHPP_LOGD("Rx successful transport-loopback (payload len=%" PRIuSIZE ")",
- context->rxDatagram.length);
- }
-
- context->transportLoopbackData.length = 0;
- CHPP_FREE_AND_NULLIFY(context->transportLoopbackData.payload);
- CHPP_FREE_AND_NULLIFY(context->rxDatagram.payload);
- chppClearRxDatagram(context);
-}
-#endif
-
-/**
- * Method to invoke when the reset sequence is completed.
- *
- * @param context Maintains status for each transport layer instance.
- */
-static void chppSetResetComplete(struct ChppTransportState *context) {
- context->resetState = CHPP_RESET_STATE_NONE;
- context->resetCount = 0;
- chppConditionVariableSignal(&context->resetCondVar);
-}
-
-/**
- * An incoming reset-ack packet indicates that a reset is complete at the other
- * end of the CHPP link.
- *
- * @param context Maintains status for each transport layer instance.
- */
-static void chppProcessResetAck(struct ChppTransportState *context) {
- if (context->resetState == CHPP_RESET_STATE_NONE) {
- CHPP_LOGE("Unexpected reset-ack seq=%" PRIu8 " code=0x%" PRIx8,
- context->rxHeader.seq, context->rxHeader.packetCode);
- // In a reset race condition with both endpoints sending resets and
- // reset-acks, the sent resets and reset-acks will both have a sequence
- // number of 0.
- // By ignoring the received reset-ack, the next expected sequence number
- // will remain at 1 (following a reset with a sequence number of 0).
- // Therefore, no further correction is necessary (beyond ignoring the
- // received reset-ack), as the next packet (e.g. discovery) will have a
- // sequence number of 1.
-
- chppDatagramProcessDoneCb(context, context->rxDatagram.payload);
- chppClearRxDatagram(context);
-
- return;
- }
-
- chppSetResetComplete(context);
- context->rxStatus.receivedPacketCode = context->rxHeader.packetCode;
- context->rxStatus.expectedSeq = context->rxHeader.seq + 1;
- chppRegisterRxAck(context);
-
- // TODO: Configure transport layer based on (optional?) received config
- chppDatagramProcessDoneCb(context, context->rxDatagram.payload);
- chppClearRxDatagram(context);
-
-#ifdef CHPP_CLIENT_ENABLED_DISCOVERY
- if (!context->appContext->isDiscoveryComplete) {
- chppMutexUnlock(&context->mutex);
- chppInitiateDiscovery(context->appContext);
- chppMutexLock(&context->mutex);
- } else {
- chppEnqueueTxPacket(context, CHPP_TRANSPORT_ERROR_NONE);
- }
-#else
- chppEnqueueTxPacket(context, CHPP_TRANSPORT_ERROR_NONE);
-#endif
-
- // Inform the App Layer that a reset has completed
- chppMutexUnlock(&context->mutex);
- chppAppProcessReset(context->appContext);
- chppMutexLock(&context->mutex);
-}
-
-/**
- * Process a received, checksum-validated packet.
- *
- * @param context Maintains status for each transport layer instance.
- */
-static void chppProcessRxPacket(struct ChppTransportState *context) {
- uint64_t now = chppGetCurrentTimeNs();
- context->rxStatus.lastGoodPacketTimeMs = (uint32_t)(now / CHPP_NSEC_PER_MSEC);
- context->rxStatus.receivedPacketCode = context->rxHeader.packetCode;
- chppRegisterRxAck(context);
-
- enum ChppTransportErrorCode errorCode = CHPP_TRANSPORT_ERROR_NONE;
- if (context->rxHeader.length > 0 &&
- context->rxHeader.seq != context->rxStatus.expectedSeq) {
- // Out of order payload
- errorCode = CHPP_TRANSPORT_ERROR_ORDER;
- }
-
- if (context->txDatagramQueue.pending > 0 ||
- errorCode == CHPP_TRANSPORT_ERROR_ORDER) {
- // There are packets to send out (could be new or retx)
- // Note: For a future ACK window > 1, makes more sense to cap the NACKs
- // to one instead of flooding with out of order NACK errors.
- chppEnqueueTxPacket(context, CHPP_ATTR_AND_ERROR_TO_PACKET_CODE(
- CHPP_TRANSPORT_ATTR_NONE, errorCode));
+ // Done with this packet. Wait for next packet
+ chppSetRxState(context, CHPP_STATE_PREAMBLE);
}
- if (errorCode == CHPP_TRANSPORT_ERROR_ORDER) {
- CHPP_LOGE("Out of order RX discarded seq=%" PRIu8 " expect=%" PRIu8
- " len=%" PRIu16,
- context->rxHeader.seq, context->rxStatus.expectedSeq,
- context->rxHeader.length);
- chppAbortRxPacket(context);
-
- } else if (context->rxHeader.length > 0) {
- // Process payload and send ACK
- chppProcessRxPayload(context);
- }
+ return bytesToCopy;
}
/**
* Process the payload of a validated payload-bearing packet and send out the
- * ACK.
+ * ACK
*
- * @param context Maintains status for each transport layer instance.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
*/
static void chppProcessRxPayload(struct ChppTransportState *context) {
- context->rxStatus.expectedSeq++; // chppProcessRxPacket() already confirms
- // that context->rxStatus.expectedSeq ==
- // context->rxHeader.seq, protecting against
- // duplicate and out-of-order packets.
-
if (context->rxHeader.flags & CHPP_TRANSPORT_FLAG_UNFINISHED_DATAGRAM) {
- // Packet is part of a larger datagram
- CHPP_LOGD("RX packet for unfinished datagram. Seq=%" PRIu8 " len=%" PRIu16
- ". Datagram len=%" PRIuSIZE ". Sending ACK=%" PRIu8,
- context->rxHeader.seq, context->rxHeader.length,
- context->rxDatagram.length, context->rxStatus.expectedSeq);
+ // packet is part of a larger datagram
+ LOGD(
+ "Received continuation packet# %d len=%u. Previous fragment(s) "
+ "total len=%zu",
+ context->rxHeader.seq, context->rxHeader.length,
+ context->rxDatagram.length);
} else {
// End of this packet is end of a datagram
+ LOGD(
+ "Received packet# %d len=%u completing a datagram. Previous "
+ "fragment(s) total len=%zu",
+ context->rxHeader.seq, context->rxHeader.length,
+ context->rxDatagram.length);
- // Send the payload to the App Layer
- // Note that it is up to the app layer to free the buffer using
- // chppDatagramProcessDoneCb() after is is done.
- chppMutexUnlock(&context->mutex);
- chppAppProcessRxDatagram(context->appContext, context->rxDatagram.payload,
- context->rxDatagram.length);
- chppMutexLock(&context->mutex);
+ // TODO: do something with the data
- CHPP_LOGD("App layer processed datagram with len=%" PRIuSIZE
- ", ending packet seq=%" PRIu8 ", len=%" PRIu16
- ". Sending ACK=%" PRIu8 " (previously sent=%" PRIu8 ")",
- context->rxDatagram.length, context->rxHeader.seq,
- context->rxHeader.length, context->rxStatus.expectedSeq,
- context->txStatus.sentAckSeq);
- chppClearRxDatagram(context);
+ context->rxStatus.locInDatagram = 0;
+ context->rxDatagram.length = 0;
+ chppFree(context->rxDatagram.payload);
+ context->rxDatagram.payload = NULL;
}
- // Send ACK because we had RX a payload-bearing packet
- chppEnqueueTxPacket(context, CHPP_TRANSPORT_ERROR_NONE);
-}
-
-/**
- * Resets the incoming datagram state, i.e. after the datagram has been
- * processed.
- * Note that this is independent from freeing the payload. It is up to the app
- * layer to inform the transport layer using chppDatagramProcessDoneCb() once it
- * is done with the buffer so it is freed.
- *
- * @param context Maintains status for each transport layer instance.
- */
-static void chppClearRxDatagram(struct ChppTransportState *context) {
- context->rxStatus.locInDatagram = 0;
- context->rxDatagram.length = 0;
- context->rxDatagram.payload = NULL;
+ // Update next expected sequence number and send ACK
+ context->rxStatus.expectedSeq = context->rxHeader.seq + 1;
+ chppEnqueueTxPacket(context, CHPP_ERROR_NONE);
}
/**
* Validates the checksum of an incoming packet.
*
- * @param context Maintains status for each transport layer instance.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
*
- * @return True if and only if the checksum is correct.
+ * @return True if and only if the checksum is correct
*/
static bool chppRxChecksumIsOk(const struct ChppTransportState *context) {
- uint32_t crc = chppCrc32(0, (const uint8_t *)&context->rxHeader,
- sizeof(context->rxHeader));
- crc = chppCrc32(
- crc,
- &context->rxDatagram
- .payload[context->rxStatus.locInDatagram - context->rxHeader.length],
- context->rxHeader.length);
-
-#ifndef CHPP_CHECKSUM_ENABLED
- CHPP_LOGD("Assuming Rx checksum 0x%" PRIx32 " = calculated 0x%" PRIx32,
- context->rxFooter.checksum, crc);
- crc = context->rxFooter.checksum;
-#endif // CHPP_CHECKSUM_ENABLED
-
- if (context->rxFooter.checksum != crc) {
- CHPP_LOGE("Rx BAD checksum: footer=0x%" PRIx32 ", calc=0x%" PRIx32
- ", len=%" PRIuSIZE,
- context->rxFooter.checksum, crc,
- (size_t)(context->rxHeader.length +
- sizeof(struct ChppTransportHeader)));
- }
+ // TODO
+ UNUSED_VAR(context);
- return (context->rxFooter.checksum == crc);
+ LOGE("Blindly assuming checksum is correct");
+ return true;
}
/**
- * Performs consistency checks on received packet header to determine if it is
- * obviously corrupt / invalid / duplicate / out-of-order.
+ * Performs sanity check on received packet header. Discards packet if header is
+ * obviously corrupt / invalid.
*
- * @param context Maintains status for each transport layer instance.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
*
- * @return True if and only if header passes checks
+ * @return True if and only if header passes sanity check
*/
-static enum ChppTransportErrorCode chppRxHeaderCheck(
+static enum ChppErrorCode chppRxHeaderCheck(
const struct ChppTransportState *context) {
- enum ChppTransportErrorCode result = CHPP_TRANSPORT_ERROR_NONE;
+ enum ChppErrorCode result = CHPP_ERROR_NONE;
- if (context->rxHeader.length > CHPP_TRANSPORT_RX_MTU_BYTES) {
- result = CHPP_TRANSPORT_ERROR_HEADER;
+ bool invalidSeqNo = (context->rxHeader.seq != context->rxStatus.expectedSeq);
+ bool hasPayload = (context->rxHeader.length > 0);
+ if (invalidSeqNo && hasPayload) {
+ // Note: For a future ACK window > 1, might make more sense to keep quiet
+ // instead of flooding the sender with out of order NACKs
+ result = CHPP_ERROR_ORDER;
}
- if (result != CHPP_TRANSPORT_ERROR_NONE) {
- CHPP_LOGE("Bad header. seq=%" PRIu8 " expect=%" PRIu8 " len=%" PRIu16
- " err=%" PRIu8,
- context->rxHeader.seq, context->rxStatus.expectedSeq,
- context->rxHeader.length, result);
- }
+ // TODO: More sanity checks
return result;
}
@@ -727,53 +390,27 @@ static enum ChppTransportErrorCode chppRxHeaderCheck(
* Registers a received ACK. If an outgoing datagram is fully ACKed, it is
* popped from the Tx queue.
*
- * @param context Maintains status for each transport layer instance.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
*/
static void chppRegisterRxAck(struct ChppTransportState *context) {
- uint8_t rxAckSeq = context->rxHeader.ackSeq;
-
- if (context->rxStatus.receivedAckSeq != rxAckSeq) {
+ if (context->txStatus.ackedSeq != context->rxHeader.ackSeq) {
// A previously sent packet was actually ACKed
- // Note: For a future ACK window >1, we should loop by # of ACKed packets
- if ((uint8_t)(context->rxStatus.receivedAckSeq + 1) != rxAckSeq) {
- CHPP_LOGE("Out of order ACK: last=%" PRIu8 " rx=%" PRIu8,
- context->rxStatus.receivedAckSeq, rxAckSeq);
- } else {
- CHPP_LOGD(
- "ACK received (last registered=%" PRIu8 ", received=%" PRIu8
- "). Prior queue depth=%" PRIu8 ", front datagram=%" PRIu8
- " at loc=%" PRIuSIZE " of len=%" PRIuSIZE,
- context->rxStatus.receivedAckSeq, rxAckSeq,
- context->txDatagramQueue.pending, context->txDatagramQueue.front,
- context->txStatus.ackedLocInDatagram,
- context->txDatagramQueue.datagram[context->txDatagramQueue.front]
- .length);
-
- context->rxStatus.receivedAckSeq = rxAckSeq;
- if (context->txStatus.txAttempts > 1) {
- CHPP_LOGW("Seq %" PRIu8 " ACK'd after %" PRIuSIZE " reTX",
- context->rxHeader.seq, context->txStatus.txAttempts - 1);
- }
- context->txStatus.txAttempts = 0;
+ context->txStatus.ackedSeq = context->rxHeader.ackSeq;
- // Process and if necessary pop from Tx datagram queue
- context->txStatus.ackedLocInDatagram += CHPP_TRANSPORT_TX_MTU_BYTES;
- if (context->txStatus.ackedLocInDatagram >=
- context->txDatagramQueue.datagram[context->txDatagramQueue.front]
- .length) {
- // We are done with datagram
+ // Process and if necessary pop from Tx datagram queue
+ context->txStatus.ackedLocInDatagram += CHPP_TRANSPORT_MTU_BYTES;
+ if (context->txStatus.ackedLocInDatagram >=
+ context->txDatagramQueue.datagram[context->txDatagramQueue.front]
+ .length) {
+ // We are done with datagram
- context->txStatus.ackedLocInDatagram = 0;
- context->txStatus.sentLocInDatagram = 0;
+ context->txStatus.ackedLocInDatagram = 0;
+ context->txStatus.sentLocInDatagram = 0;
- // Note: For a future ACK window >1, we need to update the queue
- // position of the datagram being sent as well (relative to the
- // front-of-queue). e.g. context->txStatus.datagramBeingSent--;
+ // Note: For a future ACK window >1, we should update which datagram too
- if (chppDequeueTxDatagram(context) == 0) {
- context->txStatus.hasPacketsToSend = false;
- }
- }
+ chppDequeueTxDatagram(context);
}
} // else {nothing was ACKed}
}
@@ -781,8 +418,8 @@ static void chppRegisterRxAck(struct ChppTransportState *context) {
/**
* Enqueues an outgoing packet with the specified error code. The error code
* refers to the optional reason behind a NACK, if any. An error code of
- * CHPP_TRANSPORT_ERROR_NONE indicates that no error was reported (i.e. either
- * an ACK or an implicit NACK)
+ * CHPP_ERROR_NONE indicates that no error was reported (i.e. either an ACK or
+ * an implicit NACK)
*
* Note that the decision as to wheather to include a payload will be taken
* later, i.e. before the packet is being sent out from the queue. A payload is
@@ -794,165 +431,86 @@ static void chppRegisterRxAck(struct ChppTransportState *context) {
* would only need to send an ACK for the last (correct) packet, hence we only
* need a queue length of one here.
*
- * @param context Maintains status for each transport layer instance.
- * @param packetCode Error code and packet attributes to be sent.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
+ * @param errorCode Error code for the next outgoing packet
*/
static void chppEnqueueTxPacket(struct ChppTransportState *context,
- uint8_t packetCode) {
+ enum ChppErrorCode errorCode) {
context->txStatus.hasPacketsToSend = true;
- context->txStatus.packetCodeToSend = packetCode;
-
- CHPP_LOGD("chppEnqueueTxPacket called with packet code=0x%" PRIx8,
- packetCode);
+ context->txStatus.errorCodeToSend = errorCode;
- // Notifies the main CHPP Transport Layer to run chppTransportDoWork().
- chppNotifierSignal(&context->notifier, CHPP_TRANSPORT_SIGNAL_EVENT);
+ // TODO: Notify chppTransportDoWork
}
/**
- * Adds a CHPP preamble to the beginning of buf.
+ * Adds a CHPP preamble to the beginning of buf
*
- * @param buf The CHPP preamble will be added to buf.
+ * @param buf The CHPP preamble will be added to buf
*
- * @return Size of the added preamble.
+ * @return Size of the added preamble
*/
static size_t chppAddPreamble(uint8_t *buf) {
- buf[0] = CHPP_PREAMBLE_BYTE_FIRST;
- buf[1] = CHPP_PREAMBLE_BYTE_SECOND;
+ for (size_t i = 0; i < CHPP_PREAMBLE_LEN_BYTES; i++) {
+ buf[i] = (uint8_t)(CHPP_PREAMBLE_DATA >> (CHPP_PREAMBLE_LEN_BYTES - 1 - i) &
+ 0xff);
+ }
return CHPP_PREAMBLE_LEN_BYTES;
}
/**
- * Adds the packet header to pendingTxPacket.
+ * Calculates the checksum on a buffer indicated by buf with length len
*
- * @param context Maintains status for each transport layer instance.
+ * @param buf Pointer to buffer for the ckecksum to be calculated on.
+ * @param len Length of the buffer.
*
- * @return Pointer to the added packet header.
+ * @return Calculated checksum.
*/
-static struct ChppTransportHeader *chppAddHeader(
- struct ChppTransportState *context) {
- struct ChppTransportHeader *txHeader =
- (struct ChppTransportHeader *)&context->pendingTxPacket
- .payload[context->pendingTxPacket.length];
- context->pendingTxPacket.length += sizeof(*txHeader);
-
- txHeader->packetCode = context->txStatus.packetCodeToSend;
- context->txStatus.packetCodeToSend = CHPP_ATTR_AND_ERROR_TO_PACKET_CODE(
- context->txStatus.packetCodeToSend, CHPP_TRANSPORT_ERROR_NONE);
-
- txHeader->ackSeq = context->rxStatus.expectedSeq;
- context->txStatus.sentAckSeq = txHeader->ackSeq;
+static uint32_t chppCalculateChecksum(uint8_t *buf, size_t len) {
+ // TODO
- return txHeader;
-}
-
-/**
- * Adds the packet payload to pendingTxPacket.
- *
- * @param context Maintains status for each transport layer instance.
- */
-static void chppAddPayload(struct ChppTransportState *context) {
- struct ChppTransportHeader *txHeader =
- (struct ChppTransportHeader *)&context->pendingTxPacket
- .payload[CHPP_PREAMBLE_LEN_BYTES];
-
- size_t remainingBytes =
- context->txDatagramQueue.datagram[context->txDatagramQueue.front].length -
- context->txStatus.ackedLocInDatagram;
-
- CHPP_LOGD("Adding payload to seq=%" PRIu8 ", remainingBytes=%" PRIuSIZE
- " of pending datagrams=%" PRIu8,
- txHeader->seq, remainingBytes, context->txDatagramQueue.pending);
-
- if (remainingBytes > CHPP_TRANSPORT_TX_MTU_BYTES) {
- // Send an unfinished part of a datagram
- txHeader->flags = CHPP_TRANSPORT_FLAG_UNFINISHED_DATAGRAM;
- txHeader->length = CHPP_TRANSPORT_TX_MTU_BYTES;
- } else {
- // Send final (or only) part of a datagram
- txHeader->flags = CHPP_TRANSPORT_FLAG_FINISHED_DATAGRAM;
- txHeader->length = (uint16_t)remainingBytes;
- }
-
- // Copy payload
- chppAppendToPendingTxPacket(
- &context->pendingTxPacket,
- context->txDatagramQueue.datagram[context->txDatagramQueue.front]
- .payload +
- context->txStatus.ackedLocInDatagram,
- txHeader->length);
-
- context->txStatus.sentLocInDatagram =
- context->txStatus.ackedLocInDatagram + txHeader->length;
-}
-
-/**
- * Adds a footer (containing the checksum) to a packet.
- *
- * @param packet The packet from which to calculate the checksum and append the
- * footer.
- */
-static void chppAddFooter(struct PendingTxPacket *packet) {
- struct ChppTransportFooter footer;
- footer.checksum = chppCrc32(0, &packet->payload[CHPP_PREAMBLE_LEN_BYTES],
- packet->length - CHPP_PREAMBLE_LEN_BYTES);
-
- CHPP_LOGD("Adding transport footer. Checksum=0x%" PRIx32 ", len: %" PRIuSIZE
- " -> %" PRIuSIZE,
- footer.checksum, packet->length, packet->length + sizeof(footer));
-
- chppAppendToPendingTxPacket(packet, (const uint8_t *)&footer, sizeof(footer));
+ UNUSED_VAR(buf);
+ UNUSED_VAR(len);
+ return 1;
}
/**
* Dequeues the datagram at the front of the datagram tx queue, if any, and
- * frees the payload. Returns the number of remaining datagrams in the queue.
+ * frees the payload. Returns false if the queue is empty.
*
- * @param context Maintains status for each transport layer instance.
- * @return Number of remaining datagrams in queue.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
+ * @return True indicates success. False indicates failure, i.e. the queue was
+ * empty.
*/
-size_t chppDequeueTxDatagram(struct ChppTransportState *context) {
- if (context->txDatagramQueue.pending == 0) {
- CHPP_LOGE("Can not dequeue datagram because queue is empty");
+bool chppDequeueTxDatagram(struct ChppTransportState *context) {
+ bool success = false;
- } else {
- CHPP_LOGD("Dequeuing front datagram with index=%" PRIu8 ", len=%" PRIuSIZE
- ". Queue depth: %" PRIu8 "->%d",
- context->txDatagramQueue.front,
- context->txDatagramQueue.datagram[context->txDatagramQueue.front]
- .length,
- context->txDatagramQueue.pending,
- context->txDatagramQueue.pending - 1);
-
- CHPP_FREE_AND_NULLIFY(
- context->txDatagramQueue.datagram[context->txDatagramQueue.front]
- .payload);
+ if (context->txDatagramQueue.pending > 0) {
+ chppFree(context->txDatagramQueue.datagram[context->txDatagramQueue.front]
+ .payload);
+ context->txDatagramQueue.datagram[context->txDatagramQueue.front].payload =
+ NULL;
context->txDatagramQueue.datagram[context->txDatagramQueue.front].length =
0;
context->txDatagramQueue.pending--;
context->txDatagramQueue.front++;
context->txDatagramQueue.front %= CHPP_TX_DATAGRAM_QUEUE_LEN;
- }
- return context->txDatagramQueue.pending;
-}
+ // Note: For a future ACK window >1, we need to update the queue position of
+ // the datagram being sent as well (relative to the front-of-queue). i.e.
+ // context->txStatus.datagramBeingSent--;
-/**
- * Flushes the Tx datagram queue of any pending packets.
- *
- * @param context Maintains status for each transport layer instance.
- */
-static void chppClearTxDatagramQueue(struct ChppTransportState *context) {
- while (context->txDatagramQueue.pending > 0) {
- chppDequeueTxDatagram(context);
+ success = true;
}
- context->txStatus.hasPacketsToSend = false;
+
+ return success;
}
/**
* Sends out a pending outgoing packet based on a notification from
- * chppEnqueueTxPacket().
+ * chppEnqueueTxPacket.
*
* A payload may or may not be included be according the following:
* No payload: If Tx datagram queue is empty OR we are waiting on a pending ACK.
@@ -961,428 +519,115 @@ static void chppClearTxDatagramQueue(struct ChppTransportState *context) {
* Repeat payload: If we haven't received an ACK yet for our previous payload,
* i.e. we have registered an explicit or implicit NACK.
*
- * @param context Maintains status for each transport layer instance.
+ * @param context Is used to maintain status. Must be provided and initialized
+ * through chppTransportInit for each transport layer instance. Cannot be null.
*/
-static void chppTransportDoWork(struct ChppTransportState *context) {
- bool havePacketForLinkLayer = false;
- struct ChppTransportHeader *txHeader;
- struct ChppAppHeader *timeoutResponse = NULL;
-
+void chppTransportDoWork(struct ChppTransportState *context) {
// Note: For a future ACK window >1, there needs to be a loop outside the lock
+
chppMutexLock(&context->mutex);
- if (context->txStatus.hasPacketsToSend && !context->txStatus.linkBusy) {
- // There are pending outgoing packets and the link isn't busy
- havePacketForLinkLayer = true;
- context->txStatus.linkBusy = true;
+ if (context->txStatus.hasPacketsToSend) {
+ // There are pending outgoing packets
+
+ // Lock linkLayerMutex before modifying packetToSend
+ chppMutexLock(&context->linkLayerMutex);
- context->pendingTxPacket.length = 0;
- memset(&context->pendingTxPacket.payload, 0, CHPP_LINK_TX_MTU_BYTES);
+ context->packetToSend.length = 0;
+ memset(&context->packetToSend.payload, 0, CHPP_LINK_MTU_BYTES);
// Add preamble
- context->pendingTxPacket.length +=
- chppAddPreamble(&context->pendingTxPacket.payload[0]);
+ context->packetToSend.length +=
+ chppAddPreamble(&context->packetToSend.payload[0]);
// Add header
- txHeader = chppAddHeader(context);
+ struct ChppTransportHeader *txHeader =
+ (struct ChppTransportHeader *)&context->packetToSend
+ .payload[context->packetToSend.length];
+ context->packetToSend.length += sizeof(*txHeader);
+
+ txHeader->errorCode = context->txStatus.errorCodeToSend;
+ txHeader->ackSeq = context->rxStatus.expectedSeq;
// If applicable, add payload
- if ((context->txDatagramQueue.pending > 0)) {
- // Note: For a future ACK window >1, we need to rewrite this payload
- // adding code to base the next packet on the sent location within the
- // last sent datagram, except for the case of a NACK (explicit or
- // timeout). For a NACK, we would need to base the next packet off the
- // last ACKed location.
-
- txHeader->seq = context->rxStatus.receivedAckSeq;
+ if ((context->txDatagramQueue.pending > 0) &&
+ (context->txStatus.sentSeq == context->txStatus.ackedSeq)) {
+ // Note: For a future ACK window >1, seq # check should be against the
+ // window size.
+
+ // Note: For a future ACK window >1, this is only valid for the
+ // (context->rxStatus.receivedErrorCode != CHPP_ERROR_NONE) case,
+ // i.e. we have registered an explicit or implicit NACK. Else,
+ // txHeader->seq = ++(context->txStatus.sentSeq)
+ txHeader->seq = context->txStatus.ackedSeq + 1;
context->txStatus.sentSeq = txHeader->seq;
- if (context->txStatus.txAttempts > CHPP_TRANSPORT_MAX_RETX &&
- context->resetState != CHPP_RESET_STATE_RESETTING) {
- CHPP_LOGE("Resetting after %d retries", CHPP_TRANSPORT_MAX_RETX);
- havePacketForLinkLayer = false;
+ size_t remainingBytes =
+ context->txDatagramQueue.datagram[context->txDatagramQueue.front]
+ .length -
+ context->txStatus.sentLocInDatagram;
- chppMutexUnlock(&context->mutex);
- chppReset(context, CHPP_TRANSPORT_ATTR_RESET,
- CHPP_TRANSPORT_ERROR_MAX_RETRIES);
- chppMutexLock(&context->mutex);
+ if (remainingBytes > CHPP_TRANSPORT_MTU_BYTES) {
+ // Send an unfinished part of a datagram
+ txHeader->flags = CHPP_TRANSPORT_FLAG_UNFINISHED_DATAGRAM;
+ txHeader->length = CHPP_TRANSPORT_MTU_BYTES;
} else {
- chppAddPayload(context);
- context->txStatus.txAttempts++;
+ // Send final (or only) part of a datagram
+ txHeader->flags = CHPP_TRANSPORT_FLAG_FINISHED_DATAGRAM;
+ txHeader->length = remainingBytes;
}
- } else {
- // No payload
- context->txStatus.hasPacketsToSend = false;
- }
+ // Copy payload
+ memcpy(&context->packetToSend.payload[context->packetToSend.length],
+ context->txDatagramQueue.datagram[context->txDatagramQueue.front]
+ .payload +
+ context->txStatus.sentLocInDatagram,
+ txHeader->length);
+ context->packetToSend.length += txHeader->length;
- chppAddFooter(&context->pendingTxPacket);
+ context->txStatus.sentLocInDatagram += txHeader->length;
- } else {
- CHPP_LOGW(
- "DoWork nothing to send. hasPackets=%d, linkBusy=%d, pending=%" PRIu8
- ", Rx ACK=%" PRIu8 ", Tx seq=%" PRIu8 ", RX state=%" PRIu8,
- context->txStatus.hasPacketsToSend, context->txStatus.linkBusy,
- context->txDatagramQueue.pending, context->rxStatus.receivedAckSeq,
- context->txStatus.sentSeq, context->rxStatus.state);
- }
+ } // else {no payload}
- chppMutexUnlock(&context->mutex);
+ // Note: For a future ACK window >1, this needs to be updated
+ context->txStatus.hasPacketsToSend = false;
- if (havePacketForLinkLayer) {
- CHPP_LOGD("TX->Link: len=%" PRIuSIZE " flags=0x%" PRIx8 " code=0x%" PRIx8
- " ackSeq=%" PRIu8 " seq=%" PRIu8 " payloadLen=%" PRIu16
- " pending=%" PRIu8,
- context->pendingTxPacket.length, txHeader->flags,
- txHeader->packetCode, txHeader->ackSeq, txHeader->seq,
- txHeader->length, context->txDatagramQueue.pending);
- enum ChppLinkErrorCode error = chppSendPendingPacket(context);
-
- if (error != CHPP_LINK_ERROR_NONE_QUEUED) {
- // Platform implementation for platformLinkSend() is synchronous or an
- // error occurred. In either case, we should call chppLinkSendDoneCb()
- // here to release the contents of pendingTxPacket.
- chppLinkSendDoneCb(&context->linkParams, error);
- }
- }
+ // We are done with context. Unlock mutex ASAP.
+ chppMutexUnlock(&context->mutex);
-#ifdef CHPP_CLIENT_ENABLED
- timeoutResponse = chppTransportGetClientRequestTimeoutResponse(context);
-#endif
- if (timeoutResponse != NULL) {
- CHPP_LOGE("Response timeout H#%" PRIu8 " cmd=%" PRIu16 " ID=%" PRIu8,
- timeoutResponse->handle, timeoutResponse->command,
- timeoutResponse->transaction);
- chppAppProcessRxDatagram(context->appContext, (uint8_t *)timeoutResponse,
- sizeof(struct ChppAppHeader));
- }
-}
+ // Populate checksum
+ uint32_t *checksum = (uint32_t *)&context->packetToSend
+ .payload[context->packetToSend.length];
+ context->packetToSend.length += sizeof(*checksum);
+ *checksum = chppCalculateChecksum(context->packetToSend.payload,
+ context->packetToSend.length);
-/**
- * Appends data from a buffer of length len to a PendingTxPacket, updating its
- * length.
- *
- * @param packet The PendingTxBuffer to be appended to.
- * @param buf Input data to be copied from.
- * @param len Length of input data in bytes.
- */
-static void chppAppendToPendingTxPacket(struct PendingTxPacket *packet,
- const uint8_t *buf, size_t len) {
- CHPP_ASSERT(packet->length + len <= sizeof(packet->payload));
- memcpy(&packet->payload[packet->length], buf, len);
- packet->length += len;
-}
+ // TODO: Send out notification to function that sends out the packet.
+ // context->linkLayerMutex must be unlocked by the function that is actually
+ // sending out the packet, and only after it is done sending.
-/**
- * @return A human readable form of the packet attribution.
- */
-static const char *chppGetPacketAttrStr(uint8_t packetCode) {
- switch (CHPP_TRANSPORT_GET_ATTR(packetCode)) {
- case CHPP_TRANSPORT_ATTR_RESET:
- return "(RESET)";
- case CHPP_TRANSPORT_ATTR_RESET_ACK:
- return "(RESET-ACK)";
- case CHPP_TRANSPORT_ATTR_LOOPBACK_REQUEST:
- return "(LOOP-REQ)";
- case CHPP_TRANSPORT_ATTR_LOOPBACK_RESPONSE:
- return "(LOOP-RES)";
- default:
- return "";
- }
-}
+ // TODO: Do we even need linkLayerMutex? We'll see once the new approach
+ // to signalling is in.
-/**
- * Enqueues an outgoing datagram of a specified length. The payload must have
- * been allocated by the caller using chppMalloc.
- *
- * If enqueueing is successful, the payload will be freed by this function
- * once it has been sent out.
- * If enqueueing is unsuccessful, it is up to the caller to decide when or if
- * to free the payload and/or resend it later.
- *
- * @param context Maintains status for each transport layer instance.
- * @param packetCode Error code and packet attributes to be sent.
- * @param buf Datagram payload allocated through chppMalloc. Cannot be null.
- * @param len Datagram length in bytes.
- *
- * @return True informs the sender that the datagram was successfully enqueued.
- * False informs the sender that the queue was full.
- */
-static bool chppEnqueueTxDatagram(struct ChppTransportState *context,
- uint8_t packetCode, void *buf, size_t len) {
- bool success = false;
-
- if (len == 0) {
- CHPP_LOGE("Enqueue tx with len 0");
- CHPP_DEBUG_ASSERT(false);
+ // TODO: For now, unlocking here, but remove once above is addressed
+ chppMutexUnlock(&context->linkLayerMutex);
} else {
- if ((len < sizeof(struct ChppAppHeader)) ||
- (CHPP_TRANSPORT_GET_ATTR(packetCode) != 0)) {
- CHPP_LOGI("Enqueue TX: code=0x%" PRIx8 "%s len=%" PRIuSIZE
- " pending=%" PRIu8,
- packetCode, chppGetPacketAttrStr(packetCode), len,
- (uint8_t)(context->txDatagramQueue.pending + 1));
- } else {
- struct ChppAppHeader *header = buf;
- CHPP_LOGI(
- "Enqueue TX: len=%" PRIuSIZE " H#%" PRIu8 " type=0x%" PRIx8
- " ID=%" PRIu8 " err=%" PRIu8 " cmd=0x%" PRIx16 " pending=%" PRIu8,
- len, header->handle, header->type, header->transaction, header->error,
- header->command, (uint8_t)(context->txDatagramQueue.pending + 1));
- }
-
- chppMutexLock(&context->mutex);
-
- if (context->txDatagramQueue.pending >= CHPP_TX_DATAGRAM_QUEUE_LEN) {
- CHPP_LOGE("Cannot enqueue TX datagram");
-
- } else {
- uint16_t end =
- (context->txDatagramQueue.front + context->txDatagramQueue.pending) %
- CHPP_TX_DATAGRAM_QUEUE_LEN;
- context->txDatagramQueue.datagram[end].length = len;
- context->txDatagramQueue.datagram[end].payload = buf;
- context->txDatagramQueue.pending++;
-
- if (context->txDatagramQueue.pending == 1) {
- // Queue was empty prior. Need to kickstart transmission.
- chppEnqueueTxPacket(context, packetCode);
- }
-
- success = true;
- }
-
+ // There are no pending outgoing packets. Unlock mutex.
chppMutexUnlock(&context->mutex);
}
-
- return success;
}
-/**
- * Sends the pending outgoing packet (context->pendingTxPacket) over to the link
- * layer using chppPlatformLinkSend() and updates the last Tx packet time.
- *
- * @param context Maintains status for each transport layer instance.
- *
- * @return Result of chppPlatformLinkSend().
- */
-enum ChppLinkErrorCode chppSendPendingPacket(
- struct ChppTransportState *context) {
- enum ChppLinkErrorCode error = chppPlatformLinkSend(
- &context->linkParams, context->pendingTxPacket.payload,
- context->pendingTxPacket.length);
-
- context->txStatus.lastTxTimeNs = chppGetCurrentTimeNs();
-
- return error;
-}
-
-/**
- * Resets the transport state, maintaining the link layer parameters.
- *
- * @param context Maintains status for each transport layer instance.
- */
-static void chppResetTransportContext(struct ChppTransportState *context) {
- memset(&context->rxStatus, 0, sizeof(struct ChppRxStatus));
- memset(&context->rxDatagram, 0, sizeof(struct ChppDatagram));
-
- memset(&context->txStatus, 0, sizeof(struct ChppTxStatus));
- memset(&context->txDatagramQueue, 0, sizeof(struct ChppTxDatagramQueue));
-
- context->txStatus.sentSeq =
- UINT8_MAX; // So that the seq # of the first TX packet is 0
- context->resetState = CHPP_RESET_STATE_RESETTING;
-}
-
-/**
- * Re-initializes the CHPP transport and app layer states, e.g. when receiving a
- * reset packet, and sends out a reset or reset-ack packet over the link in
- * order to reset the remote side or inform the counterpart of a reset,
- * respectively.
- *
- * If the link layer is busy, this function will reset the link as well.
- * This function retains and restores the platform-specific values of
- * transportContext.linkParams.
- *
- * @param transportContext Maintains status for each transport layer instance.
- * @param resetType Type of reset to send after resetting CHPP (reset vs.
- * reset-ack), as defined in the ChppTransportPacketAttributes struct.
- * @param error Provides the error that led to the reset.
- */
-static void chppReset(struct ChppTransportState *transportContext,
- enum ChppTransportPacketAttributes resetType,
- enum ChppTransportErrorCode error) {
- // TODO: Configure transport layer based on (optional?) received config before
- // datagram is wiped
-
- chppMutexLock(&transportContext->mutex);
- struct ChppAppState *appContext = transportContext->appContext;
- transportContext->resetState = CHPP_RESET_STATE_RESETTING;
-
- // Reset asynchronous link layer if busy
- if (transportContext->txStatus.linkBusy == true) {
- // TODO: Give time for link layer to finish before resorting to a reset
-
- chppPlatformLinkReset(&transportContext->linkParams);
- }
-
- // Free memory allocated for any ongoing rx datagrams
- if (transportContext->rxDatagram.length > 0) {
- transportContext->rxDatagram.length = 0;
- CHPP_FREE_AND_NULLIFY(transportContext->rxDatagram.payload);
- }
-
- // Free memory allocated for any ongoing tx datagrams
- for (size_t i = 0; i < CHPP_TX_DATAGRAM_QUEUE_LEN; i++) {
- if (transportContext->txDatagramQueue.datagram[i].length > 0) {
- CHPP_FREE_AND_NULLIFY(
- transportContext->txDatagramQueue.datagram[i].payload);
- }
- }
-
- // Reset Transport Layer but restore Rx sequence number and packet code
- // (context->rxHeader is not wiped in reset)
- chppResetTransportContext(transportContext);
- transportContext->rxStatus.receivedPacketCode =
- transportContext->rxHeader.packetCode;
- transportContext->rxStatus.expectedSeq = transportContext->rxHeader.seq + 1;
-
- // Send reset or reset-ACK
- chppMutexUnlock(&transportContext->mutex);
- chppTransportSendReset(transportContext, resetType, error);
-
- // Inform the App Layer that a reset has completed
- if (resetType == CHPP_TRANSPORT_ATTR_RESET_ACK) {
- chppAppProcessReset(appContext);
- } // else reset is sent out. Rx of reset-ack will indicate completion.
-}
-
-/**
- * Checks for a timed out client request and generates a timeout response if a
- * client request timeout has occurred.
- *
- * @param context Maintains status for each transport layer instance.
- * @return App layer response header if a timeout has occurred. Null otherwise.
- */
-#ifdef CHPP_CLIENT_ENABLED
-struct ChppAppHeader *chppTransportGetClientRequestTimeoutResponse(
- struct ChppTransportState *context) {
- struct ChppAppHeader *response = NULL;
-
- bool timeoutClientFound = false;
- uint8_t timedOutClient;
- uint16_t timedOutCmd;
-
- chppMutexLock(&context->mutex);
-
- if (context->appContext->nextRequestTimeoutNs <= chppGetCurrentTimeNs()) {
- // Determine which request has timed out
-
- uint64_t lowestTimeout = CHPP_TIME_MAX;
- for (uint8_t clientIdx = 0;
- clientIdx < context->appContext->registeredClientCount; clientIdx++) {
- for (uint16_t cmdIdx = 0;
- cmdIdx <
- context->appContext->registeredClients[clientIdx]->rRStateCount;
- cmdIdx++) {
- struct ChppRequestResponseState *rRState =
- &context->appContext->registeredClientStates[clientIdx]
- ->rRStates[cmdIdx];
-
- if (rRState->requestState == CHPP_REQUEST_STATE_REQUEST_SENT &&
- rRState->responseTimeNs != CHPP_TIME_NONE &&
- rRState->responseTimeNs < lowestTimeout) {
- lowestTimeout = rRState->responseTimeNs;
- timedOutClient = clientIdx;
- timedOutCmd = cmdIdx;
- timeoutClientFound = true;
- }
- }
- }
-
- if (!timeoutClientFound) {
- CHPP_LOGE("Timeout at %" PRIu64 " but no client",
- context->appContext->nextRequestTimeoutNs / CHPP_NSEC_PER_MSEC);
- chppClientRecalculateNextTimeout(context->appContext);
- }
- }
-
- if (timeoutClientFound) {
- CHPP_LOGE("Client=%" PRIu8 " cmd=%" PRIu16 " timed out", timedOutClient,
- timedOutCmd);
- response = chppMalloc(sizeof(struct ChppAppHeader));
- if (response == NULL) {
- CHPP_LOG_OOM();
- } else {
- response->handle = CHPP_SERVICE_HANDLE_OF_INDEX(timedOutClient);
- response->type = CHPP_MESSAGE_TYPE_SERVICE_RESPONSE;
- response->transaction =
- context->appContext->registeredClientStates[timedOutClient]
- ->rRStates[timedOutCmd]
- .transaction;
- response->error = CHPP_APP_ERROR_TIMEOUT;
- response->command = timedOutCmd;
- }
- }
-
- chppMutexUnlock(&context->mutex);
-
- return response;
-}
-#endif
-
/************************************************
* Public Functions
***********************************************/
-void chppTransportInit(struct ChppTransportState *transportContext,
- struct ChppAppState *appContext) {
- CHPP_NOT_NULL(transportContext);
- CHPP_NOT_NULL(appContext);
- CHPP_ASSERT_LOG(!transportContext->initialized,
- "CHPP transport already initialized");
-
- CHPP_LOGD("Initializing CHPP transport");
-
- chppResetTransportContext(transportContext);
- chppMutexInit(&transportContext->mutex);
- chppNotifierInit(&transportContext->notifier);
- chppConditionVariableInit(&transportContext->resetCondVar);
-
- transportContext->appContext = appContext;
- transportContext->initialized = true;
-
- chppPlatformLinkInit(&transportContext->linkParams);
-}
-
-void chppTransportDeinit(struct ChppTransportState *transportContext) {
- CHPP_NOT_NULL(transportContext);
- CHPP_ASSERT_LOG(transportContext->initialized,
- "CHPP transport already deinitialized");
-
- chppPlatformLinkDeinit(&transportContext->linkParams);
- chppConditionVariableDeinit(&transportContext->resetCondVar);
- chppNotifierDeinit(&transportContext->notifier);
- chppMutexDeinit(&transportContext->mutex);
-
- chppClearTxDatagramQueue(transportContext);
-
- transportContext->initialized = false;
-}
+void chppTransportInit(struct ChppTransportState *context) {
+ CHPP_NOT_NULL(context);
-bool chppTransportWaitForResetComplete(
- struct ChppTransportState *transportContext, uint64_t timeoutMs) {
- bool success = true;
- chppMutexLock(&transportContext->mutex);
- while (success && transportContext->resetState != CHPP_RESET_STATE_NONE) {
- success = chppConditionVariableTimedWait(&transportContext->resetCondVar,
- &transportContext->mutex,
- timeoutMs * CHPP_NSEC_PER_MSEC);
- }
- chppMutexUnlock(&transportContext->mutex);
- return success;
+ memset(context, 0, sizeof(struct ChppTransportState));
+ chppMutexInit(&context->mutex);
}
bool chppRxDataCb(struct ChppTransportState *context, const uint8_t *buf,
@@ -1390,20 +635,8 @@ bool chppRxDataCb(struct ChppTransportState *context, const uint8_t *buf,
CHPP_NOT_NULL(buf);
CHPP_NOT_NULL(context);
- chppMutexLock(&context->mutex);
- if (context->rxStatus.state != CHPP_STATE_PREAMBLE &&
- chppGetCurrentTimeNs() >
- context->rxStatus.packetStartTimeNs + CHPP_TRANSPORT_RX_TIMEOUT_NS) {
- CHPP_LOGE("Packet RX timeout");
- chppAbortRxPacket(context);
- }
- chppMutexUnlock(&context->mutex);
-
- CHPP_LOGD("RX %" PRIuSIZE " bytes: state=%" PRIu8, len,
- context->rxStatus.state);
- uint64_t now = chppGetCurrentTimeNs();
- context->rxStatus.lastDataTimeMs = (uint32_t)(now / CHPP_NSEC_PER_MSEC);
- context->rxStatus.numTotalDataBytes += len;
+ LOGD("chppRxDataCb received %zu bytes (state = %d)", len,
+ context->rxStatus.state);
size_t consumed = 0;
while (consumed < len) {
@@ -1432,11 +665,13 @@ bool chppRxDataCb(struct ChppTransportState *context, const uint8_t *buf,
break;
default:
- CHPP_LOGE("Invalid RX state %" PRIu8, context->rxStatus.state);
- CHPP_DEBUG_ASSERT(false);
+ LOGE("Invalid state %d", context->rxStatus.state);
chppSetRxState(context, CHPP_STATE_PREAMBLE);
}
+ LOGD("chppRxDataCb consumed %zu of %zu bytes (state = %d)", consumed, len,
+ context->rxStatus.state);
+
chppMutexUnlock(&context->mutex);
}
@@ -1444,308 +679,41 @@ bool chppRxDataCb(struct ChppTransportState *context, const uint8_t *buf,
context->rxStatus.locInState == 0);
}
-void chppRxPacketCompleteCb(struct ChppTransportState *context) {
+void chppTxTimeoutTimerCb(struct ChppTransportState *context) {
chppMutexLock(&context->mutex);
- if (context->rxStatus.state != CHPP_STATE_PREAMBLE) {
- CHPP_LOGE("Rx pkt ended early: state=%" PRIu8 " packet=%" PRIu8
- " len=%" PRIu16,
- context->rxStatus.state, context->rxHeader.seq,
- context->rxHeader.length);
- chppAbortRxPacket(context);
- chppEnqueueTxPacket(context, CHPP_TRANSPORT_ERROR_HEADER); // NACK
- }
- chppMutexUnlock(&context->mutex);
-}
-bool chppEnqueueTxDatagramOrFail(struct ChppTransportState *context, void *buf,
- size_t len) {
- bool success = false;
- bool resetting = (context->resetState == CHPP_RESET_STATE_RESETTING);
+ // Implicit NACK. Set received error code accordingly
+ context->rxStatus.receivedErrorCode = CHPP_ERROR_TIMEOUT;
- if (len == 0) {
- CHPP_LOGE("Enqueue datagram len 0");
- CHPP_DEBUG_ASSERT(false);
-
- } else if (resetting || !chppEnqueueTxDatagram(
- context, CHPP_TRANSPORT_ERROR_NONE, buf, len)) {
- uint8_t *handle = buf;
- CHPP_LOGE("Resetting=%d. Discarding %" PRIuSIZE " bytes for H#%" PRIu8,
- resetting, len, *handle);
-
- CHPP_FREE_AND_NULLIFY(buf);
-
- } else {
- success = true;
- }
-
- return success;
-}
-
-// TODO(b/192359485): Consider removing this function, or making it more robust.
-void chppEnqueueTxErrorDatagram(struct ChppTransportState *context,
- enum ChppTransportErrorCode errorCode) {
- bool resetting = (context->resetState == CHPP_RESET_STATE_RESETTING);
- if (resetting) {
- CHPP_LOGE("Discarding app error 0x%" PRIx8 " (resetting)", errorCode);
- } else {
- switch (errorCode) {
- case CHPP_TRANSPORT_ERROR_OOM: {
- CHPP_LOGD("App layer enqueueing CHPP_TRANSPORT_ERROR_OOM");
- break;
- }
- case CHPP_TRANSPORT_ERROR_APPLAYER: {
- CHPP_LOGD("App layer enqueueing CHPP_TRANSPORT_ERROR_APPLAYER");
- break;
- }
- default: {
- // App layer should not invoke any other errors
- CHPP_LOGE("App enqueueing invalid err=%" PRIu8, errorCode);
- CHPP_DEBUG_ASSERT(false);
- }
- }
- chppEnqueueTxPacket(context, CHPP_ATTR_AND_ERROR_TO_PACKET_CODE(
- CHPP_TRANSPORT_ATTR_NONE, errorCode));
- }
-}
-
-uint64_t chppTransportGetTimeUntilNextDoWorkNs(
- struct ChppTransportState *context) {
- uint64_t currentTime = chppGetCurrentTimeNs();
- uint64_t nextDoWorkTime = context->appContext->nextRequestTimeoutNs;
-
- if (context->txStatus.hasPacketsToSend ||
- context->resetState == CHPP_RESET_STATE_RESETTING) {
- nextDoWorkTime =
- MIN(nextDoWorkTime, CHPP_TRANSPORT_TX_TIMEOUT_NS +
- ((context->txStatus.lastTxTimeNs == 0)
- ? currentTime
- : context->txStatus.lastTxTimeNs));
- }
-
- CHPP_LOGD("NextDoWork=%" PRIu64 " currentTime=%" PRIu64 " delta=%" PRId64,
- nextDoWorkTime / CHPP_NSEC_PER_MSEC,
- currentTime / CHPP_NSEC_PER_MSEC,
- (nextDoWorkTime - currentTime) / (int64_t)CHPP_NSEC_PER_MSEC);
-
- if (nextDoWorkTime == CHPP_TIME_MAX) {
- return CHPP_TRANSPORT_TIMEOUT_INFINITE;
- } else if (nextDoWorkTime <= currentTime) {
- return CHPP_TRANSPORT_TIMEOUT_IMMEDIATE;
- } else {
- return nextDoWorkTime - currentTime;
- }
-}
-
-void chppWorkThreadStart(struct ChppTransportState *context) {
- chppTransportSendReset(context, CHPP_TRANSPORT_ATTR_RESET,
- CHPP_TRANSPORT_ERROR_NONE);
- CHPP_LOGD("CHPP Work Thread started");
-
- uint32_t signals;
- do {
- uint64_t timeout = chppTransportGetTimeUntilNextDoWorkNs(context);
- if (timeout == CHPP_TRANSPORT_TIMEOUT_IMMEDIATE) {
- signals = chppNotifierGetSignal(&context->notifier);
- } else if (timeout == CHPP_TRANSPORT_TIMEOUT_INFINITE) {
- signals = chppNotifierWait(&context->notifier);
- } else {
- signals = chppNotifierTimedWait(&context->notifier, timeout);
- }
-
- } while (chppWorkThreadHandleSignal(context, signals));
-}
-
-bool chppWorkThreadHandleSignal(struct ChppTransportState *context,
- uint32_t signals) {
- if (signals & CHPP_TRANSPORT_SIGNAL_EXIT) {
- CHPP_LOGD("CHPP Work Thread terminated");
- return false;
- }
-
- if (signals & CHPP_TRANSPORT_SIGNAL_EVENT) {
- chppTransportDoWork(context);
- }
-
- if (signals == 0) {
- // Triggered by timeout
-
- if (chppGetCurrentTimeNs() - context->txStatus.lastTxTimeNs >=
- CHPP_TRANSPORT_TX_TIMEOUT_NS) {
- CHPP_LOGE("ACK timeout. Tx t=%" PRIu64,
- context->txStatus.lastTxTimeNs / CHPP_NSEC_PER_MSEC);
- chppTransportDoWork(context);
- }
-
- if ((context->resetState == CHPP_RESET_STATE_RESETTING) &&
- (chppGetCurrentTimeNs() - context->resetTimeNs >=
- CHPP_TRANSPORT_RESET_TIMEOUT_NS)) {
- if (context->resetCount + 1 < CHPP_TRANSPORT_MAX_RESET) {
- CHPP_LOGE("RESET-ACK timeout; retrying");
- context->resetCount++;
- chppReset(context, CHPP_TRANSPORT_ATTR_RESET,
- CHPP_TRANSPORT_ERROR_TIMEOUT);
- } else {
- CHPP_LOGE("RESET-ACK timeout; giving up");
- context->resetState = CHPP_RESET_STATE_PERMANENT_FAILURE;
- chppClearTxDatagramQueue(context);
- }
- }
- }
-
- if (signals & CHPP_TRANSPORT_SIGNAL_PLATFORM_MASK) {
- chppPlatformLinkDoWork(&context->linkParams,
- signals & CHPP_TRANSPORT_SIGNAL_PLATFORM_MASK);
- }
-
- return true;
-}
-
-void chppWorkThreadStop(struct ChppTransportState *context) {
- chppNotifierSignal(&context->notifier, CHPP_TRANSPORT_SIGNAL_EXIT);
-}
-
-void chppLinkSendDoneCb(struct ChppPlatformLinkParameters *params,
- enum ChppLinkErrorCode error) {
- if (error != CHPP_LINK_ERROR_NONE_SENT) {
- CHPP_LOGE("Async send failure: %" PRIu8, error);
- }
-
- struct ChppTransportState *context =
- container_of(params, struct ChppTransportState, linkParams);
-
- chppMutexLock(&context->mutex);
-
- context->txStatus.linkBusy = false;
-
- // No need to free anything as pendingTxPacket.payload is static. Likewise, we
- // keep pendingTxPacket.length to assist testing.
+ // Enqueue Tx packet which will be a retransmission based on the above
+ chppEnqueueTxPacket(context, CHPP_ERROR_NONE);
chppMutexUnlock(&context->mutex);
}
-void chppDatagramProcessDoneCb(struct ChppTransportState *context,
- uint8_t *buf) {
- UNUSED_VAR(context);
-
- CHPP_FREE_AND_NULLIFY(buf);
-}
-
-uint8_t chppRunTransportLoopback(struct ChppTransportState *context,
- uint8_t *buf, size_t len) {
- UNUSED_VAR(buf);
- UNUSED_VAR(len);
- uint8_t result = CHPP_APP_ERROR_UNSUPPORTED;
- context->loopbackResult = result;
-
-#ifdef CHPP_CLIENT_ENABLED_TRANSPORT_LOOPBACK
- result = CHPP_APP_ERROR_NONE;
- context->loopbackResult = CHPP_APP_ERROR_UNSPECIFIED;
-
- if (len == 0 || len > CHPP_TRANSPORT_TX_MTU_BYTES) {
- result = CHPP_APP_ERROR_INVALID_LENGTH;
- context->loopbackResult = result;
-
- } else if (context->txStatus.linkBusy) {
- result = CHPP_APP_ERROR_BLOCKED;
- context->loopbackResult = result;
-
- } else if (context->transportLoopbackData.payload != NULL) {
- result = CHPP_APP_ERROR_BUSY;
- context->loopbackResult = result;
-
- } else if ((context->transportLoopbackData.payload = chppMalloc(len)) ==
- NULL) {
- result = CHPP_APP_ERROR_OOM;
- context->loopbackResult = result;
-
- } else {
- context->transportLoopbackData.length = len;
- memcpy(context->transportLoopbackData.payload, buf, len);
-
- context->txStatus.linkBusy = true;
- context->pendingTxPacket.length = 0;
- memset(&context->pendingTxPacket.payload, 0, CHPP_LINK_TX_MTU_BYTES);
- context->pendingTxPacket.length +=
- chppAddPreamble(&context->pendingTxPacket.payload[0]);
-
- struct ChppTransportHeader *txHeader =
- (struct ChppTransportHeader *)&context->pendingTxPacket
- .payload[context->pendingTxPacket.length];
- context->pendingTxPacket.length += sizeof(*txHeader);
-
- txHeader->packetCode = CHPP_ATTR_AND_ERROR_TO_PACKET_CODE(
- CHPP_TRANSPORT_ATTR_LOOPBACK_REQUEST, txHeader->packetCode);
-
- size_t payloadLen = MIN(len, CHPP_TRANSPORT_TX_MTU_BYTES);
- txHeader->length = (uint16_t)payloadLen;
- chppAppendToPendingTxPacket(&context->pendingTxPacket, buf, payloadLen);
-
- chppAddFooter(&context->pendingTxPacket);
+bool chppEnqueueTxDatagram(struct ChppTransportState *context, size_t len,
+ uint8_t *buf) {
+ bool success = false;
+ chppMutexLock(&context->mutex);
- CHPP_LOGD("Sending transport-loopback request (packet len=%" PRIuSIZE
- ", payload len=%" PRIu16 ", asked len was %" PRIuSIZE ")",
- context->pendingTxPacket.length, txHeader->length, len);
- enum ChppLinkErrorCode error = chppSendPendingPacket(context);
+ if (context->txDatagramQueue.pending < CHPP_TX_DATAGRAM_QUEUE_LEN) {
+ uint16_t end =
+ (context->txDatagramQueue.front + context->txDatagramQueue.pending) %
+ CHPP_TX_DATAGRAM_QUEUE_LEN;
- if (error != CHPP_LINK_ERROR_NONE_QUEUED) {
- // Either sent synchronously or an error has occurred
- chppLinkSendDoneCb(&context->linkParams, error);
+ context->txDatagramQueue.datagram[end].length = len;
+ context->txDatagramQueue.datagram[end].payload = buf;
+ context->txDatagramQueue.pending++;
- if (error != CHPP_LINK_ERROR_NONE_SENT) {
- // An error has occurred
- CHPP_FREE_AND_NULLIFY(context->transportLoopbackData.payload);
- context->transportLoopbackData.length = 0;
- result = CHPP_APP_ERROR_UNSPECIFIED;
- }
+ if (context->txDatagramQueue.pending == 1) {
+ // Queue was empty prior. Need to kickstart transmission.
+ chppEnqueueTxPacket(context, CHPP_ERROR_NONE);
}
- }
-
- if (result != CHPP_APP_ERROR_NONE) {
- CHPP_LOGE("Transport-loopback failure: %" PRIu8, result);
- }
-#endif
- return result;
-}
-void chppTransportSendReset(struct ChppTransportState *context,
- enum ChppTransportPacketAttributes resetType,
- enum ChppTransportErrorCode error) {
- // Make sure CHPP is in an initialized state
- CHPP_ASSERT_LOG((context->txDatagramQueue.pending == 0 &&
- context->txDatagramQueue.front == 0),
- "Not init to send reset");
-
- struct ChppTransportConfiguration *config =
- chppMalloc(sizeof(struct ChppTransportConfiguration));
-
- // CHPP transport version
- config->version.major = 1;
- config->version.minor = 0;
- config->version.patch = 0;
-
- // Rx MTU size
- config->rxMtu = CHPP_PLATFORM_LINK_RX_MTU_BYTES;
-
- // Max Rx window size
- // Note: current implementation does not support a window size >1
- config->windowSize = 1;
-
- // Advertised transport layer (ACK) timeout
- config->timeoutInMs = CHPP_PLATFORM_TRANSPORT_TIMEOUT_MS;
-
- if (resetType == CHPP_TRANSPORT_ATTR_RESET_ACK) {
- CHPP_LOGD("Sending RESET-ACK");
- } else {
- CHPP_LOGD("Sending RESET");
- }
-
- if (resetType == CHPP_TRANSPORT_ATTR_RESET_ACK) {
- chppSetResetComplete(context);
+ success = true;
}
- context->resetTimeNs = chppGetCurrentTimeNs();
+ chppMutexUnlock(&context->mutex);
- chppEnqueueTxDatagram(context,
- CHPP_ATTR_AND_ERROR_TO_PACKET_CODE(resetType, error),
- config, sizeof(*config));
+ return success;
}
diff --git a/chre_api/chre_api_version.mk b/chre_api/chre_api_version.mk
index f810e5ff..0af5455f 100644
--- a/chre_api/chre_api_version.mk
+++ b/chre_api/chre_api_version.mk
@@ -18,7 +18,7 @@ $(CURRENT_CHRE_API_VERSION_MK): $(PRINT_CURRENT_CHRE_API_VERSION_BIN)
# Only include default version if this is not a clean operation.
ifeq ($(filter clean, $(MAKECMDGOALS)),)
--include $(CURRENT_CHRE_API_VERSION_MK)
+include $(CURRENT_CHRE_API_VERSION_MK)
endif
# Target CHRE API Version ######################################################
diff --git a/chre_api/doc/Doxyfile b/chre_api/doc/Doxyfile
index 4b64b585..b8ff2d27 100644
--- a/chre_api/doc/Doxyfile
+++ b/chre_api/doc/Doxyfile
@@ -1261,7 +1261,7 @@ CHM_FILE =
HHC_LOCATION =
# The GENERATE_CHI flag controls if a separate .chi index file is generated
-# (YES) or that it should be included in the main.chm file (NO).
+# (YES) or that it should be included in the master .chm file (NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
diff --git a/chre_api/include/chre_api/chre.h b/chre_api/include/chre_api/chre.h
index b03c08db..5ac4720e 100644
--- a/chre_api/include/chre_api/chre.h
+++ b/chre_api/include/chre_api/chre.h
@@ -36,7 +36,6 @@
#include <chre/re.h>
#include <chre/sensor.h>
#include <chre/toolchain.h>
-#include <chre/user_settings.h>
#include <chre/version.h>
#include <chre/wifi.h>
#include <chre/wwan.h>
diff --git a/chre_api/include/chre_api/chre/audio.h b/chre_api/include/chre_api/chre/audio.h
index fb4d4a7c..201ab0e7 100644
--- a/chre_api/include/chre_api/chre/audio.h
+++ b/chre_api/include/chre_api/chre/audio.h
@@ -303,16 +303,6 @@ struct chreAudioDataEvent {
bool chreAudioGetSource(uint32_t handle, struct chreAudioSource *audioSource);
/**
- * Nanoapps must define CHRE_NANOAPP_USES_AUDIO somewhere in their build
- * system (e.g. Makefile) if the nanoapp needs to use the following audio APIs.
- * In addition to allowing access to these APIs, defining this macro will also
- * ensure CHRE enforces that all host clients this nanoapp talks to have the
- * required Android permissions needed to listen to audio data by adding
- * metadata to the nanoapp.
- */
-#if defined(CHRE_NANOAPP_USES_AUDIO) || !defined(CHRE_IS_NANOAPP_BUILD)
-
-/**
* Configures delivery of audio data to the current nanoapp. Note that this may
* not fully disable the audio source if it is used by other clients in the
* system but it will halt data delivery to the nanoapp.
@@ -391,7 +381,6 @@ bool chreAudioGetSource(uint32_t handle, struct chreAudioSource *audioSource);
* were provided (non-existent handle, invalid buffering configuration).
*
* @since v1.2
- * @note Requires audio permission
*/
bool chreAudioConfigureSource(uint32_t handle, bool enable,
uint64_t bufferDuration,
@@ -408,20 +397,9 @@ bool chreAudioConfigureSource(uint32_t handle, bool enable,
* successfully, false if the handle was invalid or status is NULL.
*
* @since v1.2
- * @note Requires audio permission
*/
bool chreAudioGetStatus(uint32_t handle, struct chreAudioSourceStatus *status);
-#else /* defined(CHRE_NANOAPP_USES_AUDIO) || !defined(CHRE_IS_NANOAPP_BUILD) */
-#define CHRE_AUDIO_PERM_ERROR_STRING \
- "CHRE_NANOAPP_USES_AUDIO must be defined when building this nanoapp in " \
- "order to refer to "
-#define chreAudioConfigureSource(...) \
- CHRE_BUILD_ERROR(CHRE_AUDIO_PERM_ERROR_STRING "chreAudioConfigureSource")
-#define chreAudioGetStatus(...) \
- CHRE_BUILD_ERROR(CHRE_AUDIO_PERM_ERROR_STRING "chreAudioGetStatus")
-#endif /* defined(CHRE_NANOAPP_USES_AUDIO) || !defined(CHRE_IS_NANOAPP_BUILD) */
-
#ifdef __cplusplus
}
#endif
diff --git a/chre_api/include/chre_api/chre/common.h b/chre_api/include/chre_api/chre/common.h
index 0224e9ac..e41201e4 100644
--- a/chre_api/include/chre_api/chre/common.h
+++ b/chre_api/include/chre_api/chre/common.h
@@ -108,10 +108,9 @@ enum chreError {
CHRE_ERROR_REJECTED_RATE_LIMIT = 8,
//! The requested functionality is not currently accessible from the CHRE,
- //! because another client, such as the main applications processor, is
+ //! because another master, such as the main applications processor, is
//! currently controlling it.
CHRE_ERROR_FUNCTION_RESTRICTED_TO_OTHER_MASTER = 9,
- CHRE_ERROR_FUNCTION_RESTRICTED_TO_OTHER_CLIENT = 9,
//!< Do not exceed this value when adding new error codes
CHRE_ERROR_LAST = UINT8_MAX,
diff --git a/chre_api/include/chre_api/chre/event.h b/chre_api/include/chre_api/chre/event.h
index 9002085b..1eecbfe6 100644
--- a/chre_api/include/chre_api/chre/event.h
+++ b/chre_api/include/chre_api/chre/event.h
@@ -33,8 +33,8 @@ extern "C" {
#endif
/**
- * The CHRE implementation is required to provide the following preprocessor
- * defines via the build system.
+ * The CHRE implementation is required to provide the following
+ * preprocessor defines via the build system.
*
* CHRE_MESSAGE_TO_HOST_MAX_SIZE: The maximum size, in bytes, allowed for
* a message sent to chreSendMessageToHostEndpoint(). This must be at least
@@ -42,27 +42,16 @@ extern "C" {
*/
#ifndef CHRE_MESSAGE_TO_HOST_MAX_SIZE
-#error CHRE_MESSAGE_TO_HOST_MAX_SIZE must be defined by the CHRE implementation
+#error CHRE_MESSAGE_TO_HOST_MAX_SIZE must be defined by the Context Hub Runtime Environment implementation
#endif
/**
- * The minimum size, in bytes, any CHRE implementation will use for
- * CHRE_MESSAGE_TO_HOST_MAX_SIZE is set to 1000 for v1.5+ CHRE implementations,
- * and 128 for v1.0-v1.4 implementations (previously kept in
- * CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE, which has been removed).
- *
- * All CHRE implementations supporting v1.5+ must support the raised limit of
- * 1000 bytes, however a nanoapp compiled against v1.5 cannot assume this
- * limit if there is a possibility their binary will run on a v1.4 or earlier
- * implementation that had a lower limit. To allow for nanoapp compilation in
- * these situations, CHRE_MESSAGE_TO_HOST_MAX_SIZE must be set to the minimum
- * value the nanoapp may encounter, and CHRE_NANOAPP_SUPPORTS_PRE_V1_5 can be
- * defined to skip the compile-time check.
+ * The minimum size, in bytes, any CHRE implementation will
+ * use for CHRE_MESSAGE_TO_HOST_MAX_SIZE.
*/
-#if (!defined(CHRE_NANOAPP_SUPPORTS_PRE_V1_5) && \
- CHRE_MESSAGE_TO_HOST_MAX_SIZE < 1000) || \
- (defined(CHRE_NANOAPP_SUPPORTS_PRE_V1_5) && \
- CHRE_MESSAGE_TO_HOST_MAX_SIZE < 128)
+#define CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE 128
+
+#if CHRE_MESSAGE_TO_HOST_MAX_SIZE < CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE
#error CHRE_MESSAGE_TO_HOST_MAX_SIZE is too small.
#endif
@@ -199,15 +188,6 @@ extern "C" {
#define CHRE_EVENT_AUDIO_LAST_EVENT UINT16_C(0x033F)
/**
- * First event in the block reserved for settings changed notifications.
- * These events are defined in chre/user_settings.h
- *
- * @since v1.5
- */
-#define CHRE_EVENT_SETTING_CHANGED_FIRST_EVENT UINT16_C(0x340)
-#define CHRE_EVENT_SETTING_CHANGED_LAST_EVENT UINT16_C(0x34F)
-
-/**
* First in the extended range of values dedicated for internal CHRE
* implementation usage.
*
@@ -256,40 +236,6 @@ extern "C" {
*/
#define CHRE_HOST_ENDPOINT_UNSPECIFIED UINT16_C(0xFFFE)
-/**
- * Bitmask values that can be given as input to the messagePermissions parameter
- * of chreSendMessageWithPermissions(). These values are typically used by
- * nanoapps when they used data from the corresponding CHRE APIs to produce the
- * message contents being sent and is used to attribute permissions usage on
- * the Android side. See chreSendMessageWithPermissions() for more details on
- * how these values are used when sending a message.
- *
- * Values in the range
- * [CHRE_MESSAGE_PERMISSION_VENDOR_START, CHRE_MESSAGE_PERMISSION_VENDOR_END]
- * are reserved for vendors to use when adding support for permission-gated APIs
- * in their implementations.
- *
- * On the Android side, CHRE permissions are mapped as follows:
- * - CHRE_MESSAGE_PERMISSION_AUDIO: android.permission.RECORD_AUDIO
- * - CHRE_MESSAGE_PERMISSION_GNSS, CHRE_MESSAGE_PERMISSION_WIFI, and
- * CHRE_MESSAGE_PERMISSION_WWAN: android.permission.ACCESS_FINE_LOCATION, and
- * android.permissions.ACCESS_BACKGROUND_LOCATION
- *
- * @since v1.5
- *
- * @defgroup CHRE_MESSAGE_PERMISSION
- * @{
- */
-
-#define CHRE_MESSAGE_PERMISSION_NONE UINT32_C(0)
-#define CHRE_MESSAGE_PERMISSION_AUDIO UINT32_C(1)
-#define CHRE_MESSAGE_PERMISSION_GNSS (UINT32_C(1) << 1)
-#define CHRE_MESSAGE_PERMISSION_WIFI (UINT32_C(1) << 2)
-#define CHRE_MESSAGE_PERMISSION_WWAN (UINT32_C(1) << 3)
-#define CHRE_MESSAGE_PERMISSION_VENDOR_START (UINT32_C(1) << 24)
-#define CHRE_MESSAGE_PERMISSION_VENDOR_END (UINT32_C(1) << 31)
-
-/** @} */
/**
* Data provided with CHRE_EVENT_MESSAGE_FROM_HOST.
@@ -433,7 +379,7 @@ typedef void (chreMessageFreeFunction)(void *message, size_t messageSize);
* @param targetInstanceId The ID of the instance we're delivering this event
* to. Note that this is allowed to be our own instance. The instance ID
* of a nanoapp can be retrieved by using chreGetNanoappInfoByInstanceId().
- * @return true if the event was enqueued, false otherwise. Note that even
+ * @returns true if the event was enqueued, false otherwise. Note that even
* if this method returns 'false', the 'freeCallback' will be invoked,
* if non-NULL. Note in the 'false' case, the 'freeCallback' may be
* invoked directly from within chreSendEvent(), so it's necessary
@@ -462,21 +408,6 @@ bool chreSendMessageToHost(void *message, uint32_t messageSize,
CHRE_DEPRECATED("Use chreSendMessageToHostEndpoint instead");
/**
- * Send a message to the host, using CHRE_MESSAGE_PERMISSION_NONE for the
- * associated message permissions. This method must only be used if no data
- * provided by CHRE's audio, GNSS, WiFi, and WWAN APIs was used to produce the
- * contents of the message being sent. Refer to chreSendMessageWithPermissions()
- * for further details.
- *
- * @see chreSendMessageWithPermissions
- *
- * @since v1.1
- */
-bool chreSendMessageToHostEndpoint(void *message, size_t messageSize,
- uint32_t messageType, uint16_t hostEndpoint,
- chreMessageFreeFunction *freeCallback);
-
-/**
* Send a message to the host, waking it up if it is currently asleep.
*
* This message is by definition arbitrarily defined. Since we're not
@@ -499,30 +430,13 @@ bool chreSendMessageToHostEndpoint(void *message, size_t messageSize,
* implementations (although on some implementations less calls to this
* method may be necessary).
*
- * When sending a message to the host, the ContextHub service will enforce
- * the host client has been granted Android-level permissions corresponding to
- * the ones the nanoapp declares it uses through CHRE_NANOAPP_USES_AUDIO, etc.
- * In addition to this, the permissions bitmask provided as input to this method
- * results in the Android framework using app-ops to verify and log access upon
- * message delivery to an application. This is primarily useful for ensuring
- * accurate attribution for messages generated using permission-controlled data.
- * The bitmask declared by the nanoapp for this message must be a
- * subset of the permissions it declared it would use at build time or the
- * message will be rejected.
- *
- * Nanoapps must use this method if the data they are sending contains or was
- * derived from any data sampled through CHRE's audio, GNSS, WiFi, or WWAN APIs.
- * Additionally, if vendors add APIs to expose data that would be guarded by a
- * permission in Android, vendors must support declaring a message permission
- * through this method.
- *
* @param message Pointer to a block of memory to send to the host.
* NULL is acceptable only if messageSize is 0. If non-NULL, this
* must be a legitimate pointer (that is, unlike chreSendEvent(), a small
* integral value cannot be cast to a pointer for this). Note that the
* caller no longer owns this memory after the call.
- * @param messageSize The size, in bytes, of the given message. If this exceeds
- * CHRE_MESSAGE_TO_HOST_MAX_SIZE, the message will be rejected.
+ * @param messageSize The size, in bytes, of the given message.
+ * This cannot exceed CHRE_MESSAGE_TO_HOST_MAX_SIZE.
* @param messageType Message type sent to the app on the host.
* NOTE: In CHRE API v1.0, support for forwarding this field to the host was
* not strictly required, and some implementations did not support it.
@@ -533,19 +447,13 @@ bool chreSendMessageToHostEndpoint(void *message, size_t messageSize,
* host side, and nanoapps may learn of the host endpoint ID of an intended
* recipient via an initial message sent by the host. This parameter is
* always treated as CHRE_HOST_ENDPOINT_BROADCAST if running on a CHRE API
- * v1.0 implementation. CHRE_HOST_ENDPOINT_BROADCAST isn't allowed to be
- * specified if anything other than CHRE_MESSAGE_PERMISSION_NONE is given
- * as messagePermissions since doing so would potentially attribute
- * permissions usage to host clients that don't intend to consume the data.
- * @param messagePermissions Bitmasked CHRE_MESSAGE_PERMISSION_ values that will
- * be converted to corresponding Android-level permissions and attributed
- * the host endpoint upon consumption of the message.
+ * v1.0 implementation.
* @param freeCallback A pointer to a callback function. After the lifetime
* of 'message' is over (which does not assure that 'message' made it to
* the host, just that the transport layer no longer needs this memory),
* this callback will be invoked. This argument is allowed
* to be NULL, in which case no callback will be invoked.
- * @return true if the message was accepted for transmission, false otherwise.
+ * @returns true if the message was accepted for transmission, false otherwise.
* Note that even if this method returns 'false', the 'freeCallback' will
* be invoked, if non-NULL. In either case, the 'freeCallback' may be
* invoked directly from within chreSendMessageToHostEndpoint(), so it's
@@ -553,12 +461,11 @@ bool chreSendMessageToHostEndpoint(void *message, size_t messageSize,
*
* @see chreMessageFreeFunction
*
- * @since v1.5
+ * @since v1.1
*/
-bool chreSendMessageWithPermissions(void *message, size_t messageSize,
- uint32_t messageType, uint16_t hostEndpoint,
- uint32_t messagePermissions,
- chreMessageFreeFunction *freeCallback);
+bool chreSendMessageToHostEndpoint(void *message, size_t messageSize,
+ uint32_t messageType, uint16_t hostEndpoint,
+ chreMessageFreeFunction *freeCallback);
/**
* Queries for information about a nanoapp running in the system.
@@ -572,7 +479,7 @@ bool chreSendMessageWithPermissions(void *message, size_t messageSize,
* information about.
* @param info Output parameter. If this function returns true, this structure
* will be populated with details of the specified nanoapp.
- * @return true if a nanoapp with the given ID is currently running, and the
+ * @returns true if a nanoapp with the given ID is currently running, and the
* supplied info parameter was populated with its information.
*
* @since v1.1
@@ -587,7 +494,7 @@ bool chreGetNanoappInfoByAppId(uint64_t appId, struct chreNanoappInfo *info);
* @param instanceId
* @param info Output parameter. If this function returns true, this structure
* will be populated with details of the specified nanoapp.
- * @return true if a nanoapp with the given instance ID is currently running,
+ * @returns true if a nanoapp with the given instance ID is currently running,
* and the supplied info parameter was populated with its information.
*
* @since v1.1
@@ -650,7 +557,7 @@ void chreConfigureHostSleepStateEvents(bool enable);
* state is instantaneous, and it may also change between querying the state and
* performing a host-waking action like sending a message to the host.
*
- * @return true if by CHRE's own estimation the host is currently awake,
+ * @returns true if by CHRE's own estimation the host is currently awake,
* false otherwise
*
* @since v1.2
diff --git a/chre_api/include/chre_api/chre/gnss.h b/chre_api/include/chre_api/chre/gnss.h
index 79a8f46b..368f54d2 100644
--- a/chre_api/include/chre_api/chre/gnss.h
+++ b/chre_api/include/chre_api/chre/gnss.h
@@ -35,7 +35,6 @@
* applicable.
*/
-
#include <stdbool.h>
#include <stdint.h>
@@ -149,13 +148,8 @@ extern "C" {
/**
* The maximum number of instances of struct chreGnssMeasurement that may be
* included in a single struct chreGnssDataEvent.
- *
- * The value of this struct was increased from 64 to 128 in CHRE v1.5. For
- * nanoapps targeting CHRE v1.4 or lower, the measurement_count will be capped
- * at 64.
*/
-#define CHRE_GNSS_MAX_MEASUREMENT UINT8_C(128)
-#define CHRE_GNSS_MAX_MEASUREMENT_PRE_1_5 UINT8_C(64)
+#define CHRE_GNSS_MAX_MEASUREMENT UINT8_C(64)
// Flags indicating the GNSS measurement state (ref: GnssMeasurementState)
#define CHRE_GNSS_MEASUREMENT_STATE_UNKNOWN UINT16_C(0)
@@ -414,16 +408,6 @@ struct chreGnssLocationEvent {
uint32_t chreGnssGetCapabilities(void);
/**
- * Nanoapps must define CHRE_NANOAPP_USES_GNSS somewhere in their build
- * system (e.g. Makefile) if the nanoapp needs to use the following GNSS APIs.
- * In addition to allowing access to these APIs, defining this macro will also
- * ensure CHRE enforces that all host clients this nanoapp talks to have the
- * required Android permissions needed to listen to GNSS data by adding metadata
- * to the nanoapp.
- */
-#if defined(CHRE_NANOAPP_USES_GNSS) || !defined(CHRE_IS_NANOAPP_BUILD)
-
-/**
* Initiates a GNSS positioning session, or changes the requested interval of an
* existing session. If starting or modifying the session was successful, then
* the GNSS engine will work on determining the device's position.
@@ -453,7 +437,6 @@ uint32_t chreGnssGetCapabilities(void);
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.1
- * @note Requires GNSS permission
*/
bool chreGnssLocationSessionStartAsync(uint32_t minIntervalMs,
uint32_t minTimeToNextFixMs,
@@ -481,7 +464,6 @@ bool chreGnssLocationSessionStartAsync(uint32_t minIntervalMs,
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.1
- * @note Requires GNSS permission
*/
bool chreGnssLocationSessionStopAsync(const void *cookie);
@@ -512,7 +494,6 @@ bool chreGnssLocationSessionStopAsync(const void *cookie);
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.1
- * @note Requires GNSS permission
*/
bool chreGnssMeasurementSessionStartAsync(uint32_t minIntervalMs,
const void *cookie);
@@ -536,7 +517,6 @@ bool chreGnssMeasurementSessionStartAsync(uint32_t minIntervalMs,
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.1
- * @note Requires GNSS permission
*/
bool chreGnssMeasurementSessionStopAsync(const void *cookie);
@@ -572,31 +552,9 @@ bool chreGnssMeasurementSessionStopAsync(const void *cookie);
* or if this feature is not supported
*
* @since v1.2
- * @note Requires GNSS permission
*/
bool chreGnssConfigurePassiveLocationListener(bool enable);
-#else /* defined(CHRE_NANOAPP_USES_GNSS) || !defined(CHRE_IS_NANOAPP_BUILD) */
-#define CHRE_GNSS_PERM_ERROR_STRING \
- "CHRE_NANOAPP_USES_GNSS must be defined when building this nanoapp in " \
- "order to refer to "
-#define chreGnssLocationSessionStartAsync(...) \
- CHRE_BUILD_ERROR(CHRE_GNSS_PERM_ERROR_STRING \
- "chreGnssLocationSessionStartAsync")
-#define chreGnssLocationSessionStopAsync(...) \
- CHRE_BUILD_ERROR(CHRE_GNSS_PERM_ERROR_STRING \
- "chreGnssLocationSessionStopAsync")
-#define chreGnssMeasurementSessionStartAsync(...) \
- CHRE_BUILD_ERROR(CHRE_GNSS_PERM_ERROR_STRING \
- "chreGnssMeasurementSessionStartAsync")
-#define chreGnssMeasurementSessionStopAsync(...) \
- CHRE_BUILD_ERROR(CHRE_GNSS_PERM_ERROR_STRING \
- "chreGnssMeasurementSessionStopAsync")
-#define chreGnssConfigurePassiveLocationListener(...) \
- CHRE_BUILD_ERROR(CHRE_GNSS_PERM_ERROR_STRING \
- "chreGnssConfigurePassiveLocationListener")
-#endif /* defined(CHRE_NANOAPP_USES_GNSS) || !defined(CHRE_IS_NANOAPP_BUILD) */
-
#ifdef __cplusplus
}
#endif
diff --git a/chre_api/include/chre_api/chre/nanoapp.h b/chre_api/include/chre_api/chre/nanoapp.h
index da199ee0..e5282edc 100644
--- a/chre_api/include/chre_api/chre/nanoapp.h
+++ b/chre_api/include/chre_api/chre/nanoapp.h
@@ -35,7 +35,7 @@ extern "C" {
*
* Every CHRE method is legal to call from this method.
*
- * @return 'true' if the nanoapp successfully started. 'false' if the nanoapp
+ * @returns 'true' if the nanoapp successfully started. 'false' if the nanoapp
* failed to properly initialize itself (for example, could not obtain
* sufficient memory from the heap). If this method returns 'false', the
* nanoapp will be unloaded by the CHRE (and nanoappEnd will
diff --git a/chre_api/include/chre_api/chre/re.h b/chre_api/include/chre_api/chre/re.h
index 20a69b66..ba898105 100644
--- a/chre_api/include/chre_api/chre/re.h
+++ b/chre_api/include/chre_api/chre/re.h
@@ -101,7 +101,7 @@ enum chreLogLevel {
* The application ID is set by the loader of the nanoapp. This is not
* assured to be unique among all nanoapps running in the system.
*
- * @return The application ID.
+ * @returns The application ID.
*/
uint64_t chreGetAppId(void);
@@ -113,7 +113,7 @@ uint64_t chreGetAppId(void);
* different from the CHRE_INSTANCE_ID. This is the ID used to communicate
* between nanoapps.
*
- * @return The instance ID
+ * @returns The instance ID
*/
uint32_t chreGetInstanceId(void);
@@ -149,7 +149,7 @@ uint32_t chreGetInstanceId(void);
*
* For a nanoapp author, an OPTIONAL format means you might not get exactly
* what you want on every CHRE implementation, but you will always get
- * something valid.
+ * something sane.
*
* To be clearer, here's an example with the OPTIONAL 0-padding for integers
* for different hypothetical CHRE implementations.
@@ -174,10 +174,10 @@ uint32_t chreGetInstanceId(void);
*
* OPTIONAL format sub-specifiers:
* - '-' (left-justify within the given field width)
- * - '+' (precede the result with a '+' sign if it is positive)
- * - ' ' (precede the result with a blank space if no sign is going to be
+ * - '+' (preceed the result with a '+' sign if it is positive)
+ * - ' ' (preceed the result with a blank space if no sign is going to be
* output)
- * - '#' (For 'o', 'x' or 'X', precede output with "0", "0x" or "0X",
+ * - '#' (For 'o', 'x' or 'X', preceed output with "0", "0x" or "0X",
* respectively. For floating point, unconditionally output a decimal
* point.)
* - '0' (left pad the number with zeroes instead of spaces when <width>
@@ -242,7 +242,7 @@ void chreLog(enum chreLogLevel level, const char *formatStr, ...);
* This value must always increase (and must never roll over). This
* value has no meaning across CHRE reboots.
*
- * @return The system time, in nanoseconds.
+ * @returns The system time, in nanoseconds.
*/
uint64_t chreGetTime(void);
@@ -261,7 +261,7 @@ uint64_t chreGetTime(void);
* some fixed/invalid value while waiting for the initial offset estimate to be
* determined - this initial offset must be ready before nanoapps are started.
*
- * @return An estimate of the offset between CHRE's time returned in
+ * @returns An estimate of the offset between CHRE's time returned in
* chreGetTime() and the time on the host given in the Android API
* SystemClock.elapsedRealtimeNanos(), accurate to within +/- 10
* milliseconds, such that adding this offset to chreGetTime() produces the
@@ -277,7 +277,7 @@ int64_t chreGetEstimatedHostTimeOffset(void);
* Convenience function to retrieve CHRE's estimate of the current time on the
* host, corresponding to the Android API SystemClock.elapsedRealtimeNanos().
*
- * @return An estimate of the current time on the host, accurate to within
+ * @returns An estimate of the current time on the host, accurate to within
* +/- 10 milliseconds. This estimate is *not* guaranteed to be
* monotonically increasing, and may move backwards as a result of receiving
* new information from the host.
@@ -325,7 +325,7 @@ static inline uint64_t chreGetEstimatedHostTime(void) {
* timer will continue to refire every 'duration', until this timer is
* canceled (@see chreTimerCancel).
*
- * @return The timer ID. If the system is unable to set a timer
+ * @returns The timer ID. If the system is unable to set a timer
* (no more available timers, etc.) then CHRE_TIMER_INVALID will
* be returned.
*
@@ -341,7 +341,7 @@ uint32_t chreTimerSet(uint64_t duration, const void *cookie, bool oneShot);
* will need to be evicted from the queue by the CHRE.
*
* @param timerId A timer ID obtained by this nanoapp via chreTimerSet().
- * @return true if the timer was cancelled, false otherwise. We may
+ * @returns true if the timer was cancelled, false otherwise. We may
* fail to cancel the timer if it's a one shot which (just) fired,
* or if the given timer ID is not owned by the calling app.
*/
@@ -360,7 +360,7 @@ bool chreTimerCancel(uint32_t timerId);
* @param abortCode A value indicating the reason for aborting. (Note that
* in this version of the API, there is no way for anyone to access this
* code, but future APIs may expose it.)
- * @return Never. This method does not return, as the CHRE stops nanoapp
+ * @returns Never. This method does not return, as the CHRE stops nanoapp
* execution immediately.
*/
void chreAbort(uint32_t abortCode);
@@ -377,7 +377,7 @@ void chreAbort(uint32_t abortCode);
* to properly manage their heap resources.
*
* @param bytes The number of bytes requested.
- * @return A pointer to 'bytes' contiguous bytes of heap memory, or NULL
+ * @returns A pointer to 'bytes' contiguous bytes of heap memory, or NULL
* if the allocation could not be performed. This pointer must be suitably
* aligned for any kind of variable.
*
diff --git a/chre_api/include/chre_api/chre/sensor.h b/chre_api/include/chre_api/chre/sensor.h
index bf9e12e5..12fed4e5 100644
--- a/chre_api/include/chre_api/chre/sensor.h
+++ b/chre_api/include/chre_api/chre/sensor.h
@@ -147,46 +147,12 @@ extern "C" {
*
* This data is generated every time a step is taken by the user.
*
- * This is backed by the same algorithm that feeds Android's
- * SENSOR_TYPE_STEP_DETECTOR, and therefore sacrifices some accuracy to target
- * an update latency of under 2 seconds.
- *
* @since v1.3
*/
#define CHRE_EVENT_SENSOR_STEP_DETECT_DATA \
(CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_STEP_DETECT)
/**
- * nanoappHandleEvent argument: struct chreSensorUint64Data
- *
- * The value of the data is the cumulative number of steps taken by the user
- * since the last reboot while the sensor is active. This data is generated
- * every time a step is taken by the user.
- *
- * This is backed by the same algorithm that feeds Android's
- * SENSOR_TYPE_STEP_COUNTER, and therefore targets high accuracy with under
- * 10 seconds of update latency.
- *
- * @since v1.5
- */
-#define CHRE_EVENT_SENSOR_STEP_COUNTER_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_STEP_COUNTER)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorFloatData
- *
- * The value of the data is the measured hinge angle between 0 and 360 degrees
- * inclusive.
- *
- * This is backed by the same algorithm that feeds Android's
- * SENSOR_TYPE_HINGE_ANGLE.
- *
- * @since v1.5
- */
-#define CHRE_EVENT_SENSOR_HINGE_ANGLE_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_HINGE_ANGLE)
-
-/**
* nanoappHandleEvent argument: struct chreSensorThreeAxisData
*
* The data can be interpreted using the 'x', 'y', and 'z' fields within
@@ -428,13 +394,6 @@ extern "C" {
#define CHRE_SENSOR_LATENCY_DEFAULT UINT64_C(-1)
/**
- * A sensor index value indicating that it is the default sensor.
- *
- * @see chreSensorFind
- */
-#define CHRE_SENSOR_INDEX_DEFAULT UINT8_C(0)
-
-/**
* Special value indicating non-importance of the batch interval.
*
* @see chreSensorConfigureWithBatchInterval
@@ -618,20 +577,6 @@ struct chreSensorInfo {
* @since v1.1
*/
uint64_t minInterval;
-
- /**
- * Uniquely identifies the sensor for a given type. A value of 0 indicates
- * that this is the "default" sensor, which is returned by
- * chreSensorFindDefault().
- *
- * The sensor index of a given type must be stable across boots (i.e. must
- * not change), and a different sensor of the same type must have different
- * sensor index values, and the set of sensorIndex values for a given sensor
- * type must be continuguous.
- *
- * @since v1.5
- */
- uint8_t sensorIndex;
};
/**
@@ -725,43 +670,11 @@ struct chreSensorFlushCompleteEvent {
* @param sensorType One of the CHRE_SENSOR_TYPE_* constants.
* @param handle If a sensor is found, then the memory will be filled with
* the value for the sensor's handle. This argument must be non-NULL.
- * @return true if a sensor was found, false otherwise.
+ * @returns true if a sensor was found, false otherwise.
*/
bool chreSensorFindDefault(uint8_t sensorType, uint32_t *handle);
/**
- * Finds a sensor of a given index and sensor type.
- *
- * For CHRE implementations that support multiple sensors of the same sensor
- * type, this method can be used to get the non-default sensor(s). The default
- * sensor, as defined in the chreSensorFindDefault(), will be returned if
- * a sensor index of zero is specified.
- *
- * A simple example of iterating all available sensors of a given type is
- * provided here:
- *
- * uint32_t handle;
- * for (uint8_t i = 0; chreSensorFind(sensorType, i, &handle); i++) {
- * chreLog(CHRE_LOG_INFO,
- * "Found sensor index %" PRIu8 ", which has handle %" PRIu32,
- * i, handle);
- * }
- *
- * If this method is invoked for CHRE versions prior to v1.5, invocations with
- * sensorIndex value of 0 will be equivalent to using chreSensorFindDefault, and
- * if sensorIndex is non-zero will return false.
- *
- * @param sensorType One of the CHRE_SENSOR_TYPE_* constants.
- * @param sensorIndex The index of the desired sensor.
- * @param handle If a sensor is found, then the memory will be filled with
- * the value for the sensor's handle. This argument must be non-NULL.
- * @return true if a sensor was found, false otherwise.
- *
- * @since v1.5
- */
-bool chreSensorFind(uint8_t sensorType, uint8_t sensorIndex, uint32_t *handle);
-
-/**
* Get the chreSensorInfo struct for a given sensor.
*
* @param sensorHandle The sensor handle, as obtained from
@@ -769,7 +682,7 @@ bool chreSensorFind(uint8_t sensorType, uint8_t sensorIndex, uint32_t *handle);
* @param info If the sensor is valid, then this memory will be filled with
* the SensorInfo contents for this sensor. This argument must be
* non-NULL.
- * @return true if the senor handle is valid and 'info' was filled in;
+ * @returns true if the senor handle is valid and 'info' was filled in;
* false otherwise.
*/
bool chreGetSensorInfo(uint32_t sensorHandle, struct chreSensorInfo *info);
@@ -794,7 +707,7 @@ bool chreGetSensorInfo(uint32_t sensorHandle, struct chreSensorInfo *info);
* @param status If the sensor is valid, then this memory will be filled with
* the sampling status contents for this sensor. This argument must be
* non-NULL.
- * @return true if the senor handle is valid and 'status' was filled in;
+ * @returns true if the senor handle is valid and 'status' was filled in;
* false otherwise.
*/
bool chreGetSensorSamplingStatus(uint32_t sensorHandle,
@@ -895,7 +808,7 @@ bool chreGetSensorSamplingStatus(uint32_t sensorHandle,
* nanoapp receives the information. The current CHRE API has no
* real-time elements, although future versions may introduce some to
* help with this issue.
- * @return true if the configuration succeeded, false otherwise.
+ * @returns true if the configuration succeeded, false otherwise.
*
* @see chreSensorConfigureMode
* @see chreSensorFindDefault
diff --git a/chre_api/include/chre_api/chre/sensor_types.h b/chre_api/include/chre_api/chre/sensor_types.h
index 63b495bb..f69c6f25 100644
--- a/chre_api/include/chre_api/chre/sensor_types.h
+++ b/chre_api/include/chre_api/chre/sensor_types.h
@@ -170,36 +170,6 @@ extern "C" {
#define CHRE_SENSOR_TYPE_STEP_DETECT UINT8_C(23)
/**
- * Step counter.
- *
- * Generates: CHRE_EVENT_SENSOR_STEP_COUNTER_DATA
- *
- * This is an on-change sensor. Note that the data returned by this sensor must
- * match the value that can be obtained via the Android sensors framework at the
- * same point in time. This means, if CHRE reboots from the rest of the system,
- * the counter must not reset to 0.
- *
- * @since v1.5
- */
-#define CHRE_SENSOR_TYPE_STEP_COUNTER UINT8_C(24)
-
-/**
- * Hinge angle sensor.
- *
- * Generates: CHRE_EVENT_SENSOR_HINGE_ANGLE_DATA
- *
- * This is an on-change sensor.
- *
- * A sensor of this type measures the angle, in degrees, between two
- * integral parts of the device. Movement of a hinge measured by this sensor
- * type is expected to alter the ways in which the user may interact with
- * the device, for example by unfolding or revealing a display.
- *
- * @since v1.5
- */
-#define CHRE_SENSOR_TYPE_HINGE_ANGLE UINT8_C(36)
-
-/**
* Uncalibrated accelerometer.
*
* Generates: CHRE_EVENT_SENSOR_UNCALIBRATED_ACCELEROMETER_DATA
@@ -310,8 +280,7 @@ extern "C" {
*/
struct chreSensorDataHeader {
/**
- * The base timestamp, in nanoseconds; must be in the same time base as
- * chreGetTime().
+ * The base timestamp, in nanoseconds.
*/
uint64_t baseTimestamp;
@@ -410,9 +379,8 @@ struct chreSensorOccurrenceData {
* This is used by CHRE_EVENT_SENSOR_LIGHT_DATA,
* CHRE_EVENT_SENSOR_PRESSURE_DATA,
* CHRE_EVENT_SENSOR_ACCELEROMETER_TEMPERATURE_DATA,
- * CHRE_EVENT_SENSOR_GYROSCOPE_TEMPERATURE_DATA,
- * CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_TEMPERATURE_DATA, and
- * CHRE_EVENT_SENSOR_HINGE_ANGLE_DATA.
+ * CHRE_EVENT_SENSOR_GYROSCOPE_TEMPERATURE_DATA, and
+ * CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_TEMPERATURE_DATA.
*/
struct chreSensorFloatData {
struct chreSensorDataHeader header;
@@ -423,7 +391,6 @@ struct chreSensorFloatData {
float light; //!< Unit: lux
float pressure; //!< Unit: hectopascals (hPa)
float temperature; //!< Unit: degrees Celsius
- float angle; //!< Unit: angular degrees
};
} readings[1];
};
@@ -448,18 +415,6 @@ struct chreSensorByteData {
} readings[1];
};
-/**
- * Data for a sensor which reports a single uint64 value.
- *
- * This is used by CHRE_EVENT_SENSOR_STEP_COUNTER_DATA.
- */
-struct chreSensorUint64Data {
- struct chreSensorDataHeader header;
- struct chreSensorUint64SampleData {
- uint32_t timestampDelta;
- uint64_t value;
- } readings[1];
-};
#ifdef __cplusplus
}
diff --git a/chre_api/include/chre_api/chre/toolchain.h b/chre_api/include/chre_api/chre/toolchain.h
index 1ed6a2a8..4dfc051f 100644
--- a/chre_api/include/chre_api/chre/toolchain.h
+++ b/chre_api/include/chre_api/chre/toolchain.h
@@ -23,7 +23,6 @@
*/
#if defined(__GNUC__) || defined(__clang__)
-// For GCC and clang
#define CHRE_DEPRECATED(message) \
__attribute__((deprecated(message)))
@@ -32,35 +31,10 @@
#define CHRE_PRINTF_ATTR(formatPos, argStart) \
__attribute__((format(printf, formatPos, argStart)))
-#define CHRE_BUILD_ERROR(message) CHRE_DO_PRAGMA(GCC error message)
-#define CHRE_DO_PRAGMA(message) _Pragma(#message)
-
-#elif defined(__ICCARM__) || defined(__CC_ARM)
-// For IAR ARM and Keil MDK-ARM compilers
-
-#define CHRE_PRINTF_ATTR(formatPos, argStart)
-
-#elif defined(_MSC_VER)
-// For Microsoft Visual Studio
-
-#define CHRE_PRINTF_ATTR(formatPos, argStart)
-
#else // if !defined(__GNUC__) && !defined(__clang__)
#error Need to add support for new compiler
#endif
-// For platforms that don't support error pragmas, utilize the best method of
-// showing an error depending on the platform support.
-#ifndef CHRE_BUILD_ERROR
-#ifdef __cplusplus // C++11 or greater assumed
-#define CHRE_BUILD_ERROR(message) static_assert(0, message)
-#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
-#define CHRE_BUILD_ERROR(message) _Static_assert(0, message)
-#else
-#define CHRE_BUILD_ERROR(message) char buildError[-1] = message
-#endif
-#endif
-
#endif // CHRE_TOOLCHAIN_H_
diff --git a/chre_api/include/chre_api/chre/user_settings.h b/chre_api/include/chre_api/chre/user_settings.h
deleted file mode 100644
index d1050049..00000000
--- a/chre_api/include/chre_api/chre/user_settings.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 _CHRE_USER_SETTINGS_H_
-#define _CHRE_USER_SETTINGS_H_
-
-/**
- * @file
- * The API for requesting notifications on changes in the settings of the
- * active user. If the device is set up with one or more secondary users
- * (see https://source.android.com/devices/tech/admin/multi-user), the user
- * settings in CHRE reflect that of the currently active user.
- */
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include <chre/event.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * The user settings that nanoapps can request notifications for on a status
- * change.
- * Note that the WIFI Available setting indicates the overall availability
- * of WIFI related functionality. For example, if wifi is disabled for
- * connectivity but enabled for location, the WIFI Available setting is
- * enabled.
- *
- * @defgroup CHRE_USER_SETTINGS
- * @{
- */
-#define CHRE_USER_SETTING_LOCATION UINT8_C(0)
-#define CHRE_USER_SETTING_WIFI_AVAILABLE UINT8_C(1)
-#define CHRE_USER_SETTING_AIRPLANE_MODE UINT8_C(2)
-#define CHRE_USER_SETTING_MICROPHONE UINT8_C(3)
-
-/** @} */
-
-/**
- * Produce an event ID in the block of IDs reserved for settings notifications.
- *
- * @param offset Index into the event ID block, valid in the range [0,15]
- */
-#define CHRE_SETTING_EVENT_ID(offset) (CHRE_EVENT_SETTING_CHANGED_FIRST_EVENT + (offset))
-
-/**
- * nanoappHandleEvent argument: struct chreUserSettingChangedEvent
- *
- * Notify nanoapps of a change in the associated setting. Nanoapps must first
- * register (via chreUserSettingConfigureEvents) for events before they are
- * sent out.
- */
-#define CHRE_EVENT_SETTING_CHANGED_LOCATION CHRE_SETTING_EVENT_ID(0)
-#define CHRE_EVENT_SETTING_CHANGED_WIFI_AVAILABLE CHRE_SETTING_EVENT_ID(1)
-#define CHRE_EVENT_SETTING_CHANGED_AIRPLANE_MODE CHRE_SETTING_EVENT_ID(2)
-#define CHRE_EVENT_SETTING_CHANGED_MICROPHONE CHRE_SETTING_EVENT_ID(3)
-
-#if CHRE_EVENT_SETTING_CHANGED_MICROPHONE > CHRE_EVENT_SETTING_CHANGED_LAST_EVENT
-#error Too many setting changed events.
-#endif
-
-/**
- * Indicates the current state of a setting.
- * The setting state is 'unknown' only in the following scenarios:
- * - CHRE hasn't received the initial state yet on a restart.
- * - The nanoapp is running on CHRE v1.4 or older
- * - Nanoapp provided in invalid setting ID to chreUserSettingGetStatus.
- */
-enum chreUserSettingState {
- CHRE_USER_SETTING_STATE_UNKNOWN = -1,
- CHRE_USER_SETTING_STATE_DISABLED = 0,
- CHRE_USER_SETTING_STATE_ENABLED = 1
-};
-
-/**
- * The nanoappHandleEvent argument for CHRE settings changed notifications.
- */
-struct chreUserSettingChangedEvent {
- //! Indicates the setting whose state has changed.
- uint8_t setting;
-
- //! A value that corresponds to a member in enum chreUserSettingState,
- // indicating the latest value of the setting.
- int8_t settingState;
-};
-
-/**
- * Get the current state of a given setting.
- *
- * @param setting The setting to get the current status of.
- *
- * @return The current state of the requested setting. The state is returned
- * as an int8_t to be consistent with the associated event data, but is
- * guaranteed to be a valid enum chreUserSettingState member.
- *
- * @since v1.5
- */
-int8_t chreUserSettingGetState(uint8_t setting);
-
-/**
- * Register or deregister for a notification on a status change for a given
- * setting. Note that registration does not produce an event with the initial
- * (or current) state, though nanoapps can use chreUserSettingGetState() for
- * this purpose.
- *
- * @param setting The setting on whose change a notification is desired.
- * @param enable The nanoapp is registered to receive notifications on a
- * change in the user settings if this parameter is true, otherwise the
- * nanoapp receives no further notifications for this setting.
- *
- * @since v1.5
- */
-void chreUserSettingConfigureEvents(uint8_t setting, bool enable);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_USER_SETTINGS_H_ */
diff --git a/chre_api/include/chre_api/chre/version.h b/chre_api/include/chre_api/chre/version.h
index 1e9e62ce..60ac2d16 100644
--- a/chre_api/include/chre_api/chre/version.h
+++ b/chre_api/include/chre_api/chre/version.h
@@ -85,26 +85,14 @@ extern "C" {
/**
* Value for version 1.4 of the Context Hub Runtime Environment API interface.
*
- * The version of the CHRE API shipped with the Android R release. It adds
- * support for collecting debug dump information from nanoapps, receiving L5
- * GNSS measurements, determining if a sensor supports passive requests,
- * receiving 5G cell info, and deprecates chreSendMessageToHost.
- *
- * @see CHRE_API_VERSION
- */
-#define CHRE_API_VERSION_1_4 UINT32_C(0x01040000)
-
-/**
- * Value for version 1.5 of the Context Hub Runtime Environment API interface.
- *
- * The version of the CHRE API shipped with the Android S release.
+ * The version of the CHRE API shipped with the Android R release.
*
* @note This version of the CHRE API has not been finalized yet, and is
* currently considered a preview that is subject to change.
*
* @see CHRE_API_VERSION
*/
-#define CHRE_API_VERSION_1_5 UINT32_C(0x01050000)
+#define CHRE_API_VERSION_1_4 UINT32_C(0x01040000)
/**
* Major and Minor Version of this Context Hub Runtime Environment API.
@@ -123,7 +111,7 @@ extern "C" {
* Note that version numbers can always be numerically compared with
* expected results, so 1.0.0 < 1.0.4 < 1.1.0 < 2.0.300 < 3.5.0.
*/
-#define CHRE_API_VERSION CHRE_API_VERSION_1_5
+#define CHRE_API_VERSION CHRE_API_VERSION_1_4
/**
* Utility macro to extract only the API major version of a composite CHRE
@@ -132,7 +120,7 @@ extern "C" {
* @param version A uint32_t version, e.g. the value returned by
* chreGetApiVersion()
*
- * @return The API major version in the least significant byte, e.g. 0x01
+ * @returns The API major version in the least significant byte, e.g. 0x01
*/
#define CHRE_EXTRACT_MAJOR_VERSION(version) \
(((version) & UINT32_C(0xFF000000)) >> 24)
@@ -143,7 +131,7 @@ extern "C" {
*
* @param version A uint32_t version, e.g. the CHRE_API_VERSION constant
*
- * @return The API minor version in the least significant byte, e.g. 0x01
+ * @returns The API minor version in the least significant byte, e.g. 0x01
*/
#define CHRE_EXTRACT_MINOR_VERSION(version) \
(((version) & UINT32_C(0x00FF0000)) >> 16)
@@ -155,7 +143,7 @@ extern "C" {
* @param version A complete uint32_t version, e.g. the value returned by
* chreGetVersion()
*
- * @return The implementation patch version in the least significant two bytes,
+ * @returns The implementation patch version in the least significant two bytes,
* e.g. 0x0123, with all other bytes set to 0
*/
#define CHRE_EXTRACT_PATCH_VERSION(version) ((version) & UINT32_C(0xFFFF))
@@ -171,7 +159,7 @@ extern "C" {
* By definition, this will have the two least significant bytes set to 0,
* and only contain the major and minor version number.
*
- * @return The API version.
+ * @returns The API version.
*/
uint32_t chreGetApiVersion(void);
@@ -185,7 +173,7 @@ uint32_t chreGetApiVersion(void);
* of this specific platform ID. It is increased by the platform every time
* a backwards-compatible bug fix is released.
*
- * @return The version.
+ * @returns The version.
*
* @see chreGetPlatformId()
*/
@@ -207,7 +195,7 @@ uint32_t chreGetVersion(void);
* to have code that can conditionally work around the bug on a buggy version.
* Thus, we require this uniqueness to allow such a setup to work.
*
- * @return The platform ID.
+ * @returns The platform ID.
*
* @see CHRE_EXTRACT_VENDOR_ID
*/
diff --git a/chre_api/include/chre_api/chre/wifi.h b/chre_api/include/chre_api/chre/wifi.h
index 6c338c52..c2578d30 100644
--- a/chre_api/include/chre_api/chre/wifi.h
+++ b/chre_api/include/chre_api/chre/wifi.h
@@ -29,15 +29,7 @@
* "802.11" | IEEE Std 802.11-2007
* "HT" | IEEE Std 802.11n-2009
* "VHT" | IEEE Std 802.11ac-2013
- * "WiFi 6" | IEEE Std 802.11ax draft
*
- * In the current version of CHRE API, the 6GHz band introduced in WiFi 6 is
- * not supported. A scan request from CHRE should not result in scanning 6GHz
- * channels. In particular, if a 6GHz channel is specified in scanning or
- * ranging request parameter, CHRE should return an error code of
- * CHRE_ERROR_NOT_SUPPORTED. Additionally, CHRE implementations must not include
- * observations of access points on 6GHz channels in scan results, especially
- * those produced due to scan monitoring.
*/
#include <chre/common.h>
@@ -195,7 +187,7 @@ extern "C" {
//! Element ID 192 (VHT Operation) is present (see VHT 8.4.2)
#define CHRE_WIFI_SCAN_RESULT_FLAGS_VHT_OPS_PRESENT UINT8_C(1 << 1)
-//! Element ID 127 (Extended Capabilities) is present, and bit 70 (Fine Timing
+//! Element ID 127 (Extended Capbilities) is present, and bit 70 (Fine Timing
//! Measurement Responder) is set to 1 (see IEEE Std 802.11-2016 9.4.2.27)
#define CHRE_WIFI_SCAN_RESULT_FLAGS_IS_FTM_RESPONDER UINT8_C(1 << 2)
@@ -228,16 +220,7 @@ extern "C" {
#define CHRE_WIFI_SECURITY_MODE_OPEN UINT8_C(1 << 0) //!< No auth/security
#define CHRE_WIFI_SECURITY_MODE_WEP UINT8_C(1 << 1)
#define CHRE_WIFI_SECURITY_MODE_PSK UINT8_C(1 << 2) //!< WPA-PSK or WPA2-PSK
-#define CHRE_WIFI_SECURITY_MODE_EAP UINT8_C(1 << 3) //!< WPA-EAP or WPA2-EAP
-
-//! @since v1.5
-#define CHRE_WIFI_SECURITY_MODE_SAE UINT8_C(1 << 4)
-
-//! @since v1.5
-#define CHRE_WIFI_SECURITY_MODE_EAP_SUITE_B UINT8_C(1 << 5)
-
-//! @since v1.5
-#define CHRE_WIFI_SECURITY_MODE_OWE UINT8_C(1 << 6)
+#define CHRE_WIFI_SECURITY_MODE_EAP UINT8_C(1 << 3) //!< Any type of EAPOL
/** @} */
@@ -302,32 +285,12 @@ enum chreWifiScanType {
//! Perform an active scan on unrestricted channels, and also perform a
//! passive scan on channels that are restricted to use via Dynamic
- //! Frequency Selection (DFS), e.g. the U-NII bands 5250-5350MHz and
+ //! Frequency Selection (DFS), e.g. the U-NIII bands 5250-5350MHz and
//! 5470-5725MHz in the USA as mandated by FCC regulation.
CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS = 1,
//! Perform a passive scan, only listening for beacons.
CHRE_WIFI_SCAN_TYPE_PASSIVE = 2,
-
- //! Client has no preference for a particular scan type.
- //! Only valid in a {@link #chreWifiScanParams}.
- //!
- //! On a v1.4 or earlier platform, this will fall back to
- //! CHRE_WIFI_SCAN_TYPE_ACTIVE if {@link #chreWifiScanParams.channelSet} is
- //! set to CHRE_WIFI_CHANNEL_SET_NON_DFS, and to
- //! CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS otherwise.
- //!
- //! If CHRE_WIFI_CAPABILITIES_RADIO_CHAIN_PREF is supported, a v1.5 or
- //! later platform shall perform a type of scan optimized for {@link
- //! #chreWifiScanParams.radioChainPref}.
- //!
- //! Clients are strongly encouraged to set this value in {@link
- //! #chreWifiScanParams.scanType} and instead express their preferences
- //! through {@link #chreWifiRadioChainPref} and {@link #chreWifiChannelSet}
- //! so the platform can best optimize power and performance.
- //!
- //! @since v1.5
- CHRE_WIFI_SCAN_TYPE_NO_PREFERENCE = 3,
};
/**
@@ -399,19 +362,6 @@ struct chreWifiSsidListItem {
};
/**
- * Indicates the set of channels to be scanned.
- *
- * @since v1.5
- */
-enum chreWifiChannelSet {
- //! The set of channels that allows active scan using probe request.
- CHRE_WIFI_CHANNEL_SET_NON_DFS = 0,
-
- //! The set of all channels supported.
- CHRE_WIFI_CHANNEL_SET_ALL = 1,
-};
-
-/**
* Data structure passed to chreWifiRequestScanAsync
*/
struct chreWifiScanParams {
@@ -454,14 +404,6 @@ struct chreWifiScanParams {
//! parameter is ignored.
//! @since v1.2
uint8_t radioChainPref;
-
- //! Set to a value from enum chreWifiChannelSet to specify the set of
- //! channels to be scanned. This field is considered by the platform only
- //! if scanType is CHRE_WIFI_SCAN_TYPE_NO_PREFERENCE and frequencyListLen
- //! is equal to zero.
- //!
- //! @since v1.5
- uint8_t channelSet;
};
/**
@@ -793,16 +735,6 @@ struct chreWifiRangingEvent {
uint32_t chreWifiGetCapabilities(void);
/**
- * Nanoapps must define CHRE_NANOAPP_USES_WIFI somewhere in their build
- * system (e.g. Makefile) if the nanoapp needs to use the following WiFi APIs.
- * In addition to allowing access to these APIs, defining this macro will also
- * ensure CHRE enforces that all host clients this nanoapp talks to have the
- * required Android permissions needed to listen to WiFi data by adding metadata
- * to the nanoapp.
- */
-#if defined(CHRE_NANOAPP_USES_WIFI) || !defined(CHRE_IS_NANOAPP_BUILD)
-
-/**
* Manages a client's request to receive the results of WiFi scans performed for
* other purposes, for example scans done to maintain connectivity and scans
* requested by other clients. The presence of this request has no effect on the
@@ -847,7 +779,6 @@ uint32_t chreWifiGetCapabilities(void);
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.1
- * @note Requires WiFi permission
*/
bool chreWifiConfigureScanMonitorAsync(bool enable, const void *cookie);
@@ -866,8 +797,8 @@ bool chreWifiConfigureScanMonitorAsync(bool enable, const void *cookie);
* which arrive consecutively without any other scan results in between)
* of type CHRE_EVENT_WIFI_SCAN_RESULT.
*
- * WiFi scanning must be disabled if both "WiFi scanning" and "WiFi" settings
- * are disabled at the Android level. In this case, the CHRE implementation is
+ * WiFi scanning must be disabled if both "WiFi scanning" and "WiFi" settings are
+ * disabled at the Android level. In this case, the CHRE implementation is
* expected to return a result with CHRE_ERROR_FUNCTION_DISABLED.
*
* It is not valid for a client to request a new scan while a result is pending
@@ -886,7 +817,6 @@ bool chreWifiConfigureScanMonitorAsync(bool enable, const void *cookie);
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.1
- * @note Requires WiFi permission
*/
bool chreWifiRequestScanAsync(const struct chreWifiScanParams *params,
const void *cookie);
@@ -901,19 +831,14 @@ bool chreWifiRequestScanAsync(const struct chreWifiScanParams *params,
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.1
- * @note Requires WiFi permission
*/
static inline bool chreWifiRequestScanAsyncDefault(const void *cookie) {
- static const struct chreWifiScanParams params = {
- /*.scanType=*/ CHRE_WIFI_SCAN_TYPE_NO_PREFERENCE,
- /*.maxScanAgeMs=*/ 5000, // 5 seconds
- /*.frequencyListLen=*/ 0,
- /*.frequencyList=*/ NULL,
- /*.ssidListLen=*/ 0,
- /*.ssidList=*/ NULL,
- /*.radioChainPref=*/ CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT,
- /*.channelSet=*/ CHRE_WIFI_CHANNEL_SET_NON_DFS
- };
+ struct chreWifiScanParams params = {};
+ params.scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE;
+ params.maxScanAgeMs = 5000; // 5 seconds
+ params.frequencyListLen = 0;
+ params.ssidListLen = 0;
+ params.radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT;
return chreWifiRequestScanAsync(&params, cookie);
}
@@ -951,7 +876,6 @@ static inline bool chreWifiRequestScanAsyncDefault(const void *cookie) {
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.2
- * @note Requires WiFi permission
*/
bool chreWifiRequestRangingAsync(const struct chreWifiRangingParams *params,
const void *cookie);
@@ -964,8 +888,6 @@ bool chreWifiRequestRangingAsync(const struct chreWifiRangingParams *params,
*
* @param scanResult The scan result to parse as input
* @param rangingTarget The RTT ranging target to populate as output
- *
- * @note Requires WiFi permission
*/
static inline void chreWifiRangingTargetFromScanResult(
const struct chreWifiScanResult *scanResult,
@@ -983,25 +905,6 @@ static inline void chreWifiRangingTargetFromScanResult(
memset(rangingTarget->reserved, 0, sizeof(rangingTarget->reserved));
}
-#else /* defined(CHRE_NANOAPP_USES_WIFI) || !defined(CHRE_IS_NANOAPP_BUILD) */
-#define CHRE_WIFI_PERM_ERROR_STRING \
- "CHRE_NANOAPP_USES_WIFI must be defined when building this nanoapp in " \
- "order to refer to "
-#define chreWifiConfigureScanMonitorAsync(...) \
- CHRE_BUILD_ERROR(CHRE_WIFI_PERM_ERROR_STRING \
- "chreWifiConfigureScanMonitorAsync")
-#define chreWifiRequestScanAsync(...) \
- CHRE_BUILD_ERROR(CHRE_WIFI_PERM_ERROR_STRING \
- "chreWifiRequestScanAsync")
-#define chreWifiRequestScanAsyncDefault(...) \
- CHRE_BUILD_ERROR(CHRE_WIFI_PERM_ERROR_STRING \
- "chreWifiRequestScanAsyncDefault")
-#define chreWifiRequestRangingAsync(...) \
- CHRE_BUILD_ERROR(CHRE_WIFI_PERM_ERROR_STRING "chreWifiRequestRangingAsync")
-#define chreWifiRangingTargetFromScanResult(...) \
- CHRE_BUILD_ERROR(CHRE_WIFI_PERM_ERROR_STRING \
- "chreWifiRangingTargetFromScanResult")
-#endif /* defined(CHRE_NANOAPP_USES_WIFI) || !defined(CHRE_IS_NANOAPP_BUILD) */
#ifdef __cplusplus
}
diff --git a/chre_api/include/chre_api/chre/wwan.h b/chre_api/include/chre_api/chre/wwan.h
index 51cf5f9d..a418d19f 100644
--- a/chre_api/include/chre_api/chre/wwan.h
+++ b/chre_api/include/chre_api/chre/wwan.h
@@ -307,7 +307,7 @@ struct chreWwanSignalStrengthLte {
//! Valid values are (0-31, 99) as defined in TS 27.007 8.5
int32_t signalStrength;
- //! The current Reference Signal Receive Power in dBm multiplied by -1.
+ //! The current Reference Signal Receive Power in dBm multipled by -1.
//! Range: 44 to 140 dBm
//! INT32_MAX means invalid/unreported.
//! Reference: 3GPP TS 36.133 9.1.4
@@ -342,7 +342,7 @@ struct chreWwanSignalStrengthLte {
//! Reference: RIL_TD_SCDMA_SignalStrength
struct chreWwanSignalStrengthTdscdma {
- //! The Received Signal Code Power in dBm multiplied by -1.
+ //! The Received Signal Code Power in dBm multipled by -1.
//! Range : 25 to 120
//! INT32_MAX means invalid/unreported.
//! Reference: 3GPP TS 25.123, section 9.1.1.1
@@ -525,16 +525,6 @@ struct chreWwanCellInfoResult {
uint32_t chreWwanGetCapabilities(void);
/**
- * Nanoapps must define CHRE_NANOAPP_USES_WWAN somewhere in their build
- * system (e.g. Makefile) if the nanoapp needs to use the following WWAN APIs.
- * In addition to allowing access to these APIs, defining this macro will also
- * ensure CHRE enforces that all host clients this nanoapp talks to have the
- * required Android permissions needed to listen to WWAN data by adding metadata
- * to the nanoapp.
- */
-#if defined(CHRE_NANOAPP_USES_WWAN) || !defined(CHRE_IS_NANOAPP_BUILD)
-
-/**
* Query information about the current serving cell and its neighbors. This does
* not perform a network scan, but should return state from the current network
* registration data stored in the cellular modem. This is effectively the same
@@ -555,7 +545,6 @@ uint32_t chreWwanGetCapabilities(void);
* @return true if the request was accepted for processing, false otherwise
*
* @since v1.1
- * @note Requires WWAN permission
*/
bool chreWwanGetCellInfoAsync(const void *cookie);
@@ -567,23 +556,12 @@ bool chreWwanGetCellInfoAsync(const void *cookie);
* @see chreWwanCellIdentityNr
*
* @since v1.4
- * @note Requires WWAN permission
*/
static inline int64_t chreWwanUnpackNrNci(
const struct chreWwanCellIdentityNr *nrCellId) {
return (int64_t) (((uint64_t) nrCellId->nci1 << 32) | nrCellId->nci0);
}
-#else /* defined(CHRE_NANOAPP_USES_WWAN) || !defined(CHRE_IS_NANOAPP_BUILD) */
-#define CHRE_WWAN_PERM_ERROR_STRING \
- "CHRE_NANOAPP_USES_WWAN must be defined when building this nanoapp in " \
- "order to refer to "
-#define chreWwanGetCellInfoAsync(...) \
- CHRE_BUILD_ERROR(CHRE_WWAN_PERM_ERROR_STRING "chreWwanGetCellInfoAsync")
-#define chreWwanUnpackNrNci(...) \
- CHRE_BUILD_ERROR(CHRE_WWAN_PERM_ERROR_STRING "chreWwanUnpackNrNci")
-#endif /* defined(CHRE_NANOAPP_USES_WWAN) || !defined(CHRE_IS_NANOAPP_BUILD) */
-
#ifdef __cplusplus
}
#endif
diff --git a/chre_api/legacy/v1_1/chre/wwan.h b/chre_api/legacy/v1_1/chre/wwan.h
index 1507677d..cbdb8b31 100644
--- a/chre_api/legacy/v1_1/chre/wwan.h
+++ b/chre_api/legacy/v1_1/chre/wwan.h
@@ -253,7 +253,7 @@ struct chreWwanSignalStrengthLte {
//! Valid values are (0-31, 99) as defined in TS 27.007 8.5
int32_t signalStrength;
- //! The current Reference Signal Receive Power in dBm multiplied by -1.
+ //! The current Reference Signal Receive Power in dBm multipled by -1.
//! Range: 44 to 140 dBm
//! INT32_MAX: 0x7FFFFFFF denotes invalid value.
//! Reference: 3GPP TS 36.133 9.1.4
@@ -288,7 +288,7 @@ struct chreWwanSignalStrengthLte {
//! Reference: RIL_TD_SCDMA_SignalStrength
struct chreWwanSignalStrengthTdscdma {
- //! The Received Signal Code Power in dBm multiplied by -1.
+ //! The Received Signal Code Power in dBm multipled by -1.
//! Range : 25 to 120
//! INT32_MAX: 0x7FFFFFFF denotes invalid value.
//! Reference: 3GPP TS 25.123, section 9.1.1.1
diff --git a/chre_api/legacy/v1_2/chre/wwan.h b/chre_api/legacy/v1_2/chre/wwan.h
index 1507677d..cbdb8b31 100644
--- a/chre_api/legacy/v1_2/chre/wwan.h
+++ b/chre_api/legacy/v1_2/chre/wwan.h
@@ -253,7 +253,7 @@ struct chreWwanSignalStrengthLte {
//! Valid values are (0-31, 99) as defined in TS 27.007 8.5
int32_t signalStrength;
- //! The current Reference Signal Receive Power in dBm multiplied by -1.
+ //! The current Reference Signal Receive Power in dBm multipled by -1.
//! Range: 44 to 140 dBm
//! INT32_MAX: 0x7FFFFFFF denotes invalid value.
//! Reference: 3GPP TS 36.133 9.1.4
@@ -288,7 +288,7 @@ struct chreWwanSignalStrengthLte {
//! Reference: RIL_TD_SCDMA_SignalStrength
struct chreWwanSignalStrengthTdscdma {
- //! The Received Signal Code Power in dBm multiplied by -1.
+ //! The Received Signal Code Power in dBm multipled by -1.
//! Range : 25 to 120
//! INT32_MAX: 0x7FFFFFFF denotes invalid value.
//! Reference: 3GPP TS 25.123, section 9.1.1.1
diff --git a/chre_api/legacy/v1_3/chre/wwan.h b/chre_api/legacy/v1_3/chre/wwan.h
index 1507677d..cbdb8b31 100644
--- a/chre_api/legacy/v1_3/chre/wwan.h
+++ b/chre_api/legacy/v1_3/chre/wwan.h
@@ -253,7 +253,7 @@ struct chreWwanSignalStrengthLte {
//! Valid values are (0-31, 99) as defined in TS 27.007 8.5
int32_t signalStrength;
- //! The current Reference Signal Receive Power in dBm multiplied by -1.
+ //! The current Reference Signal Receive Power in dBm multipled by -1.
//! Range: 44 to 140 dBm
//! INT32_MAX: 0x7FFFFFFF denotes invalid value.
//! Reference: 3GPP TS 36.133 9.1.4
@@ -288,7 +288,7 @@ struct chreWwanSignalStrengthLte {
//! Reference: RIL_TD_SCDMA_SignalStrength
struct chreWwanSignalStrengthTdscdma {
- //! The Received Signal Code Power in dBm multiplied by -1.
+ //! The Received Signal Code Power in dBm multipled by -1.
//! Range : 25 to 120
//! INT32_MAX: 0x7FFFFFFF denotes invalid value.
//! Reference: 3GPP TS 25.123, section 9.1.1.1
diff --git a/chre_api/legacy/v1_4/chre.h b/chre_api/legacy/v1_4/chre.h
deleted file mode 100644
index 5ac4720e..00000000
--- a/chre_api/legacy/v1_4/chre.h
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_H_
-#define _CHRE_H_
-
-/**
- * @file
- * This header file includes all the headers which combine to fully define the
- * interface for the Context Hub Runtime Environment (CHRE). This interface is
- * of interest to both implementers of CHREs and authors of nanoapps. The API
- * documentation attempts to address concerns of both.
- *
- * See individual header files for API details, and general comments below
- * for overall platform information.
- */
-
-#include <chre/audio.h>
-#include <chre/common.h>
-#include <chre/event.h>
-#include <chre/gnss.h>
-#include <chre/nanoapp.h>
-#include <chre/re.h>
-#include <chre/sensor.h>
-#include <chre/toolchain.h>
-#include <chre/version.h>
-#include <chre/wifi.h>
-#include <chre/wwan.h>
-
-/**
- * @mainpage
- * CHRE is the Context Hub Runtime Environment. CHRE is used in Android to run
- * contextual applications, called nanoapps, in a low-power processing domain
- * other than the applications processor that runs Android itself. The CHRE
- * API, documented herein, is the common interface exposed to nanoapps for any
- * compatible CHRE implementation. The CHRE API provides the ability for
- * creating nanoapps that are code-compatible across different CHRE
- * implementations and underlying platforms. Refer to the following sections for
- * a discussion on some important details of CHRE that aren't explicitly exposed
- * in the API itself.
- *
- * @section entry_points Entry points
- *
- * The following entry points are used to bind a nanoapp to the CHRE system, and
- * all three must be implemented by any nanoapp (see chre/nanoapp.h):
- * - nanoappStart: initialization
- * - nanoappHandleEvent: hook for event-driven processing
- * - nanoappEnd: graceful teardown
- *
- * The CHRE implementation must also ensure that it performs these functions
- * prior to invoking nanoappStart, or after nanoappEnd returns:
- * - bss section zeroed out (prior to nanoappStart)
- * - static variables initialized (prior to nanoappStart)
- * - global C++ constructors called (prior to nanoappStart)
- * - global C++ destructors called (after nanoappEnd)
- *
- * @section threading Threading model
- *
- * A CHRE implementation is free to choose among many different
- * threading models, including a single-threaded system or a multi-threaded
- * system with preemption. The current platform definition is agnostic to this
- * underlying choice. However, the CHRE implementation must ensure that time
- * spent executing within a nanoapp does not significantly degrade or otherwise
- * interfere with other functions of the system in which CHRE is implemented,
- * especially latency-sensitive tasks such as sensor event delivery to the AP.
- * In other words, it must ensure that these functions can either occur in
- * parallel or preempt a nanoapp's execution. The current version of the API
- * does not specify whether the implementation allows for CPU sharing between
- * nanoapps on a more granular level than the handling of individual events [1].
- * In any case, event ordering from the perspective of an individual nanoapp
- * must be FIFO, but the CHRE implementation may choose to violate total
- * ordering of events across all nanoapps to achieve more fair resource sharing,
- * but this is not required.
- *
- * This version of the CHRE API does require that all nanoapps are treated as
- * non-reentrant, meaning that only one instance of program flow can be inside
- * an individual nanoapp at any given time. That is, any of the functions of
- * the nanoapp, including the entry points and all other callbacks, cannot be
- * invoked if a previous invocation to the same or any other function in the
- * nanoapp has not completed yet.
- *
- * For example, if a nanoapp is currently in nanoappHandleEvent(), the CHRE is
- * not allowed to call nanoappHandleEvent() again, or to call a memory freeing
- * callback. Similarly, if a nanoapp is currently in a memory freeing
- * callback, the CHRE is not allowed to call nanoappHandleEvent(), or invoke
- * another memory freeing callback.
- *
- * There are two exceptions to this rule: If an invocation of chreSendEvent()
- * fails (returns 'false'), it is allowed to immediately invoke the memory
- * freeing callback passed into that function. This is a rare case, and one
- * where otherwise a CHRE implementation is likely to leak memory. Similarly,
- * chreSendMessageToHost() is allowed to invoke the memory freeing callback
- * directly, whether it returns 'true' or 'false'. This is because the CHRE
- * implementation may copy the message data to its own buffer, and therefore
- * wouldn't need the nanoapp-supplied buffer after chreSendMessageToHost()
- * returns.
- *
- * For a nanoapp author, this means no thought needs to be given to
- * synchronization issues with global objects, as they will, by definition,
- * only be accessed by a single thread at once.
- *
- * [1]: Note to CHRE implementers: A future version of the CHRE platform may
- * require multi-threading with preemption. This is mentioned as a heads up,
- * and to allow implementors deciding between implementation approaches to
- * make the most informed choice.
- *
- * @section timing Timing
- *
- * Nanoapps should expect to be running on a highly constrained system, with
- * little memory and little CPU. Any single nanoapp should expect to
- * be one of several nanoapps on the system, which also share the CPU with the
- * CHRE and possibly other services as well.
- *
- * Thus, a nanoapp needs to be efficient in its memory and CPU usage.
- * Also, as noted in the Threading Model section, a CHRE implementation may
- * be single threaded. As a result, all methods invoked in a nanoapp
- * (like nanoappStart, nanoappHandleEvent, memory free callbacks, etc.)
- * must run "quickly". "Quickly" is difficult to define, as there is a
- * diversity of Context Hub hardware. Nanoapp authors are strongly recommended
- * to limit their application to consuming no more than 1 second of CPU time
- * prior to returning control to the CHRE implementation. A CHRE implementation
- * may consider a nanoapp as unresponsive if it spends more time than this to
- * process a single event, and take corrective action.
- *
- * A nanoapp may have the need to occasionally perform a large block of
- * calculations that exceeds the 1 second guidance. The recommended approach in
- * this case is to split up the large block of calculations into smaller
- * batches. In one call into the nanoapp, the nanoapp can perform the first
- * batch, and then set a timer or send an event (chreSendEvent()) to itself
- * indicating which batch should be done next. This will allow the nanoapp to
- * perform the entire calculation over time, without monopolizing system
- * resources.
- *
- * @section floats Floating point support
- *
- * The C type 'float' is used in this API, and thus a CHRE implementation
- * is required to support 'float's.
- *
- * Support of the C types 'double' and 'long double' is optional for a
- * CHRE implementation. Note that if a CHRE decides to support them, unlike
- * 'float' support, there is no requirement that this support is particularly
- * efficient. So nanoapp authors should be aware this may be inefficient.
- *
- * If a CHRE implementation chooses not to support 'double' or
- * 'long double', then the build toolchain setup provided needs to set
- * the preprocessor define CHRE_NO_DOUBLE_SUPPORT.
- *
- * @section compat CHRE and Nanoapp compatibility
- *
- * CHRE implementations must make affordances to maintain binary compatibility
- * across minor revisions of the API version (e.g. v1.1 to v1.2). This applies
- * to both running a nanoapp compiled for a newer version of the API on a CHRE
- * implementation built against an older version (backwards compatibility), and
- * vice versa (forwards compatibility). API changes that are acceptable in
- * minor version changes that may require special measures to ensure binary
- * compatibility include: addition of new functions; addition of arguments to
- * existing functions when the default value used for nanoapps compiled against
- * the old version is well-defined and does not affect existing functionality;
- * and addition of fields to existing structures, even when this induces a
- * binary layout change (this should be made rare via judicious use of reserved
- * fields). API changes that must only occur alongside a major version change
- * and are therefore not compatible include: removal of any function, argument,
- * field in a data structure, or mandatory functional behavior that a nanoapp
- * may depend on; any change in the interpretation of an existing data structure
- * field that alters the way it was defined previously (changing the units of a
- * field would fall under this, but appropriating a previously reserved field
- * for some new functionality would not); and any change in functionality or
- * expected behavior that conflicts with the previous definition.
- *
- * Note that the CHRE API only specifies the software interface between a
- * nanoapp and the CHRE system - the binary interface (ABI) between nanoapp and
- * CHRE is necessarily implementation-dependent. Therefore, the recommended
- * approach to accomplish binary compatibility is to build a Nanoapp Support
- * Library (NSL) that is specific to the CHRE implementation into the nanoapp
- * binary, and use it to handle ABI details in a way that ensures compatibility.
- * In addition, to accomplish forwards compatibility, the CHRE implementation is
- * expected to recognize the CHRE API version that a nanoapp is targeting and
- * engage compatibility behaviors where necessary.
- *
- * By definition, major API version changes (e.g. v1.1 to v2.0) break
- * compatibility. Therefore, a CHRE implementation must not attempt to load a
- * nanoapp that is targeting a newer major API version.
- */
-
-#endif /* _CHRE_H_ */
-
diff --git a/chre_api/legacy/v1_4/chre/audio.h b/chre_api/legacy/v1_4/chre/audio.h
deleted file mode 100644
index 201ab0e7..00000000
--- a/chre_api/legacy/v1_4/chre/audio.h
+++ /dev/null
@@ -1,407 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * 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 _CHRE_AUDIO_H_
-#define _CHRE_AUDIO_H_
-
-/**
- * @file
- * The API for requesting audio in the Context Hub Runtime Environment.
- *
- * This includes the definition of audio data structures and the ability to
- * request audio streams.
- */
-
-#include <chre/event.h>
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * The current compatibility version of the chreAudioDataEvent structure.
- */
-#define CHRE_AUDIO_DATA_EVENT_VERSION UINT8_C(1)
-
-/**
- * Produce an event ID in the block of IDs reserved for audio
- * @param offset Index into audio event ID block; valid range [0,15]
- */
-#define CHRE_AUDIO_EVENT_ID(offset) (CHRE_EVENT_AUDIO_FIRST_EVENT + (offset))
-
-/**
- * nanoappHandleEvent argument: struct chreAudioSourceStatusEvent
- *
- * Indicates a change in the format and/or rate of audio data provided to a
- * nanoapp.
- */
-#define CHRE_EVENT_AUDIO_SAMPLING_CHANGE CHRE_AUDIO_EVENT_ID(0)
-
-/**
- * nanoappHandleEvent argument: struct chreAudioDataEvent
- *
- * Provides a buffer of audio data to a nanoapp.
- */
-#define CHRE_EVENT_AUDIO_DATA CHRE_AUDIO_EVENT_ID(1)
-
-/**
- * The maximum size of the name of an audio source including the
- * null-terminator.
- */
-#define CHRE_AUDIO_SOURCE_NAME_MAX_SIZE (40)
-
-/**
- * Helper values for sample rates.
- *
- * @defgroup CHRE_AUDIO_SAMPLE_RATES
- * @{
- */
-
-//! 16kHz Audio Sample Data
-#define CHRE_AUDIO_SAMPLE_RATE_16KHZ (16000)
-
-/** @} */
-
-/**
- * Formats for audio that can be provided to a nanoapp.
- */
-enum chreAudioDataFormat {
- /**
- * Unsigned, 8-bit u-Law encoded data as specified by ITU-T G.711.
- */
- CHRE_AUDIO_DATA_FORMAT_8_BIT_U_LAW = 0,
-
- /**
- * Signed, 16-bit linear PCM data. Endianness must be native to the local
- * processor.
- */
- CHRE_AUDIO_DATA_FORMAT_16_BIT_SIGNED_PCM = 1,
-};
-
-/**
- * A description of an audio source available to a nanoapp.
- *
- * This provides a description of an audio source with a name and a
- * description of the format of the provided audio data.
- */
-struct chreAudioSource {
- /**
- * A human readable name for this audio source. This is a C-style,
- * null-terminated string. The length must be less than or equal to
- * CHRE_AUDIO_SOURCE_NAME_MAX_SIZE bytes (including the null-terminator) and
- * is expected to describe the source of the audio in US English. All
- * characters must be printable (i.e.: isprint would return true for all
- * characters in the name for the EN-US locale). The typical use of this field
- * is for a nanoapp to log the name of the audio source that it is using.
- *
- * Example: "Camcorder Microphone"
- */
- const char *name;
-
- /**
- * The sampling rate in hertz of this mode. This value is rounded to the
- * nearest integer. Typical values might include 16000, 44100 and 44800.
- *
- * If the requested audio source is preempted by another feature of the system
- * (e.g. hotword), a gap may occur in received audio data. This is indicated
- * to the client by posting a CHRE_EVENT_AUDIO_SAMPLING_CHANGE event. The
- * nanoapp will then receive another CHRE_EVENT_AUDIO_SAMPLING_CHANGE event
- * once the audio source is available again.
- */
- uint32_t sampleRate;
-
- /**
- * The minimum amount of time that this audio source can be buffered, in
- * nanoseconds. Audio data is delivered to nanoapps in buffers. This specifies
- * the minimum amount of data that can be delivered to a nanoapp without
- * losing data. A request for a buffer that is smaller than this will fail.
- */
- uint64_t minBufferDuration;
-
- /**
- * The maximum amount of time that this audio source can be buffered, in
- * nanoseconds. Audio data is delivered to nanoapps in buffers. This specifies
- * the maximum amount of data that can be stored by the system in one event
- * without losing data. A request for a buffer that is larger than this will
- * fail.
- */
- uint64_t maxBufferDuration;
-
- /**
- * The format for data provided to the nanoapp. This will be assigned to one
- * of the enum chreAudioDataFormat values.
- */
- uint8_t format;
-};
-
-/**
- * The current status of an audio source.
- */
-struct chreAudioSourceStatus {
- /**
- * Set to true if the audio source is currently enabled by this nanoapp. If
- * this struct is provided by a CHRE_EVENT_AUDIO_SAMPLING_CHANGE event, it
- * must necessarily be set to true because sampling change events are only
- * sent for sources which this nanoapp has actively subscribed to. If this
- * struct is obtained from the chreAudioGetStatus API, it may be set to true
- * or false depending on if audio is currently enabled.
- */
- bool enabled;
-
- /**
- * Set to true if the audio source is currently suspended and no audio data
- * will be received from this source.
- */
- bool suspended;
-};
-
-/**
- * The nanoappHandleEvent argument for CHRE_EVENT_AUDIO_SAMPLING_CHANGE.
- */
-struct chreAudioSourceStatusEvent {
- /**
- * The audio source which has completed a status change.
- */
- uint32_t handle;
-
- /**
- * The status of this audio source.
- */
- struct chreAudioSourceStatus status;
-};
-
-/**
- * The nanoappHandleEvent argument for CHRE_EVENT_AUDIO_DATA.
- *
- * One example of the sequence of events for a nanoapp to receive audio data is:
- *
- * 1. CHRE_EVENT_AUDIO_SAMPLING_CHANGE - Indicates that audio data is not
- * suspended.
- * 2. CHRE_EVENT_AUDIO_DATA - One buffer of audio samples. Potentially repeated.
- * 3. CHRE_EVENT_AUDIO_SAMPLING_CHANGE - Indicates that audio data has suspended
- * which indicates a gap in the audio.
- * 4. CHRE_EVENT_AUDIO_SAMPLING_CHANGE - Indicates that audio data has resumed
- * and that audio data may be delivered
- * again if enough samples are buffered.
- * 5. CHRE_EVENT_AUDIO_DATA - One buffer of audio samples. Potentially repeated.
- * The nanoapp must tolerate a gap in the timestamps.
- *
- * This process repeats for as long as an active request is made for an audio
- * source. A CHRE_EVENT_AUDIO_SAMPLING_CHANGE does not guarantee that the next
- * event will be a CHRE_EVENT_AUDIO_DATA event when suspended is set to false.
- * It may happen that the audio source is suspended before a complete buffer can
- * be captured. This will cause another CHRE_EVENT_AUDIO_SAMPLING_CHANGE event
- * to be dispatched with suspended set to true before a buffer is delivered.
- *
- * Audio events must be delivered to a nanoapp in order.
- */
-struct chreAudioDataEvent {
- /**
- * Indicates the version of the structure, for compatibility purposes. Clients
- * do not normally need to worry about this field; the CHRE implementation
- * guarantees that the client only receives the structure version it expects.
- */
- uint8_t version;
-
- /**
- * Additional bytes reserved for future use; must be set to 0.
- */
- uint8_t reserved[3];
-
- /**
- * The handle for which this audio data originated from.
- */
- uint32_t handle;
-
- /**
- * The base timestamp for this buffer of audio data, from the same time base
- * as chreGetTime() (in nanoseconds). The audio API does not provide
- * timestamps for each audio sample. This timestamp corresponds to the first
- * sample of the buffer. Even though the value is expressed in nanoseconds,
- * there is an expectation that the sample clock may drift and nanosecond
- * level accuracy may not be possible. The goal is to be as accurate as
- * possible within reasonable limitations of a given system.
- */
- uint64_t timestamp;
-
- /**
- * The sample rate for this buffer of data in hertz, rounded to the nearest
- * integer. Fractional sampling rates are not supported. Typical values might
- * include 16000, 44100 and 48000.
- */
- uint32_t sampleRate;
-
- /**
- * The number of samples provided with this buffer.
- */
- uint32_t sampleCount;
-
- /**
- * The format of this audio data. This enumeration and union of pointers below
- * form a tagged struct. The consumer of this API must use this enum to
- * determine which samples pointer below to dereference. This will be assigned
- * to one of the enum chreAudioDataFormat values.
- */
- uint8_t format;
-
- /**
- * A union of pointers to various formats of sample data. These correspond to
- * the valid chreAudioDataFormat values.
- */
- union {
- const uint8_t *samplesULaw8;
- const int16_t *samplesS16;
- };
-};
-
-/**
- * Retrieves information about an audio source supported by the current CHRE
- * implementation. The source returned by the runtime must not change for the
- * entire lifecycle of the Nanoapp and hot-pluggable audio sources are not
- * supported.
- *
- * A simple example of iterating all available audio sources is provided here:
- *
- * struct chreAudioSource audioSource;
- * for (uint32_t i = 0; chreAudioGetSource(i, &audioSource); i++) {
- * chreLog(CHRE_LOG_INFO, "Found audio source: %s", audioSource.name);
- * }
- *
- * Handles provided to this API must be a stable value for the entire duration
- * of a nanoapp. Handles for all audio sources must be zero-indexed and
- * contiguous. The following are examples of handles that could be provided to
- * this API:
- *
- * Valid: 0
- * Valid: 0, 1, 2, 3
- * Invalid: 1, 2, 3
- * Invalid: 0, 2
- *
- * @param handle The handle for an audio source to obtain details for. The
- * range of acceptable handles must be zero-indexed and contiguous.
- * @param audioSource A struct to populate with details of the audio source.
- * @return true if the query was successful, false if the provided handle is
- * invalid or the supplied audioSource is NULL.
- *
- * @since v1.2
- */
-bool chreAudioGetSource(uint32_t handle, struct chreAudioSource *audioSource);
-
-/**
- * Configures delivery of audio data to the current nanoapp. Note that this may
- * not fully disable the audio source if it is used by other clients in the
- * system but it will halt data delivery to the nanoapp.
- *
- * The bufferDuration and deliveryInterval parameters as described below are
- * used together to determine both how much and how often to deliver data to a
- * nanoapp, respectively. A nanoapp will always be provided the requested
- * amount of data at the requested interval, even if another nanoapp in CHRE
- * requests larger/more frequent buffers or smaller/less frequent buffers.
- * These two buffering parameters allow describing the duty cycle of captured
- * audio data. If a nanoapp wishes to receive all available audio data, it will
- * specify a bufferDuration and deliveryInterval that are equal. A 50% duty
- * cycle would be achieved by specifying a deliveryInterval that is double the
- * value of the bufferDuration provided. These parameters allow the audio
- * subsystem to operate at less than 100% duty cycle and permits use of
- * incomplete audio data without periodic reconfiguration of the source.
- *
- * Two examples are illustrated below:
- *
- * Target duty cycle: 50%
- * bufferDuration: 2
- * deliveryInterval: 4
- *
- * Time 0 1 2 3 4 5 6 7
- * Batch A B
- * Sample -- -- a1 a2 -- -- b1 b2
- * Duration [ ] [ ]
- * Interval [ ] [ ]
- *
- *
- * Target duty cycle: 100%
- * bufferDuration: 4
- * deliveryInterval: 4
- *
- * Time 0 1 2 3 4 5 6 7
- * Batch A B
- * Sample a1 a2 a3 a4 b1 b2 b3 b4
- * Duration [ ] [ ]
- * Interval [ ] [ ]
- *
- *
- * This is expected to reduce power overall.
- *
- * The first audio buffer supplied to the nanoapp may contain data captured
- * prior to the request. This could happen if the microphone was already enabled
- * and reading into a buffer prior to the nanoapp requesting audio data for
- * itself. The nanoapp must tolerate this.
- *
- * It is important to note that multiple logical audio sources (e.g. different
- * sample rate, format, etc.) may map to one physical audio source. It is
- * possible for a nanoapp to request audio data from more than one logical
- * source at a time. Audio data may be suspended for either the current or other
- * requests. The CHRE_EVENT_AUDIO_SAMPLING_CHANGE will be posted to all clients
- * if such a change occurs. It is also possible for the request to succeed and
- * all audio sources are serviced simultaneously. This is implementation defined
- * but at least one audio source must function correctly if it is advertised,
- * under normal conditions (e.g. not required for some other system function,
- * such as hotword).
- *
- * @param handle The handle for this audio source. The handle for the desired
- * audio source can be determined using chreAudioGetSource().
- * @param enable true if enabling the source, false otherwise. When passed as
- * false, the bufferDuration and deliveryInterval parameters are ignored.
- * @param bufferDuration The amount of time to capture audio samples from this
- * audio source, in nanoseconds per delivery interval. This value must be
- * in the range of minBufferDuration/maxBufferDuration for this source or
- * the request will fail. The number of samples captured per buffer will be
- * derived from the sample rate of the source and the requested duration and
- * rounded down to the nearest sample boundary.
- * @param deliveryInterval Desired time between each CHRE_EVENT_AUDIO_DATA
- * event. This allows specifying the commplete duty cycle of a request
- * for audio data, in nanoseconds. This value must be greater than or equal
- * to bufferDuration or the request will fail due to an invalid
- * configuration.
- * @return true if the configuration was successful, false if invalid parameters
- * were provided (non-existent handle, invalid buffering configuration).
- *
- * @since v1.2
- */
-bool chreAudioConfigureSource(uint32_t handle, bool enable,
- uint64_t bufferDuration,
- uint64_t deliveryInterval);
-
-/**
- * Gets the current chreAudioSourceStatus struct for a given audio handle.
- *
- * @param handle The handle for the audio source to query. The provided handle
- * is obtained from a chreAudioSource which is requested from the
- * chreAudioGetSource API.
- * @param status The current status of the supplied audio source.
- * @return true if the provided handle is valid and the status was obtained
- * successfully, false if the handle was invalid or status is NULL.
- *
- * @since v1.2
- */
-bool chreAudioGetStatus(uint32_t handle, struct chreAudioSourceStatus *status);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_AUDIO_H_ */
diff --git a/chre_api/legacy/v1_4/chre/common.h b/chre_api/legacy/v1_4/chre/common.h
deleted file mode 100644
index 0224e9ac..00000000
--- a/chre_api/legacy/v1_4/chre/common.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_COMMON_H_
-#define _CHRE_COMMON_H_
-
-/**
- * @file
- * Definitions shared across multiple CHRE header files
- */
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Mask of the 5 most significant bytes in a 64-bit nanoapp or CHRE platform
- * identifier, which represents the vendor ID portion of the ID.
- */
-#define CHRE_VENDOR_ID_MASK UINT64_C(0xFFFFFFFFFF000000)
-
-/**
- * Vendor ID "Googl". Used in nanoapp IDs and CHRE platform IDs developed and
- * released by Google.
- */
-#define CHRE_VENDOR_ID_GOOGLE UINT64_C(0x476F6F676C000000)
-
-/**
- * Vendor ID "GoogT". Used for nanoapp IDs associated with testing done by
- * Google.
- */
-#define CHRE_VENDOR_ID_GOOGLE_TEST UINT64_C(0x476F6F6754000000)
-
-/**
- * Helper macro to mask off all bytes other than the vendor ID (most significant
- * 5 bytes) in 64-bit nanoapp and CHRE platform identifiers.
- *
- * @see chreGetNanoappInfo()
- * @see chreGetPlatformId()
- */
-#define CHRE_EXTRACT_VENDOR_ID(id) ((id) & CHRE_VENDOR_ID_MASK)
-
-/**
- * Number of nanoseconds in one second, represented as an unsigned 64-bit
- * integer
- */
-#define CHRE_NSEC_PER_SEC UINT64_C(1000000000)
-
-/**
- * General timeout for asynchronous API requests. Unless specified otherwise, a
- * function call that returns data asynchronously via an event, such as
- * CHRE_EVENT_ASYNC_GNSS_RESULT, must do so within this amount of time.
- */
-#define CHRE_ASYNC_RESULT_TIMEOUT_NS (5 * CHRE_NSEC_PER_SEC)
-
-
-/**
- * A generic listing of error codes for use in {@link #chreAsyncResult} and
- * elsewhere. In general, module-specific error codes may be added to this enum,
- * but effort should be made to come up with a generic name that still captures
- * the meaning of the error.
- */
-enum chreError {
- //! No error occurred
- CHRE_ERROR_NONE = 0,
-
- //! An unspecified failure occurred
- CHRE_ERROR = 1,
-
- //! One or more supplied arguments are invalid
- CHRE_ERROR_INVALID_ARGUMENT = 2,
-
- //! Unable to satisfy request because the system is busy
- CHRE_ERROR_BUSY = 3,
-
- //! Unable to allocate memory
- CHRE_ERROR_NO_MEMORY = 4,
-
- //! The requested feature is not supported
- CHRE_ERROR_NOT_SUPPORTED = 5,
-
- //! A timeout occurred while processing the request
- CHRE_ERROR_TIMEOUT = 6,
-
- //! The relevant capability is disabled, for example due to a user
- //! configuration that takes precedence over this request
- CHRE_ERROR_FUNCTION_DISABLED = 7,
-
- //! The request was rejected due to internal rate limiting of the requested
- //! functionality - the client may try its request again after waiting an
- //! unspecified amount of time
- CHRE_ERROR_REJECTED_RATE_LIMIT = 8,
-
- //! The requested functionality is not currently accessible from the CHRE,
- //! because another client, such as the main applications processor, is
- //! currently controlling it.
- CHRE_ERROR_FUNCTION_RESTRICTED_TO_OTHER_MASTER = 9,
- CHRE_ERROR_FUNCTION_RESTRICTED_TO_OTHER_CLIENT = 9,
-
- //!< Do not exceed this value when adding new error codes
- CHRE_ERROR_LAST = UINT8_MAX,
-};
-
-/**
- * Generic data structure to indicate the result of an asynchronous operation.
- *
- * @note
- * The general model followed by CHRE for asynchronous operations is that a
- * request function returns a boolean value that indicates whether the request
- * was accepted for further processing. The actual result of the operation is
- * provided in a subsequent event sent with an event type that is defined in the
- * specific API. Typically, a "cookie" parameter is supplied to allow the client
- * to tie the response to a specific request, or pass data through, etc. The
- * response is expected to be delivered within CHRE_ASYNC_RESULT_TIMEOUT_NS if
- * not specified otherwise.
- *
- * The CHRE implementation must allow for multiple asynchronous requests to be
- * outstanding at a given time, under reasonable resource constraints. Further,
- * requests must be processed in the same order as supplied by the client of the
- * API in order to maintain causality. Using GNSS as an example, if a client
- * calls chreGnssLocationSessionStartAsync() and then immediately calls
- * chreGnssLocationSessionStopAsync(), the final result must be that the
- * location session is stopped. Whether requests always complete in the
- * order that they are given is implementation-defined. For example, if a client
- * calls chreGnssLocationSessionStart() and then immediately calls
- * chreGnssMeasurementSessionStart(), it is possible for the
- * CHRE_EVENT_GNSS_RESULT associated with the measurement session to be
- * delivered before the one for the location session.
- */
-struct chreAsyncResult {
- //! Indicates the request associated with this result. The interpretation of
- //! values in this field is dependent upon the event type provided when this
- //! result was delivered.
- uint8_t requestType;
-
- //! Set to true if the request was successfully processed
- bool success;
-
- //! If the request failed (success is false), this is set to a value from
- //! enum chreError (other than CHRE_ERROR_NONE), which may provide
- //! additional information about the nature of the failure.
- //! @see #chreError
- uint8_t errorCode;
-
- //! Reserved for future use, set to 0
- uint8_t reserved;
-
- //! Set to the cookie parameter given to the request function tied to this
- //! result
- const void *cookie;
-};
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_COMMON_H_ */
diff --git a/chre_api/legacy/v1_4/chre/event.h b/chre_api/legacy/v1_4/chre/event.h
deleted file mode 100644
index 0cc49350..00000000
--- a/chre_api/legacy/v1_4/chre/event.h
+++ /dev/null
@@ -1,587 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_EVENT_H_
-#define _CHRE_EVENT_H_
-
-/**
- * @file
- * Context Hub Runtime Environment API dealing with events and messages.
- */
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-#include <chre/toolchain.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * The CHRE implementation is required to provide the following
- * preprocessor defines via the build system.
- *
- * CHRE_MESSAGE_TO_HOST_MAX_SIZE: The maximum size, in bytes, allowed for
- * a message sent to chreSendMessageToHostEndpoint(). This must be at least
- * CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE.
- */
-
-#ifndef CHRE_MESSAGE_TO_HOST_MAX_SIZE
-#error CHRE_MESSAGE_TO_HOST_MAX_SIZE must be defined by the Context Hub Runtime Environment implementation
-#endif
-
-/**
- * The minimum size, in bytes, any CHRE implementation will
- * use for CHRE_MESSAGE_TO_HOST_MAX_SIZE.
- */
-#define CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE 128
-
-#if CHRE_MESSAGE_TO_HOST_MAX_SIZE < CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE
-#error CHRE_MESSAGE_TO_HOST_MAX_SIZE is too small.
-#endif
-
-/**
- * The lowest numerical value legal for a user-defined event.
- *
- * The system reserves all event values from 0 to 0x7FFF, inclusive.
- * User events may use any value in the range 0x8000 to 0xFFFF, inclusive.
- *
- * Note that the same event values might be used by different nanoapps
- * for different meanings. This is not a concern, as these values only
- * have meaning when paired with the originating nanoapp.
- */
-#define CHRE_EVENT_FIRST_USER_VALUE UINT16_C(0x8000)
-
-/**
- * nanoappHandleEvent argument: struct chreMessageFromHostData
- *
- * The format of the 'message' part of this structure is left undefined,
- * and it's up to the nanoapp and host to have an established protocol
- * beforehand.
- */
-#define CHRE_EVENT_MESSAGE_FROM_HOST UINT16_C(0x0001)
-
-/**
- * nanoappHandleEvent argument: 'cookie' given to chreTimerSet() method.
- *
- * Indicates that a timer has elapsed, in accordance with how chreTimerSet() was
- * invoked.
- */
-#define CHRE_EVENT_TIMER UINT16_C(0x0002)
-
-/**
- * nanoappHandleEvent argument: struct chreNanoappInfo
- *
- * Indicates that a nanoapp has successfully started (its nanoappStart()
- * function has been called, and it returned true) and is able to receive events
- * sent via chreSendEvent(). Note that this event is not sent for nanoapps that
- * were started prior to the current nanoapp - use chreGetNanoappInfo() to
- * determine if another nanoapp is already running.
- *
- * @see chreConfigureNanoappInfoEvents
- * @since v1.1
- */
-#define CHRE_EVENT_NANOAPP_STARTED UINT16_C(0x0003)
-
-/**
- * nanoappHandleEvent argument: struct chreNanoappInfo
- *
- * Indicates that a nanoapp has stopped executing and is no longer able to
- * receive events sent via chreSendEvent(). Any events sent prior to receiving
- * this event are not guaranteed to have been delivered.
- *
- * @see chreConfigureNanoappInfoEvents
- * @since v1.1
- */
-#define CHRE_EVENT_NANOAPP_STOPPED UINT16_C(0x0004)
-
-/**
- * nanoappHandleEvent argument: NULL
- *
- * Indicates that CHRE has observed the host wake from low-power sleep state.
- *
- * @see chreConfigureHostSleepStateEvents
- * @since v1.2
- */
-#define CHRE_EVENT_HOST_AWAKE UINT16_C(0x0005)
-
-/**
- * nanoappHandleEvent argument: NULL
- *
- * Indicates that CHRE has observed the host enter low-power sleep state.
- *
- * @see chreConfigureHostSleepStateEvents
- * @since v1.2
- */
-#define CHRE_EVENT_HOST_ASLEEP UINT16_C(0x0006)
-
-/**
- * nanoappHandleEvent argument: NULL
- *
- * Indicates that CHRE is collecting debug dumps. Nanoapps can call
- * chreDebugDumpLog() to log their debug data while handling this event.
- *
- * @see chreConfigureDebugDumpEvent
- * @see chreDebugDumpLog
- * @since v1.4
- */
-#define CHRE_EVENT_DEBUG_DUMP UINT16_C(0x0007)
-
-/**
- * First possible value for CHRE_EVENT_SENSOR events.
- *
- * This allows us to separately define our CHRE_EVENT_SENSOR_* events in
- * chre/sensor.h, without fear of collision with other event values.
- */
-#define CHRE_EVENT_SENSOR_FIRST_EVENT UINT16_C(0x0100)
-
-/**
- * Last possible value for CHRE_EVENT_SENSOR events.
- *
- * This allows us to separately define our CHRE_EVENT_SENSOR_* events in
- * chre/sensor.h, without fear of collision with other event values.
- */
-#define CHRE_EVENT_SENSOR_LAST_EVENT UINT16_C(0x02FF)
-
-/**
- * First event in the block reserved for GNSS. These events are defined in
- * chre/gnss.h.
- */
-#define CHRE_EVENT_GNSS_FIRST_EVENT UINT16_C(0x0300)
-#define CHRE_EVENT_GNSS_LAST_EVENT UINT16_C(0x030F)
-
-/**
- * First event in the block reserved for WiFi. These events are defined in
- * chre/wifi.h.
- */
-#define CHRE_EVENT_WIFI_FIRST_EVENT UINT16_C(0x0310)
-#define CHRE_EVENT_WIFI_LAST_EVENT UINT16_C(0x031F)
-
-/**
- * First event in the block reserved for WWAN. These events are defined in
- * chre/wwan.h.
- */
-#define CHRE_EVENT_WWAN_FIRST_EVENT UINT16_C(0x0320)
-#define CHRE_EVENT_WWAN_LAST_EVENT UINT16_C(0x032F)
-
-/**
- * First event in the block reserved for audio. These events are defined in
- * chre/audio.h.
- */
-
-#define CHRE_EVENT_AUDIO_FIRST_EVENT UINT16_C(0x0330)
-#define CHRE_EVENT_AUDIO_LAST_EVENT UINT16_C(0x033F)
-
-/**
- * First in the extended range of values dedicated for internal CHRE
- * implementation usage.
- *
- * This range is semantically the same as the internal event range defined
- * below, but has been extended to allow for more implementation-specific events
- * to be used.
- *
- * @since v1.1
- */
-#define CHRE_EVENT_INTERNAL_EXTENDED_FIRST_EVENT UINT16_C(0x7000)
-
-/**
- * First in a range of values dedicated for internal CHRE implementation usage.
- *
- * If a CHRE wishes to use events internally, any values within this range
- * are assured not to be taken by future CHRE API additions.
- */
-#define CHRE_EVENT_INTERNAL_FIRST_EVENT UINT16_C(0x7E00)
-
-/**
- * Last in a range of values dedicated for internal CHRE implementation usage.
- *
- * If a CHRE wishes to use events internally, any values within this range
- * are assured not to be taken by future CHRE API additions.
- */
-#define CHRE_EVENT_INTERNAL_LAST_EVENT UINT16_C(0x7FFF)
-
-/**
- * A special value for the hostEndpoint argument in
- * chreSendMessageToHostEndpoint() that indicates that the message should be
- * delivered to all host endpoints. This value will not be used in the
- * hostEndpoint field of struct chreMessageFromHostData supplied with
- * CHRE_EVENT_MESSAGE_FROM_HOST.
- *
- * @since v1.1
- */
-#define CHRE_HOST_ENDPOINT_BROADCAST UINT16_C(0xFFFF)
-
-/**
- * A special value for hostEndpoint in struct chreMessageFromHostData that
- * indicates that a host endpoint is unknown or otherwise unspecified. This
- * value may be received in CHRE_EVENT_MESSAGE_FROM_HOST, but it is not valid to
- * provide it to chreSendMessageToHostEndpoint().
- *
- * @since v1.1
- */
-#define CHRE_HOST_ENDPOINT_UNSPECIFIED UINT16_C(0xFFFE)
-
-
-/**
- * Data provided with CHRE_EVENT_MESSAGE_FROM_HOST.
- */
-struct chreMessageFromHostData {
- /**
- * Message type supplied by the host.
- *
- * @note In CHRE API v1.0, support for forwarding this field from the host
- * was not strictly required, and some implementations did not support it.
- * However, its support is mandatory as of v1.1.
- */
- union {
- /**
- * The preferred name to use when referencing this field.
- *
- * @since v1.1
- */
- uint32_t messageType;
-
- /**
- * @deprecated This is the name for the messageType field used in v1.0.
- * Left to allow code to compile against both v1.0 and v1.1 of the API
- * definition without needing to use #ifdefs. This will be removed in a
- * future API update - use messageType instead.
- */
- uint32_t reservedMessageType;
- };
-
- /**
- * The size, in bytes of the following 'message'.
- *
- * This can be 0.
- */
- uint32_t messageSize;
-
- /**
- * The message from the host.
- *
- * These contents are of a format that the host and nanoapp must have
- * established beforehand.
- *
- * This data is 'messageSize' bytes in length. Note that if 'messageSize'
- * is 0, this might be NULL.
- */
- const void *message;
-
- /**
- * An identifier for the host-side entity that sent this message. Unless
- * this is set to CHRE_HOST_ENDPOINT_UNSPECIFIED, it can be used in
- * chreSendMessageToHostEndpoint() to send a directed reply that will only
- * be received by the given entity on the host. Endpoint identifiers are
- * opaque values assigned at runtime, so they cannot be assumed to always
- * describe a specific entity across restarts.
- *
- * If running on a CHRE API v1.0 implementation, this field will always be
- * set to CHRE_HOST_ENDPOINT_UNSPECIFIED.
- *
- * @since v1.1
- */
- uint16_t hostEndpoint;
-};
-
-/**
- * Provides metadata for a nanoapp in the system.
- */
-struct chreNanoappInfo {
- /**
- * Nanoapp identifier. The convention for populating this value is to set
- * the most significant 5 bytes to a value that uniquely identifies the
- * vendor, and the lower 3 bytes identify the nanoapp.
- */
- uint64_t appId;
-
- /**
- * Nanoapp version. The semantics of this field are defined by the nanoapp,
- * however nanoapps are recommended to follow the same scheme used for the
- * CHRE version exposed in chreGetVersion(). That is, the most significant
- * byte represents the major version, the next byte the minor version, and
- * the lower two bytes the patch version.
- */
- uint32_t version;
-
- /**
- * The instance ID of this nanoapp, which can be used in chreSendEvent() to
- * address an event specifically to this nanoapp. This identifier is
- * guaranteed to be unique among all nanoapps in the system.
- */
- uint32_t instanceId;
-};
-
-/**
- * Callback which frees data associated with an event.
- *
- * This callback is (optionally) provided to the chreSendEvent() method as
- * a means for freeing the event data and performing any other cleanup
- * necessary when the event is completed. When this callback is invoked,
- * 'eventData' is no longer needed and can be released.
- *
- * @param eventType The 'eventType' argument from chreSendEvent().
- * @param eventData The 'eventData' argument from chreSendEvent().
- *
- * @see chreSendEvent
- */
-typedef void (chreEventCompleteFunction)(uint16_t eventType, void *eventData);
-
-/**
- * Callback which frees a message.
- *
- * This callback is (optionally) provided to the chreSendMessageToHostEndpoint()
- * method as a means for freeing the message. When this callback is invoked,
- * 'message' is no longer needed and can be released. Note that this in
- * no way assures that said message did or did not make it to the host, simply
- * that this memory is no longer needed.
- *
- * @param message The 'message' argument from chreSendMessageToHostEndpoint().
- * @param messageSize The 'messageSize' argument from
- * chreSendMessageToHostEndpoint().
- *
- * @see chreSendMessageToHostEndpoint
- */
-typedef void (chreMessageFreeFunction)(void *message, size_t messageSize);
-
-
-/**
- * Enqueue an event to be sent to another nanoapp.
- *
- * @param eventType This is a user-defined event type, of at least the
- * value CHRE_EVENT_FIRST_USER_VALUE. It is illegal to attempt to use any
- * of the CHRE_EVENT_* values reserved for the CHRE.
- * @param eventData A pointer value that will be understood by the receiving
- * app. Note that NULL is perfectly acceptable. It also is not required
- * that this be a valid pointer, although if this nanoapp is intended to
- * work on arbitrary CHRE implementations, then the size of a
- * pointer cannot be assumed to be a certain size. Note that the caller
- * no longer owns this memory after the call.
- * @param freeCallback A pointer to a callback function. After the lifetime
- * of 'eventData' is over (either through successful delivery or the event
- * being dropped), this callback will be invoked. This argument is allowed
- * to be NULL, in which case no callback will be invoked.
- * @param targetInstanceId The ID of the instance we're delivering this event
- * to. Note that this is allowed to be our own instance. The instance ID
- * of a nanoapp can be retrieved by using chreGetNanoappInfoByInstanceId().
- * @return true if the event was enqueued, false otherwise. Note that even
- * if this method returns 'false', the 'freeCallback' will be invoked,
- * if non-NULL. Note in the 'false' case, the 'freeCallback' may be
- * invoked directly from within chreSendEvent(), so it's necessary
- * for nanoapp authors to avoid possible recursion with this.
- *
- * @see chreEventDataFreeFunction
- */
-bool chreSendEvent(uint16_t eventType, void *eventData,
- chreEventCompleteFunction *freeCallback,
- uint32_t targetInstanceId);
-
-/**
- * Send a message to the host, using the broadcast endpoint
- * CHRE_HOST_ENDPOINT_BROADCAST. Refer to chreSendMessageToHostEndpoint() for
- * further details.
- *
- * @see chreSendMessageToHostEndpoint
- *
- * @deprecated New code should use chreSendMessageToHostEndpoint() instead of
- * this function. A future update to the API may cause references to this
- * function to produce a compiler warning.
- */
-bool chreSendMessageToHost(void *message, uint32_t messageSize,
- uint32_t messageType,
- chreMessageFreeFunction *freeCallback)
- CHRE_DEPRECATED("Use chreSendMessageToHostEndpoint instead");
-
-/**
- * Send a message to the host, waking it up if it is currently asleep.
- *
- * This message is by definition arbitrarily defined. Since we're not
- * just a passing a pointer to memory around the system, but need to copy
- * this into various buffers to send it to the host, the CHRE
- * implementation cannot be asked to support an arbitrarily large message
- * size. As a result, we have the CHRE implementation define
- * CHRE_MESSAGE_TO_HOST_MAX_SIZE.
- *
- * CHRE_MESSAGE_TO_HOST_MAX_SIZE is not given a value by the Platform API. The
- * Platform API does define CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE, and requires
- * that CHRE_MESSAGE_TO_HOST_MAX_SIZE is at least that value.
- *
- * As a result, if your message sizes are all less than
- * CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE, then you have no concerns on any
- * CHRE implementation. If your message sizes are larger, you'll need to
- * come up with a strategy for splitting your message across several calls
- * to this method. As long as that strategy works for
- * CHRE_MESSAGE_TO_HOST_MINIMUM_MAX_SIZE, it will work across all CHRE
- * implementations (although on some implementations less calls to this
- * method may be necessary).
- *
- * @param message Pointer to a block of memory to send to the host.
- * NULL is acceptable only if messageSize is 0. If non-NULL, this
- * must be a legitimate pointer (that is, unlike chreSendEvent(), a small
- * integral value cannot be cast to a pointer for this). Note that the
- * caller no longer owns this memory after the call.
- * @param messageSize The size, in bytes, of the given message.
- * This cannot exceed CHRE_MESSAGE_TO_HOST_MAX_SIZE.
- * @param messageType Message type sent to the app on the host.
- * NOTE: In CHRE API v1.0, support for forwarding this field to the host was
- * not strictly required, and some implementations did not support it.
- * However, its support is mandatory as of v1.1.
- * @param hostEndpoint An identifier for the intended recipient of the message,
- * or CHRE_HOST_ENDPOINT_BROADCAST if all registered endpoints on the host
- * should receive the message. Endpoint identifiers are assigned on the
- * host side, and nanoapps may learn of the host endpoint ID of an intended
- * recipient via an initial message sent by the host. This parameter is
- * always treated as CHRE_HOST_ENDPOINT_BROADCAST if running on a CHRE API
- * v1.0 implementation.
- * @param freeCallback A pointer to a callback function. After the lifetime
- * of 'message' is over (which does not assure that 'message' made it to
- * the host, just that the transport layer no longer needs this memory),
- * this callback will be invoked. This argument is allowed
- * to be NULL, in which case no callback will be invoked.
- * @return true if the message was accepted for transmission, false otherwise.
- * Note that even if this method returns 'false', the 'freeCallback' will
- * be invoked, if non-NULL. In either case, the 'freeCallback' may be
- * invoked directly from within chreSendMessageToHostEndpoint(), so it's
- * necessary for nanoapp authors to avoid possible recursion with this.
- *
- * @see chreMessageFreeFunction
- *
- * @since v1.1
- */
-bool chreSendMessageToHostEndpoint(void *message, size_t messageSize,
- uint32_t messageType, uint16_t hostEndpoint,
- chreMessageFreeFunction *freeCallback);
-
-/**
- * Queries for information about a nanoapp running in the system.
- *
- * In the current API, appId is required to be unique, i.e. there cannot be two
- * nanoapps running concurrently with the same appId. If this restriction is
- * removed in a future API version and multiple instances of the same appId are
- * present, this function must always return the first app to start.
- *
- * @param appId Identifier for the nanoapp that the caller is requesting
- * information about.
- * @param info Output parameter. If this function returns true, this structure
- * will be populated with details of the specified nanoapp.
- * @return true if a nanoapp with the given ID is currently running, and the
- * supplied info parameter was populated with its information.
- *
- * @since v1.1
- */
-bool chreGetNanoappInfoByAppId(uint64_t appId, struct chreNanoappInfo *info);
-
-/**
- * Queries for information about a nanoapp running in the system, using the
- * runtime unique identifier. This method can be used to get information about
- * the sender of an event.
- *
- * @param instanceId
- * @param info Output parameter. If this function returns true, this structure
- * will be populated with details of the specified nanoapp.
- * @return true if a nanoapp with the given instance ID is currently running,
- * and the supplied info parameter was populated with its information.
- *
- * @since v1.1
- */
-bool chreGetNanoappInfoByInstanceId(uint32_t instanceId,
- struct chreNanoappInfo *info);
-
-/**
- * Configures whether this nanoapp will be notified when other nanoapps in the
- * system start and stop, via CHRE_EVENT_NANOAPP_STARTED and
- * CHRE_EVENT_NANOAPP_STOPPED. These events are disabled by default, and if a
- * nanoapp is not interested in interacting with other nanoapps, then it does
- * not need to register for them. However, if inter-nanoapp communication is
- * desired, nanoapps are recommended to call this function from nanoappStart().
- *
- * If running on a CHRE platform that only supports v1.0 of the CHRE API, this
- * function has no effect.
- *
- * @param enable true to enable these events, false to disable
- *
- * @see CHRE_EVENT_NANOAPP_STARTED
- * @see CHRE_EVENT_NANOAPP_STOPPED
- *
- * @since v1.1
- */
-void chreConfigureNanoappInfoEvents(bool enable);
-
-/**
- * Configures whether this nanoapp will be notified when the host (applications
- * processor) transitions between wake and sleep, via CHRE_EVENT_HOST_AWAKE and
- * CHRE_EVENT_HOST_ASLEEP. As chreSendMessageToHostEndpoint() wakes the host if
- * it is asleep, these events can be used to opportunistically send data to the
- * host only when it wakes up for some other reason. Note that this event is
- * not instantaneous - there is an inherent delay in CHRE observing power state
- * changes of the host processor, which may be significant depending on the
- * implementation, especially in the wake to sleep direction. Therefore,
- * nanoapps are not guaranteed that messages sent to the host between AWAKE and
- * ASLEEP events will not trigger a host wakeup. However, implementations must
- * ensure that the nominal wake-up notification latency is strictly less than
- * the minimum wake-sleep time of the host processor. Implementations are also
- * encouraged to minimize this and related latencies where possible, to avoid
- * unnecessary host wake-ups.
- *
- * These events are only sent on transitions, so the initial state will not be
- * sent to the nanoapp as an event - use chreIsHostAwake().
- *
- * @param enable true to enable these events, false to disable
- *
- * @see CHRE_EVENT_HOST_AWAKE
- * @see CHRE_EVENT_HOST_ASLEEP
- *
- * @since v1.2
- */
-void chreConfigureHostSleepStateEvents(bool enable);
-
-/**
- * Retrieves the current sleep/wake state of the host (applications processor).
- * Note that, as with the CHRE_EVENT_HOST_AWAKE and CHRE_EVENT_HOST_ASLEEP
- * events, there is no guarantee that CHRE's view of the host processor's sleep
- * state is instantaneous, and it may also change between querying the state and
- * performing a host-waking action like sending a message to the host.
- *
- * @return true if by CHRE's own estimation the host is currently awake,
- * false otherwise
- *
- * @since v1.2
- */
-bool chreIsHostAwake(void);
-
-/**
- * Configures whether this nanoapp will be notified when CHRE is collecting
- * debug dumps, via CHRE_EVENT_DEBUG_DUMP. This event is disabled by default,
- * and if a nanoapp is not interested in logging its debug data, then it does
- * not need to register for it.
- *
- * @param enable true to enable receipt of this event, false to disable.
- *
- * @see CHRE_EVENT_DEBUG_DUMP
- * @see chreDebugDumpLog
- *
- * @since v1.4
- */
-void chreConfigureDebugDumpEvent(bool enable);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_EVENT_H_ */
-
diff --git a/chre_api/legacy/v1_4/chre/gnss.h b/chre_api/legacy/v1_4/chre/gnss.h
deleted file mode 100644
index 368f54d2..00000000
--- a/chre_api/legacy/v1_4/chre/gnss.h
+++ /dev/null
@@ -1,562 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_GNSS_H_
-#define _CHRE_GNSS_H_
-
-/**
- * @file
- * Global Navigation Satellite System (GNSS) API.
- *
- * These structures and definitions are based on the Android N GPS HAL.
- * Refer to that header file (located at this path as of the time of this
- * comment: hardware/libhardware/include/hardware/gps.h) and associated
- * documentation for further details and explanations for these fields.
- * References in comments like "(ref: GnssAccumulatedDeltaRangeState)" map to
- * the relevant element in the GPS HAL where additional information can be
- * found.
- *
- * In general, the parts of this API that are taken from the GPS HAL follow the
- * naming conventions established in that interface rather than the CHRE API
- * conventions, in order to avoid confusion and enable code re-use where
- * applicable.
- */
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include <chre/common.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * The set of flags that may be returned by chreGnssGetCapabilities()
- * @defgroup CHRE_GNSS_CAPABILITIES
- * @{
- */
-
-//! A lack of flags indicates that GNSS is not supported in this CHRE
-#define CHRE_GNSS_CAPABILITIES_NONE UINT32_C(0)
-
-//! GNSS position fixes are supported via chreGnssLocationSessionStartAsync()
-#define CHRE_GNSS_CAPABILITIES_LOCATION UINT32_C(1 << 0)
-
-//! GNSS raw measurements are supported via
-//! chreGnssMeasurementSessionStartAsync()
-#define CHRE_GNSS_CAPABILITIES_MEASUREMENTS UINT32_C(1 << 1)
-
-//! Location fixes supplied from chreGnssConfigurePassiveLocationListener()
-//! are tapped in at the GNSS engine level, so they include additional fixes
-//! such as those requested by the AP, and not just those requested by other
-//! nanoapps within CHRE (which is the case when this flag is not set)
-#define CHRE_GNSS_CAPABILITIES_GNSS_ENGINE_BASED_PASSIVE_LISTENER \
- UINT32_C(1 << 2)
-
-/** @} */
-
-/**
- * The current version of struct chreGnssDataEvent associated with this API
- */
-#define CHRE_GNSS_DATA_EVENT_VERSION UINT8_C(0)
-
-/**
- * The maximum time the CHRE implementation is allowed to elapse before sending
- * an event with the result of an asynchronous request, unless specified
- * otherwise
- */
-#define CHRE_GNSS_ASYNC_RESULT_TIMEOUT_NS (5 * CHRE_NSEC_PER_SEC)
-
-/**
- * Produce an event ID in the block of IDs reserved for GNSS
- * @param offset Index into GNSS event ID block; valid range [0,15]
- */
-#define CHRE_GNSS_EVENT_ID(offset) (CHRE_EVENT_GNSS_FIRST_EVENT + (offset))
-
-/**
- * nanoappHandleEvent argument: struct chreAsyncResult
- *
- * Communicates the asynchronous result of a request to the GNSS API, such as
- * starting a location session via chreGnssLocationSessionStartAsync(). The
- * requestType field in chreAsyncResult is set to a value from enum
- * chreGnssRequestType.
- */
-#define CHRE_EVENT_GNSS_ASYNC_RESULT CHRE_GNSS_EVENT_ID(0)
-
-/**
- * nanoappHandleEvent argument: struct chreGnssLocationEvent
- *
- * Represents a location fix provided by the GNSS subsystem.
- */
-#define CHRE_EVENT_GNSS_LOCATION CHRE_GNSS_EVENT_ID(1)
-
-/**
- * nanoappHandleEvent argument: struct chreGnssDataEvent
- *
- * Represents a set of GNSS measurements with associated clock data.
- */
-#define CHRE_EVENT_GNSS_DATA CHRE_GNSS_EVENT_ID(2)
-
-// NOTE: Do not add new events with ID > 15; only values 0-15 are reserved
-// (see chre/event.h)
-
-// Flags indicating the Accumulated Delta Range's states
-// (ref: GnssAccumulatedDeltaRangeState)
-#define CHRE_GNSS_ADR_STATE_UNKNOWN UINT16_C(0)
-#define CHRE_GNSS_ADR_STATE_VALID UINT16_C(1 << 0)
-#define CHRE_GNSS_ADR_STATE_RESET UINT16_C(1 << 1)
-#define CHRE_GNSS_ADR_STATE_CYCLE_SLIP UINT16_C(1 << 2)
-
-// Flags to indicate what fields in chreGnssClock are valid (ref: GnssClockFlags)
-#define CHRE_GNSS_CLOCK_HAS_LEAP_SECOND UINT16_C(1 << 0)
-#define CHRE_GNSS_CLOCK_HAS_TIME_UNCERTAINTY UINT16_C(1 << 1)
-#define CHRE_GNSS_CLOCK_HAS_FULL_BIAS UINT16_C(1 << 2)
-#define CHRE_GNSS_CLOCK_HAS_BIAS UINT16_C(1 << 3)
-#define CHRE_GNSS_CLOCK_HAS_BIAS_UNCERTAINTY UINT16_C(1 << 4)
-#define CHRE_GNSS_CLOCK_HAS_DRIFT UINT16_C(1 << 5)
-#define CHRE_GNSS_CLOCK_HAS_DRIFT_UNCERTAINTY UINT16_C(1 << 6)
-
-// Flags to indicate which values are valid in a GpsLocation
-// (ref: GpsLocationFlags)
-#define CHRE_GPS_LOCATION_HAS_LAT_LONG UINT16_C(1 << 0)
-#define CHRE_GPS_LOCATION_HAS_ALTITUDE UINT16_C(1 << 1)
-#define CHRE_GPS_LOCATION_HAS_SPEED UINT16_C(1 << 2)
-#define CHRE_GPS_LOCATION_HAS_BEARING UINT16_C(1 << 3)
-#define CHRE_GPS_LOCATION_HAS_ACCURACY UINT16_C(1 << 4)
-
-//! @since v1.3
-#define CHRE_GPS_LOCATION_HAS_ALTITUDE_ACCURACY UINT16_C(1 << 5)
-//! @since v1.3
-#define CHRE_GPS_LOCATION_HAS_SPEED_ACCURACY UINT16_C(1 << 6)
-//! @since v1.3
-#define CHRE_GPS_LOCATION_HAS_BEARING_ACCURACY UINT16_C(1 << 7)
-
-/**
- * The maximum number of instances of struct chreGnssMeasurement that may be
- * included in a single struct chreGnssDataEvent.
- */
-#define CHRE_GNSS_MAX_MEASUREMENT UINT8_C(64)
-
-// Flags indicating the GNSS measurement state (ref: GnssMeasurementState)
-#define CHRE_GNSS_MEASUREMENT_STATE_UNKNOWN UINT16_C(0)
-#define CHRE_GNSS_MEASUREMENT_STATE_CODE_LOCK UINT16_C(1 << 0)
-#define CHRE_GNSS_MEASUREMENT_STATE_BIT_SYNC UINT16_C(1 << 1)
-#define CHRE_GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC UINT16_C(1 << 2)
-#define CHRE_GNSS_MEASUREMENT_STATE_TOW_DECODED UINT16_C(1 << 3)
-#define CHRE_GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS UINT16_C(1 << 4)
-#define CHRE_GNSS_MEASUREMENT_STATE_SYMBOL_SYNC UINT16_C(1 << 5)
-#define CHRE_GNSS_MEASUREMENT_STATE_GLO_STRING_SYNC UINT16_C(1 << 6)
-#define CHRE_GNSS_MEASUREMENT_STATE_GLO_TOD_DECODED UINT16_C(1 << 7)
-#define CHRE_GNSS_MEASUREMENT_STATE_BDS_D2_BIT_SYNC UINT16_C(1 << 8)
-#define CHRE_GNSS_MEASUREMENT_STATE_BDS_D2_SUBFRAME_SYNC UINT16_C(1 << 9)
-#define CHRE_GNSS_MEASUREMENT_STATE_GAL_E1BC_CODE_LOCK UINT16_C(1 << 10)
-#define CHRE_GNSS_MEASUREMENT_STATE_GAL_E1C_2ND_CODE_LOCK UINT16_C(1 << 11)
-#define CHRE_GNSS_MEASUREMENT_STATE_GAL_E1B_PAGE_SYNC UINT16_C(1 << 12)
-#define CHRE_GNSS_MEASUREMENT_STATE_SBAS_SYNC UINT16_C(1 << 13)
-
-#define CHRE_GNSS_MEASUREMENT_CARRIER_FREQUENCY_UNKNOWN 0.f
-
-/**
- * Indicates a type of request made in this API. Used to populate the resultType
- * field of struct chreAsyncResult sent with CHRE_EVENT_GNSS_ASYNC_RESULT.
- */
-enum chreGnssRequestType {
- CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_START = 1,
- CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_STOP = 2,
- CHRE_GNSS_REQUEST_TYPE_MEASUREMENT_SESSION_START = 3,
- CHRE_GNSS_REQUEST_TYPE_MEASUREMENT_SESSION_STOP = 4,
-};
-
-/**
- * Constellation type associated with an SV
- */
-enum chreGnssConstellationType {
- CHRE_GNSS_CONSTELLATION_UNKNOWN = 0,
- CHRE_GNSS_CONSTELLATION_GPS = 1,
- CHRE_GNSS_CONSTELLATION_SBAS = 2,
- CHRE_GNSS_CONSTELLATION_GLONASS = 3,
- CHRE_GNSS_CONSTELLATION_QZSS = 4,
- CHRE_GNSS_CONSTELLATION_BEIDOU = 5,
- CHRE_GNSS_CONSTELLATION_GALILEO = 6,
-};
-
-/**
- * Enumeration of available values for the chreGnssMeasurement multipath indicator
- */
-enum chreGnssMultipathIndicator {
- //! The indicator is not available or unknown
- CHRE_GNSS_MULTIPATH_INDICATOR_UNKNOWN = 0,
- //! The measurement is indicated to be affected by multipath
- CHRE_GNSS_MULTIPATH_INDICATOR_PRESENT = 1,
- //! The measurement is indicated to be not affected by multipath
- CHRE_GNSS_MULTIPATH_INDICATOR_NOT_PRESENT = 2,
-};
-
-/**
- * Represents an estimate of the GNSS clock time (see the Android GPS HAL for
- * more detailed information)
- */
-struct chreGnssClock {
- //! The GNSS receiver hardware clock value in nanoseconds, including
- //! uncertainty
- int64_t time_ns;
-
- //! The difference between hardware clock inside GNSS receiver and the
- //! estimated GNSS time in nanoseconds; contains bias uncertainty
- int64_t full_bias_ns;
-
- //! Sub-nanosecond bias, adds to full_bias_ns
- float bias_ns;
-
- //! The clock's drift in nanoseconds per second
- float drift_nsps;
-
- //! 1-sigma uncertainty associated with the clock's bias in nanoseconds
- float bias_uncertainty_ns;
-
- //! 1-sigma uncertainty associated with the clock's drift in nanoseconds
- //! per second
- float drift_uncertainty_nsps;
-
- //! While this number stays the same, timeNs should flow continuously
- uint32_t hw_clock_discontinuity_count;
-
- //! A set of flags indicating the validity of the fields in this data
- //! structure (see GNSS_CLOCK_HAS_*)
- uint16_t flags;
-
- //! Reserved for future use; set to 0
- uint8_t reserved[2];
-};
-
-/**
- * Represents a GNSS measurement; contains raw and computed information (see the
- * Android GPS HAL for more detailed information)
- */
-struct chreGnssMeasurement {
- //! Hardware time offset from time_ns for this measurement, in nanoseconds
- int64_t time_offset_ns;
-
- //! Accumulated delta range since the last channel reset in micro-meters
- int64_t accumulated_delta_range_um;
-
- //! Received GNSS satellite time at the time of measurement, in nanoseconds
- int64_t received_sv_time_in_ns;
-
- //! 1-sigma uncertainty of received GNSS satellite time, in nanoseconds
- int64_t received_sv_time_uncertainty_in_ns;
-
- //! Pseudorange rate at the timestamp in meters per second (uncorrected)
- float pseudorange_rate_mps;
-
- //! 1-sigma uncertainty of pseudorange rate in meters per second
- float pseudorange_rate_uncertainty_mps;
-
- //! 1-sigma uncertainty of the accumulated delta range in meters
- float accumulated_delta_range_uncertainty_m;
-
- //! Carrier-to-noise density in dB-Hz, in the range of [0, 63]
- float c_n0_dbhz;
-
- //! Signal to noise ratio (dB), power above observed noise at correlators
- float snr_db;
-
- //! Satellite sync state flags (GNSS_MEASUREMENT_STATE_*) - sets modulus for
- //! received_sv_time_in_ns
- uint16_t state;
-
- //! Set of ADR state flags (GNSS_ADR_STATE_*)
- uint16_t accumulated_delta_range_state;
-
- //! Satellite vehicle ID number
- int16_t svid;
-
- //! Constellation of the given satellite vehicle
- //! @see #chreGnssConstellationType
- uint8_t constellation;
-
- //! @see #chreGnssMultipathIndicator
- uint8_t multipath_indicator;
-
- //! Carrier frequency of the signal tracked in Hz.
- //! For example, it can be the GPS central frequency for L1 = 1575.45 MHz,
- //! or L2 = 1227.60 MHz, L5 = 1176.45 MHz, various GLO channels, etc.
- //!
- //! Set to CHRE_GNSS_MEASUREMENT_CARRIER_FREQUENCY_UNKNOWN if not reported.
- //!
- //! For an L1, L5 receiver tracking a satellite on L1 and L5 at the same
- //! time, two chreGnssMeasurement structs must be reported for this same
- //! satellite, in one of the measurement structs, all the values related to
- //! L1 must be filled, and in the other all of the values related to L5
- //! must be filled.
- //! @since v1.4
- float carrier_frequency_hz;
-};
-
-/**
- * Data structure sent with events associated with CHRE_EVENT_GNSS_DATA, enabled
- * via chreGnssMeasurementSessionStartAsync()
- */
-struct chreGnssDataEvent {
- //! Indicates the version of the structure, for compatibility purposes.
- //! Clients do not normally need to worry about this field; the CHRE
- //! implementation guarantees that it only sends the client the structure
- //! version it expects.
- uint8_t version;
-
- //! Number of chreGnssMeasurement entries included in this event. Must be in
- //! the range [0, CHRE_GNSS_MAX_MEASUREMENT]
- uint8_t measurement_count;
-
- //! Reserved for future use; set to 0
- uint8_t reserved[6];
-
- struct chreGnssClock clock;
-
- //! Pointer to an array containing measurement_count measurements
- const struct chreGnssMeasurement *measurements;
-};
-
-/**
- * Data structure sent with events of type CHRE_EVENT_GNSS_LOCATION, enabled via
- * chreGnssLocationSessionStartAsync(). This is modeled after GpsLocation in the
- * GPS HAL, but does not use the double data type.
- */
-struct chreGnssLocationEvent {
- //! UTC timestamp for location fix in milliseconds since January 1, 1970
- uint64_t timestamp;
-
- //! Fixed point latitude, degrees times 10^7 (roughly centimeter resolution)
- int32_t latitude_deg_e7;
-
- //! Fixed point longitude, degrees times 10^7 (roughly centimeter
- //! resolution)
- int32_t longitude_deg_e7;
-
- //! Altitude in meters above the WGS 84 reference ellipsoid
- float altitude;
-
- //! Horizontal speed in meters per second
- float speed;
-
- //! Clockwise angle between north and current heading, in degrees; range
- //! [0, 360)
- float bearing;
-
- //! Expected horizontal accuracy in meters such that a circle with a radius
- //! of length 'accuracy' from the latitude and longitude has a 68%
- //! probability of including the true location.
- float accuracy;
-
- //! A set of flags indicating which fields in this structure are valid.
- //! If any fields are not available, the flag must not be set and the field
- //! must be initialized to 0.
- //! @see #GpsLocationFlags
- uint16_t flags;
-
- //! Reserved for future use; set to 0
- //! @since v1.3
- uint8_t reserved[2];
-
- //! Expected vertical accuracy in meters such that a range of
- //! 2 * altitude_accuracy centered around altitude has a 68% probability of
- //! including the true altitude.
- //! @since v1.3
- float altitude_accuracy;
-
- //! Expected speed accuracy in meters per second such that a range of
- //! 2 * speed_accuracy centered around speed has a 68% probability of
- //! including the true speed.
- //! @since v1.3
- float speed_accuracy;
-
- //! Expected bearing accuracy in degrees such that a range of
- //! 2 * bearing_accuracy centered around bearing has a 68% probability of
- //! including the true bearing.
- //! @since v1.3
- float bearing_accuracy;
-};
-
-
-/**
- * Retrieves a set of flags indicating the GNSS features supported by the
- * current CHRE implementation. The value returned by this function must be
- * consistent for the entire duration of the Nanoapp's execution.
- *
- * The client must allow for more flags to be set in this response than it knows
- * about, for example if the implementation supports a newer version of the API
- * than the client was compiled against.
- *
- * @return A bitmask with zero or more CHRE_GNSS_CAPABILITIES_* flags set
- *
- * @since v1.1
- */
-uint32_t chreGnssGetCapabilities(void);
-
-/**
- * Initiates a GNSS positioning session, or changes the requested interval of an
- * existing session. If starting or modifying the session was successful, then
- * the GNSS engine will work on determining the device's position.
- *
- * This result of this request is delivered asynchronously via an event of type
- * CHRE_EVENT_GNSS_ASYNC_RESULT. Refer to the note in {@link #chreAsyncResult}
- * for more details. If the "Location" setting is disabled at the Android level,
- * the CHRE implementation is expected to return a result with
- * CHRE_ERROR_FUNCTION_DISABLED.
- *
- * If chreGnssGetCapabilities() returns a value that does not have the
- * CHRE_GNSS_CAPABILITIES_LOCATION flag set, then this method will return false.
- *
- * @param minIntervalMs The desired minimum interval between location fixes
- * delivered to the client via CHRE_EVENT_GNSS_LOCATION, in milliseconds.
- * The requesting client must allow for fixes to be delivered at shorter
- * or longer interval than requested. For example, adverse RF conditions
- * may result in fixes arriving at a longer interval, etc.
- * @param minTimeToNextFixMs The desired minimum time to the next location fix.
- * If this is 0, the GNSS engine should start working on the next fix
- * immediately. If greater than 0, the GNSS engine should not spend
- * measurable power to produce a location fix until this amount of time
- * has elapsed.
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.1
- */
-bool chreGnssLocationSessionStartAsync(uint32_t minIntervalMs,
- uint32_t minTimeToNextFixMs,
- const void *cookie);
-
-/**
- * Terminates an existing GNSS positioning session. If no positioning session
- * is active at the time of this request, it is treated as if an active session
- * was successfully ended.
- *
- * This result of this request is delivered asynchronously via an event of type
- * CHRE_EVENT_GNSS_ASYNC_RESULT. Refer to the note in {@link #chreAsyncResult}
- * for more details.
- *
- * After CHRE_EVENT_GNSS_ASYNC_RESULT is delivered to the client, no more
- * CHRE_EVENT_GNSS_LOCATION events will be delievered until a new location
- * session is started.
- *
- * If chreGnssGetCapabilities() returns a value that does not have the
- * CHRE_GNSS_CAPABILITIES_LOCATION flag set, then this method will return false.
- *
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.1
- */
-bool chreGnssLocationSessionStopAsync(const void *cookie);
-
-/**
- * Initiates a request to receive raw GNSS measurements. A GNSS measurement
- * session can exist independently of location sessions. In other words, a
- * Nanoapp is able to receive measurements at its requested interval both with
- * and without an active location session.
- *
- * This result of this request is delivered asynchronously via an event of type
- * CHRE_EVENT_GNSS_ASYNC_RESULT. Refer to the note in {@link #chreAsyncResult}
- * for more details. If the "Location" setting is disabled at the Android level,
- * the CHRE implementation is expected to return a result with
- * CHRE_ERROR_FUNCTION_DISABLED.
- *
- * If chreGnssGetCapabilities() returns a value that does not have the
- * CHRE_GNSS_CAPABILITIES_MEASUREMENTS flag set, then this method will return
- * false.
- *
- * @param minIntervalMs The desired minimum interval between measurement reports
- * delivered via CHRE_EVENT_GNSS_DATA. When requested at 1000ms or
- * faster, and GNSS measurements are tracked, device should report
- * measurements as fast as requested, and shall report no slower than
- * once every 1000ms, on average.
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.1
- */
-bool chreGnssMeasurementSessionStartAsync(uint32_t minIntervalMs,
- const void *cookie);
-
-/**
- * Terminates an existing raw GNSS measurement session. If no measurement
- * session is active at the time of this request, it is treated as if an active
- * session was successfully ended.
- *
- * This result of this request is delivered asynchronously via an event of type
- * CHRE_EVENT_GNSS_ASYNC_RESULT. Refer to the note in {@link #chreAsyncResult}
- * for more details.
- *
- * If chreGnssGetCapabilities() returns a value that does not have the
- * CHRE_GNSS_CAPABILITIES_MEASUREMENTS flag set, then this method will return
- * false.
- *
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.1
- */
-bool chreGnssMeasurementSessionStopAsync(const void *cookie);
-
-/**
- * Controls whether this nanoapp will passively receive GNSS-based location
- * fixes produced as a result of location sessions initiated by other entities.
- * This function allows a nanoapp to opportunistically receive location fixes
- * via CHRE_EVENT_GNSS_LOCATION events without imposing additional power cost,
- * though with no guarantees as to when or how often those events will arrive.
- * There will be no duplication of events if a passive location listener and
- * location session are enabled in parallel.
- *
- * Enabling passive location listening is not required to receive events for an
- * active location session started via chreGnssLocationSessionStartAsync(). This
- * setting is independent of the active location session, so modifying one does
- * not have an effect on the other.
- *
- * If chreGnssGetCapabilities() returns a value that does not have the
- * CHRE_GNSS_CAPABILITIES_LOCATION flag set or the value returned by
- * chreGetApiVersion() is less than CHRE_API_VERSION_1_2, then this method will
- * return false.
- *
- * If chreGnssGetCapabilities() includes
- * CHRE_GNSS_CAPABILITIES_GNSS_ENGINE_BASED_PASSIVE_LISTENER, the passive
- * registration is recorded at the GNSS engine level, so events include fixes
- * requested by the applications processor and potentially other non-CHRE
- * clients. If this flag is not set, then only fixes requested by other nanoapps
- * within CHRE are provided.
- *
- * @param enable true to receive opportunistic location fixes, false to disable
- *
- * @return true if the configuration was processed successfully, false on error
- * or if this feature is not supported
- *
- * @since v1.2
- */
-bool chreGnssConfigurePassiveLocationListener(bool enable);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_GNSS_H_ */
diff --git a/chre_api/legacy/v1_4/chre/nanoapp.h b/chre_api/legacy/v1_4/chre/nanoapp.h
deleted file mode 100644
index da199ee0..00000000
--- a/chre_api/legacy/v1_4/chre/nanoapp.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_NANOAPP_H_
-#define _CHRE_NANOAPP_H_
-
-/**
- * @file
- * Methods in the Context Hub Runtime Environment which must be implemented
- * by the nanoapp.
- */
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Method invoked by the CHRE when loading the nanoapp.
- *
- * Every CHRE method is legal to call from this method.
- *
- * @return 'true' if the nanoapp successfully started. 'false' if the nanoapp
- * failed to properly initialize itself (for example, could not obtain
- * sufficient memory from the heap). If this method returns 'false', the
- * nanoapp will be unloaded by the CHRE (and nanoappEnd will
- * _not_ be invoked in that case).
- * @see nanoappEnd
- */
-bool nanoappStart(void);
-
-/**
- * Method invoked by the CHRE when there is an event for this nanoapp.
- *
- * Every CHRE method is legal to call from this method.
- *
- * @param senderInstanceId The Instance ID for the source of this event.
- * Note that this may be CHRE_INSTANCE_ID, indicating that the event
- * was generated by the CHRE.
- * @param eventType The event type. This might be one of the CHRE_EVENT_*
- * types defined in this API. But it might also be a user-defined event.
- * @param eventData The associated data, if any, for this specific type of
- * event. From the nanoapp's perspective, this eventData's lifetime ends
- * when this method returns, and thus any data the nanoapp wishes to
- * retain must be copied. Note that interpretation of event data is
- * given by the event type, and for some events may not be a valid
- * pointer. See documentation of the specific CHRE_EVENT_* types for how to
- * interpret this data for those. Note that for user events, you will
- * need to establish what this data means.
- */
-void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
- const void *eventData);
-
-/**
- * Method invoked by the CHRE when unloading the nanoapp.
- *
- * It is not valid to attempt to send events or messages, or to invoke functions
- * which will generate events to this app, within the nanoapp implementation of
- * this function. That means it is illegal for the nanoapp invoke any of the
- * following:
- *
- * - chreSendEvent()
- * - chreSendMessageToHost()
- * - chreSensorConfigure()
- * - chreSensorConfigureModeOnly()
- * - chreTimerSet()
- * - etc.
- *
- * @see nanoappStart
- */
-void nanoappEnd(void);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_NANOAPP_H_ */
diff --git a/chre_api/legacy/v1_4/chre/re.h b/chre_api/legacy/v1_4/chre/re.h
deleted file mode 100644
index 20a69b66..00000000
--- a/chre_api/legacy/v1_4/chre/re.h
+++ /dev/null
@@ -1,437 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_RE_H_
-#define _CHRE_RE_H_
-
-/**
- * @file
- * Some of the core Runtime Environment utilities of the Context Hub
- * Runtime Environment.
- *
- * This includes functions for memory allocation, logging, and timers.
- */
-
-#include <stdarg.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-#include <chre/toolchain.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * The instance ID for the CHRE.
- *
- * This ID is used to identify events generated by the CHRE (as
- * opposed to events generated by another nanoapp).
- */
-#define CHRE_INSTANCE_ID UINT32_C(0)
-
-/**
- * A timer ID representing an invalid timer.
- *
- * This valid is returned by chreTimerSet() if a timer cannot be
- * started.
- */
-#define CHRE_TIMER_INVALID UINT32_C(-1)
-
-
-/**
- * The maximum size, in characters including null terminator, guaranteed for
- * logging debug data with one call of chreDebugDumpLog() without getting
- * truncated.
- *
- * @see chreDebugDumpLog
- * @since v1.4
- */
-#define CHRE_DEBUG_DUMP_MINIMUM_MAX_SIZE 1000
-
-/**
- * Logging levels used to indicate severity level of logging messages.
- *
- * CHRE_LOG_ERROR: Something fatal has happened, i.e. something that will have
- * user-visible consequences and won't be recoverable without explicitly
- * deleting some data, uninstalling applications, wiping the data
- * partitions or reflashing the entire phone (or worse).
- * CHRE_LOG_WARN: Something that will have user-visible consequences but is
- * likely to be recoverable without data loss by performing some explicit
- * action, ranging from waiting or restarting an app all the way to
- * re-downloading a new version of an application or rebooting the device.
- * CHRE_LOG_INFO: Something interesting to most people happened, i.e. when a
- * situation is detected that is likely to have widespread impact, though
- * isn't necessarily an error.
- * CHRE_LOG_DEBUG: Used to further note what is happening on the device that
- * could be relevant to investigate and debug unexpected behaviors. You
- * should log only what is needed to gather enough information about what
- * is going on about your component.
- *
- * There is currently no API to turn on/off logging by level, but we anticipate
- * adding such in future releases.
- *
- * @see chreLog
- */
-enum chreLogLevel {
- CHRE_LOG_ERROR,
- CHRE_LOG_WARN,
- CHRE_LOG_INFO,
- CHRE_LOG_DEBUG
-};
-
-
-/**
- * Get the application ID.
- *
- * The application ID is set by the loader of the nanoapp. This is not
- * assured to be unique among all nanoapps running in the system.
- *
- * @return The application ID.
- */
-uint64_t chreGetAppId(void);
-
-/**
- * Get the instance ID.
- *
- * The instance ID is the CHRE handle to this nanoapp. This is assured
- * to be unique among all nanoapps running in the system, and to be
- * different from the CHRE_INSTANCE_ID. This is the ID used to communicate
- * between nanoapps.
- *
- * @return The instance ID
- */
-uint32_t chreGetInstanceId(void);
-
-/**
- * A method for logging information about the system.
- *
- * The chreLog logging activity alone must not cause host wake-ups. For
- * example, logs could be buffered in internal memory when the host is asleep,
- * and delivered when appropriate (e.g. the host wakes up). If done this way,
- * the internal buffer is recommended to be large enough (at least a few KB), so
- * that multiple messages can be buffered. When these logs are sent to the host,
- * they are strongly recommended to be made visible under the tag 'CHRE' in
- * logcat - a future version of the CHRE API may make this a hard requirement.
- *
- * A log entry can have a variety of levels (@see LogLevel). This function
- * allows a variable number of arguments, in a printf-style format.
- *
- * A nanoapp needs to be able to rely upon consistent printf format
- * recognition across any platform, and thus we establish formats which
- * are required to be handled by every CHRE implementation. Some of the
- * integral formats may seem obscure, but this API heavily uses types like
- * uint32_t and uint16_t. The platform independent macros for those printf
- * formats, like PRId32 or PRIx16, end up using some of these "obscure"
- * formats on some platforms, and thus are required.
- *
- * For the initial N release, our emphasis is on correctly getting information
- * into the log, and minimizing the requirements for CHRE implementations
- * beyond that. We're not as concerned about how the information is visually
- * displayed. As a result, there are a number of format sub-specifiers which
- * are "OPTIONAL" for the N implementation. "OPTIONAL" in this context means
- * that a CHRE implementation is allowed to essentially ignore the specifier,
- * but it must understand the specifier enough in order to properly skip it.
- *
- * For a nanoapp author, an OPTIONAL format means you might not get exactly
- * what you want on every CHRE implementation, but you will always get
- * something valid.
- *
- * To be clearer, here's an example with the OPTIONAL 0-padding for integers
- * for different hypothetical CHRE implementations.
- * Compliant, chose to implement OPTIONAL format:
- * chreLog(level, "%04x", 20) ==> "0014"
- * Compliant, chose not to implement OPTIONAL format:
- * chreLog(level, "%04x", 20) ==> "14"
- * Non-compliant, discarded format because the '0' was assumed to be incorrect:
- * chreLog(level, "%04x", 20) ==> ""
- *
- * Note that some of the OPTIONAL specifiers will probably become
- * required in future APIs.
- *
- * We also have NOT_SUPPORTED specifiers. Nanoapp authors should not use any
- * NOT_SUPPORTED specifiers, as unexpected things could happen on any given
- * CHRE implementation. A CHRE implementation is allowed to support this
- * (for example, when using shared code which already supports this), but
- * nanoapp authors need to avoid these.
- *
- * Unless specifically noted as OPTIONAL or NOT_SUPPORTED, format
- * (sub-)specifiers listed below are required.
- *
- * OPTIONAL format sub-specifiers:
- * - '-' (left-justify within the given field width)
- * - '+' (precede the result with a '+' sign if it is positive)
- * - ' ' (precede the result with a blank space if no sign is going to be
- * output)
- * - '#' (For 'o', 'x' or 'X', precede output with "0", "0x" or "0X",
- * respectively. For floating point, unconditionally output a decimal
- * point.)
- * - '0' (left pad the number with zeroes instead of spaces when <width>
- * needs padding)
- * - <width> (A number representing the minimum number of characters to be
- * output, left-padding with blank spaces if needed to meet the
- * minimum)
- * - '.'<precision> (A number which has different meaning depending on context.)
- * - Integer context: Minimum number of digits to output, padding with
- * leading zeros if needed to meet the minimum.
- * - 'f' context: Number of digits to output after the decimal
- * point (to the right of it).
- * - 's' context: Maximum number of characters to output.
- *
- * Integral format specifiers:
- * - 'd' (signed)
- * - 'u' (unsigned)
- * - 'o' (octal)
- * - 'x' (hexadecimal, lower case)
- * - 'X' (hexadecimal, upper case)
- *
- * Integral format sub-specifiers (as prefixes to an above integral format):
- * - 'hh' (char)
- * - 'h' (short)
- * - 'l' (long)
- * - 'll' (long long)
- * - 'z' (size_t)
- * - 't' (ptrdiff_t)
- *
- * Other format specifiers:
- * - 'f' (floating point)
- * - 'c' (character)
- * - 's' (character string, terminated by '\0')
- * - 'p' (pointer)
- * - '%' (escaping the percent sign (i.e. "%%" becomes "%"))
- *
- * NOT_SUPPORTED specifiers:
- * - 'n' (output nothing, but fill in a given pointer with the number
- * of characters written so far)
- * - '*' (indicates that the width/precision value comes from one of the
- * arguments to the function)
- * - 'e', 'E' (scientific notation output)
- * - 'g', 'G' (Shortest floating point representation)
- *
- * @param level The severity level for this message.
- * @param formatStr Either the entirety of the message, or a printf-style
- * format string of the format documented above.
- * @param ... A variable number of arguments necessary for the given
- * 'formatStr' (there may be no additional arguments for some 'formatStr's).
- */
-CHRE_PRINTF_ATTR(2, 3)
-void chreLog(enum chreLogLevel level, const char *formatStr, ...);
-
-/**
- * Get the system time.
- *
- * This returns a time in nanoseconds in reference to some arbitrary
- * time in the past. This method is only useful for determining timing
- * between events on the system, and is not useful for determining
- * any sort of absolute time.
- *
- * This value must always increase (and must never roll over). This
- * value has no meaning across CHRE reboots.
- *
- * @return The system time, in nanoseconds.
- */
-uint64_t chreGetTime(void);
-
-/**
- * Retrieves CHRE's current estimated offset between the local CHRE clock
- * exposed in chreGetTime(), and the host-side clock exposed in the Android API
- * SystemClock.elapsedRealtimeNanos(). This offset is formed as host time minus
- * CHRE time, so that it can be added to the value returned by chreGetTime() to
- * determine the current estimate of the host time.
- *
- * A call to this function must not require waking up the host and should return
- * quickly.
- *
- * This function must always return a valid value from the earliest point that
- * it can be called by a nanoapp. In other words, it is not valid to return
- * some fixed/invalid value while waiting for the initial offset estimate to be
- * determined - this initial offset must be ready before nanoapps are started.
- *
- * @return An estimate of the offset between CHRE's time returned in
- * chreGetTime() and the time on the host given in the Android API
- * SystemClock.elapsedRealtimeNanos(), accurate to within +/- 10
- * milliseconds, such that adding this offset to chreGetTime() produces the
- * estimated current time on the host. This value may change over time to
- * account for drift, etc., so multiple calls to this API may produce
- * different results.
- *
- * @since v1.1
- */
-int64_t chreGetEstimatedHostTimeOffset(void);
-
-/**
- * Convenience function to retrieve CHRE's estimate of the current time on the
- * host, corresponding to the Android API SystemClock.elapsedRealtimeNanos().
- *
- * @return An estimate of the current time on the host, accurate to within
- * +/- 10 milliseconds. This estimate is *not* guaranteed to be
- * monotonically increasing, and may move backwards as a result of receiving
- * new information from the host.
- *
- * @since v1.1
- */
-static inline uint64_t chreGetEstimatedHostTime(void) {
- int64_t offset = chreGetEstimatedHostTimeOffset();
- uint64_t time = chreGetTime();
-
- // Just casting time to int64_t and adding the (potentially negative) offset
- // should be OK under most conditions, but this way avoids issues if
- // time >= 2^63, which is technically allowed since we don't specify a start
- // value for chreGetTime(), though one would assume 0 is roughly boot time.
- if (offset >= 0) {
- time += (uint64_t) offset;
- } else {
- // Assuming chreGetEstimatedHostTimeOffset() is implemented properly,
- // this will never underflow, because offset = hostTime - chreTime,
- // and both times are monotonically increasing (e.g. when determining
- // the offset, if hostTime is 0 and chreTime is 100 we'll have
- // offset = -100, but chreGetTime() will always return >= 100 after that
- // point).
- time -= (uint64_t) (offset * -1);
- }
-
- return time;
-}
-
-/**
- * Set a timer.
- *
- * When the timer fires, nanoappHandleEvent will be invoked with
- * CHRE_EVENT_TIMER and with the given 'cookie'.
- *
- * A CHRE implementation is required to provide at least 32
- * timers. However, there's no assurance there will be any available
- * for any given nanoapp (if it's loaded late, etc).
- *
- * @param duration Time, in nanoseconds, before the timer fires.
- * @param cookie Argument that will be sent to nanoappHandleEvent upon the
- * timer firing. This is allowed to be NULL and does not need to be
- * a valid pointer (assuming the nanoappHandleEvent code is expecting such).
- * @param oneShot If true, the timer will just fire once. If false, the
- * timer will continue to refire every 'duration', until this timer is
- * canceled (@see chreTimerCancel).
- *
- * @return The timer ID. If the system is unable to set a timer
- * (no more available timers, etc.) then CHRE_TIMER_INVALID will
- * be returned.
- *
- * @see nanoappHandleEvent
- */
-uint32_t chreTimerSet(uint64_t duration, const void *cookie, bool oneShot);
-
-/**
- * Cancel a timer.
- *
- * After this method returns, the CHRE assures there will be no more
- * events sent from this timer, and any enqueued events from this timer
- * will need to be evicted from the queue by the CHRE.
- *
- * @param timerId A timer ID obtained by this nanoapp via chreTimerSet().
- * @return true if the timer was cancelled, false otherwise. We may
- * fail to cancel the timer if it's a one shot which (just) fired,
- * or if the given timer ID is not owned by the calling app.
- */
-bool chreTimerCancel(uint32_t timerId);
-
-/**
- * Terminate this nanoapp.
- *
- * This takes effect immediately.
- *
- * The CHRE will no longer execute this nanoapp. The CHRE will not invoke
- * nanoappEnd(), nor will it call any memory free callbacks in the nanoapp.
- *
- * The CHRE will unload/evict this nanoapp's code.
- *
- * @param abortCode A value indicating the reason for aborting. (Note that
- * in this version of the API, there is no way for anyone to access this
- * code, but future APIs may expose it.)
- * @return Never. This method does not return, as the CHRE stops nanoapp
- * execution immediately.
- */
-void chreAbort(uint32_t abortCode);
-
-/**
- * Allocate a given number of bytes from the system heap.
- *
- * The nanoapp is required to free this memory via chreHeapFree() prior to
- * the nanoapp ending.
- *
- * While the CHRE implementation is required to free up heap resources of
- * a nanoapp when unloading it, future requirements and tests focused on
- * nanoapps themselves may check for memory leaks, and will require nanoapps
- * to properly manage their heap resources.
- *
- * @param bytes The number of bytes requested.
- * @return A pointer to 'bytes' contiguous bytes of heap memory, or NULL
- * if the allocation could not be performed. This pointer must be suitably
- * aligned for any kind of variable.
- *
- * @see chreHeapFree.
- */
-void *chreHeapAlloc(uint32_t bytes);
-
-/**
- * Free a heap allocation.
- *
- * This allocation must be from a value returned from a chreHeapAlloc() call
- * made by this nanoapp. In other words, it is illegal to free memory
- * allocated by another nanoapp (or the CHRE).
- *
- * @param ptr 'ptr' is required to be a value returned from chreHeapAlloc().
- * Note that since chreHeapAlloc can return NULL, CHRE
- * implementations must safely handle 'ptr' being NULL.
- *
- * @see chreHeapAlloc.
- */
-void chreHeapFree(void *ptr);
-
-/**
- * Logs the nanoapp's debug data into debug dumps.
- *
- * A debug dump is a string representation of information that can be used to
- * diagnose and debug issues. While chreLog() is useful for logging events as
- * they happen, the debug dump is a complementary function typically used to
- * output a snapshot of a nanoapp's state, history, vital statistics, etc. The
- * CHRE framework is required to pass this information to the debug method in
- * the Context Hub HAL, where it can be captured in Android bugreports, etc.
- *
- * This function must only be called while handling CHRE_DEBUG_DUMP_EVENT,
- * otherwise it will have no effect. A nanoapp can call this function multiple
- * times while handling the event. If the resulting formatted string from a
- * single call to this function is longer than CHRE_DEBUG_DUMP_MINIMUM_MAX_SIZE
- * characters, it may get truncated.
- *
- * @param formatStr A printf-style format string of the format documented in
- * chreLog().
- * @param ... A variable number of arguments necessary for the given 'formatStr'
- * (there may be no additional arguments for some 'formatStr's).
- *
- * @see chreConfigureDebugDumpEvent
- * @see chreLog
- *
- * @since v1.4
- */
-CHRE_PRINTF_ATTR(1, 2)
-void chreDebugDumpLog(const char *formatStr, ...);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_RE_H_ */
-
diff --git a/chre_api/legacy/v1_4/chre/sensor.h b/chre_api/legacy/v1_4/chre/sensor.h
deleted file mode 100644
index 88cfce8e..00000000
--- a/chre_api/legacy/v1_4/chre/sensor.h
+++ /dev/null
@@ -1,1018 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_SENSOR_H_
-#define _CHRE_SENSOR_H_
-
-/**
- * @file
- * API dealing with sensor interaction in the Context Hub Runtime
- * Environment.
- *
- * This includes the definition of our sensor types and the ability to
- * configure them for receiving events.
- */
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include <chre/common.h>
-#include <chre/event.h>
-#include <chre/sensor_types.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/**
- * Base value for all of the data events for sensors.
- *
- * The value for a data event FOO is
- * CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_FOO
- *
- * This allows for easy mapping, and also explains why there are gaps
- * in our values since we don't have all possible sensor types assigned.
- */
-#define CHRE_EVENT_SENSOR_DATA_EVENT_BASE CHRE_EVENT_SENSOR_FIRST_EVENT
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x', 'y', and 'z' fields within
- * 'readings', or by the 3D array 'v' (v[0] == x; v[1] == y; v[2] == z).
- *
- * All values are in SI units (m/s^2) and measure the acceleration applied to
- * the device.
- */
-#define CHRE_EVENT_SENSOR_ACCELEROMETER_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_ACCELEROMETER)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorOccurrenceData
- *
- * Since this is a one-shot sensor, after this event is delivered to the
- * nanoapp, the sensor automatically goes into DONE mode. Sensors of this
- * type must be configured with a ONE_SHOT mode.
- */
-#define CHRE_EVENT_SENSOR_INSTANT_MOTION_DETECT_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_INSTANT_MOTION_DETECT)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorOccurrenceData
- *
- * Since this is a one-shot sensor, after this event is delivered to the
- * nanoapp, the sensor automatically goes into DONE mode. Sensors of this
- * type must be configured with a ONE_SHOT mode.
- */
-#define CHRE_EVENT_SENSOR_STATIONARY_DETECT_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_STATIONARY_DETECT)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x', 'y', and 'z' fields within
- * 'readings', or by the 3D array 'v' (v[0] == x; v[1] == y; v[2] == z).
- *
- * All values are in radians/second and measure the rate of rotation
- * around the X, Y and Z axis.
- */
-#define CHRE_EVENT_SENSOR_GYROSCOPE_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_GYROSCOPE)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x', 'y', and 'z' fields within
- * 'readings', or by the 3D array 'v' (v[0] == x; v[1] == y; v[2] == z).
- *
- * All values are in micro-Tesla (uT) and measure the geomagnetic
- * field in the X, Y and Z axis.
- */
-#define CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorFloatData
- *
- * The data can be interpreted using the 'pressure' field within 'readings'.
- * This value is in hectopascals (hPa).
- */
-#define CHRE_EVENT_SENSOR_PRESSURE_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_PRESSURE)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorFloatData
- *
- * The data can be interpreted using the 'light' field within 'readings'.
- * This value is in SI lux units.
- */
-#define CHRE_EVENT_SENSOR_LIGHT_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_LIGHT)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorByteData
- *
- * The data is interpreted from the following fields in 'readings':
- * o 'isNear': If set to 1, we are nearby (on the order of centimeters);
- * if set to 0, we are far. The meaning of near/far in this field must be
- * consistent with the Android definition.
- * o 'invalid': If set to 1, this is not a valid reading of this data.
- * As of CHRE API v1.2, this field is deprecated and must always be set to
- * 0. If an invalid reading is generated by the sensor hardware, it must
- * be dropped and not delivered to any nanoapp.
- *
- * In prior versions of the CHRE API, there can be an invalid event generated
- * upon configuring this sensor. Thus, the 'invalid' field must be checked on
- * the first event before interpreting 'isNear'.
- */
-#define CHRE_EVENT_SENSOR_PROXIMITY_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_PROXIMITY)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorOccurrenceData
- *
- * This data is generated every time a step is taken by the user.
- *
- * @since v1.3
- */
-#define CHRE_EVENT_SENSOR_STEP_DETECT_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_STEP_DETECT)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x', 'y', and 'z' fields within
- * 'readings', or by the 3D array 'v' (v[0] == x; v[1] == y; v[2] == z).
- *
- * All values are in SI units (m/s^2) and measure the acceleration applied to
- * the device.
- */
-#define CHRE_EVENT_SENSOR_UNCALIBRATED_ACCELEROMETER_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x', 'y', and 'z' fields within
- * 'readings', or by the 3D array 'v' (v[0] == x; v[1] == y; v[2] == z).
- *
- * All values are in radians/second and measure the rate of rotation
- * around the X, Y and Z axis.
- */
-#define CHRE_EVENT_SENSOR_UNCALIBRATED_GYROSCOPE_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x', 'y', and 'z' fields within
- * 'readings', or by the 3D array 'v' (v[0] == x; v[1] == y; v[2] == z).
- *
- * All values are in micro-Tesla (uT) and measure the geomagnetic
- * field in the X, Y and Z axis.
- */
-#define CHRE_EVENT_SENSOR_UNCALIBRATED_GEOMAGNETIC_FIELD_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorFloatData
- *
- * The data can be interpreted using the 'temperature' field within 'readings'.
- * This value is in degrees Celsius.
- */
-#define CHRE_EVENT_SENSOR_ACCELEROMETER_TEMPERATURE_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_ACCELEROMETER_TEMPERATURE)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorFloatData
- *
- * The data can be interpreted using the 'temperature' field within 'readings'.
- * This value is in degrees Celsius.
- */
-#define CHRE_EVENT_SENSOR_GYROSCOPE_TEMPERATURE_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_GYROSCOPE_TEMPERATURE)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorFloatData
- *
- * The data can be interpreted using the 'temperature' field within 'readings'.
- * This value is in degrees Celsius.
- */
-#define CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_TEMPERATURE_DATA \
- (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD_TEMPERATURE)
-
-/**
- * First value for sensor events which are not data from the sensor.
- *
- * Unlike the data event values, these other event values don't have any
- * mapping to sensor types.
- */
-#define CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE \
- (CHRE_EVENT_SENSOR_FIRST_EVENT + 0x0100)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorSamplingStatusEvent
- *
- * Indicates that the interval and/or the latency which this sensor is
- * sampling at has changed.
- */
-#define CHRE_EVENT_SENSOR_SAMPLING_CHANGE \
- (CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE + 0)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x_bias', 'y_bias', and 'z_bias'
- * field within 'readings', or by the 3D array 'bias' (bias[0] == x_bias;
- * bias[1] == y_bias; bias[2] == z_bias). Bias is subtracted from uncalibrated
- * data to generate calibrated data.
- *
- * All values are in radians/second and measure the rate of rotation
- * around the X, Y and Z axis.
- *
- * If bias delivery is supported, this event is generated by default when
- * chreSensorConfigure is called to enable for the sensor of type
- * CHRE_SENSOR_TYPE_GYROSCOPE, or if bias delivery is explicitly enabled
- * through chreSensorConfigureBiasEvents() for the sensor.
- */
-#define CHRE_EVENT_SENSOR_GYROSCOPE_BIAS_INFO \
- (CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE + 1)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x_bias', 'y_bias', and 'z_bias'
- * field within 'readings', or by the 3D array 'bias' (bias[0] == x_bias;
- * bias[1] == y_bias; bias[2] == z_bias). Bias is subtracted from uncalibrated
- * data to generate calibrated data.
- *
- * All values are in micro-Tesla (uT) and measure the geomagnetic
- * field in the X, Y and Z axis.
- *
- * If bias delivery is supported, this event is generated by default when
- * chreSensorConfigure is called to enable for the sensor of type
- * CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD, or if bias delivery is explicitly enabled
- * through chreSensorConfigureBiasEvents() for the sensor.
- */
-#define CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_BIAS_INFO \
- (CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE + 2)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data can be interpreted using the 'x_bias', 'y_bias', and 'z_bias'
- * field within 'readings', or by the 3D array 'bias' (bias[0] == x_bias;
- * bias[1] == y_bias; bias[2] == z_bias). Bias is subtracted from uncalibrated
- * data to generate calibrated data.
- *
- * All values are in SI units (m/s^2) and measure the acceleration applied to
- * the device.
- *
- * If bias delivery is supported, this event is generated by default when
- * chreSensorConfigure is called to enable for the sensor of type
- * CHRE_SENSOR_TYPE_ACCELEROMETER, or if bias delivery is explicitly enabled
- * through chreSensorConfigureBiasEvents() for the sensor.
- *
- * @since v1.3
- */
-#define CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO \
- (CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE + 3)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorFlushCompleteEvent
- *
- * An event indicating that a flush request made by chreSensorFlushAsync has
- * completed.
- *
- * @see chreSensorFlushAsync
- *
- * @since v1.3
- */
-#define CHRE_EVENT_SENSOR_FLUSH_COMPLETE \
- (CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE + 4)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data of this event is the same as that of
- * CHRE_EVENT_SENSOR_GYROSCOPE_BIAS_INFO, except the sensorHandle field of
- * chreSensorDataHeader contains the handle of the sensor of type
- * CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE.
- *
- * This event is only generated if the bias reporting is explicitly enabled
- * for a nanoapp through chreSensorConfigureBiasEvents() for the sensor of type
- * CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE.
- *
- * @see CHRE_EVENT_SENSOR_GYROSCOPE_BIAS_INFO
- *
- * @since v1.3
- */
-#define CHRE_EVENT_SENSOR_UNCALIBRATED_GYROSCOPE_BIAS_INFO \
- (CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE + 5)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data of this event is the same as that of
- * CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_BIAS_INFO, except the sensorHandle field
- * of chreSensorDataHeader contains the handle of the sensor of type
- * CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD.
- *
- * This event is only generated if the bias reporting is explicitly enabled
- * for a nanoapp through chreSensorConfigureBiasEvents() for the sensor of type
- * CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD.
- *
- * @see CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_BIAS_INFO
- *
- * @since v1.3
- */
-#define CHRE_EVENT_SENSOR_UNCALIBRATED_GEOMAGNETIC_FIELD_BIAS_INFO \
- (CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE + 6)
-
-/**
- * nanoappHandleEvent argument: struct chreSensorThreeAxisData
- *
- * The data of this event is the same as that of
- * CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO, except the sensorHandle field
- * of chreSensorDataHeader contains the handle of the sensor of type
- * CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER.
- *
- * This event is only generated if the bias reporting is explicitly enabled
- * for a nanoapp through chreSensorConfigureBiasEvents for the sensor of type
- * CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER.
- *
- * @see CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO
- *
- * @since v1.3
- */
-#define CHRE_EVENT_SENSOR_UNCALIBRATED_ACCELEROMETER_BIAS_INFO \
- (CHRE_EVENT_SENSOR_OTHER_EVENTS_BASE + 7)
-
-#if CHRE_EVENT_SENSOR_UNCALIBRATED_ACCELEROMETER_BIAS_INFO > \
- CHRE_EVENT_SENSOR_LAST_EVENT
-#error Too many sensor events.
-#endif
-
-/**
- * Value indicating we want the smallest possible latency for a sensor.
- *
- * This literally translates to 0 nanoseconds for the chreSensorConfigure()
- * argument. While we won't get exactly 0 nanoseconds, the CHRE will
- * queue up this event As Soon As Possible.
- */
-#define CHRE_SENSOR_LATENCY_ASAP UINT64_C(0)
-
-/**
- * Special value indicating non-importance, or non-applicability of the sampling
- * interval.
- *
- * @see chreSensorConfigure
- * @see chreSensorSamplingStatus
- */
-#define CHRE_SENSOR_INTERVAL_DEFAULT UINT64_C(-1)
-
-/**
- * Special value indicating non-importance of the latency.
- *
- * @see chreSensorConfigure
- * @see chreSensorSamplingStatus
- */
-#define CHRE_SENSOR_LATENCY_DEFAULT UINT64_C(-1)
-
-/**
- * Special value indicating non-importance of the batch interval.
- *
- * @see chreSensorConfigureWithBatchInterval
- */
-#define CHRE_SENSOR_BATCH_INTERVAL_DEFAULT UINT64_C(-1)
-
-// This is used to define elements of enum chreSensorConfigureMode.
-#define CHRE_SENSOR_CONFIGURE_RAW_POWER_ON (1 << 0)
-
-// This is used to define elements of enum chreSensorConfigureMode.
-#define CHRE_SENSOR_CONFIGURE_RAW_REPORT_CONTINUOUS (1 << 1)
-
-// This is used to define elements of enum chreSensorConfigureMode.
-#define CHRE_SENSOR_CONFIGURE_RAW_REPORT_ONE_SHOT (2 << 1)
-
-/**
- * The maximum amount of time allowed to elapse between the call to
- * chreSensorFlushAsync() and when CHRE_EVENT_SENSOR_FLUSH_COMPLETE is delivered
- * to the nanoapp on a successful flush.
- */
-#define CHRE_SENSOR_FLUSH_COMPLETE_TIMEOUT_NS (5 * CHRE_NSEC_PER_SEC)
-
-/**
- * Modes we can configure a sensor to use.
- *
- * Our mode will affect not only how/if we receive events, but
- * also whether or not the sensor will be powered on our behalf.
- *
- * @see chreSensorConfigure
- */
-enum chreSensorConfigureMode {
- /**
- * Get events from the sensor.
- *
- * Power: Turn on if not already on.
- * Reporting: Continuous. Send each new event as it comes (subject to
- * batching and latency).
- */
- CHRE_SENSOR_CONFIGURE_MODE_CONTINUOUS =
- (CHRE_SENSOR_CONFIGURE_RAW_POWER_ON |
- CHRE_SENSOR_CONFIGURE_RAW_REPORT_CONTINUOUS),
-
- /**
- * Get a single event from the sensor and then become DONE.
- *
- * Once the event is sent, the sensor automatically
- * changes to CHRE_SENSOR_CONFIGURE_MODE_DONE mode.
- *
- * Power: Turn on if not already on.
- * Reporting: One shot. Send the next event and then be DONE.
- */
- CHRE_SENSOR_CONFIGURE_MODE_ONE_SHOT =
- (CHRE_SENSOR_CONFIGURE_RAW_POWER_ON |
- CHRE_SENSOR_CONFIGURE_RAW_REPORT_ONE_SHOT),
-
- /**
- * Get events from a sensor that are generated for any client in the system.
- *
- * This is considered passive because the sensor will not be powered on for
- * the sake of our nanoapp. If and only if another client in the system has
- * requested this sensor power on will we get events.
- *
- * This can be useful for something which is interested in seeing data, but
- * not interested enough to be responsible for powering on the sensor.
- *
- * Power: Do not power the sensor on our behalf.
- * Reporting: Continuous. Send each event as it comes.
- */
- CHRE_SENSOR_CONFIGURE_MODE_PASSIVE_CONTINUOUS =
- CHRE_SENSOR_CONFIGURE_RAW_REPORT_CONTINUOUS,
-
- /**
- * Get a single event from a sensor that is generated for any client in the
- * system.
- *
- * See CHRE_SENSOR_CONFIGURE_MODE_PASSIVE_CONTINUOUS for more details on
- * what the "passive" means.
- *
- * Power: Do not power the sensor on our behalf.
- * Reporting: One shot. Send only the next event and then be DONE.
- */
- CHRE_SENSOR_CONFIGURE_MODE_PASSIVE_ONE_SHOT =
- CHRE_SENSOR_CONFIGURE_RAW_REPORT_ONE_SHOT,
-
- /**
- * Indicate we are done using this sensor and no longer interested in it.
- *
- * See chreSensorConfigure for more details on expressing interest or
- * lack of interest in a sensor.
- *
- * Power: Do not power the sensor on our behalf.
- * Reporting: None.
- */
- CHRE_SENSOR_CONFIGURE_MODE_DONE = 0,
-};
-
-/**
- * A structure containing information about a Sensor.
- *
- * See documentation of individual fields below.
- */
-struct chreSensorInfo {
- /**
- * The name of the sensor.
- *
- * A text name, useful for logging/debugging, describing the Sensor. This
- * is not assured to be unique (i.e. there could be multiple sensors with
- * the name "Temperature").
- *
- * CHRE implementations may not set this as NULL. An empty
- * string, while discouraged, is legal.
- */
- const char *sensorName;
-
- /**
- * One of the CHRE_SENSOR_TYPE_* defines above.
- */
- uint8_t sensorType;
-
- /**
- * Flag indicating if this sensor is on-change.
- *
- * An on-change sensor only generates events when underlying state
- * changes. This has the same meaning as on-change does in the Android
- * Sensors HAL. See sensors.h for much more details.
- *
- * A value of 1 indicates this is on-change. 0 indicates this is not
- * on-change.
- */
- uint8_t isOnChange : 1;
-
- /**
- * Flag indicating if this sensor is one-shot.
- *
- * A one-shot sensor only triggers a single event, and then automatically
- * disables itself.
- *
- * A value of 1 indicates this is one-shot. 0 indicates this is not
- * on-change.
- */
- uint8_t isOneShot : 1;
-
- /**
- * Flag indicating if this sensor supports reporting bias info events.
- *
- * This field will be set to 0 when running on CHRE API versions prior to
- * v1.3, but must be ignored (i.e. does not mean bias info event is not
- * supported).
- *
- * @see chreSensorConfigureBiasEvents
- *
- * @since v1.3
- */
- uint8_t reportsBiasEvents : 1;
-
- /**
- * Flag indicating if this sensor supports passive mode requests.
- *
- * This field will be set to 0 when running on CHRE API versions prior to
- * v1.4, and must be ignored (i.e. does not mean passive mode requests are
- * not supported).
- *
- * @see chreSensorConfigure
- *
- * @since v1.4
- */
- uint8_t supportsPassiveMode : 1;
-
- uint8_t unusedFlags : 4;
-
- /**
- * The minimum sampling interval supported by this sensor, in nanoseconds.
- *
- * Requests to chreSensorConfigure with a lower interval than this will
- * fail. If the sampling interval is not applicable to this sensor, this
- * will be set to CHRE_SENSOR_INTERVAL_DEFAULT.
- *
- * This field will be set to 0 when running on CHRE API versions prior to
- * v1.1, indicating that the minimum interval is not known.
- *
- * @since v1.1
- */
- uint64_t minInterval;
-};
-
-/**
- * The status of a sensor's sampling configuration.
- */
-struct chreSensorSamplingStatus {
- /**
- * The interval, in nanoseconds, at which the sensor is now sampling.
- *
- * If this is CHRE_SENSOR_INTERVAL_DEFAULT, then a sampling interval
- * isn't meaningful for this sensor.
- *
- * Note that if 'enabled' is false, this value is not meaningful.
- */
- uint64_t interval;
-
- /**
- * The latency, in nanoseconds, at which the senor is now reporting.
- *
- * If this is CHRE_SENSOR_LATENCY_DEFAULT, then a latency
- * isn't meaningful for this sensor.
- *
- * The effective batch interval can be derived from this value by
- * adding the current sampling interval.
- *
- * Note that if 'enabled' is false, this value is not meaningful.
- */
- uint64_t latency;
-
- /**
- * True if the sensor is actively powered and sampling; false otherwise.
- */
- bool enabled;
-};
-
-/**
- * The nanoappHandleEvent argument for CHRE_EVENT_SENSOR_SAMPLING_CHANGE.
- *
- * Note that only at least one of 'interval' or 'latency' must be
- * different than it was prior to this event. Thus, one of these
- * fields may be (but doesn't need to be) the same as before.
- */
-struct chreSensorSamplingStatusEvent {
- /**
- * The handle of the sensor which has experienced a change in sampling.
- */
- uint32_t sensorHandle;
-
- /**
- * The new sampling status.
- *
- * At least one of the field in this struct will be different from
- * the previous sampling status event.
- */
- struct chreSensorSamplingStatus status;
-};
-
-/**
- * The nanoappHandleEvent argument for CHRE_EVENT_SENSOR_FLUSH_COMPLETE.
- *
- * @see chreSensorFlushAsync
- *
- * @since v1.3
- */
-struct chreSensorFlushCompleteEvent {
- /**
- * The handle of the sensor which a flush was completed.
- */
- uint32_t sensorHandle;
-
- /**
- * Populated with a value from enum {@link #chreError}, indicating whether
- * the flush failed, and if so, provides the cause of the failure.
- */
- uint8_t errorCode;
-
- /**
- * Reserved for future use. Set to 0.
- */
- uint8_t reserved[3];
-
- /**
- * Set to the cookie parameter given to chreSensorFlushAsync.
- */
- const void *cookie;
-};
-
-/**
- * Find the default sensor for a given sensor type.
- *
- * @param sensorType One of the CHRE_SENSOR_TYPE_* constants.
- * @param handle If a sensor is found, then the memory will be filled with
- * the value for the sensor's handle. This argument must be non-NULL.
- * @return true if a sensor was found, false otherwise.
- */
-bool chreSensorFindDefault(uint8_t sensorType, uint32_t *handle);
-
-/**
- * Get the chreSensorInfo struct for a given sensor.
- *
- * @param sensorHandle The sensor handle, as obtained from
- * chreSensorFindDefault() or passed to nanoappHandleEvent().
- * @param info If the sensor is valid, then this memory will be filled with
- * the SensorInfo contents for this sensor. This argument must be
- * non-NULL.
- * @return true if the senor handle is valid and 'info' was filled in;
- * false otherwise.
- */
-bool chreGetSensorInfo(uint32_t sensorHandle, struct chreSensorInfo *info);
-
-/**
- * Get the chreSensorSamplingStatus struct for a given sensor.
- *
- * Note that this may be different from what was requested in
- * chreSensorConfigure(), for multiple reasons. It's possible that the sensor
- * does not exactly support the interval requested in chreSensorConfigure(), so
- * a faster one was chosen.
- *
- * It's also possible that there is another user of this sensor who has
- * requested a faster interval and/or lower latency. This latter scenario
- * should be noted, because it means the sensor rate can change due to no
- * interaction from this nanoapp. Note that the
- * CHRE_EVENT_SENSOR_SAMPLING_CHANGE event will trigger in this case, so it's
- * not necessary to poll for such a change.
- *
- * @param sensorHandle The sensor handle, as obtained from
- * chreSensorFindDefault() or passed to nanoappHandleEvent().
- * @param status If the sensor is valid, then this memory will be filled with
- * the sampling status contents for this sensor. This argument must be
- * non-NULL.
- * @return true if the senor handle is valid and 'status' was filled in;
- * false otherwise.
- */
-bool chreGetSensorSamplingStatus(uint32_t sensorHandle,
- struct chreSensorSamplingStatus *status);
-
-/**
- * Configures a given sensor at a specific interval and latency and mode.
- *
- * If this sensor's chreSensorInfo has isOneShot set to 1,
- * then the mode must be one of the ONE_SHOT modes, or this method will fail.
- *
- * The CHRE wants to power as few sensors as possible, in keeping with its
- * low power design. As such, it only turns on sensors when there are clients
- * actively interested in that sensor data, and turns off sensors as soon as
- * there are no clients interested in them. Calling this method generally
- * indicates an interest, and using CHRE_SENSOR_CONFIGURE_MODE_DONE shows
- * when we are no longer interested.
- *
- * Thus, each initial Configure of a sensor (per nanoapp) needs to eventually
- * have a DONE call made, either directly or on its behalf. Subsequent calls
- * to a Configure method within the same nanoapp, when there has been no DONE
- * in between, still only require a single DONE call.
- *
- * For example, the following is valid usage:
- * <code>
- * chreSensorConfigure(myHandle, mode, interval0, latency0);
- * [...]
- * chreSensorConfigure(myHandle, mode, interval1, latency0);
- * [...]
- * chreSensorConfigure(myHandle, mode, interval1, latency1);
- * [...]
- * chreSensorConfigureModeOnly(myHandle, CHRE_SENSOR_CONFIGURE_MODE_DONE);
- * </code>
- *
- * The first call to Configure is the one which creates the requirement
- * to eventually call with DONE. The subsequent calls are just changing the
- * interval/latency. They have not changed the fact that this nanoapp is
- * still interested in output from the sensor 'myHandle'. Thus, only one
- * single call for DONE is needed.
- *
- * There is a special case. One-shot sensors, sensors which
- * just trigger a single event and never trigger again, implicitly go into
- * DONE mode after that single event triggers. Thus, the
- * following are legitimate usages:
- * <code>
- * chreSensorConfigure(myHandle, MODE_ONE_SHOT, interval, latency);
- * [...]
- * [myHandle triggers an event]
- * [no need to configure to DONE].
- * </code>
- *
- * And:
- * <code>
- * chreSensorConfigure(myHandle, MODE_ONE_SHOT, interval, latency);
- * [...]
- * chreSensorConfigureModeOnly(myHandle, MODE_DONE);
- * [we cancelled myHandle before it ever triggered an event]
- * </code>
- *
- * Note that while PASSIVE modes, by definition, don't express an interest in
- * powering the sensor, DONE is still necessary to silence the event reporting.
- * Starting with CHRE API v1.4, for sensors that do not support passive mode, a
- * request with mode set to CHRE_SENSOR_CONFIGURE_MODE_PASSIVE_CONTINUOUS or
- * CHRE_SENSOR_CONFIGURE_MODE_PASSIVE_ONE_SHOT will be rejected. CHRE API
- * versions 1.3 and older implicitly assume that passive mode is supported
- * across all sensors, however this is not necessarily the case. Clients can
- * call chreSensorInfo to identify whether a sensor supports passive mode.
- *
- * When a calibrated sensor (e.g. CHRE_SENSOR_TYPE_ACCELEROMETER) is
- * successfully enabled through this method and if bias delivery is supported,
- * by default CHRE will start delivering bias events for the sensor
- * (e.g. CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO) to the nanoapp. If the
- * nanoapp does not wish to receive these events, they can be disabled through
- * chreSensorConfigureBiasEvents after enabling the sensor.
- *
- * @param sensorHandle The handle to the sensor, as obtained from
- * chreSensorFindDefault().
- * @param mode The mode to use. See descriptions within the
- * chreSensorConfigureMode enum.
- * @param interval The interval, in nanoseconds, at which we want events from
- * the sensor. On success, the sensor will be set to 'interval', or a value
- * less than 'interval'. There is a special value
- * CHRE_SENSOR_INTERVAL_DEFAULT, in which we don't express a preference for
- * the interval, and allow the sensor to choose what it wants. Note that
- * due to batching, we may receive events less frequently than
- * 'interval'.
- * @param latency The maximum latency, in nanoseconds, allowed before the
- * CHRE begins delivery of an event. This will control how many events
- * can be queued by the sensor before requiring a delivery event.
- * Latency is defined as the "timestamp when event is queued by the CHRE"
- * minus "timestamp of oldest unsent data reading".
- * There is a special value CHRE_SENSOR_LATENCY_DEFAULT, in which we don't
- * express a preference for the latency, and allow the sensor to choose what
- * it wants.
- * Note that there is no assurance of how long it will take an event to
- * get through a CHRE's queueing system, and thus there is no ability to
- * request a minimum time from the occurrence of a phenomenon to when the
- * nanoapp receives the information. The current CHRE API has no
- * real-time elements, although future versions may introduce some to
- * help with this issue.
- * @return true if the configuration succeeded, false otherwise.
- *
- * @see chreSensorConfigureMode
- * @see chreSensorFindDefault
- * @see chreSensorInfo
- * @see chreSensorConfigureBiasEvents
- */
-bool chreSensorConfigure(uint32_t sensorHandle,
- enum chreSensorConfigureMode mode,
- uint64_t interval, uint64_t latency);
-
-/**
- * Short cut for chreSensorConfigure where we only want to configure the mode
- * and do not care about interval/latency.
- *
- * @see chreSensorConfigure
- */
-static inline bool chreSensorConfigureModeOnly(
- uint32_t sensorHandle, enum chreSensorConfigureMode mode) {
- return chreSensorConfigure(sensorHandle,
- mode,
- CHRE_SENSOR_INTERVAL_DEFAULT,
- CHRE_SENSOR_LATENCY_DEFAULT);
-}
-
-/**
- * Convenience function that wraps chreSensorConfigure but enables batching to
- * be controlled by specifying the desired maximum batch interval rather
- * than maximum sample latency. Users may find the batch interval to be a more
- * intuitive method of expressing the desired batching behavior.
- *
- * Batch interval is different from latency as the batch interval time is
- * counted starting when the prior event containing a batch of sensor samples is
- * delivered, while latency starts counting when the first sample is deferred to
- * start collecting a batch. In other words, latency ignores the time between
- * the last sample in a batch to the first sample of the next batch, while it's
- * included in the batch interval, as illustrated below.
- *
- * Time 0 1 2 3 4 5 6 7 8
- * Batch A B C
- * Sample a1 a2 a3 b1 b2 b3 c1 c2 c3
- * Latency [ ] [ ] [ ]
- * BatchInt | | |
- *
- * In the diagram, the effective sample interval is 1 time unit, latency is 2
- * time units, and batch interval is 3 time units.
- *
- * @param sensorHandle See chreSensorConfigure#sensorHandle
- * @param mode See chreSensorConfigure#mode
- * @param sampleInterval See chreSensorConfigure#interval, but note that
- * CHRE_SENSOR_INTERVAL_DEFAULT is not a supported input to this method.
- * @param batchInterval The desired maximum interval, in nanoseconds, between
- * CHRE enqueuing each batch of sensor samples.
- * @return Same as chreSensorConfigure
- *
- * @see chreSensorConfigure
- *
- * @since v1.1
- */
-static inline bool chreSensorConfigureWithBatchInterval(
- uint32_t sensorHandle, enum chreSensorConfigureMode mode,
- uint64_t sampleInterval, uint64_t batchInterval) {
- bool result = false;
-
- if (sampleInterval != CHRE_SENSOR_INTERVAL_DEFAULT) {
- uint64_t latency;
- if (batchInterval == CHRE_SENSOR_BATCH_INTERVAL_DEFAULT) {
- latency = CHRE_SENSOR_LATENCY_DEFAULT;
- } else if (batchInterval > sampleInterval) {
- latency = batchInterval - sampleInterval;
- } else {
- latency = CHRE_SENSOR_LATENCY_ASAP;
- }
- result = chreSensorConfigure(sensorHandle, mode, sampleInterval,
- latency);
- }
-
- return result;
-}
-
-/**
- * Configures the reception of bias events for a specific sensor.
- *
- * If bias event delivery is supported for a sensor, the sensor's chreSensorInfo
- * has reportsBiasEvents set to 1. If supported, it must be supported for both
- * calibrated and uncalibrated versions of the sensor. If supported, CHRE must
- * provide bias events to the nanoapp by default when chreSensorConfigure is
- * called to enable the calibrated version of the sensor (for backwards
- * compatibility reasons, as this is the defined behavior for CHRE API v1.0).
- * When configuring uncalibrated sensors, nanoapps must explicitly configure an
- * enable request through this method to receive bias events. If bias event
- * delivery is not supported for the sensor, this method will return false and
- * no bias events will be generated.
- *
- * To enable bias event delivery (enable=true), the nanoapp must be registered
- * to the sensor through chreSensorConfigure, and bias events will only be
- * generated when the sensor is powered on. To disable the bias event delivery,
- * this method can be invoked with enable=false.
- *
- * If an enable configuration is successful, the calling nanoapp will receive
- * bias info events, e.g. CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO, when the
- * bias status changes (or first becomes available). Calibrated data
- * (e.g. CHRE_SENSOR_TYPE_ACCELEROMETER) is generated by subracting bias from
- * uncalibrated data (e.g. CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER).
- * Calibrated sensor events are generated by applying the most recent bias
- * available (i.e. timestamp of calibrated data are greater than or equal to the
- * timestamp of the bias data that has been applied to it). The configuration of
- * bias event delivery persists until the sensor is unregistered by the nanoapp
- * through chreSensorConfigure or modified through this method.
- *
- * To get an initial bias before new bias events, the nanoapp should get the
- * bias synchronously after this method is invoked, e.g.:
- *
- * if (chreSensorConfigure(handle, ...)) {
- * chreSensorConfigureBiasEvents(handle, true);
- * chreSensorGetThreeAxisBias(handle, &bias);
- * }
- *
- * Note that chreSensorGetThreeAxisBias() should be called after
- * chreSensorConfigureBiasEvents() to ensure that no bias events are lost.
- *
- * If called while running on a CHRE API version below v1.3, this function
- * returns false and has no effect. The default behavior regarding bias events
- * is unchanged, meaning that the implementation may still send bias events
- * when a calibrated sensor is registered (if supported), and will not send bias
- * events when an uncalibrated sensor is registered.
- *
- * @param sensorHandle The handle to the sensor, as obtained from
- * chreSensorFindDefault().
- * @param enable true to receive bias events, false otherwise
- *
- * @return true if the configuration succeeded, false otherwise
- *
- * @since v1.3
- */
-bool chreSensorConfigureBiasEvents(uint32_t sensorHandle, bool enable);
-
-/**
- * Synchronously provides the most recent bias info available for a sensor. The
- * bias will only be provided for a sensor that supports bias event delivery
- * using the chreSensorThreeAxisData type. If the bias is not yet available
- * (but is supported), this method will store data with a bias of 0 and the
- * accuracy field in chreSensorDataHeader set to CHRE_SENSOR_ACCURACY_UNKNOWN.
- *
- * If called while running on a CHRE API version below v1.3, this function
- * returns false.
- *
- * @param sensorHandle The handle to the sensor, as obtained from
- * chreSensorFindDefault().
- * @param bias A pointer to where the bias will be stored.
- *
- * @return true if the bias was successfully stored, false if sensorHandle was
- * invalid or the sensor does not support three axis bias delivery
- *
- * @since v1.3
- *
- * @see chreSensorConfigureBiasEvents
- */
-bool chreSensorGetThreeAxisBias(uint32_t sensorHandle,
- struct chreSensorThreeAxisData *bias);
-
-/**
- * Makes a request to flush all samples stored for batching. The nanoapp must be
- * registered to the sensor through chreSensorConfigure, and the sensor must be
- * powered on. If the request is accepted, all batched samples of the sensor
- * are sent to nanoapps registered to the sensor. During a flush, it is treated
- * as though the latency as given in chreSensorConfigure has expired. When all
- * batched samples have been flushed (or the flush fails), the nanoapp will
- * receive a unicast CHRE_EVENT_SENSOR_FLUSH_COMPLETE event. The time to deliver
- * this event must not exceed CHRE_SENSOR_FLUSH_COMPLETE_TIMEOUT_NS after this
- * method is invoked. If there are no samples in the batch buffer (either in
- * hardware FIFO or software), then this method will return true and a
- * CHRE_EVENT_SENSOR_FLUSH_COMPLETE event is delivered immediately.
- *
- * If a flush request is invalid (e.g. the sensor refers to a one-shot sensor,
- * or the sensor was not enabled), and this API will return false and no
- * CHRE_EVENT_SENSOR_FLUSH_COMPLETE event will be delivered.
- *
- * If multiple flush requests are made for a sensor prior to flush completion,
- * then the requesting nanoapp will receive all batched samples existing at the
- * time of the latest flush request. In this case, the number of
- * CHRE_EVENT_SENSOR_FLUSH_COMPLETE events received must equal the number of
- * flush requests made.
- *
- * If a sensor request is disabled after a flush request is made through this
- * method but before the flush operation is completed, the nanoapp will receive
- * a CHRE_EVENT_SENSOR_FLUSH_COMPLETE with the error code
- * CHRE_ERROR_FUNCTION_DISABLED for any pending flush requests.
- *
- * Starting with CHRE API v1.3, implementations must support this capability
- * across all exposed sensor types.
- *
- * @param sensorHandle The handle to the sensor, as obtained from
- * chreSensorFindDefault().
- * @param cookie An opaque value that will be included in the
- * chreSensorFlushCompleteEvent sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.3
- */
-bool chreSensorFlushAsync(uint32_t sensorHandle, const void *cookie);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_SENSOR_H_ */
diff --git a/chre_api/legacy/v1_4/chre/sensor_types.h b/chre_api/legacy/v1_4/chre/sensor_types.h
deleted file mode 100644
index f69c6f25..00000000
--- a/chre_api/legacy/v1_4/chre/sensor_types.h
+++ /dev/null
@@ -1,423 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * 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 _CHRE_SENSOR_TYPES_H_
-#define _CHRE_SENSOR_TYPES_H_
-
-/**
- * @file
- * Standalone definition of sensor types, and the data structures of the sample
- * events they emit.
- */
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * @file
- * The CHRE_SENSOR_TYPE_* defines are the sensor types supported.
- *
- * Unless otherwise noted, each of these sensor types is based off of a
- * corresponding sensor type in the Android API's sensors.h interface.
- * For a given CHRE_SENSOR_TYPE_FOO, it corresponds to the SENSOR_TYPE_FOO in
- * hardware/libhardware/include/hardware/sensors.h of the Android code base.
- *
- * Unless otherwise noted below, a CHRE_SENSOR_TYPE_FOO should be assumed
- * to work the same as the Android SENSOR_TYPE_FOO, as documented in the
- * sensors.h documentation and as detailed within the Android Compatibility
- * Definition Document.
- *
- * Note that every sensor will generate CHRE_EVENT_SENSOR_SAMPLING_CHANGE
- * events, so it is not listed with each individual sensor.
- */
-
-/**
- * Start value for all of the vendor-defined private sensors.
- *
- * @since v1.2
- */
-#define CHRE_SENSOR_TYPE_VENDOR_START UINT8_C(192)
-
-/**
- * Accelerometer.
- *
- * Generates: CHRE_EVENT_SENSOR_ACCELEROMETER_DATA and
- * optionally CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO
- *
- * Note that the ACCELEROMETER_DATA is always the fully calibrated data,
- * including factory calibration and runtime calibration if available.
- *
- * @see chreConfigureSensorBiasEvents
- */
-#define CHRE_SENSOR_TYPE_ACCELEROMETER UINT8_C(1)
-
-/**
- * Instantaneous motion detection.
- *
- * Generates: CHRE_EVENT_SENSOR_INSTANT_MOTION_DETECT_DATA
- *
- * This is a one-shot sensor.
- *
- * This does not have a direct analogy within sensors.h. This is similar
- * to SENSOR_TYPE_MOTION_DETECT, but this triggers instantly upon any
- * motion, instead of waiting for a period of continuous motion.
- */
-#define CHRE_SENSOR_TYPE_INSTANT_MOTION_DETECT UINT8_C(2)
-
-/**
- * Stationary detection.
- *
- * Generates: CHRE_EVENT_SENSOR_STATIONARY_DETECT_DATA
- *
- * This is a one-shot sensor.
- */
-#define CHRE_SENSOR_TYPE_STATIONARY_DETECT UINT8_C(3)
-
-/**
- * Gyroscope.
- *
- * Generates: CHRE_EVENT_SENSOR_GYROSCOPE_DATA and
- * optionally CHRE_EVENT_SENSOR_GYROSCOPE_BIAS_INFO
- *
- * Note that the GYROSCOPE_DATA is always the fully calibrated data, including
- * factory calibration and runtime calibration if available.
- *
- * @see chreConfigureSensorBiasEvents
- */
-#define CHRE_SENSOR_TYPE_GYROSCOPE UINT8_C(6)
-
-/**
- * Uncalibrated gyroscope.
- *
- * Generates: CHRE_EVENT_SENSOR_UNCALIBRATED_GYROSCOPE_DATA
- *
- * Note that the UNCALIBRATED_GYROSCOPE_DATA must be factory calibrated data,
- * but not runtime calibrated.
- */
-#define CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE UINT8_C(7)
-
-/**
- * Magnetometer.
- *
- * Generates: CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_DATA and
- * optionally CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_BIAS_INFO
- *
- * Note that the GEOMAGNETIC_FIELD_DATA is always the fully calibrated data,
- * including factory calibration and runtime calibration if available.
- *
- * @see chreConfigureSensorBiasEvents
- */
-#define CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD UINT8_C(8)
-
-/**
- * Uncalibrated magnetometer.
- *
- * Generates: CHRE_EVENT_SENSOR_UNCALIBRATED_GEOMAGNETIC_FIELD_DATA
- *
- * Note that the UNCALIBRATED_GEOMAGNETIC_FIELD_DATA must be factory calibrated
- * data, but not runtime calibrated.
- */
-#define CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD UINT8_C(9)
-
-/**
- * Barometric pressure sensor.
- *
- * Generates: CHRE_EVENT_SENSOR_PRESSURE_DATA
- */
-#define CHRE_SENSOR_TYPE_PRESSURE UINT8_C(10)
-
-/**
- * Ambient light sensor.
- *
- * Generates: CHRE_EVENT_SENSOR_LIGHT_DATA
- *
- * This is an on-change sensor.
- */
-#define CHRE_SENSOR_TYPE_LIGHT UINT8_C(12)
-
-/**
- * Proximity detection.
- *
- * Generates: CHRE_EVENT_SENSOR_PROXIMITY_DATA
- *
- * This is an on-change sensor.
- */
-#define CHRE_SENSOR_TYPE_PROXIMITY UINT8_C(13)
-
-/**
- * Step detection.
- *
- * Generates: CHRE_EVENT_SENSOR_STEP_DETECT_DATA
- *
- * @since v1.3
- */
-#define CHRE_SENSOR_TYPE_STEP_DETECT UINT8_C(23)
-
-/**
- * Uncalibrated accelerometer.
- *
- * Generates: CHRE_EVENT_SENSOR_UNCALIBRATED_ACCELEROMETER_DATA
- *
- * Note that the UNCALIBRATED_ACCELEROMETER_DATA must be factory calibrated
- * data, but not runtime calibrated.
- */
-#define CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER UINT8_C(55)
-
-/**
- * Accelerometer temperature.
- *
- * Generates: CHRE_EVENT_SENSOR_ACCELEROMETER_TEMPERATURE_DATA
- */
-#define CHRE_SENSOR_TYPE_ACCELEROMETER_TEMPERATURE UINT8_C(56)
-
-/**
- * Gyroscope temperature.
- *
- * Generates: CHRE_EVENT_SENSOR_GYROSCOPE_TEMPERATURE_DATA
- */
-#define CHRE_SENSOR_TYPE_GYROSCOPE_TEMPERATURE UINT8_C(57)
-
-/**
- * Magnetometer temperature.
- *
- * Generates: CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_TEMPERATURE_DATA
- */
-#define CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD_TEMPERATURE UINT8_C(58)
-
-#if CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD_TEMPERATURE >= CHRE_SENSOR_TYPE_VENDOR_START
-#error Too many sensor types
-#endif
-
-/**
- * Values that can be stored in the accuracy field of chreSensorDataHeader.
- * If CHRE_SENSOR_ACCURACY_UNKNOWN is returned, then the driver did not provide
- * accuracy information with the data. Values in the range
- * [CHRE_SENSOR_ACCURACY_VENDOR_START, CHRE_SENSOR_ACCURACY_VENDOR_END] are
- * reserved for vendor-specific values for vendor sensor types, and are not used
- * by CHRE for standard sensor types.
- *
- * Otherwise, the values have the same meaning as defined in the Android
- * Sensors definition:
- * https://developer.android.com/reference/android/hardware/SensorManager
- *
- * @since v1.3
- *
- * @defgroup CHRE_SENSOR_ACCURACY
- * @{
- */
-
-#define CHRE_SENSOR_ACCURACY_UNKNOWN UINT8_C(0)
-#define CHRE_SENSOR_ACCURACY_UNRELIABLE UINT8_C(1)
-#define CHRE_SENSOR_ACCURACY_LOW UINT8_C(2)
-#define CHRE_SENSOR_ACCURACY_MEDIUM UINT8_C(3)
-#define CHRE_SENSOR_ACCURACY_HIGH UINT8_C(4)
-#define CHRE_SENSOR_ACCURACY_VENDOR_START UINT8_C(192)
-#define CHRE_SENSOR_ACCURACY_VENDOR_END UINT8_MAX
-
-/** @} */
-
-/**
- * Header used in every structure containing batchable data from a sensor.
- *
- * The typical structure for sensor data looks like:
- *
- * struct chreSensorTypeData {
- * struct chreSensorDataHeader header;
- * struct chreSensorTypeSampleData {
- * uint32_t timestampDelta;
- * union {
- * <type> value;
- * <type> interpretation0;
- * <type> interpretation1;
- * };
- * } readings[1];
- * };
- *
- * Despite 'readings' being declared as an array of 1 element,
- * an instance of the struct will actually have 'readings' as
- * an array of header.readingCount elements (which may be 1).
- * The 'timestampDelta' is in relation to the previous 'readings' (or
- * the baseTimestamp for readings[0]. So,
- * Timestamp for readings[0] == header.baseTimestamp +
- * readings[0].timestampDelta.
- * Timestamp for readings[1] == timestamp for readings[0] +
- * readings[1].timestampDelta.
- * And thus, in order to determine the timestamp for readings[N], it's
- * necessary to process through all of the N-1 readings. The advantage,
- * though, is that our entire readings can span an arbitrary length of time,
- * just as long as any two consecutive readings differ by no more than
- * 4.295 seconds (timestampDelta, like all time in the CHRE, is in
- * nanoseconds).
- *
- * If a sensor has batched readings where two consecutive readings differ by
- * more than 4.295 seconds, the CHRE will split them across multiple
- * instances of the struct, and send multiple events.
- *
- * The value from the sensor is typically expressed in a union,
- * allowing a generic access to the data ('value'), along with
- * differently named access giving a more natural interpretation
- * of the data for the specific sensor types which use this
- * structure. This allows, for example, barometer code to
- * reference readings[N].pressure, and an ambient light sensor
- * to reference readings[N].light, while both use the same
- * structure.
- */
-struct chreSensorDataHeader {
- /**
- * The base timestamp, in nanoseconds.
- */
- uint64_t baseTimestamp;
-
- /**
- * The handle of the sensor producing this event.
- */
- uint32_t sensorHandle;
-
- /**
- * The number elements in the 'readings' array.
- *
- * This must be at least 1.
- */
- uint16_t readingCount;
-
- /**
- * The accuracy of the sensor data.
- *
- * @ref CHRE_SENSOR_ACCURACY
- *
- * @since v1.3
- */
- uint8_t accuracy;
-
- /**
- * Reserved bytes.
- *
- * This must be 0.
- */
- uint8_t reserved;
-};
-
-/**
- * Data for a sensor which reports on three axes.
- *
- * This is used by CHRE_EVENT_SENSOR_ACCELEROMETER_DATA,
- * CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO,
- * CHRE_EVENT_SENSOR_UNCALIBRATED_ACCELEROMETER_DATA,
- * CHRE_EVENT_SENSOR_GYROSCOPE_DATA,
- * CHRE_EVENT_SENSOR_GYROSCOPE_BIAS_INFO,
- * CHRE_EVENT_SENSOR_UNCALIBRATED_GYROSCOPE_DATA,
- * CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_DATA,
- * CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_BIAS_INFO, and
- * CHRE_EVENT_SENSOR_UNCALIBRATED_GEOMAGNETIC_FIELD_DATA.
- */
-struct chreSensorThreeAxisData {
- /**
- * @see chreSensorDataHeader
- */
- struct chreSensorDataHeader header;
- struct chreSensorThreeAxisSampleData {
- /**
- * @see chreSensorDataHeader
- */
- uint32_t timestampDelta;
- union {
- float values[3];
- float v[3];
- struct {
- float x;
- float y;
- float z;
- };
- float bias[3];
- struct {
- float x_bias;
- float y_bias;
- float z_bias;
- };
- };
- } readings[1];
-};
-
-/**
- * Data from a sensor where we only care about a event occurring.
- *
- * This is a bit unusual in that our readings have no data in addition
- * to the timestamp. But since we only care about the occurrence, we
- * don't need to know anything else.
- *
- * Used by: CHRE_EVENT_SENSOR_INSTANT_MOTION_DETECT_DATA,
- * CHRE_EVENT_SENSOR_STATIONARY_DETECT_DATA, and
- * CHRE_EVENT_SENSOR_STEP_DETECT_DATA.
- */
-struct chreSensorOccurrenceData {
- struct chreSensorDataHeader header;
- struct chreSensorOccurrenceSampleData {
- uint32_t timestampDelta;
- // This space intentionally left blank.
- // Only the timestamp is meaningful here, there
- // is no additional data.
- } readings[1];
-};
-
-/**
- * This is used by CHRE_EVENT_SENSOR_LIGHT_DATA,
- * CHRE_EVENT_SENSOR_PRESSURE_DATA,
- * CHRE_EVENT_SENSOR_ACCELEROMETER_TEMPERATURE_DATA,
- * CHRE_EVENT_SENSOR_GYROSCOPE_TEMPERATURE_DATA, and
- * CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_TEMPERATURE_DATA.
- */
-struct chreSensorFloatData {
- struct chreSensorDataHeader header;
- struct chreSensorFloatSampleData {
- uint32_t timestampDelta;
- union {
- float value;
- float light; //!< Unit: lux
- float pressure; //!< Unit: hectopascals (hPa)
- float temperature; //!< Unit: degrees Celsius
- };
- } readings[1];
-};
-
-/**
- * CHRE_EVENT_SENSOR_PROXIMITY_DATA.
- */
-struct chreSensorByteData {
- struct chreSensorDataHeader header;
- struct chreSensorByteSampleData {
- uint32_t timestampDelta;
- union {
- uint8_t value;
- struct {
- uint8_t isNear : 1;
- //! @deprecated As of v1.2, this field is deprecated and must
- //! always be set to 0
- uint8_t invalid : 1;
- uint8_t padding0 : 6;
- };
- };
- } readings[1];
-};
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_SENSOR_TYPES_H_ */
diff --git a/chre_api/legacy/v1_4/chre/toolchain.h b/chre_api/legacy/v1_4/chre/toolchain.h
deleted file mode 100644
index 4dfc051f..00000000
--- a/chre_api/legacy/v1_4/chre/toolchain.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_TOOLCHAIN_H_
-#define CHRE_TOOLCHAIN_H_
-
-/**
- * @file
- * Compiler/build toolchain-specific macros used by the CHRE API
- */
-
-#if defined(__GNUC__) || defined(__clang__)
-
-#define CHRE_DEPRECATED(message) \
- __attribute__((deprecated(message)))
-
-// Enable printf-style compiler warnings for mismatched format string and args
-#define CHRE_PRINTF_ATTR(formatPos, argStart) \
- __attribute__((format(printf, formatPos, argStart)))
-
-#else // if !defined(__GNUC__) && !defined(__clang__)
-
-#error Need to add support for new compiler
-
-#endif
-
-#endif // CHRE_TOOLCHAIN_H_
diff --git a/chre_api/legacy/v1_4/chre/version.h b/chre_api/legacy/v1_4/chre/version.h
deleted file mode 100644
index 08586a16..00000000
--- a/chre_api/legacy/v1_4/chre/version.h
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_VERSION_H_
-#define _CHRE_VERSION_H_
-
-/**
- * @file
- * Definitions and methods for the versioning of the Context Hub Runtime
- * Environment.
- *
- * The CHRE API versioning pertains to all header files in the CHRE API.
- */
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Value for version 0.1 of the Context Hub Runtime Environment API interface.
- *
- * This is a legacy version. Version 1.0 is considered the first official
- * version of the API.
- *
- * @see CHRE_API_VERSION
- */
-#define CHRE_API_VERSION_0_1 UINT32_C(0x00010000)
-
-/**
- * Value for version 1.0 of the Context Hub Runtime Environment API interface.
- *
- * The version of the CHRE API which shipped with the Android Nougat release.
- *
- * @see CHRE_API_VERSION
- */
-#define CHRE_API_VERSION_1_0 UINT32_C(0x01000000)
-
-/**
- * Value for version 1.1 of the Context Hub Runtime Environment API interface.
- *
- * The version of the CHRE API shipped with the Android O release. It adds
- * initial support for new GNSS, WiFi, and WWAN modules.
- *
- * @see CHRE_API_VERSION
- */
-#define CHRE_API_VERSION_1_1 UINT32_C(0x01010000)
-
-/**
- * Value for version 1.2 of the Context Hub Runtime Environment API interface.
- *
- * The version of the CHRE API shipped with the Android P release. It adds
- * initial support for the new audio module.
- *
- * @see CHRE_API_VERSION
- */
-#define CHRE_API_VERSION_1_2 UINT32_C(0x01020000)
-
-/**
- * Value for version 1.3 of the Context Hub Runtime Environment API interface.
- *
- * The version of the CHRE API shipped with the Android Q release. It adds
- * support for GNSS location altitude/speed/bearing accuracy. It also adds step
- * detect as a standard CHRE sensor and supports bias event delivery and sensor
- * data flushing.
- *
- * @see CHRE_API_VERSION
- */
-#define CHRE_API_VERSION_1_3 UINT32_C(0x01030000)
-
-/**
- * Value for version 1.4 of the Context Hub Runtime Environment API interface.
- *
- * The version of the CHRE API shipped with the Android R release. It adds
- * support for collecting debug dump information from nanoapps, receiving L5
- * GNSS measurements, determining if a sensor supports passive requests,
- * receiving 5G cell info, and deprecates chreSendMessageToHost.
- *
- * @see CHRE_API_VERSION
- */
-#define CHRE_API_VERSION_1_4 UINT32_C(0x01040000)
-
-/**
- * Major and Minor Version of this Context Hub Runtime Environment API.
- *
- * The major version changes when there is an incompatible API change.
- *
- * The minor version changes when there is an addition in functionality
- * in a backwards-compatible manner.
- *
- * We define the version number as an unsigned 32-bit value. The most
- * significant byte is the Major Version. The second-most significant byte
- * is the Minor Version. The two least significant bytes are the Patch
- * Version. The Patch Version is not defined by this header API, but
- * is provided by a specific CHRE implementation (see chreGetVersion()).
- *
- * Note that version numbers can always be numerically compared with
- * expected results, so 1.0.0 < 1.0.4 < 1.1.0 < 2.0.300 < 3.5.0.
- */
-#define CHRE_API_VERSION CHRE_API_VERSION_1_4
-
-/**
- * Utility macro to extract only the API major version of a composite CHRE
- * version.
- *
- * @param version A uint32_t version, e.g. the value returned by
- * chreGetApiVersion()
- *
- * @return The API major version in the least significant byte, e.g. 0x01
- */
-#define CHRE_EXTRACT_MAJOR_VERSION(version) \
- (((version) & UINT32_C(0xFF000000)) >> 24)
-
-/**
- * Utility macro to extract only the API minor version of a composite CHRE
- * version.
- *
- * @param version A uint32_t version, e.g. the CHRE_API_VERSION constant
- *
- * @return The API minor version in the least significant byte, e.g. 0x01
- */
-#define CHRE_EXTRACT_MINOR_VERSION(version) \
- (((version) & UINT32_C(0x00FF0000)) >> 16)
-
-/**
- * Utility macro to extract only the API minor version of a composite CHRE
- * version.
- *
- * @param version A complete uint32_t version, e.g. the value returned by
- * chreGetVersion()
- *
- * @return The implementation patch version in the least significant two bytes,
- * e.g. 0x0123, with all other bytes set to 0
- */
-#define CHRE_EXTRACT_PATCH_VERSION(version) ((version) & UINT32_C(0xFFFF))
-
-
-/**
- * Get the API version the CHRE implementation was compiled against.
- *
- * This is not necessarily the CHRE_API_VERSION in the header the nanoapp was
- * built against, and indeed may not have even appeared in the context_hub_os.h
- * header which this nanoapp was built against.
- *
- * By definition, this will have the two least significant bytes set to 0,
- * and only contain the major and minor version number.
- *
- * @return The API version.
- */
-uint32_t chreGetApiVersion(void);
-
-/**
- * Get the version of this CHRE implementation.
- *
- * By definition, ((chreGetApiVersion() & UINT32_C(0xFFFF0000)) ==
- * (chreGetVersion() & UINT32_C(0xFFFF0000))).
- *
- * The Patch Version, in the lower two bytes, only have meaning in context
- * of this specific platform ID. It is increased by the platform every time
- * a backwards-compatible bug fix is released.
- *
- * @return The version.
- *
- * @see chreGetPlatformId()
- */
-uint32_t chreGetVersion(void);
-
-/**
- * Get the Platform ID of this CHRE.
- *
- * The most significant five bytes are the vendor ID as set out by the
- * NANOAPP_VENDOR convention in the original context hub HAL header file
- * (context_hub.h), also used by nanoapp IDs.
- *
- * The least significant three bytes are set by the vendor, but must be
- * unique for each different CHRE implementation/hardware that the vendor
- * supplies.
- *
- * The idea is that in the case of known bugs in the field, a new nanoapp could
- * be shipped with a workaround that would use this value, and chreGetVersion(),
- * to have code that can conditionally work around the bug on a buggy version.
- * Thus, we require this uniqueness to allow such a setup to work.
- *
- * @return The platform ID.
- *
- * @see CHRE_EXTRACT_VENDOR_ID
- */
-uint64_t chreGetPlatformId(void);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_VERSION_H_ */
-
diff --git a/chre_api/legacy/v1_4/chre/wifi.h b/chre_api/legacy/v1_4/chre/wifi.h
deleted file mode 100644
index d14fd48e..00000000
--- a/chre_api/legacy/v1_4/chre/wifi.h
+++ /dev/null
@@ -1,913 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_WIFI_H_
-#define _CHRE_WIFI_H_
-
-/**
- * @file
- * WiFi (IEEE 802.11) API, currently covering scanning features useful for
- * determining location and offloading certain connectivity scans.
- *
- * In this file, specification references use the following shorthand:
- *
- * Shorthand | Full specification name
- * ---------- | ------------------------
- * "802.11" | IEEE Std 802.11-2007
- * "HT" | IEEE Std 802.11n-2009
- * "VHT" | IEEE Std 802.11ac-2013
- *
- */
-
-#include <chre/common.h>
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * The set of flags returned by chreWifiGetCapabilities().
- * @defgroup CHRE_WIFI_CAPABILITIES
- * @{
- */
-
-//! No WiFi APIs are supported
-#define CHRE_WIFI_CAPABILITIES_NONE UINT32_C(0)
-
-//! Listening to scan results is supported, as enabled via
-//! chreWifiConfigureScanMonitorAsync()
-#define CHRE_WIFI_CAPABILITIES_SCAN_MONITORING UINT32_C(1 << 0)
-
-//! Requesting WiFi scans on-demand is supported via chreWifiRequestScanAsync()
-#define CHRE_WIFI_CAPABILITIES_ON_DEMAND_SCAN UINT32_C(1 << 1)
-
-//! Specifying the radio chain preference in on-demand scan requests, and
-//! reporting it in scan events is supported
-//! @since v1.2
-#define CHRE_WIFI_CAPABILITIES_RADIO_CHAIN_PREF UINT32_C(1 << 2)
-
-//! Requesting RTT ranging is supported via chreWifiRequestRangingAsync()
-//! @since v1.2
-#define CHRE_WIFI_CAPABILITIES_RTT_RANGING UINT32_C(1 << 3)
-
-/** @} */
-
-/**
- * Produce an event ID in the block of IDs reserved for WiFi
- * @param offset Index into WiFi event ID block; valid range [0,15]
- */
-#define CHRE_WIFI_EVENT_ID(offset) (CHRE_EVENT_WIFI_FIRST_EVENT + (offset))
-
-/**
- * nanoappHandleEvent argument: struct chreAsyncResult
- *
- * Communicates the asynchronous result of a request to the WiFi API. The
- * requestType field in {@link #chreAsyncResult} is set to a value from enum
- * chreWifiRequestType.
- */
-#define CHRE_EVENT_WIFI_ASYNC_RESULT CHRE_WIFI_EVENT_ID(0)
-
-/**
- * nanoappHandleEvent argument: struct chreWifiScanEvent
- *
- * Provides results of a WiFi scan.
- */
-#define CHRE_EVENT_WIFI_SCAN_RESULT CHRE_WIFI_EVENT_ID(1)
-
-/**
- * nanoappHandleEvent argument: struct chreWifiRangingEvent
- *
- * Provides results of an RTT ranging request.
- */
-#define CHRE_EVENT_WIFI_RANGING_RESULT CHRE_WIFI_EVENT_ID(2)
-
-// NOTE: Do not add new events with ID > 15; only values 0-15 are reserved
-// (see chre/event.h)
-
-/**
- * The maximum amount of time that is allowed to elapse between a call to
- * chreWifiRequestScanAsync() that returns true, and the associated
- * CHRE_EVENT_WIFI_ASYNC_RESULT used to indicate whether the scan completed
- * successfully or not.
- */
-#define CHRE_WIFI_SCAN_RESULT_TIMEOUT_NS (30 * CHRE_NSEC_PER_SEC)
-
-/**
- * The maximum amount of time that is allowed to elapse between a call to
- * chreWifiRequestRangingAsync() that returns true, and the associated
- * CHRE_EVENT_WIFI_RANGING_RESULT used to indicate whether the ranging operation
- * completed successfully or not.
- */
-#define CHRE_WIFI_RANGING_RESULT_TIMEOUT_NS (30 * CHRE_NSEC_PER_SEC)
-
-/**
- * The current compatibility version of the chreWifiScanEvent structure,
- * including nested structures.
- */
-#define CHRE_WIFI_SCAN_EVENT_VERSION UINT8_C(1)
-
-/**
- * The current compatibility version of the chreWifiRangingEvent structure,
- * including nested structures.
- */
-#define CHRE_WIFI_RANGING_EVENT_VERSION UINT8_C(0)
-
-/**
- * Maximum number of frequencies that can be explicitly specified when
- * requesting a scan
- * @see #chreWifiScanParams
- */
-#define CHRE_WIFI_FREQUENCY_LIST_MAX_LEN (20)
-
-/**
- * Maximum number of SSIDs that can be explicitly specified when requesting a
- * scan
- * @see #chreWifiScanParams
- */
-#define CHRE_WIFI_SSID_LIST_MAX_LEN (20)
-
-/**
- * The maximum number of devices that can be specified in a single RTT ranging
- * request.
- * @see #chreWifiRangingParams
- */
-#define CHRE_WIFI_RANGING_LIST_MAX_LEN (10)
-
-/**
- * The maximum number of octets in an SSID (see 802.11 7.3.2.1)
- */
-#define CHRE_WIFI_SSID_MAX_LEN (32)
-
-/**
- * The number of octets in a BSSID (see 802.11 7.1.3.3.3)
- */
-#define CHRE_WIFI_BSSID_LEN (6)
-
-/**
- * Set of flags which can either indicate a frequency band. Specified as a bit
- * mask to allow for combinations in future API versions.
- * @defgroup CHRE_WIFI_BAND_MASK
- * @{
- */
-
-#define CHRE_WIFI_BAND_MASK_2_4_GHZ UINT8_C(1 << 0) //!< 2.4 GHz
-#define CHRE_WIFI_BAND_MASK_5_GHZ UINT8_C(1 << 1) //!< 5 GHz
-
-/** @} */
-
-/**
- * Characteristics of a scanned device given in struct chreWifiScanResult.flags
- * @defgroup CHRE_WIFI_SCAN_RESULT_FLAGS
- * @{
- */
-
-#define CHRE_WIFI_SCAN_RESULT_FLAGS_NONE UINT8_C(0)
-
-//! Element ID 61 (HT Operation) is present (see HT 7.3.2)
-#define CHRE_WIFI_SCAN_RESULT_FLAGS_HT_OPS_PRESENT UINT8_C(1 << 0)
-
-//! Element ID 192 (VHT Operation) is present (see VHT 8.4.2)
-#define CHRE_WIFI_SCAN_RESULT_FLAGS_VHT_OPS_PRESENT UINT8_C(1 << 1)
-
-//! Element ID 127 (Extended Capabilities) is present, and bit 70 (Fine Timing
-//! Measurement Responder) is set to 1 (see IEEE Std 802.11-2016 9.4.2.27)
-#define CHRE_WIFI_SCAN_RESULT_FLAGS_IS_FTM_RESPONDER UINT8_C(1 << 2)
-
-//! Retained for backwards compatibility
-//! @see CHRE_WIFI_SCAN_RESULT_FLAGS_IS_FTM_RESPONDER
-#define CHRE_WIFI_SCAN_RESULT_FLAGS_IS_80211MC_RTT_RESPONDER \
- CHRE_WIFI_SCAN_RESULT_FLAGS_IS_FTM_RESPONDER
-
-//! HT Operation element indicates that a secondary channel is present
-//! (see HT 7.3.2.57)
-#define CHRE_WIFI_SCAN_RESULT_FLAGS_HAS_SECONDARY_CHANNEL_OFFSET UINT8_C(1 << 3)
-
-//! HT Operation element indicates that the secondary channel is below the
-//! primary channel (see HT 7.3.2.57)
-#define CHRE_WIFI_SCAN_RESULT_FLAGS_SECONDARY_CHANNEL_OFFSET_IS_BELOW \
- UINT8_C(1 << 4)
-
-/** @} */
-
-/**
- * Identifies the authentication methods supported by an AP. Note that not every
- * combination of flags may be possible. Based on WIFI_PNO_AUTH_CODE_* from
- * hardware/libhardware_legacy/include/hardware_legacy/gscan.h in Android.
- * @defgroup CHRE_WIFI_SECURITY_MODE_FLAGS
- * @{
- */
-
-#define CHRE_WIFI_SECURITY_MODE_UNKONWN UINT8_C(0)
-
-#define CHRE_WIFI_SECURITY_MODE_OPEN UINT8_C(1 << 0) //!< No auth/security
-#define CHRE_WIFI_SECURITY_MODE_WEP UINT8_C(1 << 1)
-#define CHRE_WIFI_SECURITY_MODE_PSK UINT8_C(1 << 2) //!< WPA-PSK or WPA2-PSK
-#define CHRE_WIFI_SECURITY_MODE_EAP UINT8_C(1 << 3) //!< Any type of EAPOL
-
-/** @} */
-
-/**
- * Identifies which radio chain was used to discover an AP. The underlying
- * hardware does not necessarily support more than one radio chain.
- * @defgroup CHRE_WIFI_RADIO_CHAIN_FLAGS
- * @{
- */
-
-#define CHRE_WIFI_RADIO_CHAIN_UNKNOWN UINT8_C(0)
-#define CHRE_WIFI_RADIO_CHAIN_0 UINT8_C(1 << 0)
-#define CHRE_WIFI_RADIO_CHAIN_1 UINT8_C(1 << 1)
-
-/** @} */
-
-//! Special value indicating that an LCI uncertainty fields is not provided
-//! Ref: RFC 6225
-#define CHRE_WIFI_LCI_UNCERTAINTY_UNKNOWN UINT8_C(0)
-
-/**
- * Defines the flags that may be returned in
- * {@link #chreWifiRangingResult.flags}. Undefined bits are reserved for future
- * use and must be ignored by nanoapps.
- * @defgroup CHRE_WIFI_RTT_RESULT_FLAGS
- * @{
- */
-
-//! If set, the nested chreWifiLci structure is populated; otherwise it is
-//! invalid and must be ignored
-#define CHRE_WIFI_RTT_RESULT_HAS_LCI UINT8_C(1 << 0)
-
-/** @} */
-
-/**
- * Identifies a WiFi frequency band
- */
-enum chreWifiBand {
- CHRE_WIFI_BAND_2_4_GHZ = CHRE_WIFI_BAND_MASK_2_4_GHZ,
- CHRE_WIFI_BAND_5_GHZ = CHRE_WIFI_BAND_MASK_5_GHZ,
-};
-
-/**
- * Indicates the BSS operating channel width determined from the VHT and/or HT
- * Operation elements. Refer to VHT 8.4.2.161 and HT 7.3.2.57.
- */
-enum chreWifiChannelWidth {
- CHRE_WIFI_CHANNEL_WIDTH_20_MHZ = 0,
- CHRE_WIFI_CHANNEL_WIDTH_40_MHZ = 1,
- CHRE_WIFI_CHANNEL_WIDTH_80_MHZ = 2,
- CHRE_WIFI_CHANNEL_WIDTH_160_MHZ = 3,
- CHRE_WIFI_CHANNEL_WIDTH_80_PLUS_80_MHZ = 4,
-};
-
-/**
- * Indicates the type of scan requested or performed
- */
-enum chreWifiScanType {
- //! Perform a purely active scan using probe requests. Do not scan channels
- //! restricted to use via Dynamic Frequency Selection (DFS) only.
- CHRE_WIFI_SCAN_TYPE_ACTIVE = 0,
-
- //! Perform an active scan on unrestricted channels, and also perform a
- //! passive scan on channels that are restricted to use via Dynamic
- //! Frequency Selection (DFS), e.g. the U-NIII bands 5250-5350MHz and
- //! 5470-5725MHz in the USA as mandated by FCC regulation.
- CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS = 1,
-
- //! Perform a passive scan, only listening for beacons.
- CHRE_WIFI_SCAN_TYPE_PASSIVE = 2,
-};
-
-/**
- * Indicates whether RTT ranging with a specific device succeeded
- */
-enum chreWifiRangingStatus {
- //! Ranging completed successfully
- CHRE_WIFI_RANGING_STATUS_SUCCESS = 0,
-
- //! Ranging failed due to an unspecified error
- CHRE_WIFI_RANGING_STATUS_ERROR = 1,
-};
-
-/**
- * Possible values for {@link #chreWifiLci.altitudeType}. Ref: RFC 6225 2.4
- */
-enum chreWifiLciAltitudeType {
- CHRE_WIFI_LCI_ALTITUDE_TYPE_UNKNOWN = 0,
- CHRE_WIFI_LCI_ALTITUDE_TYPE_METERS = 1,
- CHRE_WIFI_LCI_ALTITUDE_TYPE_FLOORS = 2,
-};
-
-/**
- * Indicates a type of request made in this API. Used to populate the resultType
- * field of struct chreAsyncResult sent with CHRE_EVENT_WIFI_ASYNC_RESULT.
- */
-enum chreWifiRequestType {
- CHRE_WIFI_REQUEST_TYPE_CONFIGURE_SCAN_MONITOR = 1,
- CHRE_WIFI_REQUEST_TYPE_REQUEST_SCAN = 2,
- CHRE_WIFI_REQUEST_TYPE_RANGING = 3,
-};
-
-/**
- * Allows a nanoapp to express its preference for how multiple available
- * radio chains should be used when performing an on-demand scan. This is only a
- * preference from the nanoapp and is not guaranteed to be honored by the WiFi
- * firmware.
- */
-enum chreWifiRadioChainPref {
- //! No preference for radio chain usage
- CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT = 0,
-
- //! In a scan result, indicates that the radio chain preference used for the
- //! scan is not known
- CHRE_WIFI_RADIO_CHAIN_PREF_UNKNOWN = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT,
-
- //! Prefer to use available radio chains in a way that minimizes time to
- //! complete the scan
- CHRE_WIFI_RADIO_CHAIN_PREF_LOW_LATENCY = 1,
-
- //! Prefer to use available radio chains in a way that minimizes total power
- //! consumed for the scan
- CHRE_WIFI_RADIO_CHAIN_PREF_LOW_POWER = 2,
-
- //! Prefer to use available radio chains in a way that maximizes accuracy of
- //! the scan result, e.g. RSSI measurements
- CHRE_WIFI_RADIO_CHAIN_PREF_HIGH_ACCURACY = 3,
-};
-
-/**
- * SSID with an explicit length field, used when an array of SSIDs is supplied.
- */
-struct chreWifiSsidListItem {
- //! Number of valid bytes in ssid. Valid range [0, CHRE_WIFI_SSID_MAX_LEN]
- uint8_t ssidLen;
-
- //! Service Set Identifier (SSID)
- uint8_t ssid[CHRE_WIFI_SSID_MAX_LEN];
-};
-
-/**
- * Data structure passed to chreWifiRequestScanAsync
- */
-struct chreWifiScanParams {
- //! Set to a value from enum chreWifiScanType
- uint8_t scanType;
-
- //! Indicates whether the client is willing to tolerate receiving cached
- //! results of a previous scan, and if so, the maximum age of the scan that
- //! the client will accept. "Age" in this case is defined as the elapsed
- //! time between when the most recent scan was completed and the request is
- //! received, in milliseconds. If set to 0, no cached results may be
- //! provided, and all scan results must come from a "fresh" WiFi scan, i.e.
- //! one that completes strictly after this request is received. If more than
- //! one scan is cached and meets this age threshold, only the newest scan is
- //! provided.
- uint32_t maxScanAgeMs;
-
- //! If set to 0, scan all frequencies. Otherwise, this indicates the number
- //! of frequencies to scan, as specified in the frequencyList array. Valid
- //! range [0, CHRE_WIFI_FREQUENCY_LIST_MAX_LEN].
- uint16_t frequencyListLen;
-
- //! Pointer to an array of frequencies to scan, given as channel center
- //! frequencies in MHz. This field may be NULL if frequencyListLen is 0.
- const uint32_t *frequencyList;
-
- //! If set to 0, do not restrict scan to any SSIDs. Otherwise, this
- //! indicates the number of SSIDs in the ssidList array to be used for
- //! directed probe requests. Not applicable and ignore when scanType is
- //! CHRE_WIFI_SCAN_TYPE_PASSIVE.
- uint8_t ssidListLen;
-
- //! Pointer to an array of SSIDs to use for directed probe requests. May be
- //! NULL if ssidListLen is 0.
- const struct chreWifiSsidListItem *ssidList;
-
- //! Set to a value from enum chreWifiRadioChainPref to specify the desired
- //! trade-off between power consumption, accuracy, etc. If
- //! chreWifiGetCapabilities() does not have the applicable bit set, this
- //! parameter is ignored.
- //! @since v1.2
- uint8_t radioChainPref;
-};
-
-/**
- * Provides information about a single access point (AP) detected in a scan.
- */
-struct chreWifiScanResult {
- //! Number of milliseconds prior to referenceTime in the enclosing
- //! chreWifiScanEvent struct when the probe response or beacon frame that
- //! was used to populate this structure was received.
- uint32_t ageMs;
-
- //! Capability Information field sent by the AP (see 802.11 7.3.1.4). This
- //! field must reflect native byte order and bit ordering, such that
- //! (capabilityInfo & 1) gives the bit for the ESS subfield.
- uint16_t capabilityInfo;
-
- //! Number of valid bytes in ssid. Valid range [0, CHRE_WIFI_SSID_MAX_LEN]
- uint8_t ssidLen;
-
- //! Service Set Identifier (SSID), a series of 0 to 32 octets identifying
- //! the access point. Note that this is commonly a human-readable ASCII
- //! string, but this is not the required encoding per the standard.
- uint8_t ssid[CHRE_WIFI_SSID_MAX_LEN];
-
- //! Basic Service Set Identifier (BSSID), represented in big-endian byte
- //! order, such that the first octet of the OUI is accessed in byte index 0.
- uint8_t bssid[CHRE_WIFI_BSSID_LEN];
-
- //! A set of flags from CHRE_WIFI_SCAN_RESULT_FLAGS_*
- uint8_t flags;
-
- //! RSSI (Received Signal Strength Indicator), in dBm. Typically negative.
- //! If multiple radio chains were used to scan this AP, this is a "best
- //! available" measure that may be a composite of measurements taken across
- //! the radio chains.
- int8_t rssi;
-
- //! Operating band, set to a value from enum chreWifiBand
- uint8_t band;
-
- /**
- * Indicates the center frequency of the primary 20MHz channel, given in
- * MHz. This value is derived from the channel number via the formula:
- *
- * primaryChannel (MHz) = CSF + 5 * primaryChannelNumber
- *
- * Where CSF is the channel starting frequency (in MHz) given by the
- * operating class/band (i.e. 2407 or 5000), and primaryChannelNumber is the
- * channel number in the range [1, 200].
- *
- * Refer to VHT 22.3.14.
- */
- uint32_t primaryChannel;
-
- /**
- * If the channel width is 20 MHz, this field is not relevant and set to 0.
- * If the channel width is 40, 80, or 160 MHz, then this denotes the channel
- * center frequency (in MHz). If the channel is 80+80 MHz, then this denotes
- * the center frequency of segment 0, which contains the primary channel.
- * This value is derived from the frequency index using the same formula as
- * for primaryChannel.
- *
- * Refer to VHT 8.4.2.161, and VHT 22.3.14.
- *
- * @see #primaryChannel
- */
- uint32_t centerFreqPrimary;
-
- /**
- * If the channel width is 80+80MHz, then this denotes the center frequency
- * of segment 1, which does not contain the primary channel. Otherwise, this
- * field is not relevant and set to 0.
- *
- * @see #centerFreqPrimary
- */
- uint32_t centerFreqSecondary;
-
- //! @see #chreWifiChannelWidth
- uint8_t channelWidth;
-
- //! Flags from CHRE_WIFI_SECURITY_MODE_* indicating supported authentication
- //! and associated security modes
- //! @see CHRE_WIFI_SECURITY_MODE_FLAGS
- uint8_t securityMode;
-
- //! Identifies the radio chain(s) used to discover this AP
- //! @see CHRE_WIFI_RADIO_CHAIN_FLAGS
- //! @since v1.2
- uint8_t radioChain;
-
- //! If the CHRE_WIFI_RADIO_CHAIN_0 bit is set in radioChain, gives the RSSI
- //! measured on radio chain 0 in dBm; otherwise invalid and set to 0. This
- //! field, along with its relative rssiChain1, can be used to determine RSSI
- //! measurements from each radio chain when multiple chains were used to
- //! discover this AP.
- //! @see #radioChain
- //! @since v1.2
- int8_t rssiChain0;
- int8_t rssiChain1; //!< @see #rssiChain0
-
- //! Reserved; set to 0
- uint8_t reserved[7];
-};
-
-/**
- * Data structure sent with events of type CHRE_EVENT_WIFI_SCAN_RESULT.
- */
-struct chreWifiScanEvent {
- //! Indicates the version of the structure, for compatibility purposes.
- //! Clients do not normally need to worry about this field; the CHRE
- //! implementation guarantees that the client only receives the structure
- //! version it expects.
- uint8_t version;
-
- //! The number of entries in the results array in this event. The CHRE
- //! implementation may split scan results across multiple events for memory
- //! concerns, etc.
- uint8_t resultCount;
-
- //! The total number of results returned by the scan. Allows an event
- //! consumer to identify when it has received all events associated with a
- //! scan.
- uint8_t resultTotal;
-
- //! Sequence number for this event within the series of events comprising a
- //! complete scan result. Scan events are delivered strictly in order, i.e.
- //! this is monotonically increasing for the results of a single scan. Valid
- //! range [0, <number of events for scan> - 1]. The number of events for a
- //! scan is typically given by
- //! ceil(resultTotal / <max results per event supported by platform>).
- uint8_t eventIndex;
-
- //! A value from enum chreWifiScanType indicating the type of scan performed
- uint8_t scanType;
-
- //! If a directed scan was performed to a limited set of SSIDs, then this
- //! identifies the number of unique SSIDs included in the probe requests.
- //! Otherwise, this is set to 0, indicating that the scan was not limited by
- //! SSID. Note that if this is non-zero, the list of SSIDs used is not
- //! included in the scan event.
- uint8_t ssidSetSize;
-
- //! If 0, indicates that all frequencies applicable for the scanType were
- //! scanned. Otherwise, indicates the number of frequencies scanned, as
- //! specified in scannedFreqList.
- uint16_t scannedFreqListLen;
-
- //! Timestamp when the scan was completed, from the same time base as
- //! chreGetTime() (in nanoseconds)
- uint64_t referenceTime;
-
- //! Pointer to an array containing scannedFreqListLen values comprising the
- //! set of frequencies that were scanned. Frequencies are specified as
- //! channel center frequencies in MHz. May be NULL if scannedFreqListLen is
- //! 0.
- const uint32_t *scannedFreqList;
-
- //! Pointer to an array containing resultCount entries. May be NULL if
- //! resultCount is 0.
- const struct chreWifiScanResult *results;
-
- //! Set to a value from enum chreWifiRadioChainPref indicating the radio
- //! chain preference used for the scan. If the applicable bit is not set in
- //! chreWifiGetCapabilities(), this will always be set to
- //! CHRE_WIFI_RADIO_CHAIN_PREF_UNKNOWN.
- //! @since v1.2
- uint8_t radioChainPref;
-};
-
-/**
- * Identifies a device to perform RTT ranging against. These values are normally
- * populated based on the contents of a scan result.
- * @see #chreWifiScanResult
- * @see chreWifiRangingTargetFromScanResult()
- */
-struct chreWifiRangingTarget {
- //! Device MAC address, specified in the same byte order as
- //! {@link #chreWifiScanResult.bssid}
- uint8_t macAddress[CHRE_WIFI_BSSID_LEN];
-
- //! Center frequency of the primary 20MHz channel, in MHz
- //! @see #chreWifiScanResult.primaryChannel
- uint32_t primaryChannel;
-
- //! Channel center frequency, in MHz, or 0 if not relevant
- //! @see #chreWifiScanResult.centerFreqPrimary
- uint32_t centerFreqPrimary;
-
- //! Channel center frequency of segment 1 if channel width is 80+80MHz,
- //! otherwise 0
- //! @see #chreWifiScanResult.centerFreqSecondary
- uint32_t centerFreqSecondary;
-
- //! @see #chreWifiChannelWidth
- uint8_t channelWidth;
-
- //! Reserved for future use and ignored by CHRE
- uint8_t reserved[3];
-};
-
-/**
- * Parameters for an RTT ("Fine Timing Measurement" in terms of 802.11-2016)
- * ranging request, supplied to chreWifiRequestRangingAsync().
- */
-struct chreWifiRangingParams {
- //! Number of devices to perform ranging against and the length of
- //! targetList, in range [1, CHRE_WIFI_RANGING_LIST_MAX_LEN]
- uint8_t targetListLen;
-
- //! Array of macAddressListLen MAC addresses (e.g. BSSIDs) with which to
- //! attempt RTT ranging
- const struct chreWifiRangingTarget *targetList;
-};
-
-/**
- * Provides the result of RTT ranging with a single device.
- */
-struct chreWifiRangingResult {
- //! Time when the ranging operation on this device was performed, in the
- //! same time base as chreGetTime() (in nanoseconds)
- uint64_t timestamp;
-
- //! MAC address of the device for which ranging was requested
- uint8_t macAddress[CHRE_WIFI_BSSID_LEN];
-
- //! Gives the result of ranging to this device. If not set to
- //! CHRE_WIFI_RANGING_STATUS_SUCCESS, the ranging attempt to this device
- //! failed, and other fields in this structure may be invalid.
- //! @see #chreWifiRangingStatus
- uint8_t status;
-
- //! The mean RSSI measured during the RTT burst, in dBm. Typically negative.
- //! If status is not CHRE_WIFI_RANGING_STATUS_SUCCESS, will be set to 0.
- int8_t rssi;
-
- //! Estimated distance to the device with the given BSSID, in millimeters.
- //! Generally the mean of multiple measurements performed in a single burst.
- //! If status is not CHRE_WIFI_RANGING_STATUS_SUCCESS, will be set to 0.
- uint32_t distance;
-
- //! Standard deviation of estimated distance across multiple measurements
- //! performed in a single RTT burst, in millimeters. If status is not
- //! CHRE_WIFI_RANGING_STATUS_SUCCESS, will be set to 0.
- uint32_t distanceStdDev;
-
- //! Location Configuration Information (LCI) information optionally returned
- //! during the ranging procedure. Only valid if {@link #flags} has the
- //! CHRE_WIFI_RTT_RESULT_HAS_LCI bit set. Refer to IEEE 802.11-2016
- //! 9.4.2.22.10, 11.24.6.7, and RFC 6225 (July 2011) for more information.
- //! Coordinates are to be interpreted according to the WGS84 datum.
- struct chreWifiLci {
- //! Latitude in degrees as 2's complement fixed-point with 25 fractional
- //! bits, i.e. degrees * 2^25. Ref: RFC 6225 2.3
- int64_t latitude;
-
- //! Longitude, same format as {@link #latitude}
- int64_t longitude;
-
- //! Altitude represented as a 2's complement fixed-point value with 8
- //! fractional bits. Interpretation depends on {@link #altitudeType}. If
- //! UNKNOWN, this field must be ignored. If *METERS, distance relative
- //! to the zero point in the vertical datum. If *FLOORS, a floor value
- //! relative to the ground floor, potentially fractional, e.g. to
- //! indicate mezzanine levels. Ref: RFC 6225 2.4
- int32_t altitude;
-
- //! Maximum extent of latitude uncertainty in degrees, decoded via this
- //! formula: 2 ^ (8 - x) where "x" is the encoded value passed in this
- //! field. Unknown if set to CHRE_WIFI_LCI_UNCERTAINTY_UNKNOWN.
- //! Ref: RFC 6225 2.3.2
- uint8_t latitudeUncertainty;
-
- //! @see #latitudeUncertainty
- uint8_t longitudeUncertainty;
-
- //! Defines how to interpret altitude, set to a value from enum
- //! chreWifiLciAltitudeType
- uint8_t altitudeType;
-
- //! Uncertainty in altitude, decoded via this formula: 2 ^ (21 - x)
- //! where "x" is the encoded value passed in this field. Unknown if set
- //! to CHRE_WIFI_LCI_UNCERTAINTY_UNKNOWN. Only applies when altitudeType
- //! is CHRE_WIFI_LCI_ALTITUDE_TYPE_METERS. Ref: RFC 6225 2.4.5
- uint8_t altitudeUncertainty;
- } lci;
-
- //! Refer to CHRE_WIFI_RTT_RESULT_FLAGS
- uint8_t flags;
-
- //! Reserved; set to 0
- uint8_t reserved[7];
-};
-
-/**
- * Data structure sent with events of type CHRE_EVENT_WIFI_RANGING_RESULT.
- */
-struct chreWifiRangingEvent {
- //! Indicates the version of the structure, for compatibility purposes.
- //! Clients do not normally need to worry about this field; the CHRE
- //! implementation guarantees that the client only receives the structure
- //! version it expects.
- uint8_t version;
-
- //! The number of ranging results included in the results array; matches the
- //! number of MAC addresses specified in the request
- uint8_t resultCount;
-
- //! Reserved; set to 0
- uint8_t reserved[2];
-
- //! Pointer to an array containing resultCount entries
- const struct chreWifiRangingResult *results;
-};
-
-
-/**
- * Retrieves a set of flags indicating the WiFi features supported by the
- * current CHRE implementation. The value returned by this function must be
- * consistent for the entire duration of the Nanoapp's execution.
- *
- * The client must allow for more flags to be set in this response than it knows
- * about, for example if the implementation supports a newer version of the API
- * than the client was compiled against.
- *
- * @return A bitmask with zero or more CHRE_WIFI_CAPABILITIES_* flags set
- *
- * @since v1.1
- */
-uint32_t chreWifiGetCapabilities(void);
-
-/**
- * Manages a client's request to receive the results of WiFi scans performed for
- * other purposes, for example scans done to maintain connectivity and scans
- * requested by other clients. The presence of this request has no effect on the
- * frequency or configuration of the WiFi scans performed - it is purely a
- * registration by the client to receive the results of scans that would
- * otherwise occur normally. This should include all available scan results,
- * including those that are not normally sent to the applications processor,
- * such as Preferred Network Offload (PNO) scans. Scan results provided because
- * of this registration must not contain cached results - they are always
- * expected to contain the fresh results from a recent scan.
- *
- * An active scan monitor subscription must persist across temporary conditions
- * under which no WiFi scans will be performed, for example if WiFi is
- * completely disabled via user-controlled settings, or if the WiFi system
- * restarts independently of CHRE. Likewise, a request to enable a scan monitor
- * subscription must succeed under normal conditions, even in circumstances
- * where no WiFi scans will be performed. In these cases, the scan monitor
- * implementation must produce scan results once the temporary condition is
- * cleared, for example after WiFi is enabled by the user.
- *
- * These scan results are delivered to the Nanoapp's handle event callback using
- * CHRE_EVENT_WIFI_SCAN_RESULT.
- *
- * An active scan monitor subscription is not necessary to receive the results
- * of an on-demand scan request sent via chreWifiRequestScanAsync(), and it does
- * not result in duplicate delivery of scan results generated from
- * chreWifiRequestScanAsync().
- *
- * If no monitor subscription is active at the time of a request with
- * enable=false, it is treated as if an active subscription was successfully
- * ended.
- *
- * The result of this request is delivered asynchronously via an event of type
- * CHRE_EVENT_WIFI_ASYNC_RESULT. Refer to the note in {@link #chreAsyncResult}
- * for more details.
- *
- * @param enable Set to true to enable monitoring scan results, false to
- * disable
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.1
- */
-bool chreWifiConfigureScanMonitorAsync(bool enable, const void *cookie);
-
-/**
- * Sends an on-demand request for WiFi scan results. This may trigger a new
- * scan, or be entirely serviced from cache, depending on the maxScanAgeMs
- * parameter.
- *
- * This resulting status of this request is delivered asynchronously via an
- * event of type CHRE_EVENT_WIFI_ASYNC_RESULT. The result must be delivered
- * within CHRE_WIFI_SCAN_RESULT_TIMEOUT_NS of the this request. Refer to the
- * note in {@link #chreAsyncResult} for more details.
- *
- * A successful result provided in CHRE_EVENT_WIFI_ASYNC_RESULT indicates that
- * the scan results are ready to be delivered in a subsequent event (or events,
- * which arrive consecutively without any other scan results in between)
- * of type CHRE_EVENT_WIFI_SCAN_RESULT.
- *
- * WiFi scanning must be disabled if both "WiFi scanning" and "WiFi" settings are
- * disabled at the Android level. In this case, the CHRE implementation is
- * expected to return a result with CHRE_ERROR_FUNCTION_DISABLED.
- *
- * It is not valid for a client to request a new scan while a result is pending
- * based on a previous scan request from the same client. In this situation, the
- * CHRE implementation is expected to return a result with CHRE_ERROR_BUSY.
- * However, if a scan is currently pending or in progress due to a request from
- * another client, whether within the CHRE or otherwise, the implementation must
- * not fail the request for this reason. If the pending scan satisfies the
- * client's request parameters, then the implementation should use its results
- * to satisfy the request rather than scheduling a new scan.
- *
- * @param params A set of parameters for the scan request. Must not be NULL.
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.1
- */
-bool chreWifiRequestScanAsync(const struct chreWifiScanParams *params,
- const void *cookie);
-
-/**
- * Convenience function which calls chreWifiRequestScanAsync() with a default
- * set of scan parameters.
- *
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.1
- */
-static inline bool chreWifiRequestScanAsyncDefault(const void *cookie) {
- struct chreWifiScanParams params = {};
- params.scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE;
- params.maxScanAgeMs = 5000; // 5 seconds
- params.frequencyListLen = 0;
- params.ssidListLen = 0;
- params.radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT;
- return chreWifiRequestScanAsync(&params, cookie);
-}
-
-/**
- * Issues a request to initiate distance measurements using round-trip time
- * (RTT), aka Fine Timing Measurement (FTM), to one or more devices identified
- * by MAC address. Within CHRE, MACs are typically the BSSIDs of scanned APs
- * that have the CHRE_WIFI_SCAN_RESULT_FLAGS_IS_FTM_RESPONDER flag set.
- *
- * This resulting status of this request is delivered asynchronously via an
- * event of type CHRE_EVENT_WIFI_ASYNC_RESULT. The result must be delivered
- * within CHRE_WIFI_RANGING_RESULT_TIMEOUT_NS of the this request. Refer to the
- * note in {@link #chreAsyncResult} for more details.
- *
- * WiFi RTT ranging must be disabled if any of the following is true:
- * - Both "WiFi" and "WiFi Scanning" settings are disabled at the Android level.
- * - The "Location" setting is disabled at the Android level.
- * In this case, the CHRE implementation is expected to return a result with
- * CHRE_ERROR_FUNCTION_DISABLED.
- *
- * A successful result provided in CHRE_EVENT_WIFI_ASYNC_RESULT indicates that
- * the results of ranging will be delivered in a subsequent event of type
- * CHRE_EVENT_WIFI_RANGING_RESULT. Note that the CHRE_EVENT_WIFI_ASYNC_RESULT
- * gives an overall status - for example, it is used to indicate failure if the
- * entire ranging request was rejected because WiFi is disabled. However, it is
- * valid for this event to indicate success, but RTT ranging to fail for all
- * requested devices - for example, they may be out of range. Therefore, it is
- * also necessary to check the status field in {@link #chreWifiRangingResult}.
- *
- * @param params Structure containing the parameters of the scan request,
- * including the list of devices to attempt ranging.
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.2
- */
-bool chreWifiRequestRangingAsync(const struct chreWifiRangingParams *params,
- const void *cookie);
-
-/**
- * Helper function to populate an instance of struct chreWifiRangingTarget with
- * the contents of a scan result provided in struct chreWifiScanResult.
- * Populates other parameters that are not directly derived from the scan result
- * with default values.
- *
- * @param scanResult The scan result to parse as input
- * @param rangingTarget The RTT ranging target to populate as output
- */
-static inline void chreWifiRangingTargetFromScanResult(
- const struct chreWifiScanResult *scanResult,
- struct chreWifiRangingTarget *rangingTarget) {
- memcpy(rangingTarget->macAddress, scanResult->bssid,
- sizeof(rangingTarget->macAddress));
- rangingTarget->primaryChannel = scanResult->primaryChannel;
- rangingTarget->centerFreqPrimary = scanResult->centerFreqPrimary;
- rangingTarget->centerFreqSecondary = scanResult->centerFreqSecondary;
- rangingTarget->channelWidth = scanResult->channelWidth;
-
- // Note that this is not strictly necessary (CHRE can see which API version
- // the nanoapp was built against, so it knows to ignore these fields), but
- // we do it here to keep things nice and tidy
- memset(rangingTarget->reserved, 0, sizeof(rangingTarget->reserved));
-}
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_WIFI_H_ */
diff --git a/chre_api/legacy/v1_4/chre/wwan.h b/chre_api/legacy/v1_4/chre/wwan.h
deleted file mode 100644
index 03f7ab59..00000000
--- a/chre_api/legacy/v1_4/chre/wwan.h
+++ /dev/null
@@ -1,569 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 _CHRE_WWAN_H_
-#define _CHRE_WWAN_H_
-
-/**
- * @file
- * Wireless Wide Area Network (WWAN, i.e. mobile/cellular network) API relevant
- * for querying cell tower identity and associated information that can be
- * useful in determining location.
- *
- * Based on Android N RIL definitions (located at this path as of the time of
- * this comment: hardware/ril/include/telephony/ril.h), version 12. Updated
- * based on Android radio HAL definition (hardware/interfaces/radio) for more
- * recent Android builds. Refer to those files and associated documentation for
- * further details.
- *
- * In general, the parts of this API that are taken from the RIL follow the
- * field naming conventions established in that interface rather than the CHRE
- * API conventions, in order to avoid confusion and enable code re-use where
- * applicable. Note that structure names include the chreWwan* prefix rather
- * than RIL_*, but field names are the same. If necessary to enable code
- * sharing, it is recommended to create typedefs that map from the CHRE
- * structures to the associated RIL type names, for example "typedef struct
- * chreWwanCellIdentityGsm RIL_CellIdentityGsm_v12", etc.
- */
-
-#include <chre/common.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * The set of flags returned by chreWwanGetCapabilities().
- * @defgroup CHRE_WWAN_CAPABILITIES
- * @{
- */
-
-//! No WWAN APIs are supported
-#define CHRE_WWAN_CAPABILITIES_NONE UINT32_C(0)
-
-//! Current cell information can be queried via chreWwanGetCellInfoAsync()
-#define CHRE_WWAN_GET_CELL_INFO UINT32_C(1 << 0)
-
-/** @} */
-
-/**
- * Produce an event ID in the block of IDs reserved for WWAN
- * @param offset Index into WWAN event ID block; valid range [0,15]
- */
-#define CHRE_WWAN_EVENT_ID(offset) (CHRE_EVENT_WWAN_FIRST_EVENT + (offset))
-
-/**
- * nanoappHandleEvent argument: struct chreWwanCellInfoResult
- *
- * Provides the result of an asynchronous request for cell info sent via
- * chreWwanGetCellInfoAsync().
- */
-#define CHRE_EVENT_WWAN_CELL_INFO_RESULT CHRE_WWAN_EVENT_ID(0)
-
-// NOTE: Do not add new events with ID > 15; only values 0-15 are reserved
-// (see chre/event.h)
-
-/**
- * The current version of struct chreWwanCellInfoResult associated with this
- * API definition.
- */
-#define CHRE_WWAN_CELL_INFO_RESULT_VERSION UINT8_C(1)
-
-//! Reference: RIL_CellIdentityGsm_v12
-struct chreWwanCellIdentityGsm {
- //! 3-digit Mobile Country Code, 0..999, INT32_MAX if unknown
- int32_t mcc;
-
- //! 2 or 3-digit Mobile Network Code, 0..999, INT32_MAX if unknown
- int32_t mnc;
-
- //! 16-bit Location Area Code, 0..65535, INT32_MAX if unknown
- int32_t lac;
-
- //! 16-bit GSM Cell Identity described in TS 27.007, 0..65535,
- //! INT32_MAX if unknown
- int32_t cid;
-
- //! 16-bit GSM Absolute RF channel number, INT32_MAX if unknown
- int32_t arfcn;
-
- //! 6-bit Base Station Identity Code, UINT8_MAX if unknown
- uint8_t bsic;
-
- //! Reserved for future use; must be set to 0
- uint8_t reserved[3];
-};
-
-//! Reference: RIL_CellIdentityWcdma_v12
-struct chreWwanCellIdentityWcdma {
- //! 3-digit Mobile Country Code, 0..999, INT32_MAX if unknown
- int32_t mcc;
-
- //! 2 or 3-digit Mobile Network Code, 0..999, INT32_MAX if unknown
- int32_t mnc;
-
- //! 16-bit Location Area Code, 0..65535, INT32_MAX if unknown
- int32_t lac;
-
- //! 28-bit UMTS Cell Identity described in TS 25.331, 0..268435455,
- //! INT32_MAX if unknown
- int32_t cid;
-
- //! 9-bit UMTS Primary Scrambling Code described in TS 25.331, 0..511,
- //! INT32_MAX if unknown
- int32_t psc;
-
- //! 16-bit UMTS Absolute RF Channel Number, INT32_MAX if unknown
- int32_t uarfcn;
-};
-
-//! Reference: RIL_CellIdentityCdma
-struct chreWwanCellIdentityCdma {
- //! Network Id 0..65535, INT32_MAX if unknown
- int32_t networkId;
-
- //! CDMA System Id 0..32767, INT32_MAX if unknown
- int32_t systemId;
-
- //! Base Station Id 0..65535, INT32_MAX if unknown
- int32_t basestationId;
-
- //! Longitude is a decimal number as specified in 3GPP2 C.S0005-A v6.0.
- //! It is represented in units of 0.25 seconds and ranges from -2592000
- //! to 2592000, both values inclusive (corresponding to a range of -180
- //! to +180 degrees). INT32_MAX if unknown
- int32_t longitude;
-
- //! Latitude is a decimal number as specified in 3GPP2 C.S0005-A v6.0.
- //! It is represented in units of 0.25 seconds and ranges from -1296000
- //! to 1296000, both values inclusive (corresponding to a range of -90
- //! to +90 degrees). INT32_MAX if unknown
- int32_t latitude;
-};
-
-//! Reference: RIL_CellIdentityLte_v12
-struct chreWwanCellIdentityLte {
- //! 3-digit Mobile Country Code, 0..999, INT32_MAX if unknown
- int32_t mcc;
-
- //! 2 or 3-digit Mobile Network Code, 0..999, INT32_MAX if unknown
- int32_t mnc;
-
- //! 28-bit Cell Identity described in TS ???, INT32_MAX if unknown
- int32_t ci;
-
- //! physical cell id 0..503, INT32_MAX if unknown
- int32_t pci;
-
- //! 16-bit tracking area code, INT32_MAX if unknown
- int32_t tac;
-
- //! 18-bit LTE Absolute RF Channel Number, INT32_MAX if unknown
- int32_t earfcn;
-};
-
-//! Reference: RIL_CellIdentityTdscdma
-struct chreWwanCellIdentityTdscdma {
- //! 3-digit Mobile Country Code, 0..999, INT32_MAX if unknown
- int32_t mcc;
-
- //! 2 or 3-digit Mobile Network Code, 0..999, INT32_MAX if unknown
- int32_t mnc;
-
- //! 16-bit Location Area Code, 0..65535, INT32_MAX if unknown
- int32_t lac;
-
- //! 28-bit UMTS Cell Identity described in TS 25.331, 0..268435455,
- //! INT32_MAX if unknown
- int32_t cid;
-
- //! 8-bit Cell Parameters ID described in TS 25.331, 0..127, INT32_MAX if
- //! unknown
- int32_t cpid;
-};
-
-//! Reference: android.hardware.radio@1.4 CellIdentityNr
-//! @since v1.4
-struct chreWwanCellIdentityNr {
- //! 3-digit Mobile Country Code, in range [0, 999]. This value must be valid
- //! for registered or camped cells. INT32_MAX means invalid/unreported.
- int32_t mcc;
-
- //! 2 or 3-digit Mobile Network Code, in range [0, 999]. This value must be
- //! valid for registered or camped cells. INT32_MAX means
- //! invalid/unreported.
- int32_t mnc;
-
- //! NR Cell Identity in range [0, 68719476735] (36 bits), which
- //! unambiguously identifies a cell within a public land mobile network
- //! (PLMN). This value must be valid for registered or camped cells.
- //! Reference: TS 38.413 section 9.3.1.7.
- //!
- //! Note: for backward compatibility reasons, the nominally int64_t nci is
- //! split into two uint32_t values, with nci0 being the least significant 4
- //! bytes. If chreWwanUnpackNrNci returns INT64_MAX, it means nci is
- //! invalid/unreported.
- //!
- //! Users are recommended to use the helper accessor chreWwanUnpackNrNci to
- //! access the nci field.
- //!
- //! @see chreWwanUnpackNrNci
- uint32_t nci0;
- uint32_t nci1;
-
- //! Physical cell id in range [0, 1007]. This value must be valid.
- //! Reference: TS 38.331 section 6.3.2.
- int32_t pci;
-
- //! 24-bit tracking area code in range [0, 16777215]. INT32_MAX means
- //! invalid/unreported.
- //! Reference: TS 38.413 section 9.3.3.10 and TS 29.571 section 5.4.2.
- int32_t tac;
-
- //! NR Absolute Radio Frequency Channel Number, in range [0, 3279165]. This
- //! value must be valid.
- //! Reference: TS 38.101-1 section 5.4.2.1 and TS 38.101-2 section 5.4.2.1.
- int32_t nrarfcn;
-};
-
-//! Reference: RIL_GSM_SignalStrength_v12
-struct chreWwanSignalStrengthGsm {
- //! Valid values are (0-31, 99) as defined in TS 27.007 8.5
- //! INT32_MAX means invalid/unreported.
- int32_t signalStrength;
-
- //! bit error rate (0-7, 99) as defined in TS 27.007 8.5
- //! INT32_MAX means invalid/unreported.
- int32_t bitErrorRate;
-
- //! Timing Advance in bit periods. 1 bit period = 48.13 us.
- //! INT32_MAX means invalid/unreported.
- int32_t timingAdvance;
-};
-
-//! Reference: RIL_SignalStrengthWcdma
-struct chreWwanSignalStrengthWcdma {
- //! Valid values are (0-31, 99) as defined in TS 27.007 8.5
- //! INT32_MAX means invalid/unreported.
- int32_t signalStrength;
-
- //! bit error rate (0-7, 99) as defined in TS 27.007 8.5
- //! INT32_MAX means invalid/unreported.
- int32_t bitErrorRate;
-};
-
-//! Reference: RIL_CDMA_SignalStrength
-struct chreWwanSignalStrengthCdma {
- //! Valid values are positive integers. This value is the actual RSSI value
- //! multiplied by -1. Example: If the actual RSSI is -75, then this
- //! response value will be 75.
- //! INT32_MAX means invalid/unreported.
- int32_t dbm;
-
- //! Valid values are positive integers. This value is the actual Ec/Io
- //! multiplied by -10. Example: If the actual Ec/Io is -12.5 dB, then this
- //! response value will be 125.
- //! INT32_MAX means invalid/unreported.
- int32_t ecio;
-};
-
-//! Reference: RIL_EVDO_SignalStrength
-struct chreWwanSignalStrengthEvdo {
- //! Valid values are positive integers. This value is the actual RSSI value
- //! multiplied by -1. Example: If the actual RSSI is -75, then this
- //! response value will be 75.
- //! INT32_MAX means invalid/unreported.
- int32_t dbm;
-
- //! Valid values are positive integers. This value is the actual Ec/Io
- //! multiplied by -10. Example: If the actual Ec/Io is -12.5 dB, then this
- //! response value will be 125.
- //! INT32_MAX means invalid/unreported.
- int32_t ecio;
-
- //! Valid values are 0-8. 8 is the highest signal to noise ratio.
- //! INT32_MAX means invalid/unreported.
- int32_t signalNoiseRatio;
-};
-
-//! Reference: RIL_LTE_SignalStrength_v8
-struct chreWwanSignalStrengthLte {
- //! Valid values are (0-31, 99) as defined in TS 27.007 8.5
- int32_t signalStrength;
-
- //! The current Reference Signal Receive Power in dBm multiplied by -1.
- //! Range: 44 to 140 dBm
- //! INT32_MAX means invalid/unreported.
- //! Reference: 3GPP TS 36.133 9.1.4
- int32_t rsrp;
-
- //! The current Reference Signal Receive Quality in dB multiplied by -1.
- //! Range: 3 to 20 dB.
- //! INT32_MAX means invalid/unreported.
- //! Reference: 3GPP TS 36.133 9.1.7
- int32_t rsrq;
-
- //! The current reference signal signal-to-noise ratio in 0.1 dB units.
- //! Range: -200 to +300 (-200 = -20.0 dB, +300 = 30dB).
- //! INT32_MAX means invalid/unreported.
- //! Reference: 3GPP TS 36.101 8.1.1
- int32_t rssnr;
-
- //! The current Channel Quality Indicator.
- //! Range: 0 to 15.
- //! INT32_MAX means invalid/unreported.
- //! Reference: 3GPP TS 36.101 9.2, 9.3, A.4
- int32_t cqi;
-
- //! timing advance in micro seconds for a one way trip from cell to device.
- //! Approximate distance can be calculated using 300m/us * timingAdvance.
- //! Range: 0 to 0x7FFFFFFE
- //! INT32_MAX means invalid/unreported.
- //! Reference: 3GPP 36.321 section 6.1.3.5
- //! also: http://www.cellular-planningoptimization.com/2010/02/timing-advance-with-calculation.html
- int32_t timingAdvance;
-};
-
-//! Reference: RIL_TD_SCDMA_SignalStrength
-struct chreWwanSignalStrengthTdscdma {
- //! The Received Signal Code Power in dBm multiplied by -1.
- //! Range : 25 to 120
- //! INT32_MAX means invalid/unreported.
- //! Reference: 3GPP TS 25.123, section 9.1.1.1
- int32_t rscp;
-};
-
-//! Reference: android.hardware.radio@1.4 NrSignalStrength
-//! @since v1.4
-struct chreWwanSignalStrengthNr {
- //! SS (second synchronization) reference signal received power in dBm
- //! multiplied by -1.
- //! Range [44, 140], INT32_MAX means invalid/unreported.
- //! Reference: TS 38.215 section 5.1.1 and TS 38.133 section 10.1.6.
- int32_t ssRsrp;
-
- //! SS reference signal received quality in 0.5 dB units.
- //! Range [-86, 41] with -86 = -43.0 dB and 41 = 20.5 dB.
- //! INT32_MAX means invalid/unreported.
- //! Reference: TS 38.215 section 5.1.3 and TS 38.133 section 10.1.11.1.
- int32_t ssRsrq;
-
- //! SS signal-to-noise and interference ratio in 0.5 dB units.
- //! Range [-46, 81] with -46 = -23.0 dB and 81 = 40.5 dB.
- //! INT32_MAX means invalid/unreported.
- //! Reference: TS 38.215 section 5.1.5 and TS 38.133 section 10.1.16.1.
- int32_t ssSinr;
-
- //! CSI reference signal received power in dBm multiplied by -1.
- //! Range [44, 140], INT32_MAX means invalid/unreported.
- //! Reference: TS 38.215 section 5.1.2 and TS 38.133 section 10.1.6.
- int32_t csiRsrp;
-
- //! CSI reference signal received quality in 0.5 dB units.
- //! Range [-86, 41] with -86 = -43.0 dB and 41 = 20.5 dB.
- //! INT32_MAX means invalid/unreported.
- //! Reference: TS 38.215 section 5.1.4 and TS 38.133 section 10.1.11.1.
- int32_t csiRsrq;
-
- //! CSI signal-to-noise and interference ratio in 0.5 dB units.
- //! Range [-46, 81] with -46 = -23.0 dB and 81 = 40.5 dB.
- //! INT32_MAX means invalid/unreported.
- //! Reference: TS 38.215 section 5.1.6 and TS 38.133 section 10.1.16.1.
- int32_t csiSinr;
-};
-
-//! Reference: RIL_CellInfoGsm_v12
-struct chreWwanCellInfoGsm {
- struct chreWwanCellIdentityGsm cellIdentityGsm;
- struct chreWwanSignalStrengthGsm signalStrengthGsm;
-};
-
-//! Reference: RIL_CellInfoWcdma_v12
-struct chreWwanCellInfoWcdma {
- struct chreWwanCellIdentityWcdma cellIdentityWcdma;
- struct chreWwanSignalStrengthWcdma signalStrengthWcdma;
-};
-
-//! Reference: RIL_CellInfoCdma
-struct chreWwanCellInfoCdma {
- struct chreWwanCellIdentityCdma cellIdentityCdma;
- struct chreWwanSignalStrengthCdma signalStrengthCdma;
- struct chreWwanSignalStrengthEvdo signalStrengthEvdo;
-};
-
-//! Reference: RIL_CellInfoLte_v12
-struct chreWwanCellInfoLte {
- struct chreWwanCellIdentityLte cellIdentityLte;
- struct chreWwanSignalStrengthLte signalStrengthLte;
-};
-
-//! Reference: RIL_CellInfoTdscdma
-struct chreWwanCellInfoTdscdma {
- struct chreWwanCellIdentityTdscdma cellIdentityTdscdma;
- struct chreWwanSignalStrengthTdscdma signalStrengthTdscdma;
-};
-
-//! Reference: android.hardware.radio@1.4 CellInfoNr
-//! @since v1.4
-struct chreWwanCellInfoNr {
- struct chreWwanCellIdentityNr cellIdentityNr;
- struct chreWwanSignalStrengthNr signalStrengthNr;
-};
-
-//! Reference: RIL_CellInfoType
-//! All other values are reserved and should be ignored by nanoapps.
-enum chreWwanCellInfoType {
- CHRE_WWAN_CELL_INFO_TYPE_GSM = 1,
- CHRE_WWAN_CELL_INFO_TYPE_CDMA = 2,
- CHRE_WWAN_CELL_INFO_TYPE_LTE = 3,
- CHRE_WWAN_CELL_INFO_TYPE_WCDMA = 4,
- CHRE_WWAN_CELL_INFO_TYPE_TD_SCDMA = 5,
- CHRE_WWAN_CELL_INFO_TYPE_NR = 6, //! @since v1.4
-};
-
-//! Reference: RIL_TimeStampType
-enum chreWwanCellTimeStampType {
- CHRE_WWAN_CELL_TIMESTAMP_TYPE_UNKNOWN = 0,
- CHRE_WWAN_CELL_TIMESTAMP_TYPE_ANTENNA = 1,
- CHRE_WWAN_CELL_TIMESTAMP_TYPE_MODEM = 2,
- CHRE_WWAN_CELL_TIMESTAMP_TYPE_OEM_RIL = 3,
- CHRE_WWAN_CELL_TIMESTAMP_TYPE_JAVA_RIL = 4,
-};
-
-//! Reference: RIL_CellInfo_v12
-struct chreWwanCellInfo {
- //! Timestamp in nanoseconds; must be in the same time base as chreGetTime()
- uint64_t timeStamp;
-
- //! A value from enum {@link #CellInfoType} indicating the radio access
- //! technology of the cell, and which field in union CellInfo can be used
- //! to retrieve additional information
- uint8_t cellInfoType;
-
- //! A value from enum {@link #CellTimeStampType} that identifies the source
- //! of the value in timeStamp. This is typically set to
- //! CHRE_WWAN_CELL_TIMESTAMP_TYPE_OEM_RIL, and indicates the time given by
- //! chreGetTime() that an intermediate module received the data from the
- //! modem and forwarded it to the requesting CHRE client.
- uint8_t timeStampType;
-
- //! !0 if this cell is registered, 0 if not registered
- uint8_t registered;
-
- //! Reserved for future use; must be set to 0
- uint8_t reserved;
-
- //! The value in cellInfoType indicates which field in this union is valid
- union chreWwanCellInfoPerRat {
- struct chreWwanCellInfoGsm gsm;
- struct chreWwanCellInfoCdma cdma;
- struct chreWwanCellInfoLte lte;
- struct chreWwanCellInfoWcdma wcdma;
- struct chreWwanCellInfoTdscdma tdscdma;
- struct chreWwanCellInfoNr nr; //! @since v1.4
- } CellInfo;
-};
-
-/**
- * Data structure provided with events of type CHRE_EVENT_WWAN_CELL_INFO_RESULT.
- */
-struct chreWwanCellInfoResult {
- //! Indicates the version of the structure, for compatibility purposes.
- //! Clients do not normally need to worry about this field; the CHRE
- //! implementation guarantees that the client only receives the structure
- //! version it expects.
- uint8_t version;
-
- //! Populated with a value from enum {@link #chreError}, indicating whether
- //! the request failed, and if so, provides the cause of the failure
- uint8_t errorCode;
-
- //! The number of valid entries in cells[]
- uint8_t cellInfoCount;
-
- //! Reserved for future use; must be set to 0
- uint8_t reserved;
-
- //! Set to the cookie parameter given to chreWwanGetCellInfoAsync()
- const void *cookie;
-
- //! Pointer to an array of cellInfoCount elements containing information
- //! about serving and neighbor cells
- const struct chreWwanCellInfo *cells;
-};
-
-
-/**
- * Retrieves a set of flags indicating the WWAN features supported by the
- * current CHRE implementation. The value returned by this function must be
- * consistent for the entire duration of the Nanoapp's execution.
- *
- * The client must allow for more flags to be set in this response than it knows
- * about, for example if the implementation supports a newer version of the API
- * than the client was compiled against.
- *
- * @return A bitmask with zero or more CHRE_WWAN_CAPABILITIES_* flags set
- *
- * @since v1.1
- */
-uint32_t chreWwanGetCapabilities(void);
-
-/**
- * Query information about the current serving cell and its neighbors. This does
- * not perform a network scan, but should return state from the current network
- * registration data stored in the cellular modem. This is effectively the same
- * as a request for RIL_REQUEST_GET_CELL_INFO_LIST in the RIL.
- *
- * The requested cellular information is returned asynchronously via
- * CHRE_EVENT_WWAN_CELL_INFO_RESULT. The implementation must send this event,
- * either with successful data or an error status, within
- * CHRE_ASYNC_RESULT_TIMEOUT_NS.
- *
- * If the airplane mode setting is enabled at the Android level, the CHRE
- * implementation is expected to return a successful asynchronous result with an
- * empty cell info list.
- *
- * @param cookie An opaque value that will be included in the chreAsyncResult
- * sent in relation to this request.
- *
- * @return true if the request was accepted for processing, false otherwise
- *
- * @since v1.1
- */
-bool chreWwanGetCellInfoAsync(const void *cookie);
-
-/**
- * Helper accessor for nci in the chreWwanCellIdentityNr struct.
- *
- * @return nci or INT64_MAX if invalid/unreported.
- *
- * @see chreWwanCellIdentityNr
- *
- * @since v1.4
- */
-static inline int64_t chreWwanUnpackNrNci(
- const struct chreWwanCellIdentityNr *nrCellId) {
- return (int64_t) (((uint64_t) nrCellId->nci1 << 32) | nrCellId->nci0);
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CHRE_WWAN_H_ */
diff --git a/core/audio_request_manager.cc b/core/audio_request_manager.cc
index 6c5c5eef..174e5a77 100644
--- a/core/audio_request_manager.cc
+++ b/core/audio_request_manager.cc
@@ -16,11 +16,9 @@
#include "chre/core/audio_request_manager.h"
-#include "chre/core/audio_util.h"
#include "chre/core/event_loop_manager.h"
#include "chre/platform/fatal_error.h"
#include "chre/platform/system_time.h"
-#include "chre/util/nested_data_ptr.h"
#include "chre/util/system/debug_dump.h"
/*
@@ -75,14 +73,14 @@ void AudioRequestManager::handleAudioDataEvent(
SystemTime::getMonotonicTime();
}
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- auto *event = static_cast<struct chreAudioDataEvent *>(data);
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ auto *event = static_cast<struct chreAudioDataEvent *>(eventData);
EventLoopManagerSingleton::get()
->getAudioRequestManager()
.handleAudioDataEventSync(event);
};
- // Cast off the event const so that it can be provided to the callback as
+ // Cast off the event const so that it can be provided to the free callback as
// non-const. The event is provided to nanoapps as const and the runtime
// itself will not modify this memory so this is safe.
EventLoopManagerSingleton::get()->deferCallback(
@@ -92,18 +90,29 @@ void AudioRequestManager::handleAudioDataEvent(
void AudioRequestManager::handleAudioAvailability(uint32_t handle,
bool available) {
- auto callback = [](uint16_t /*type*/, void *data, void *extraData) {
- uint32_t cbHandle = NestedDataPtr<uint32_t>(data);
- bool cbAvailable = NestedDataPtr<bool>(extraData);
- EventLoopManagerSingleton::get()
- ->getAudioRequestManager()
- .handleAudioAvailabilitySync(cbHandle, cbAvailable);
+ struct CallbackState {
+ uint32_t handle;
+ bool available;
};
- EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::AudioAvailabilityChange,
- NestedDataPtr<uint32_t>(handle), callback,
- NestedDataPtr<bool>(available));
+ auto *cbState = memoryAlloc<CallbackState>();
+ if (cbState == nullptr) {
+ LOG_OOM();
+ } else {
+ cbState->handle = handle;
+ cbState->available = available;
+
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ auto *state = static_cast<CallbackState *>(eventData);
+ EventLoopManagerSingleton::get()
+ ->getAudioRequestManager()
+ .handleAudioAvailabilitySync(state->handle, state->available);
+ memoryFree(state);
+ };
+
+ EventLoopManagerSingleton::get()->deferCallback(
+ SystemCallbackType::AudioAvailabilityChange, cbState, callback);
+ }
}
void AudioRequestManager::logStateToBuffer(DebugDumpWrapper &debugDump) const {
@@ -156,7 +165,7 @@ bool AudioRequestManager::validateConfigureSourceArguments(
bufferDuration, audioSource.minBufferDuration,
audioSource.maxBufferDuration);
} else {
- *numSamples = AudioUtil::getSampleCountFromRateAndDuration(
+ *numSamples = getSampleCountFromRateAndDuration(
audioSource.sampleRate, Nanoseconds(bufferDuration));
success = true;
}
@@ -205,8 +214,7 @@ bool AudioRequestManager::doConfigureSource(uint32_t instanceId,
deliveryInterval));
}
- if (success &&
- (getSettingState(Setting::MICROPHONE) != SettingState::DISABLED)) {
+ if (success) {
scheduleNextAudioDataEvent(handle);
updatePlatformHandleEnabled(handle, lastNumRequests);
}
@@ -256,10 +264,7 @@ bool AudioRequestManager::createAudioRequest(uint32_t handle,
}
if (success) {
- bool suspended =
- (getSettingState(Setting::MICROPHONE) == SettingState::DISABLED);
- postAudioSamplingChangeEvent(instanceId, handle, requestList.available,
- suspended);
+ postAudioSamplingChangeEvent(instanceId, handle, requestList.available);
}
return success;
@@ -346,10 +351,8 @@ void AudioRequestManager::handleAudioAvailabilitySync(uint32_t handle,
bool available) {
if (handle < mAudioRequestLists.size()) {
if (mAudioRequestLists[handle].available != available) {
- bool suspended =
- (getSettingState(Setting::MICROPHONE) == SettingState::DISABLED);
mAudioRequestLists[handle].available = available;
- postAudioSamplingChangeEvents(handle, suspended);
+ postAudioSamplingChangeEvents(handle);
}
scheduleNextAudioDataEvent(handle);
@@ -359,17 +362,12 @@ void AudioRequestManager::handleAudioAvailabilitySync(uint32_t handle,
}
void AudioRequestManager::scheduleNextAudioDataEvent(uint32_t handle) {
- if (getSettingState(Setting::MICROPHONE) == SettingState::DISABLED) {
- LOGD("Mic access disabled, doing nothing");
- return;
- }
-
auto &reqList = mAudioRequestLists[handle];
AudioRequest *nextRequest = findNextAudioRequest(handle);
// Clear the next request and it will be reset below if needed.
reqList.nextAudioRequest = nullptr;
- if (reqList.available && (nextRequest != nullptr)) {
+ if (reqList.available && nextRequest != nullptr) {
Nanoseconds curTime = SystemTime::getMonotonicTime();
Nanoseconds eventDelay = Nanoseconds(0);
if (nextRequest->nextEventTimestamp > curTime) {
@@ -383,25 +381,22 @@ void AudioRequestManager::scheduleNextAudioDataEvent(uint32_t handle) {
}
}
-void AudioRequestManager::postAudioSamplingChangeEvents(uint32_t handle,
- bool suspended) {
+void AudioRequestManager::postAudioSamplingChangeEvents(uint32_t handle) {
const auto &requestList = mAudioRequestLists[handle];
for (const auto &request : requestList.requests) {
for (const auto &instanceId : request.instanceIds) {
- postAudioSamplingChangeEvent(instanceId, handle, requestList.available,
- suspended);
+ postAudioSamplingChangeEvent(instanceId, handle, requestList.available);
}
}
}
void AudioRequestManager::postAudioSamplingChangeEvent(uint32_t instanceId,
uint32_t handle,
- bool available,
- bool suspended) {
+ bool available) {
auto *event = memoryAlloc<struct chreAudioSourceStatusEvent>();
event->handle = handle;
event->status.enabled = true;
- event->status.suspended = !available || suspended;
+ event->status.suspended = !available;
EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
CHRE_EVENT_AUDIO_SAMPLING_CHANGE, event, freeEventDataCallback,
@@ -454,24 +449,4 @@ void AudioRequestManager::freeAudioDataEventCallback(uint16_t eventType,
.handleFreeAudioDataEvent(event);
}
-void AudioRequestManager::onSettingChanged(Setting setting,
- SettingState state) {
- if (setting == Setting::MICROPHONE) {
- for (size_t i = 0; i < mAudioRequestLists.size(); ++i) {
- uint32_t handle = static_cast<uint32_t>(i);
- if (mAudioRequestLists[i].available) {
- if (state == SettingState::DISABLED) {
- LOGD("Canceling data event request for handle %" PRIu32, handle);
- postAudioSamplingChangeEvents(handle, true /* suspended */);
- mPlatformAudio.cancelAudioDataEventRequest(handle);
- } else {
- LOGD("Scheduling data event for handle %" PRIu32, handle);
- postAudioSamplingChangeEvents(handle, false /* suspended */);
- scheduleNextAudioDataEvent(handle);
- }
- }
- }
- }
-}
-
} // namespace chre
diff --git a/core/core.mk b/core/core.mk
index 7af6511a..ef32ead4 100644
--- a/core/core.mk
+++ b/core/core.mk
@@ -16,7 +16,14 @@ COMMON_SRCS += core/event_loop_manager.cc
COMMON_SRCS += core/event_ref_queue.cc
COMMON_SRCS += core/host_comms_manager.cc
COMMON_SRCS += core/init.cc
+COMMON_SRCS += core/log.cc
COMMON_SRCS += core/nanoapp.cc
+COMMON_SRCS += core/sensor.cc
+COMMON_SRCS += core/sensor_request.cc
+COMMON_SRCS += core/sensor_request_manager.cc
+COMMON_SRCS += core/sensor_request_multiplexer.cc
+COMMON_SRCS += core/sensor_type.cc
+COMMON_SRCS += core/sensor_type_helpers.cc
COMMON_SRCS += core/settings.cc
COMMON_SRCS += core/static_nanoapps.cc
COMMON_SRCS += core/timer_pool.cc
@@ -31,16 +38,6 @@ ifeq ($(CHRE_GNSS_SUPPORT_ENABLED), true)
COMMON_SRCS += core/gnss_manager.cc
endif
-# Optional sensors support.
-ifeq ($(CHRE_SENSORS_SUPPORT_ENABLED), true)
-COMMON_SRCS += core/sensor.cc
-COMMON_SRCS += core/sensor_request.cc
-COMMON_SRCS += core/sensor_request_manager.cc
-COMMON_SRCS += core/sensor_request_multiplexer.cc
-COMMON_SRCS += core/sensor_type.cc
-COMMON_SRCS += core/sensor_type_helpers.cc
-endif
-
# Optional Wi-Fi support.
ifeq ($(CHRE_WIFI_SUPPORT_ENABLED), true)
COMMON_SRCS += core/wifi_request_manager.cc
@@ -54,7 +51,7 @@ endif
# GoogleTest Source Files ######################################################
-GOOGLETEST_SRCS += core/tests/audio_util_test.cc
+GOOGLETEST_SRCS += core/tests/audio_request_manager_test.cc
GOOGLETEST_SRCS += core/tests/memory_manager_test.cc
GOOGLETEST_SRCS += core/tests/request_multiplexer_test.cc
GOOGLETEST_SRCS += core/tests/sensor_request_test.cc
diff --git a/core/debug_dump_manager.cc b/core/debug_dump_manager.cc
index a82478b6..675414c1 100644
--- a/core/debug_dump_manager.cc
+++ b/core/debug_dump_manager.cc
@@ -24,7 +24,7 @@
namespace chre {
void DebugDumpManager::trigger() {
- auto callback = [](uint16_t /*type*/, void * /*data*/, void * /*extraData*/) {
+ auto callback = [](uint16_t /*eventType*/, void * /*eventData*/) {
DebugDumpManager &debugDumpManager =
EventLoopManagerSingleton::get()->getDebugDumpManager();
debugDumpManager.collectFrameworkDebugDumps();
@@ -65,7 +65,7 @@ void DebugDumpManager::appendNanoappLog(const Nanoapp &nanoapp,
nanoapp.getAppId());
}
- mDebugDump.printVaList(formatStr, args);
+ mDebugDump.print(formatStr, args);
}
}
@@ -74,9 +74,7 @@ void DebugDumpManager::collectFrameworkDebugDumps() {
eventLoopManager->getMemoryManager().logStateToBuffer(mDebugDump);
eventLoopManager->getEventLoop().handleNanoappWakeupBuckets();
eventLoopManager->getEventLoop().logStateToBuffer(mDebugDump);
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
eventLoopManager->getSensorRequestManager().logStateToBuffer(mDebugDump);
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
#ifdef CHRE_GNSS_SUPPORT_ENABLED
eventLoopManager->getGnssManager().logStateToBuffer(mDebugDump);
#endif // CHRE_GNSS_SUPPORT_ENABLED
@@ -90,7 +88,6 @@ void DebugDumpManager::collectFrameworkDebugDumps() {
eventLoopManager->getAudioRequestManager().logStateToBuffer(mDebugDump);
#endif // CHRE_AUDIO_SUPPORT_ENABLED
logSettingStateToBuffer(mDebugDump);
- logStateToBuffer(mDebugDump);
}
void DebugDumpManager::sendFrameworkDebugDumps() {
diff --git a/core/event.cc b/core/event.cc
index 65ecbe3f..cfcb8085 100644
--- a/core/event.cc
+++ b/core/event.cc
@@ -15,17 +15,17 @@
*/
#include "chre/core/event.h"
-#include "chre/platform/system_time.h"
-#include "chre/util/time.h"
namespace chre {
-uint16_t Event::getTimeMillis() {
- Milliseconds now = SystemTime::getMonotonicTime();
- // Truncating, but we want to save space and really only care about delta time
- // between pending events (for debugging), which shouldn't get close to 65
- // seconds unless something is very wrong
- return static_cast<uint16_t>(now.getMilliseconds());
-}
+Event::Event(uint16_t eventType_, uint16_t receivedTimeMillis_,
+ void *eventData_, chreEventCompleteFunction *freeCallback_,
+ uint32_t senderInstanceId_, uint32_t targetInstanceId_)
+ : eventType(eventType_),
+ receivedTimeMillis(receivedTimeMillis_),
+ eventData(eventData_),
+ freeCallback(freeCallback_),
+ senderInstanceId(senderInstanceId_),
+ targetInstanceId(targetInstanceId_) {}
} // namespace chre
diff --git a/core/event_loop.cc b/core/event_loop.cc
index 0f598a20..eff448ac 100644
--- a/core/event_loop.cc
+++ b/core/event_loop.cc
@@ -152,12 +152,6 @@ bool EventLoop::startNanoapp(UniquePtr<Nanoapp> &nanoapp) {
if (nanoapp.isNull()) {
// no-op, invalid argument
- } else if (nanoapp->getTargetApiVersion() <
- CHRE_FIRST_SUPPORTED_API_VERSION) {
- LOGE("Incompatible nanoapp (target ver 0x%" PRIx32
- ", first supported ver 0x%" PRIx32 ")",
- nanoapp->getTargetApiVersion(),
- static_cast<uint32_t>(CHRE_FIRST_SUPPORTED_API_VERSION));
} else if (eventLoop.findNanoappInstanceIdByAppId(nanoapp->getAppId(),
&existingInstanceId)) {
LOGE("App with ID 0x%016" PRIx64
@@ -255,70 +249,55 @@ bool EventLoop::unloadNanoapp(uint32_t instanceId,
return unloaded;
}
-void EventLoop::postEventOrDie(uint16_t eventType, void *eventData,
+bool EventLoop::postEventOrDie(uint16_t eventType, void *eventData,
chreEventCompleteFunction *freeCallback,
- uint32_t targetInstanceId,
- uint16_t targetGroupMask) {
- if (mRunning) {
- if (!allocateAndPostEvent(eventType, eventData, freeCallback,
- kSystemInstanceId, targetInstanceId,
- targetGroupMask)) {
- FATAL_ERROR("Failed to post critical system event 0x%" PRIx16, eventType);
- }
- } else if (freeCallback != nullptr) {
- freeCallback(eventType, eventData);
- }
-}
+ uint32_t targetInstanceId) {
+ bool success = false;
-bool EventLoop::postSystemEvent(uint16_t eventType, void *eventData,
- SystemEventCallbackFunction *callback,
- void *extraData) {
if (mRunning) {
- Event *event =
- mEventPool.allocate(eventType, eventData, callback, extraData);
-
- if (event == nullptr || !mEvents.push(event)) {
- FATAL_ERROR("Failed to post critical system event 0x%" PRIx16, eventType);
+ success = allocateAndPostEvent(eventType, eventData, freeCallback,
+ kSystemInstanceId, targetInstanceId);
+ if (!success) {
+ // This can only happen if the event is a system event type. This
+ // postEvent method will fail if a non-system event is posted when the
+ // memory pool is close to full.
+ FATAL_ERROR("Failed to allocate system event type %" PRIu16, eventType);
}
- return true;
}
- return false;
+
+ return success;
}
bool EventLoop::postLowPriorityEventOrFree(
uint16_t eventType, void *eventData,
chreEventCompleteFunction *freeCallback, uint32_t senderInstanceId,
- uint32_t targetInstanceId, uint16_t targetGroupMask) {
- bool eventPosted = false;
+ uint32_t targetInstanceId) {
+ bool success = false;
if (mRunning) {
if (mEventPool.getFreeBlockCount() > kMinReservedHighPriorityEventCount) {
- eventPosted = allocateAndPostEvent(eventType, eventData, freeCallback,
- senderInstanceId, targetInstanceId,
- targetGroupMask);
- if (!eventPosted) {
- LOGE("Failed to allocate event 0x%" PRIx16 " to instanceId %" PRIu32,
- eventType, targetInstanceId);
+ success = allocateAndPostEvent(eventType, eventData, freeCallback,
+ senderInstanceId, targetInstanceId);
+ }
+ if (!success) {
+ if (freeCallback != nullptr) {
+ freeCallback(eventType, eventData);
}
+ LOGE("Failed to allocate event 0x%" PRIx16 " to instanceId %" PRIu32,
+ eventType, targetInstanceId);
}
}
- if (!eventPosted && freeCallback != nullptr) {
- freeCallback(eventType, eventData);
- }
-
- return eventPosted;
+ return success;
}
void EventLoop::stop() {
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- auto *obj = static_cast<EventLoop *>(data);
- obj->onStopComplete();
+ auto callback = [](uint16_t /* type */, void * /* data */) {
+ EventLoopManagerSingleton::get()->getEventLoop().onStopComplete();
};
- // Stop accepting new events and tell the main loop to finish
- postSystemEvent(static_cast<uint16_t>(SystemCallbackType::Shutdown),
- /*eventData=*/this, callback, /*extraData=*/nullptr);
+ // Stop accepting new events and tell the main loop to finish.
+ postEventOrDie(0, nullptr, callback, kSystemInstanceId);
}
void EventLoop::onStopComplete() {
@@ -372,17 +351,22 @@ void EventLoop::logStateToBuffer(DebugDumpWrapper &debugDump) const {
bool EventLoop::allocateAndPostEvent(uint16_t eventType, void *eventData,
chreEventCompleteFunction *freeCallback,
uint32_t senderInstanceId,
- uint32_t targetInstanceId,
- uint16_t targetGroupMask) {
+ uint32_t targetInstanceId) {
bool success = false;
+ Milliseconds receivedTime = Nanoseconds(SystemTime::getMonotonicTime());
+ // The event loop should never contain more than 65 seconds worth of data
+ // unless something has gone terribly wrong so use uint16_t to save space.
+ uint16_t receivedTimeMillis =
+ static_cast<uint16_t>(receivedTime.getMilliseconds());
+
Event *event =
- mEventPool.allocate(eventType, eventData, freeCallback, senderInstanceId,
- targetInstanceId, targetGroupMask);
+ mEventPool.allocate(eventType, receivedTimeMillis, eventData,
+ freeCallback, senderInstanceId, targetInstanceId);
+
if (event != nullptr) {
success = mEvents.push(event);
}
-
return success;
}
@@ -416,23 +400,18 @@ bool EventLoop::deliverNextEvent(const UniquePtr<Nanoapp> &app) {
void EventLoop::distributeEvent(Event *event) {
for (const UniquePtr<Nanoapp> &app : mNanoapps) {
if ((event->targetInstanceId == chre::kBroadcastInstanceId &&
- app->isRegisteredForBroadcastEvent(event->eventType,
- event->targetAppGroupMask)) ||
+ app->isRegisteredForBroadcastEvent(event->eventType)) ||
event->targetInstanceId == app->getInstanceId()) {
app->postEvent(event);
}
}
if (event->isUnreferenced()) {
- // Log if an event unicast to a nanoapp isn't delivered, as this is could be
- // a bug (e.g. something isn't properly keeping track of when nanoapps are
- // unloaded), though it could just be a harmless transient issue (e.g. race
- // condition with nanoapp unload, where we post an event to a nanoapp just
- // after queues are flushed while it's unloading)
- if (event->targetInstanceId != kBroadcastInstanceId &&
- event->targetInstanceId != kSystemInstanceId) {
- LOGW("Dropping event 0x%" PRIx16 " from instanceId %" PRIu32 "->%" PRIu32,
- event->eventType, event->senderInstanceId, event->targetInstanceId);
+ // Events sent to the system instance ID are processed via the free callback
+ // and are not expected to be delivered to any nanoapp, so no need to log a
+ // warning in that case
+ if (event->senderInstanceId != kSystemInstanceId) {
+ LOGW("Dropping event 0x%" PRIx16, event->eventType);
}
freeEvent(event);
}
@@ -450,10 +429,10 @@ void EventLoop::flushNanoappEventQueues() {
}
void EventLoop::freeEvent(Event *event) {
- if (event->hasFreeCallback()) {
+ if (event->freeCallback != nullptr) {
// TODO: find a better way to set the context to the creator of the event
mCurrentApp = lookupAppByInstanceId(event->senderInstanceId);
- event->invokeFreeCallback();
+ event->freeCallback(event->eventType, event->eventData);
mCurrentApp = nullptr;
}
diff --git a/core/event_loop_manager.cc b/core/event_loop_manager.cc
index 7bff5ded..b582a3a3 100644
--- a/core/event_loop_manager.cc
+++ b/core/event_loop_manager.cc
@@ -50,9 +50,7 @@ uint32_t EventLoopManager::getNextInstanceId() {
}
void EventLoopManager::lateInit() {
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
mSensorRequestManager.init();
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
#ifdef CHRE_GNSS_SUPPORT_ENABLED
mGnssManager.init();
diff --git a/core/gnss_manager.cc b/core/gnss_manager.cc
index 32d8494e..5fdab695 100644
--- a/core/gnss_manager.cc
+++ b/core/gnss_manager.cc
@@ -20,7 +20,6 @@
#include "chre/core/settings.h"
#include "chre/platform/assert.h"
#include "chre/platform/fatal_error.h"
-#include "chre/util/nested_data_ptr.h"
#include "chre/util/system/debug_dump.h"
namespace chre {
@@ -87,121 +86,15 @@ void GnssManager::onSettingChanged(Setting setting, SettingState state) {
mMeasurementSession.onSettingChanged(setting, state);
}
-void GnssManager::handleRequestStateResyncCallback() {
- auto callback = [](uint16_t /* eventType */, void * /* eventData */,
- void * /* extraData */) {
- EventLoopManagerSingleton::get()
- ->getGnssManager()
- .handleRequestStateResyncCallbackSync();
- };
- EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::GnssRequestResyncEvent, nullptr /* data */, callback);
-}
-
-bool GnssManager::configurePassiveLocationListener(Nanoapp *nanoapp,
- bool enable) {
- bool success = false;
- uint32_t instanceId = nanoapp->getInstanceId();
-
- size_t index;
- if (nanoappHasPassiveLocationListener(instanceId, &index) != enable) {
- uint32_t capabilities = getCapabilities();
- bool locationSupported =
- (capabilities & CHRE_GNSS_CAPABILITIES_LOCATION) != 0;
- bool passiveLocationListenerSupported =
- (capabilities &
- CHRE_GNSS_CAPABILITIES_GNSS_ENGINE_BASED_PASSIVE_LISTENER) != 0;
-
- if (!locationSupported) {
- LOGE("Platform does not have the location capability");
- } else if (enable && !mPassiveLocationListenerNanoapps.prepareForPush()) {
- LOG_OOM();
- } else {
- bool platformEnable = enable && mPassiveLocationListenerNanoapps.empty();
- bool platformDisable =
- !enable && (mPassiveLocationListenerNanoapps.size() == 1);
-
- if (!passiveLocationListenerSupported) {
- // Silently succeed per API, since listener capability will occur within
- // CHRE (nanoapp requests).
- success = true;
- } else if (platformEnable || platformDisable) {
- success = platformConfigurePassiveLocationListener(enable);
- } else {
- // Platform was already in the configured state.
- success = true;
- }
-
- if (success) {
- if (enable) {
- mPassiveLocationListenerNanoapps.push_back(instanceId);
- nanoapp->registerForBroadcastEvent(CHRE_EVENT_GNSS_LOCATION);
- } else {
- mPassiveLocationListenerNanoapps.erase(index);
- if (!mLocationSession.nanoappHasRequest(instanceId)) {
- nanoapp->unregisterForBroadcastEvent(CHRE_EVENT_GNSS_LOCATION);
- }
- }
- }
- }
- } else { // else nanoapp request is already at the desired state.
- success = true;
- }
-
- return success;
-}
-
-bool GnssManager::nanoappHasPassiveLocationListener(uint32_t nanoappInstanceId,
- size_t *index) {
- size_t foundIndex = mPassiveLocationListenerNanoapps.find(nanoappInstanceId);
- bool found = (foundIndex != mPassiveLocationListenerNanoapps.size());
- if (found && index != nullptr) {
- *index = foundIndex;
- }
-
- return found;
-}
-
-bool GnssManager::platformConfigurePassiveLocationListener(bool enable) {
- bool success = mPlatformGnss.configurePassiveLocationListener(enable);
- if (!success) {
- LOGE("Platform failed to %s passive location listener",
- enable ? "enable" : "disable");
- } else {
- mPlatformPassiveLocationListenerEnabled = enable;
- }
-
- return success;
-}
-
-void GnssManager::handleRequestStateResyncCallbackSync() {
- mLocationSession.handleRequestStateResyncCallbackSync();
- mMeasurementSession.handleRequestStateResyncCallbackSync();
-
- mPlatformPassiveLocationListenerEnabled = false;
- if (!mPassiveLocationListenerNanoapps.empty()) {
- if (!platformConfigurePassiveLocationListener(true /* enable */)) {
- FATAL_ERROR("Failed to resync passive location listener");
- }
- }
-}
-
void GnssManager::logStateToBuffer(DebugDumpWrapper &debugDump) const {
debugDump.print("\nGNSS:");
mLocationSession.logStateToBuffer(debugDump);
mMeasurementSession.logStateToBuffer(debugDump);
-
- debugDump.print(
- "\n Passive location listener %s\n",
- mPlatformPassiveLocationListenerEnabled ? "enabled" : "disabled");
- for (uint32_t instanceId : mPassiveLocationListenerNanoapps) {
- debugDump.print(" nappId=%" PRIu32 "\n", instanceId);
- }
}
GnssSession::GnssSession(uint16_t reportEventType)
- : kReportEventType(reportEventType) {
- switch (kReportEventType) {
+ : mReportEventType(reportEventType) {
+ switch (mReportEventType) {
case CHRE_EVENT_GNSS_LOCATION:
mStartRequestType = CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_START;
mStopRequestType = CHRE_GNSS_REQUEST_TYPE_LOCATION_SESSION_STOP;
@@ -240,42 +133,44 @@ void GnssSession::handleStatusChange(bool enabled, uint8_t errorCode) {
struct CallbackState {
bool enabled;
uint8_t errorCode;
+ GnssSession *session;
};
- auto callback = [](uint16_t /*type*/, void *data, void *extraData) {
- auto *session = static_cast<GnssSession *>(data);
- CallbackState cbState = NestedDataPtr<CallbackState>(extraData);
- session->handleStatusChangeSync(cbState.enabled, cbState.errorCode);
- };
+ auto *cbState = memoryAlloc<CallbackState>();
+ if (cbState == nullptr) {
+ LOG_OOM();
+ } else {
+ cbState->enabled = enabled;
+ cbState->errorCode = errorCode;
+ cbState->session = this;
- CallbackState cbState = {};
- cbState.enabled = enabled;
- cbState.errorCode = errorCode;
- EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::GnssSessionStatusChange, /*data=*/this, callback,
- NestedDataPtr<CallbackState>(cbState));
-}
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ auto *state = static_cast<CallbackState *>(eventData);
+ state->session->handleStatusChangeSync(state->enabled, state->errorCode);
+ memoryFree(state);
+ };
-void GnssSession::handleReportEvent(void *event) {
- if (mRequests.empty()) {
- LOGW("Unexpected %s event", mName);
+ EventLoopManagerSingleton::get()->deferCallback(
+ SystemCallbackType::GnssSessionStatusChange, cbState, callback);
}
+}
- auto callback = [](uint16_t type, void *data, void * /*extraData*/) {
+void GnssSession::handleReportEvent(void *event) {
+ auto callback = [](uint16_t type, void *eventData) {
uint16_t reportEventType;
if (!getReportEventType(static_cast<SystemCallbackType>(type),
&reportEventType) ||
(getSettingState(Setting::LOCATION) == SettingState::DISABLED)) {
- freeReportEventCallback(reportEventType, data);
+ freeReportEventCallback(reportEventType, eventData);
} else {
EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- reportEventType, data, freeReportEventCallback);
+ reportEventType, eventData, freeReportEventCallback);
}
};
SystemCallbackType type;
- if (!getCallbackType(kReportEventType, &type)) {
- freeReportEventCallback(kReportEventType, event);
+ if (!getCallbackType(mReportEventType, &type)) {
+ freeReportEventCallback(mReportEventType, event);
} else {
EventLoopManagerSingleton::get()->deferCallback(type, event, callback);
}
@@ -283,51 +178,34 @@ void GnssSession::handleReportEvent(void *event) {
void GnssSession::onSettingChanged(Setting setting, SettingState state) {
if (setting == Setting::LOCATION) {
- if (asyncResponsePending()) {
+ if (!mStateTransitions.empty()) {
// A request is in progress, so we wait until the async response arrives
// to handle the state change.
mSettingChangePending = true;
} else {
- mInternalRequestPending = updatePlatformRequest();
+ handleLocationSettingChange(state);
mSettingChangePending = false;
}
}
}
-bool GnssSession::updatePlatformRequest(bool forceUpdate) {
- SettingState locationSetting = getSettingState(Setting::LOCATION);
-
- bool desiredPlatformState =
- (locationSetting == SettingState::ENABLED) && !mRequests.empty();
- bool shouldUpdatePlatform =
- forceUpdate ||
- (desiredPlatformState != mPlatformEnabled) /* (enable/disable) */;
+void GnssSession::handleLocationSettingChange(SettingState state) {
+ bool chreDisable = ((state == SettingState::DISABLED) && mPlatformEnabled);
+ bool chreEnable = ((state == SettingState::ENABLED) && !mPlatformEnabled &&
+ !mRequests.empty());
- bool requestPending = false;
- if (shouldUpdatePlatform) {
- if (controlPlatform(desiredPlatformState, mCurrentInterval,
+ if (chreEnable || chreDisable) {
+ if (controlPlatform(chreEnable, mCurrentInterval,
Milliseconds(0) /* minTimeToNext */)) {
- LOGD("Configured GNSS %s: enable %d", mName, desiredPlatformState);
- addSessionRequestLog(CHRE_INSTANCE_ID, mCurrentInterval,
- desiredPlatformState);
- requestPending = true;
+ LOGD("Configured GNSS %s: setting state %" PRIu8, mName,
+ static_cast<uint8_t>(state));
+ addSessionRequestLog(CHRE_INSTANCE_ID, mCurrentInterval, chreEnable);
+ mInternalRequestPending = true;
} else {
- LOGE("Failed to configure GNSS %s: enable %d", mName,
- desiredPlatformState);
+ LOGE("Failed to configure GNSS %s: setting state %" PRIu8, mName,
+ static_cast<uint8_t>(state));
}
}
-
- return requestPending;
-}
-
-void GnssSession::handleRequestStateResyncCallbackSync() {
- if (asyncResponsePending()) {
- // A request is in progress, so we wait until the async response arrives
- // to handle the resync callback.
- mResyncPending = true;
- } else {
- mInternalRequestPending = updatePlatformRequest(true /* forceUpdate */);
- }
}
void GnssSession::logStateToBuffer(DebugDumpWrapper &debugDump) const {
@@ -508,22 +386,14 @@ bool GnssSession::updateRequests(bool enable, Milliseconds minInterval,
if (!success) {
LOG_OOM();
} else {
- nanoapp->registerForBroadcastEvent(kReportEventType);
+ nanoapp->registerForBroadcastEvent(mReportEventType);
}
}
} else if (hasExistingRequest) {
// The session was successfully disabled for a previously enabled
// nanoapp. Remove it from the list of requests.
mRequests.erase(requestIndex);
-
- // We can only unregister the location events from nanoapps if it has no
- // request and has not configured the passive listener.
- if ((kReportEventType != CHRE_EVENT_GNSS_LOCATION) ||
- !EventLoopManagerSingleton::get()
- ->getGnssManager()
- .nanoappHasPassiveLocationListener(instanceId)) {
- nanoapp->unregisterForBroadcastEvent(kReportEventType);
- }
+ nanoapp->unregisterForBroadcastEvent(mReportEventType);
} // else disabling an inactive request, treat as success per CHRE API
}
@@ -545,10 +415,14 @@ bool GnssSession::postAsyncResultEvent(uint32_t instanceId, bool success,
event->reserved = 0;
event->cookie = cookie;
- EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- CHRE_EVENT_GNSS_ASYNC_RESULT, event, freeEventDataCallback,
- instanceId);
- eventPosted = true;
+ eventPosted =
+ EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
+ CHRE_EVENT_GNSS_ASYNC_RESULT, event, freeEventDataCallback,
+ instanceId);
+
+ if (!eventPosted) {
+ memoryFree(event);
+ }
}
}
@@ -569,7 +443,7 @@ void GnssSession::postAsyncResultEventFatal(uint32_t instanceId, bool success,
void GnssSession::handleStatusChangeSync(bool enabled, uint8_t errorCode) {
bool success = (errorCode == CHRE_ERROR_NONE);
- CHRE_ASSERT_LOG(asyncResponsePending(),
+ CHRE_ASSERT_LOG(!mStateTransitions.empty() || mInternalRequestPending,
"handleStatusChangeSync called with no transitions");
if (mInternalRequestPending) {
// Silently handle internal requests from CHRE, since they are not pushed
@@ -589,23 +463,12 @@ void GnssSession::handleStatusChangeSync(bool enabled, uint8_t errorCode) {
mStateTransitions.pop();
}
- // If a previous setting change or resync event is pending process, do that
- // first.
- if (mResyncPending && !success) {
- // We only send a platform request on resync if a pending request failed,
- // because we still need to restore the previous request state.
- mInternalRequestPending = updatePlatformRequest(true /* forceUpdate */);
- } else if (mSettingChangePending) {
- mInternalRequestPending = updatePlatformRequest();
- }
-
- mResyncPending = false;
- mSettingChangePending = false;
-
- // If we didn't issue an internally-generated update via
- // updatePlatformRequest(), process pending nanoapp requests (otherwise,
- // wait for it to finish, then process any pending requests)
- if (!mInternalRequestPending) {
+ // If a previous setting change event is pending process, do that first.
+ if (mSettingChangePending) {
+ handleLocationSettingChange(getSettingState(Setting::LOCATION));
+ mSettingChangePending = false;
+ } else {
+ // Dispatch pending state transition until first one succeeds
dispatchQueuedStateTransitions();
}
}
@@ -635,7 +498,7 @@ bool GnssSession::controlPlatform(bool enable, Milliseconds minInterval,
Milliseconds /* minTimeToNext */) {
bool success = false;
- switch (kReportEventType) {
+ switch (mReportEventType) {
case CHRE_EVENT_GNSS_LOCATION:
// TODO: Provide support for min time to next report. It is currently sent
// to the platform as zero.
@@ -653,7 +516,7 @@ bool GnssSession::controlPlatform(bool enable, Milliseconds minInterval,
break;
default:
- CHRE_ASSERT_LOG(false, "Unhandled event type %" PRIu16, kReportEventType);
+ CHRE_ASSERT_LOG(false, "Unhandled event type %" PRIu16, mReportEventType);
}
if (success) {
diff --git a/core/host_comms_manager.cc b/core/host_comms_manager.cc
index 14224147..9d72346b 100644
--- a/core/host_comms_manager.cc
+++ b/core/host_comms_manager.cc
@@ -21,13 +21,23 @@
#include "chre/core/host_comms_manager.h"
#include "chre/platform/assert.h"
#include "chre/platform/host_link.h"
-#include "chre/util/macros.h"
namespace chre {
+constexpr uint32_t kMessageToHostReservedFieldValue = UINT32_MAX;
+
+void HostCommsManager::flushMessagesSentByNanoapp(uint64_t appId) {
+ mHostLink.flushMessagesSentByNanoapp(appId);
+}
+
+void HostCommsManager::sendLogMessage(const char *logMessage,
+ size_t logMessageSize) {
+ mHostLink.sendLogMessage(logMessage, logMessageSize);
+}
+
bool HostCommsManager::sendMessageToHostFromNanoapp(
Nanoapp *nanoapp, void *messageData, size_t messageSize,
- uint32_t messageType, uint16_t hostEndpoint, uint32_t messagePermissions,
+ uint32_t messageType, uint16_t hostEndpoint,
chreMessageFreeFunction *freeCallback) {
bool success = false;
if (messageSize > 0 && messageData == nullptr) {
@@ -37,10 +47,6 @@ bool HostCommsManager::sendMessageToHostFromNanoapp(
CHRE_MESSAGE_TO_HOST_MAX_SIZE);
} else if (hostEndpoint == kHostEndpointUnspecified) {
LOGW("Rejecting message to invalid host endpoint");
- } else if (!BITMASK_HAS_VALUE(nanoapp->getAppPermissions(),
- messagePermissions)) {
- LOGE("Message perms %" PRIx32 " not subset of napp perms %" PRIx32,
- messagePermissions, nanoapp->getAppPermissions());
} else {
MessageToHost *msgToHost = mMessagePool.allocate();
@@ -51,17 +57,19 @@ bool HostCommsManager::sendMessageToHostFromNanoapp(
msgToHost->message.wrap(static_cast<uint8_t *>(messageData), messageSize);
msgToHost->toHostData.hostEndpoint = hostEndpoint;
msgToHost->toHostData.messageType = messageType;
- msgToHost->toHostData.messagePermissions = messagePermissions;
- msgToHost->toHostData.appPermissions = nanoapp->getAppPermissions();
msgToHost->toHostData.nanoappFreeFunction = freeCallback;
+ // Populate a special value to help disambiguate message direction when
+ // debugging
+ msgToHost->toHostData.reserved = kMessageToHostReservedFieldValue;
+
// Let the nanoapp know that it woke up the host and record it
bool hostWasAwake = EventLoopManagerSingleton::get()
->getEventLoop()
.getPowerControlManager()
.hostIsAwake();
- success = HostLink::sendMessage(msgToHost);
+ success = mHostLink.sendMessage(msgToHost);
if (!success) {
mMessagePool.deallocate(msgToHost);
} else if (!hostWasAwake && !mIsNanoappBlamedForWakeup) {
@@ -107,20 +115,22 @@ bool HostCommsManager::deliverNanoappMessageFromHost(
MessageFromHost *craftedMessage) {
const EventLoop &eventLoop = EventLoopManagerSingleton::get()->getEventLoop();
uint32_t targetInstanceId;
- bool nanoappFound = false;
+ bool success = false;
CHRE_ASSERT_LOG(craftedMessage != nullptr,
"Cannot deliver NULL pointer nanoapp message from host");
if (eventLoop.findNanoappInstanceIdByAppId(craftedMessage->appId,
&targetInstanceId)) {
- nanoappFound = true;
- EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- CHRE_EVENT_MESSAGE_FROM_HOST, &craftedMessage->fromHostData,
- freeMessageFromHostCallback, targetInstanceId);
+ success = true;
+ if (!EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
+ CHRE_EVENT_MESSAGE_FROM_HOST, &craftedMessage->fromHostData,
+ freeMessageFromHostCallback, targetInstanceId)) {
+ mMessagePool.deallocate(craftedMessage);
+ }
}
- return nanoappFound;
+ return success;
}
void HostCommsManager::sendMessageToNanoappFromHost(uint64_t appId,
@@ -144,11 +154,11 @@ void HostCommsManager::sendMessageToNanoappFromHost(uint64_t appId,
"(size %zu)",
appId, messageSize);
} else if (!deliverNanoappMessageFromHost(craftedMessage)) {
- LOGV("Deferring message; destination app ID 0x%016" PRIx64
+ LOGD("Deferring message; destination app ID 0x%016" PRIx64
" not found at this time",
appId);
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
+ auto deferredMessageCallback = [](uint16_t /*type*/, void *data) {
EventLoopManagerSingleton::get()
->getHostCommsManager()
.sendDeferredMessageToNanoappFromHost(
@@ -156,7 +166,7 @@ void HostCommsManager::sendMessageToNanoappFromHost(uint64_t appId,
};
EventLoopManagerSingleton::get()->deferCallback(
SystemCallbackType::DeferredMessageToNanoappFromHost, craftedMessage,
- callback);
+ deferredMessageCallback);
}
}
}
@@ -192,8 +202,7 @@ void HostCommsManager::onMessageToHostComplete(const MessageToHost *message) {
if (msgToHost->toHostData.nanoappFreeFunction == nullptr) {
mMessagePool.deallocate(msgToHost);
} else {
- auto freeMsgCallback = [](uint16_t /*type*/, void *data,
- void * /*extraData*/) {
+ auto freeMsgCallback = [](uint16_t /*type*/, void *data) {
EventLoopManagerSingleton::get()->getHostCommsManager().freeMessageToHost(
static_cast<MessageToHost *>(data));
};
diff --git a/core/include/chre/core/audio_request_manager.h b/core/include/chre/core/audio_request_manager.h
index da44c4ce..b53ceede 100644
--- a/core/include/chre/core/audio_request_manager.h
+++ b/core/include/chre/core/audio_request_manager.h
@@ -20,7 +20,6 @@
#include <cstdint>
#include "chre/core/nanoapp.h"
-#include "chre/core/settings.h"
#include "chre/platform/platform_audio.h"
#include "chre/util/dynamic_vector.h"
#include "chre/util/non_copyable.h"
@@ -103,13 +102,42 @@ class AudioRequestManager : public NonCopyable {
void logStateToBuffer(DebugDumpWrapper &debugDump) const;
/**
- * Invoked when the host notifies CHRE that microphone access has been
- * disabled via the user settings.
+ * A convenience function to convert sample count and sample rate into a time
+ * duration. It is illegal to call this function with a rate of zero.
*
- * @param setting The setting that changed.
- * @param state The new setting state.
+ * @param sampleCount The number of samples to convert to time at the provided
+ * rate.
+ * @param sampleRate The rate to perform the time conversion at.
+ * @return The duration of time for these two parameters.
*/
- void onSettingChanged(Setting setting, SettingState state);
+ static constexpr Nanoseconds getDurationFromSampleCountAndRate(
+ uint32_t sampleCount, uint32_t sampleRate) {
+ // This function will overflow with high sample counts but does work for
+ // reasonable expected values.
+ //
+ // Example: 22050 * 1000000000 / 44100 = 500000000ns
+ return Nanoseconds((sampleCount * kOneSecondInNanoseconds) / sampleRate);
+ }
+
+ /**
+ * A convenience function to convert sample rate and duration into a sample
+ * count. This can be used by platform implementations to ensure that the
+ * computed buffer sizes match those expected by CHRE.
+ *
+ * @param sampleRate The sample rate of the audio source.
+ * @param duration The duration of the buffer delivered.
+ * @return The number of samples given this configuration.
+ */
+ static constexpr uint32_t getSampleCountFromRateAndDuration(
+ uint32_t sampleRate, Nanoseconds duration) {
+ // This function will overflow at high sample rates or extremely high
+ // durations, but does work for reasonable expected values.
+ //
+ // Example: 44100 * 60 seconds (in nanoseconds) fits into a uint64_t as an
+ // intermediate value before casting to uint32_t.
+ return static_cast<uint32_t>((sampleRate * duration.toRawNanoseconds()) /
+ kOneSecondInNanoseconds);
+ }
/**
* @return the instance of platform audio to allow platform-specific
@@ -337,9 +365,8 @@ class AudioRequestManager : public NonCopyable {
* the supplied handle with the current availability of the source.
*
* @param handle The handle for the audio source that is changing.
- * @param suspended Boolean value that indicates if the source is suspended
*/
- void postAudioSamplingChangeEvents(uint32_t handle, bool suspended);
+ void postAudioSamplingChangeEvents(uint32_t handle);
/**
* Posts a CHRE_EVENT_AUDIO_SAMPLING_CHANGE event to the specified nanoapp.
@@ -348,10 +375,9 @@ class AudioRequestManager : public NonCopyable {
* @param handle The handle for the audio source that is changing.
* @param available true if audio is available for the supplied handle, false
* otherwise.
- * @param suspended Boolean value that indicates if the source is suspended
*/
void postAudioSamplingChangeEvent(uint32_t instanceId, uint32_t handle,
- bool available, bool suspended);
+ bool available);
/**
* Posts the provided audio data event to a nanoapp with the given instance ID
diff --git a/core/include/chre/core/audio_util.h b/core/include/chre/core/audio_util.h
deleted file mode 100644
index c0924534..00000000
--- a/core/include/chre/core/audio_util.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * 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 CHRE_CORE_AUDIO_UTIL_H_
-#define CHRE_CORE_AUDIO_UTIL_H_
-
-#include <cstdint>
-
-#include "chre/util/time.h"
-
-namespace chre {
-
-/**
- * Class to define utility functions for CHRE audio.
- */
-class AudioUtil {
- public:
- /**
- * A convenience function to convert sample count and sample rate into a time
- * duration. It is illegal to call this function with a rate of zero.
- *
- * @param sampleCount The number of samples to convert to time at the provided
- * rate.
- * @param sampleRate The rate to perform the time conversion at.
- * @return The duration of time for these two parameters.
- */
- static constexpr Nanoseconds getDurationFromSampleCountAndRate(
- uint32_t sampleCount, uint32_t sampleRate) {
- // This function will overflow with high sample counts but does work for
- // reasonable expected values.
- //
- // Example: 22050 * 1000000000 / 44100 = 500000000ns
- return Nanoseconds((sampleCount * kOneSecondInNanoseconds) / sampleRate);
- }
-
- /**
- * A convenience function to convert sample rate and duration into a sample
- * count. This can be used by platform implementations to ensure that the
- * computed buffer sizes match those expected by CHRE.
- *
- * @param sampleRate The sample rate of the audio source.
- * @param duration The duration of the buffer delivered.
- * @return The number of samples given this configuration.
- */
- static constexpr uint32_t getSampleCountFromRateAndDuration(
- uint32_t sampleRate, Nanoseconds duration) {
- // This function will overflow at high sample rates or extremely high
- // durations, but does work for reasonable expected values.
- //
- // Example: 44100 * 60 seconds (in nanoseconds) fits into a uint64_t as an
- // intermediate value before casting to uint32_t.
- return static_cast<uint32_t>((sampleRate * duration.toRawNanoseconds()) /
- kOneSecondInNanoseconds);
- }
-};
-
-} // namespace chre
-
-#endif // CHRE_CORE_AUDIO_UTIL_H_
diff --git a/core/include/chre/core/event.h b/core/include/chre/core/event.h
index e5e46a2d..84c868ac 100644
--- a/core/include/chre/core/event.h
+++ b/core/include/chre/core/event.h
@@ -17,7 +17,6 @@
#ifndef CHRE_CORE_EVENT_H_
#define CHRE_CORE_EVENT_H_
-#include "chre/core/event_loop_common.h"
#include "chre/platform/assert.h"
#include "chre/util/non_copyable.h"
#include "chre_api/chre/event.h"
@@ -37,46 +36,12 @@ constexpr uint32_t kBroadcastInstanceId = UINT32_MAX;
//! ID is invalid/not assigned yet
constexpr uint32_t kInvalidInstanceId = kBroadcastInstanceId;
-//! Default target group mask that results in the event being sent to any app
-//! registered for it.
-constexpr uint16_t kDefaultTargetGroupMask = UINT16_MAX;
-
class Event : public NonCopyable {
public:
- Event() = delete;
-
- // Events targeted at nanoapps
- Event(uint16_t eventType_, void *eventData_,
+ Event(uint16_t eventType_, uint16_t receivedTimeMillis_, void *eventData_,
chreEventCompleteFunction *freeCallback_,
- uint32_t senderInstanceId_ = kSystemInstanceId,
- uint32_t targetInstanceId_ = kBroadcastInstanceId,
- uint16_t targetAppGroupMask_ = kDefaultTargetGroupMask)
- : eventType(eventType_),
- receivedTimeMillis(getTimeMillis()),
- eventData(eventData_),
- freeCallback(freeCallback_),
- senderInstanceId(senderInstanceId_),
- targetInstanceId(targetInstanceId_),
- targetAppGroupMask(targetAppGroupMask_) {
- // Sending events to the system must only be done via the other constructor
- CHRE_ASSERT(targetInstanceId_ != kSystemInstanceId);
- CHRE_ASSERT(targetAppGroupMask_ > 0);
- }
-
- // Alternative constructor used for system-internal events (e.g. deferred
- // callbacks)
- Event(uint16_t eventType_, void *eventData_,
- SystemEventCallbackFunction *systemEventCallback_, void *extraData_)
- : eventType(eventType_),
- receivedTimeMillis(getTimeMillis()),
- eventData(eventData_),
- systemEventCallback(systemEventCallback_),
- extraData(extraData_),
- targetInstanceId(kSystemInstanceId),
- targetAppGroupMask(kDefaultTargetGroupMask) {
- // Posting events to the system must always have a corresponding callback
- CHRE_ASSERT(systemEventCallback_ != nullptr);
- }
+ uint32_t senderInstanceId = kSystemInstanceId,
+ uint32_t targetInstanceId = kBroadcastInstanceId);
void incrementRefCount() {
mRefCount++;
@@ -92,62 +57,17 @@ class Event : public NonCopyable {
return (mRefCount == 0);
}
- //! @return true if this event has an associated callback which needs to be
- //! called prior to deallocating the event
- bool hasFreeCallback() {
- return (targetInstanceId == kSystemInstanceId || freeCallback != nullptr);
- }
-
- /**
- * Invoke the callback associated with this event with the applicable function
- * signature (passing extraData if this is a system event).
- *
- * The caller MUST confirm that hasFreeCallback() is true before calling this
- * method.
- */
- void invokeFreeCallback() {
- if (targetInstanceId == kSystemInstanceId) {
- systemEventCallback(eventType, eventData, extraData);
- } else {
- freeCallback(eventType, eventData);
- }
- }
-
const uint16_t eventType;
-
//! This value can serve as a proxy for how fast CHRE is processing events
//! in its queue by substracting the newest event timestamp by the oldest one.
const uint16_t receivedTimeMillis;
void *const eventData;
-
- //! If targetInstanceId is kSystemInstanceId, senderInstanceId is always
- //! kSystemInstanceId (nanoapps can't send events to the system), so we
- //! utilize that to allow an extra 32 bits of data to be passed to the
- //! callback, which can reduce dynamic allocation in several cases. Therefore,
- //! if targetInstanceId == kSystemInstanceId, then we use the latter two
- //! elements in the following two unions
- union {
- chreEventCompleteFunction *const freeCallback;
- SystemEventCallbackFunction *const systemEventCallback;
- };
- union {
- const uint32_t senderInstanceId;
- void *const extraData;
- };
+ chreEventCompleteFunction *const freeCallback;
+ const uint32_t senderInstanceId;
const uint32_t targetInstanceId;
- // Bitmask that's used to limit the event delivery to some subset of listeners
- // registered for this type of event (useful when waking up listeners that can
- // have different power considerations). When left as the default value
- // (kDefaultTargetGroupMask), this has the same behavior as broadcasting to
- // all registered listeners.
- const uint16_t targetAppGroupMask;
-
private:
- uint16_t mRefCount = 0;
-
- //! @return Monotonic time reference for initializing receivedTimeMillis
- static uint16_t getTimeMillis();
+ size_t mRefCount = 0;
};
} // namespace chre
diff --git a/core/include/chre/core/event_loop.h b/core/include/chre/core/event_loop.h
index 0c70b776..60498b29 100644
--- a/core/include/chre/core/event_loop.h
+++ b/core/include/chre/core/event_loop.h
@@ -151,46 +151,29 @@ class EventLoop : public NonCopyable {
/**
* Posts an event to a nanoapp that is currently running (or all nanoapps if
* the target instance ID is kBroadcastInstanceId). A senderInstanceId cannot
- * be provided to this method because it must only be used to post events
- * sent by the system. If the event fails to post and the event loop thread is
- * running, this is considered a fatal error. If the thread is not running
- * (e.g. CHRE is shutting down), the event is silently dropped and the free
- * callback is invoked prior to returning (if not null).
- *
- * Safe to call from any thread.
- *
- * @param eventType Event type identifier, which implies the type of eventData
- * @param eventData The data being posted
- * @param freeCallback Function to invoke to when the event has been processed
- * by all recipients; this must be safe to call immediately, to handle
- * the case where CHRE is shutting down
- * @param targetInstanceId The instance ID of the destination of this event
- * @param targetGroupMask Mask used to limit the recipients that are
- * registered to receive this event
+ * be provided to this method because it should only be used to post events
+ * sent by the system. If the event fails to post, this is considered a fatal
+ * error.
*
* @see postLowPriorityEventOrFree
*/
- void postEventOrDie(uint16_t eventType, void *eventData,
+ bool postEventOrDie(uint16_t eventType, void *eventData,
chreEventCompleteFunction *freeCallback,
- uint32_t targetInstanceId = kBroadcastInstanceId,
- uint16_t targetGroupMask = kDefaultTargetGroupMask);
+ uint32_t targetInstanceId = kBroadcastInstanceId);
/**
* Posts an event to a nanoapp that is currently running (or all nanoapps if
* the target instance ID is kBroadcastInstanceId). If the event fails to
- * post, freeCallback is invoked prior to returning (if not null).
+ * post, it is freed with freeCallback.
*
- * Safe to call from any thread.
+ * This function is safe to call from any thread.
*
- * @param eventType Event type identifier, which implies the type of eventData
- * @param eventData The data being posted
- * @param freeCallback Function to invoke to when the event has been processed
- * by all recipients; this must be safe to call immediately, to handle
- * the case where CHRE is shutting down
- * @param senderInstanceId The instance ID of the sender of this event
- * @param targetInstanceId The instance ID of the destination of this event
- * @param targetGroupMask Mask used to limit the recipients that are
- * registered to receive this event
+ * @param eventType The type of data being posted.
+ * @param eventData The data being posted.
+ * @param freeCallback The callback to invoke when the event is no longer
+ * needed.
+ * @param senderInstanceId The instance ID of the sender of this event.
+ * @param targetInstanceId The instance ID of the destination of this event.
*
* @return true if the event was successfully added to the queue.
*
@@ -200,33 +183,7 @@ class EventLoop : public NonCopyable {
uint16_t eventType, void *eventData,
chreEventCompleteFunction *freeCallback,
uint32_t senderInstanceId = kSystemInstanceId,
- uint32_t targetInstanceId = kBroadcastInstanceId,
- uint16_t targetGroupMask = kDefaultTargetGroupMask);
-
- /**
- * Posts an event for processing by the system from within the context of the
- * CHRE thread. Uses the same underlying event queue as is used for nanoapp
- * events, but gives the ability to provide an additional data pointer. If the
- * event loop is running and the system event can't be posted (i.e. queue is
- * full), then a fatal error is raised.
- *
- * Safe to call from any thread.
- *
- * @param eventType Event type identifier, which is forwarded to the callback
- * @param eventData Arbitrary data to pass to the callback
- * @param callback Function to invoke from the context of the CHRE thread
- * @param extraData Additional arbitrary data to provide to the callback
- *
- * @return true if successfully posted; false ONLY IF the CHRE event loop is
- * shutting down and not accepting any new events - in this case,
- * the callback will not be invoked and any allocated memory must be
- * cleaned up
- *
- * @see postEventOrDie
- * @see EventLoopManager::deferCallback
- */
- bool postSystemEvent(uint16_t eventType, void *eventData,
- SystemEventCallbackFunction *callback, void *extraData);
+ uint32_t targetInstanceId = kBroadcastInstanceId);
/**
* Returns a pointer to the currently executing Nanoapp, or nullptr if none is
@@ -385,8 +342,7 @@ class EventLoop : public NonCopyable {
bool allocateAndPostEvent(uint16_t eventType, void *eventData,
chreEventCompleteFunction *freeCallback,
uint32_t senderInstanceId,
- uint32_t targetInstanceId,
- uint16_t targetGroupMask);
+ uint32_t targetInstanceId);
/**
* Do one round of Nanoapp event delivery, only considering events in
diff --git a/core/include/chre/core/event_loop_common.h b/core/include/chre/core/event_loop_common.h
index 12ddcd07..03765f02 100644
--- a/core/include/chre/core/event_loop_common.h
+++ b/core/include/chre/core/event_loop_common.h
@@ -42,6 +42,7 @@ enum class SystemCallbackType : uint16_t {
PerformDebugDump,
TimerPoolTick,
AudioHandleDataEvent,
+ WifiHandleFailedRanging,
WifiHandleRangingEvent,
AudioAvailabilityChange,
AudioHandleHostAwake,
@@ -52,19 +53,11 @@ enum class SystemCallbackType : uint16_t {
SettingChangeEvent,
GnssLocationReportEvent,
GnssMeasurementReportEvent,
- Shutdown,
- TimerSyncRequest,
- DelayedFatalError,
- GnssRequestResyncEvent,
- SendBufferedLogMessage,
};
-//! Deferred/delayed callbacks use the event subsystem but are invariably sent
-//! by the system and received by the system, so they are able to make use of an
-//! extra parameter
-//! @see Event
-using SystemEventCallbackFunction = void(uint16_t type, void *data,
- void *extraData);
+//! The function signature of a system callback mirrors the CHRE event free
+//! callback to allow it to use the same event infrastructure.
+typedef chreEventCompleteFunction SystemCallbackFunction;
/**
* Generic event free callback that can be used by any event where the event
diff --git a/core/include/chre/core/event_loop_manager.h b/core/include/chre/core/event_loop_manager.h
index 1b7e46c2..31a4ab75 100644
--- a/core/include/chre/core/event_loop_manager.h
+++ b/core/include/chre/core/event_loop_manager.h
@@ -20,10 +20,13 @@
#include "chre/core/debug_dump_manager.h"
#include "chre/core/event_loop.h"
#include "chre/core/event_loop_common.h"
+#include "chre/core/gnss_manager.h"
#include "chre/core/host_comms_manager.h"
+#include "chre/core/sensor_request_manager.h"
+#include "chre/core/wifi_request_manager.h"
+#include "chre/core/wwan_request_manager.h"
#include "chre/platform/memory_manager.h"
#include "chre/platform/mutex.h"
-#include "chre/util/always_false.h"
#include "chre/util/fixed_size_vector.h"
#include "chre/util/non_copyable.h"
#include "chre/util/singleton.h"
@@ -34,30 +37,8 @@
#include "chre/core/audio_request_manager.h"
#endif // CHRE_AUDIO_SUPPORT_ENABLED
-#ifdef CHRE_GNSS_SUPPORT_ENABLED
-#include "chre/core/gnss_manager.h"
-#endif // CHRE_GNSS_SUPPORT_ENABLED
-
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
-#include "chre/core/sensor_request_manager.h"
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
-
-#ifdef CHRE_WIFI_SUPPORT_ENABLED
-#include "chre/core/wifi_request_manager.h"
-#endif // CHRE_WIFI_SUPPORT_ENABLED
-
-#ifdef CHRE_WWAN_SUPPORT_ENABLED
-#include "chre/core/wwan_request_manager.h"
-#endif // CHRE_WWAN_SUPPORT_ENABLED
-
-#include <cstddef>
-
namespace chre {
-template <typename T>
-using TypedSystemEventCallbackFunction = void(SystemCallbackType type,
- UniquePtr<T> &&data);
-
/**
* A class that keeps track of all event loops in the system. This class
* represents the top-level object in CHRE. It will own all resources that are
@@ -93,69 +74,12 @@ class EventLoopManager : public NonCopyable {
* @param type An identifier for the callback, which is passed through to the
* callback as a uint16_t, and can also be useful for debugging
* @param data Arbitrary data to provide to the callback
- * @param callback Function to invoke from within the main CHRE thread
- * @param extraData Additional arbitrary data to provide to the callback
+ * @param callback Function to invoke from within the main CHRE event loop
*/
void deferCallback(SystemCallbackType type, void *data,
- SystemEventCallbackFunction *callback,
- void *extraData = nullptr) {
- mEventLoop.postSystemEvent(static_cast<uint16_t>(type), data, callback,
- extraData);
- }
-
- /**
- * Alternative version of deferCallback which accepts a UniquePtr for the data
- * passed to the callback. This overload helps ensure that type continuity is
- * maintained with the callback, and also helps to ensure that the memory is
- * not leaked, including when CHRE is shutting down.
- *
- * Safe to call from any thread.
- *
- * @param type An identifier for the callback, which is passed through as
- * uint16_t, and can also be useful for debugging
- * @param data Pointer to arbitrary data to provide to the callback
- * @param callback Function to invoke from within the main CHRE thread
- */
- template <typename T>
- void deferCallback(SystemCallbackType type, UniquePtr<T> &&data,
- TypedSystemEventCallbackFunction<T> *callback) {
- auto outerCallback = [](uint16_t type, void *data, void *extraData) {
- // Re-wrap eventData in UniquePtr so its destructor will get called and
- // the memory will be freed once we leave this scope
- UniquePtr<T> dataWrapped = UniquePtr<T>(static_cast<T *>(data));
- auto *innerCallback =
- reinterpret_cast<TypedSystemEventCallbackFunction<T> *>(extraData);
- innerCallback(static_cast<SystemCallbackType>(type),
- std::move(dataWrapped));
- };
- // Pass the "inner" callback (the caller's callback) through to the "outer"
- // callback using the extraData parameter. Note that we're leveraging the
- // C++11 ability to cast a function pointer to void*
- if (mEventLoop.postSystemEvent(static_cast<uint16_t>(type), data.get(),
- outerCallback,
- reinterpret_cast<void *>(callback))) {
- data.release();
- }
- }
-
- //! Override that allows passing a lambda for the callback
- template <typename T, typename LambdaT>
- void deferCallback(SystemCallbackType type, UniquePtr<T> &&data,
- LambdaT callback) {
- deferCallback(type, std::move(data),
- static_cast<TypedSystemEventCallbackFunction<T> *>(callback));
- }
-
- //! Disallows passing a null callback, as we don't include a null check in the
- //! outer callback to reduce code size. Note that this doesn't prevent the
- //! caller from passing a variable which is set to nullptr at runtime, but
- //! generally the callback is always known at compile time.
- template <typename T>
- void deferCallback(SystemCallbackType /*type*/, UniquePtr<T> && /*data*/,
- std::nullptr_t /*callback*/) {
- static_assert(AlwaysFalse<T>::value,
- "deferCallback(SystemCallbackType, UniquePtr<T>, nullptr) is "
- "not allowed");
+ SystemCallbackFunction *callback) {
+ mEventLoop.postEventOrDie(static_cast<uint16_t>(type), data, callback,
+ kSystemInstanceId);
}
/**
@@ -168,15 +92,14 @@ class EventLoopManager : public NonCopyable {
* @param type An identifier for the callback, which is passed through to the
* callback as a uint16_t, and can also be useful for debugging
* @param data Arbitrary data to provide to the callback
- * @param callback Function to invoke from within the main CHRE event loop -
- * note that extraData is always passed back as nullptr
+ * @param callback Function to invoke from within the main CHRE event loop
* @param delay The delay to postpone posting the event
* @return TimerHandle of the requested timer.
*
* @see deferCallback
*/
TimerHandle setDelayedCallback(SystemCallbackType type, void *data,
- SystemEventCallbackFunction *callback,
+ SystemCallbackFunction *callback,
Nanoseconds delay) {
return mEventLoop.getTimerPool().setSystemTimer(delay, callback, type,
data);
@@ -240,7 +163,6 @@ class EventLoopManager : public NonCopyable {
return mHostCommsManager;
}
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
/**
* @return Returns a reference to the sensor request manager. This allows
* interacting with the platform sensors and managing requests from
@@ -249,7 +171,6 @@ class EventLoopManager : public NonCopyable {
SensorRequestManager &getSensorRequestManager() {
return mSensorRequestManager;
}
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
#ifdef CHRE_WIFI_SUPPORT_ENABLED
/**
@@ -318,11 +239,9 @@ class EventLoopManager : public NonCopyable {
//! Handles communications with the host processor.
HostCommsManager mHostCommsManager;
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
//! The SensorRequestManager that handles requests for all nanoapps. This
//! manages the state of all sensors that runtime subscribes to.
SensorRequestManager mSensorRequestManager;
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
#ifdef CHRE_WIFI_SUPPORT_ENABLED
//! The WifiRequestManager that handles requests for nanoapps. This manages
@@ -351,11 +270,9 @@ typedef Singleton<EventLoopManager> EventLoopManagerSingleton;
//! calls. This reduces codesize considerably.
extern template class Singleton<EventLoopManager>;
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
inline SensorRequestManager &getSensorRequestManager() {
return EventLoopManagerSingleton::get()->getSensorRequestManager();
}
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
} // namespace chre
diff --git a/core/include/chre/core/gnss_manager.h b/core/include/chre/core/gnss_manager.h
index f189f68b..61cbb172 100644
--- a/core/include/chre/core/gnss_manager.h
+++ b/core/include/chre/core/gnss_manager.h
@@ -85,14 +85,6 @@ class GnssSession {
void handleReportEvent(void *event);
/**
- * @return true if an async response is pending from GNSS. This method should
- * be used to check if a GNSS session request is in flight.
- */
- bool asyncResponsePending() const {
- return !mStateTransitions.empty() || mInternalRequestPending;
- }
-
- /**
* Invoked when the host notifies CHRE of a settings change.
*
* @param setting The setting that changed.
@@ -101,22 +93,12 @@ class GnssSession {
void onSettingChanged(Setting setting, SettingState state);
/**
- * Updates the platform GNSS request according to the current state. It should
- * be used to synchronize the GNSS to the desired state, e.g. for setting
- * updates or handling a state resync request.
- *
- * @param forceUpdate If true, force the platform GNSS request to be made.
+ * Handles a change in the Location setting, making a GNSS request if
+ * necessary according to the new state.
*
- * @return true if the invocation resulted in dispatching an internal
- * request to control the platform layer
- */
- bool updatePlatformRequest(bool forceUpdate = false);
-
- /**
- * Invoked as a result of a requestStateResync() callback from the GNSS PAL.
- * Runs in the context of the CHRE thread.
+ * @param state The new setting state.
*/
- void handleRequestStateResyncCallbackSync();
+ void handleLocationSettingChange(SettingState state);
/**
* Prints state in a string buffer. Must only be called from the context of
@@ -174,7 +156,7 @@ class GnssSession {
};
//! The event type of the session's report data.
- const uint16_t kReportEventType;
+ uint16_t mReportEventType;
//! The request type to start and stop a session.
uint8_t mStartRequestType;
@@ -211,9 +193,6 @@ class GnssSession {
//! True if a setting change event is pending to be processed.
bool mSettingChangePending = false;
- //! True if a state resync callback is pending to be processed.
- bool mResyncPending = false;
-
// Allows GnssManager to access constructor.
friend class GnssManager;
@@ -414,27 +393,6 @@ class GnssManager : public NonCopyable {
void onSettingChanged(Setting setting, SettingState state);
/**
- * Invoked as a result of a requestStateResync() callback from the GNSS PAL.
- * Runs asynchronously in the context of the callback immediately.
- */
- void handleRequestStateResyncCallback();
-
- /**
- * Invoked as a result of a requestStateResync() callback from the GNSS PAL.
- * Runs in the context of the CHRE thread.
- */
- void handleRequestStateResyncCallbackSync();
-
- /**
- * @param nanoapp The nanoapp invoking
- * chreGnssConfigurePassiveLocationListener.
- * @param enable true to enable the configuration.
- *
- * @return true if the configuration succeeded.
- */
- bool configurePassiveLocationListener(Nanoapp *nanoapp, bool enable);
-
- /**
* Prints state in a string buffer. Must only be called from the context of
* the main CHRE thread.
*
@@ -455,34 +413,6 @@ class GnssManager : public NonCopyable {
//! The instance of measurement session.
GnssSession mMeasurementSession;
-
- //! The list of instance ID of nanoapps that has a passive location listener
- //! request.
- DynamicVector<uint32_t> mPassiveLocationListenerNanoapps;
-
- //! true if the passive location listener is enabled at the platform.
- bool mPlatformPassiveLocationListenerEnabled;
-
- /**
- * @param nanoappInstanceId The instance ID of the nanoapp to check.
- * @param index If non-null and this function returns true, stores the index
- * of mPassiveLocationListenerNanoapps where the instance ID is stored.
- *
- * @return true if the nanoapp currently has a passive location listener
- * request.
- */
- bool nanoappHasPassiveLocationListener(uint32_t nanoappInstanceId,
- size_t *index = nullptr);
-
- /**
- * Helper function to invoke configurePassiveLocationListener at the platform
- * and handle the result.
- *
- * @param enable true to enable the configuration.
- *
- * @return true if success.
- */
- bool platformConfigurePassiveLocationListener(bool enable);
};
} // namespace chre
diff --git a/core/include/chre/core/host_comms_manager.h b/core/include/chre/core/host_comms_manager.h
index 006ccceb..22956a04 100644
--- a/core/include/chre/core/host_comms_manager.h
+++ b/core/include/chre/core/host_comms_manager.h
@@ -52,16 +52,8 @@ struct HostMessage : public NonCopyable {
//! Application-specific message ID
uint32_t messageType;
- //! List of Android permissions declared by the nanoapp. This must be a
- //! superset of messagePermissions.
- uint32_t appPermissions;
-
- //! List of Android permissions that cover the contents of the message.
- //! These permissions are used to record and attribute access to
- //! permissions-controlled resources.
- //! Note that these permissions must always be a subset of uint32_t
- //! permissions. Otherwise, the message will be dropped.
- uint32_t messagePermissions;
+ //! Padding used to align this structure with chreMessageFromHostData
+ uint32_t reserved;
//! Message free callback supplied by the nanoapp. Must only be invoked
//! from the EventLoop where the nanoapp runs.
@@ -84,17 +76,30 @@ typedef HostMessage MessageFromHost;
typedef HostMessage MessageToHost;
/**
- * Common code for managing bi-directional communications between the host and
- * nanoapps. Inherits from the platform-specific HostLink class to accomplish
- * this, and also to provide an access point (lookup via the EventLoopManager
- * Singleton) to the platform-specific HostLinkBase functionality for use by
- * platform-specific code.
+ * Manages bi-directional communications with the host. There must only be one
+ * instance of this class per CHRE instance, as the HostLink is not multiplexed
+ * per-EventLoop.
*/
-class HostCommsManager : public HostLink {
+class HostCommsManager : public NonCopyable {
public:
HostCommsManager() : mIsNanoappBlamedForWakeup(false) {}
/**
+ * @see HostLink::flushMessagesSentByNanoapp
+ */
+ void flushMessagesSentByNanoapp(uint64_t appId);
+
+ /**
+ * Sends a Log Message to the host over the HostLink
+ * @see HostLink::sendLogMessage
+ *
+ * @param logMessage Buffer containing a (possibly encoded) log message
+ * @param logMessageSize size in bytes of the logMessage buffer
+ */
+
+ void sendLogMessage(const char *logMessage, size_t logMessageSize);
+
+ /**
* Formulates a MessageToHost using the supplied message contents and passes
* it to HostLink for transmission to the host.
*
@@ -107,9 +112,6 @@ class HostCommsManager : public HostLink {
* receive this message
* @param freeCallback Optional callback to invoke when the messageData is no
* longer needed (the message has been sent or an error occurred)
- * @param messagePermissions List of Android permissions that cover the
- * contents of the message. These permissions are used to record and
- * attribute access to permissions-controlled resources.
*
* @return true if the message was accepted into the outbound message queue.
* If this function returns false, it does *not* invoke freeCallback.
@@ -121,7 +123,6 @@ class HostCommsManager : public HostLink {
bool sendMessageToHostFromNanoapp(Nanoapp *nanoapp, void *messageData,
size_t messageSize, uint32_t messageType,
uint16_t hostEndpoint,
- uint32_t messagePermissions,
chreMessageFreeFunction *freeCallback);
/**
@@ -189,6 +190,9 @@ class HostCommsManager : public HostLink {
//! messages directly in onMessageToHostComplete.
SynchronizedMemoryPool<HostMessage, kMaxOutstandingMessages> mMessagePool;
+ //! The platform-specific link to the host that we manage
+ HostLink mHostLink;
+
/**
* Allocates and populates the event structure used to notify a nanoapp of an
* incoming message from the host.
@@ -216,9 +220,6 @@ class HostCommsManager : public HostLink {
*
* @param craftedMessage Message from host to be delivered to the destination
* nanoapp
- *
- * @return true if the message was delivered to the event queue (i.e.
- * destination app ID exists in the system)
*/
bool deliverNanoappMessageFromHost(MessageFromHost *craftedMessage);
diff --git a/core/include/chre/core/nanoapp.h b/core/include/chre/core/nanoapp.h
index fa7a08c8..891032fb 100644
--- a/core/include/chre/core/nanoapp.h
+++ b/core/include/chre/core/nanoapp.h
@@ -25,7 +25,6 @@
#include "chre/util/dynamic_vector.h"
#include "chre/util/fixed_size_vector.h"
#include "chre/util/system/debug_dump.h"
-#include "chre/util/system/napp_permissions.h"
namespace chre {
@@ -91,32 +90,23 @@ class Nanoapp : public PlatformNanoapp {
* @return true if the nanoapp should receive broadcast events with the given
* type
*/
- bool isRegisteredForBroadcastEvent(uint16_t eventType,
- uint16_t targetGroupIdMask) const;
+ bool isRegisteredForBroadcastEvent(uint16_t eventType) const;
/**
* Updates the Nanoapp's registration so that it will receive broadcast events
- * with the given event type.
+ * with the given event ID.
*
- * @param eventType The event type that the nanoapp will now be registered to
- * receive
- * @param groupIdMask A mask of group IDs to register the nanoapp for. If an
- * event is sent that targets any of the group IDs in the mask, it will
- * be delivered to the nanoapp.
+ * @return true if the event is newly registered
*/
- void registerForBroadcastEvent(
- uint16_t eventType, uint16_t groupIdMask = kDefaultTargetGroupMask);
+ bool registerForBroadcastEvent(uint16_t eventId);
/**
* Updates the Nanoapp's registration so that it will not receive broadcast
- * events with the given event type.
+ * events with the given event ID.
*
- * @param eventType The event type that the nanoapp will be unregistered from
- * assuming the group ID also matches a valid entry.
- * @param groupIdMask The mask of group IDs that will be unregistered from.
+ * @return true if the event was previously registered
*/
- void unregisterForBroadcastEvent(
- uint16_t eventType, uint16_t groupIdMask = kDefaultTargetGroupMask);
+ bool unregisterForBroadcastEvent(uint16_t eventId);
/**
* Adds an event to this nanoapp's queue of pending events.
@@ -159,18 +149,6 @@ class Nanoapp : public PlatformNanoapp {
void configureDebugDumpEvent(bool enable);
/**
- * Configures whether a user settings event will be sent to the nanoapp
- * for a specified setting (@see CHRE_USER_SETTINGS)
- * Nanoapps are not sent user settings events by default.
- *
- * @param setting The user setting that the nanoapp wishes to configure
- * events for.
- *
- * @param enable true if events are to be sent, false otherwise.
- */
- void configureUserSettingEvent(uint8_t setting, bool enable);
-
- /**
* Sends the next event in the queue to the nanoapp and returns the processed
* event. The hasPendingEvent() method should be tested before invoking this.
*
@@ -201,11 +179,6 @@ class Nanoapp : public PlatformNanoapp {
*/
void logStateToBuffer(DebugDumpWrapper &debugDump) const;
- /**
- * @return true if the nanoapp is permitted to use the provided permission.
- */
- bool permitPermissionUse(uint32_t permission) const;
-
private:
uint32_t mInstanceId = kInvalidInstanceId;
@@ -223,35 +196,13 @@ class Nanoapp : public PlatformNanoapp {
//! wakeups over time intervals.
FixedSizeVector<uint16_t, kMaxSizeWakeupBuckets> mWakeupBuckets;
- //! Metadata needed for keeping track of the registered events for this
- //! nanoapp.
- struct EventRegistration {
- EventRegistration(uint16_t eventType_, uint16_t groupIdMask_)
- : eventType(eventType_), groupIdMask(groupIdMask_) {}
-
- uint16_t eventType;
- uint16_t groupIdMask;
- };
-
//! The set of broadcast events that this app is registered for.
// TODO: Implement a set container and replace DynamicVector here. There may
// also be a better way of handling this (perhaps we map event type to apps
// who care about them).
- DynamicVector<EventRegistration> mRegisteredEvents;
+ DynamicVector<uint16_t> mRegisteredEvents;
EventRefQueue mEventQueue;
-
- //! @return index of event registration if found. mRegisteredEvents.size() if
- //! not.
- size_t registrationIndex(uint16_t eventType) const;
-
- /**
- * A special function to deliver GNSS measurement events to nanoapps and
- * handles version compatibility.
- *
- * @param event The pointer to the event
- */
- void handleGnssMeasurementDataEvent(const Event *event);
};
} // namespace chre
diff --git a/core/include/chre/core/sensor.h b/core/include/chre/core/sensor.h
index 53962158..d310ee11 100644
--- a/core/include/chre/core/sensor.h
+++ b/core/include/chre/core/sensor.h
@@ -66,13 +66,6 @@ class Sensor : public PlatformSensor {
}
/**
- * @return true if the sensor has bias updates enabled.
- */
- bool biasEventsEnabled() const {
- return mSensorRequests.getCurrentMaximalRequest().getBiasUpdatesRequested();
- }
-
- /**
* @return A const reference to the maximal request.
*/
const SensorRequest &getMaximalRequest() const {
@@ -214,8 +207,6 @@ class Sensor : public PlatformSensor {
/**
* Sets the current status of this sensor in the CHRE API format.
*
- * Note: This method is called on a thread other than the main event loop.
- *
* @param status The current sampling status.
*/
void setSamplingStatus(const struct chreSensorSamplingStatus &status);
@@ -229,11 +220,6 @@ class Sensor : public PlatformSensor {
return SensorTypeHelpers::getLastEventSize(getSensorType());
}
- //! Mutex used to lock setting / getting the sampling status information for
- //! sensors. Share it among all sensors since nanoapps can only request a
- //! single sensor status at a time.
- static Mutex mSamplingStatusMutex;
-
//! The latest sampling status provided by the sensor.
struct chreSensorSamplingStatus mSamplingStatus = {};
diff --git a/core/include/chre/core/sensor_request.h b/core/include/chre/core/sensor_request.h
index 03c8c02e..15c52c3b 100644
--- a/core/include/chre/core/sensor_request.h
+++ b/core/include/chre/core/sensor_request.h
@@ -77,15 +77,6 @@ class SensorRequest {
bool isEquivalentTo(const SensorRequest &request) const;
/**
- * Indicates that the only difference between the two requests is that the
- * bias request state has changed.
- *
- * @param request The request to compare against.
- * @return true if only the bias request value is different.
- */
- bool onlyBiasRequestUpdated(const SensorRequest &request) const;
-
- /**
* Assigns the current request to the maximal superset of the mode, rate
* and latency of the other request.
*
@@ -102,14 +93,6 @@ class SensorRequest {
}
/**
- * Overrides the latency specified in the request to the provided latency
- * value.
- */
- void setLatency(Nanoseconds latency) {
- mLatency = latency;
- }
-
- /**
* @return Returns the maximum amount of time samples can be batched prior to
* dispatching to the client.
*/
@@ -131,22 +114,6 @@ class SensorRequest {
return mInstanceId;
}
- /**
- * Sets whether the request also wants bias updates.
- *
- * @param requested Whether bias updates should be requested.
- */
- void setBiasUpdatesRequested(bool requested) {
- mBiasUpdatesRequested = requested;
- }
-
- /**
- * @return Whether bias updates are requested
- */
- bool getBiasUpdatesRequested() const {
- return mBiasUpdatesRequested;
- }
-
private:
//! The interval between samples for this request.
Nanoseconds mInterval;
@@ -161,9 +128,6 @@ class SensorRequest {
//! The mode of this request.
SensorMode mMode;
-
- //! Whether the nanoapp is requesting bias updates.
- bool mBiasUpdatesRequested = false;
};
} // namespace chre
diff --git a/core/include/chre/core/sensor_request_manager.h b/core/include/chre/core/sensor_request_manager.h
index bf3357a8..9eee0204 100644
--- a/core/include/chre/core/sensor_request_manager.h
+++ b/core/include/chre/core/sensor_request_manager.h
@@ -56,39 +56,11 @@ class SensorRequestManager : public NonCopyable {
* supplied sensorHandle is only populated if the sensor type is known.
*
* @param sensorType The type of the sensor.
- * @param sensorIndex The index of the sensor.
- * @param targetGroupId The target group ID that must be covered by the
- * matching sensor.
* @param sensorHandle A non-null pointer to a uint32_t to use as a sensor
* handle for nanoapps.
* @return true if the supplied sensor type is available for use.
*/
- bool getSensorHandle(uint8_t sensorType, uint8_t sensorIndex,
- uint16_t targetGroupId, uint32_t *sensorHandle) const;
-
- /**
- * Same as getSensorHandle(), but the targetGroupId is derived based on the
- * nanoapp's characteristics.
- */
- bool getSensorHandleForNanoapp(uint8_t sensorType, uint8_t sensorIndex,
- const Nanoapp &nanoapp,
- uint32_t *sensorHandle) const {
- return getSensorHandle(sensorType, sensorIndex,
- mPlatformSensorManager.getTargetGroupId(nanoapp),
- sensorHandle);
- }
-
- /**
- * Same as getSensorHandle(), but 0 is used for both the sensorIndex and
- * targetGroupId so that the first sensor matching the type is used. This is
- * useful when dealing with one-shot sensors that must only have a single
- * instance.
- */
- bool getDefaultSensorHandle(uint8_t sensorType,
- uint32_t *sensorHandle) const {
- return getSensorHandle(sensorType, 0 /* sensorIndex */,
- 0 /* targetGroupId */, sensorHandle);
- }
+ bool getSensorHandle(uint8_t sensorType, uint32_t *sensorHandle) const;
/**
* Sets a sensor request for the given nanoapp for the provided sensor handle.
@@ -303,20 +275,20 @@ class SensorRequestManager : public NonCopyable {
//! An internal structure to store sensor request logs
struct SensorRequestLog {
SensorRequestLog(Nanoseconds timestampIn, uint32_t instanceIdIn,
- uint32_t sensorHandleIn, SensorMode modeIn,
+ uint8_t sensorTypeIn, SensorMode modeIn,
Nanoseconds intervalIn, Nanoseconds latencyIn)
: timestamp(timestampIn),
interval(intervalIn),
latency(latencyIn),
instanceId(instanceIdIn),
- sensorHandle(sensorHandleIn),
+ sensorType(sensorTypeIn),
mode(modeIn) {}
Nanoseconds timestamp;
Nanoseconds interval;
Nanoseconds latency;
uint32_t instanceId;
- uint32_t sensorHandle;
+ uint8_t sensorType;
SensorMode mode;
};
@@ -466,29 +438,21 @@ class SensorRequestManager : public NonCopyable {
* off if full.
*
* @param nanoappInstanceId Instance ID of the nanoapp that made the request.
- * @param sensorHandle The sensor handle for the sensor request being added.
+ * @param sensorType The sensor type of requested sensor.
* @param sensorRequest The SensorRequest object holding params about
* request.
*/
- void addSensorRequestLog(uint32_t nanoappInstanceId, uint32_t sensorHandle,
+ void addSensorRequestLog(uint32_t nanoappInstanceId, uint8_t sensorType,
const SensorRequest &sensorRequest);
/**
* Helper function to make a sensor's maximal request to the platform, and
* reset the last event if an on-change sensor is successfully turned off.
*
- * If either bias update configuration or sensor data configuration fails,
- * this entire method will fail. When this method fails, any previous
- * configuration will be restored on a best-effort basis.
- *
- * @param sensor The sensor that will be configured.
- * @param prevSensorRequest The previous sensor request that was made for the
- * given sensor.
- * @return true if both configuring the platform for bias updates and for
- * sensor data succeeded.
+ * @param sensor The sensor that will be making the request.
+ * @return true if the platform accepted the request.
*/
- bool configurePlatformSensor(Sensor &sensor,
- const SensorRequest &prevSensorRequest);
+ bool configurePlatformSensor(Sensor &sensor);
};
} // namespace chre
diff --git a/core/include/chre/core/sensor_type.h b/core/include/chre/core/sensor_type.h
index 73497692..59afb1cb 100644
--- a/core/include/chre/core/sensor_type.h
+++ b/core/include/chre/core/sensor_type.h
@@ -47,7 +47,6 @@ union ChreSensorData {
struct chreSensorOccurrenceData occurrenceData;
struct chreSensorFloatData floatData;
struct chreSensorByteData byteData;
- struct chreSensorUint64Data uint64Data;
};
// Validate that aliasing into the header is valid for all types of the union
@@ -59,8 +58,6 @@ static_assert(offsetof(ChreSensorData, floatData.header) == 0,
"Float data header not at offset 0");
static_assert(offsetof(ChreSensorData, byteData.header) == 0,
"Byte data header not at offset 0");
-static_assert(offsetof(ChreSensorData, uint64Data.header) == 0,
- "Uint64 data header not at offset 0");
/**
* Returns a sensor sample event type for a given sensor type. The sensor type
diff --git a/core/include/chre/core/sensor_type_helpers.h b/core/include/chre/core/sensor_type_helpers.h
index 24e811da..ccbb65b7 100644
--- a/core/include/chre/core/sensor_type_helpers.h
+++ b/core/include/chre/core/sensor_type_helpers.h
@@ -99,14 +99,6 @@ class SensorTypeHelpers : public PlatformSensorTypeHelpers {
static const char *getSensorTypeName(uint8_t sensorType);
/**
- * @param sensorType The sensor type.
- * @return The corresponding uncalibrated sensor type. If the sensor does not
- * have one or is already uncalibrated, then the input sensorType is
- * returned.
- */
- static uint8_t toUncalibratedSensorType(uint8_t sensorType);
-
- /**
* Extracts the last sample from the suppled event and updates it to the
* supplied last event memory as a single-sample event. No-op if not an
* on-change sensor.
diff --git a/core/include/chre/core/settings.h b/core/include/chre/core/settings.h
index 38a6b797..6abe72c4 100644
--- a/core/include/chre/core/settings.h
+++ b/core/include/chre/core/settings.h
@@ -25,13 +25,14 @@ namespace chre {
enum class Setting : uint8_t {
LOCATION = 0,
- WIFI_AVAILABLE,
- AIRPLANE_MODE,
- MICROPHONE,
SETTING_MAX,
};
-enum class SettingState : int8_t { UNKNOWN = -1, ENABLED = 0, DISABLED };
+enum class SettingState : uint8_t {
+ ENABLED = 0,
+ DISABLED,
+ SETTING_STATE_MAX,
+};
/**
* Updates the state of a given setting.
@@ -47,23 +48,12 @@ void postSettingChange(Setting setting, SettingState state);
*
* @param setting The setting to check the current state of.
*
- * @return The current state of the setting, SETTING_STATE_UNKNOWN if the
- * provided setting is invalid.
+ * @return The current state of the setting, SETTING_STATE_MAX if the provided
+ * setting is invalid.
*/
SettingState getSettingState(Setting setting);
/**
- * Gets the current state of a given setting, but returns the state as an
- * int8_t. The state is guaranteed to be a member of enum chreUserSettingState.
- *
- * @param setting The setting to check the current state of (see
- * CHRE_USER_SETTINGS).
- *
- * @return The current state of the setting (see enum chreUserSettingState)
- */
-int8_t getSettingStateAsInt8(uint8_t setting);
-
-/**
* Logs the settings related stats in the debug dump. Must be called from the
* context of the main CHRE thread.
*
diff --git a/core/include/chre/core/timer_pool.h b/core/include/chre/core/timer_pool.h
index 128fd46d..a27247c8 100644
--- a/core/include/chre/core/timer_pool.h
+++ b/core/include/chre/core/timer_pool.h
@@ -60,30 +60,30 @@ class TimerPool : public NonCopyable {
TimerHandle setNanoappTimer(const Nanoapp *nanoapp, Nanoseconds duration,
const void *cookie, bool isOneShot) {
CHRE_ASSERT(nanoapp != nullptr);
- return setTimer(nanoapp->getInstanceId(), duration, cookie,
- nullptr /* systemCallback */,
- SystemCallbackType::FirstCallbackType, isOneShot);
+ return setTimer(nanoapp->getInstanceId(), duration, nullptr /* callback */,
+ CHRE_EVENT_TIMER, cookie, isOneShot);
}
/**
* Requests a timer for a system callback. When the timer expires, the
* specified SystemCallbackFunction will be processed in the context of the
* main CHRE event loop. Note that it is not immediately invoked when the
- * timer expires. If no system timers are available, this method will trigger
- * a fatal error.
+ * timer expires. If no system timers are available, this method will fatally
+ * error.
*
- * Safe to invoke from any thread.
+ * TODO: Consider adding a way to directly invoke a callback after the delay
+ * rather than posting an event.
*
* @param duration The duration to set the timer for.
* @param callback The callback to invoke when the timer expires.
* @param callbackType The type of this callback.
- * @param data Arbitrary data to pass to the callback. Note that extraData is
- * always given to the callback as nullptr.
+ * @param cookie A cookie to pass to this callback.
* @return TimerHandle of the requested timer.
*/
TimerHandle setSystemTimer(Nanoseconds duration,
- SystemEventCallbackFunction *callback,
- SystemCallbackType callbackType, void *data);
+ SystemCallbackFunction *callback,
+ SystemCallbackType callbackType,
+ const void *cookie);
/**
* Cancels a timer given a handle.
@@ -112,22 +112,26 @@ class TimerPool : public NonCopyable {
* Tracks metadata associated with a request for a timed event.
*/
struct TimerRequest {
- //! The instance ID from which this request was made
+ //! The instance ID from which this request was made.
uint32_t instanceId;
+
+ //! The TimerHandle assigned to this request.
TimerHandle timerHandle;
+
+ //! The time when the request was made.
Nanoseconds expirationTime;
+
+ //! The requested duration of the timer.
Nanoseconds duration;
- //! The cookie pointer to be passed as an event to the requesting nanoapp,
- //! or data pointer for system callbacks.
- const void *cookie;
+ //! The callback to invoked after the timer event is posted to CHRE.
+ SystemCallbackFunction *callback;
- //! If a system timer (instanceId == kSystemInstanceId), callback to invoke
- //! after the timer expires, otherwise nullptr
- SystemEventCallbackFunction *systemCallback;
+ //! The cookie pointer to be passed as an event to the requesting nanoapp.
+ const void *cookie;
- //! Only relevant if this is a system timer
- SystemCallbackType callbackType;
+ //! The event type to post when the timer expires.
+ uint16_t eventType;
//! Whether or not the request is a one shot or should be rescheduled.
bool isOneShot;
@@ -182,16 +186,13 @@ class TimerPool : public NonCopyable {
* @param instanceId The instance ID of the caller.
* @param duration The duration of the timer.
* @param cookie A cookie to pass to the app when the timer elapses.
- * @param systemCallback Callback to invoke (only for system-started timers).
- * @param callbackType Identifier to pass to the callback.
* @param isOneShot false if the timer is expected to auto-reload.
* @return TimerHandle of the requested timer. Returns CHRE_TIMER_INVALID if
* not successful.
*/
TimerHandle setTimer(uint32_t instanceId, Nanoseconds duration,
- const void *cookie,
- SystemEventCallbackFunction *systemCallback,
- SystemCallbackType callbackType, bool isOneShot);
+ SystemCallbackFunction *callback, uint16_t eventType,
+ const void *cookie, bool isOneShot);
/**
* Cancels a timer given a handle.
@@ -271,7 +272,7 @@ class TimerPool : public NonCopyable {
* Sets the underlying system timer to the next timer in the timer list if
* available.
*
- * @return true if at least one timer had expired
+ * @return true if any timer events were posted
*/
bool handleExpiredTimersAndScheduleNext();
@@ -279,7 +280,7 @@ class TimerPool : public NonCopyable {
* Same as handleExpiredTimersAndScheduleNext(), except mMutex must be
* acquired prior to calling this function.
*
- * @return true if at least one timer had expired
+ * @return true if any timer events were posted
*/
bool handleExpiredTimersAndScheduleNextLocked();
diff --git a/core/include/chre/core/wifi_request_manager.h b/core/include/chre/core/wifi_request_manager.h
index 5f43d94e..90ce146e 100644
--- a/core/include/chre/core/wifi_request_manager.h
+++ b/core/include/chre/core/wifi_request_manager.h
@@ -147,7 +147,7 @@ class WifiRequestManager : public NonCopyable {
* memory is guaranteed not to be modified until it has been explicitly
* released through the PlatformWifi instance.
*/
- void handleScanEvent(struct chreWifiScanEvent *event);
+ void handleScanEvent(chreWifiScanEvent *event);
/**
* Prints state in a string buffer. Must only be called from the context of
diff --git a/core/init.cc b/core/init.cc
index 3f38eb80..01991df8 100644
--- a/core/init.cc
+++ b/core/init.cc
@@ -18,10 +18,15 @@
#include "chre/core/event_loop_manager.h"
#include "chre/platform/system_time.h"
-#include "chre/platform/version.h"
#include "chre/util/singleton.h"
-static const char *kChreVersionString = chre::getChreVersionString();
+#ifndef CHRE_VERSION_STRING
+#define CHRE_VERSION_STRING "undefined"
+#endif // CHRE_VERSION_STRING
+
+//! The CHRE version string. Placed in a variable in the global namespace for
+//! easy access with debugging tools.
+static const char kChreVersionString[] = CHRE_VERSION_STRING;
namespace chre {
diff --git a/platform/shared/pw_tokenized_log.cc b/core/log.cc
index 9817bb61..00e2a1a8 100644
--- a/platform/shared/pw_tokenized_log.cc
+++ b/core/log.cc
@@ -38,7 +38,8 @@ void pw_TokenizerHandleEncodedMessageWithPayload(void *userPayload,
constexpr size_t kLogMessageHeaderSizeBytes = 1 + sizeof(uint64_t);
uint8_t *pLogBuffer = &logBuffer[0];
- chre::NestedDataPtr<uint8_t> nestedLevel(userPayload);
+ chre::NestedDataPtr<uint8_t> nestedLevel;
+ nestedLevel.dataPtr = userPayload;
*pLogBuffer = nestedLevel.data;
++pLogBuffer;
@@ -51,7 +52,7 @@ void pw_TokenizerHandleEncodedMessageWithPayload(void *userPayload,
// TODO (b/148873804): buffer log messages generated while the AP is asleep
auto &hostCommsMgr =
chre::EventLoopManagerSingleton::get()->getHostCommsManager();
- hostCommsMgr.sendLogMessage(logBuffer,
+ hostCommsMgr.sendLogMessage(reinterpret_cast<const char *>(logBuffer),
encodedMsgSize + kLogMessageHeaderSizeBytes);
}
#endif
diff --git a/core/nanoapp.cc b/core/nanoapp.cc
index a6632f9b..fecc282a 100644
--- a/core/nanoapp.cc
+++ b/core/nanoapp.cc
@@ -21,15 +21,10 @@
#include "chre/platform/fatal_error.h"
#include "chre/platform/log.h"
#include "chre/util/system/debug_dump.h"
-#include "chre_api/chre/gnss.h"
#include "chre_api/chre/version.h"
#include <algorithm>
-#if CHRE_FIRST_SUPPORTED_API_VERSION < CHRE_API_VERSION_1_5
-#define CHRE_GNSS_MEASUREMENT_BACK_COMPAT_ENABLED
-#endif
-
namespace chre {
constexpr size_t Nanoapp::kMaxSizeWakeupBuckets;
@@ -49,40 +44,30 @@ Nanoapp::~Nanoapp() {
}
}
-bool Nanoapp::isRegisteredForBroadcastEvent(uint16_t eventType,
- uint16_t targetGroupIdMask) const {
- bool registered = false;
- size_t foundIndex = registrationIndex(eventType);
- if (foundIndex < mRegisteredEvents.size()) {
- const EventRegistration &reg = mRegisteredEvents[foundIndex];
- if (targetGroupIdMask & reg.groupIdMask) {
- registered = true;
- }
- }
- return registered;
+bool Nanoapp::isRegisteredForBroadcastEvent(uint16_t eventType) const {
+ return (mRegisteredEvents.find(eventType) != mRegisteredEvents.size());
}
-void Nanoapp::registerForBroadcastEvent(uint16_t eventType,
- uint16_t groupIdMask) {
- size_t foundIndex = registrationIndex(eventType);
- if (foundIndex < mRegisteredEvents.size()) {
- mRegisteredEvents[foundIndex].groupIdMask |= groupIdMask;
- } else if (!mRegisteredEvents.push_back(
- EventRegistration(eventType, groupIdMask))) {
+bool Nanoapp::registerForBroadcastEvent(uint16_t eventId) {
+ if (isRegisteredForBroadcastEvent(eventId)) {
+ return false;
+ }
+
+ if (!mRegisteredEvents.push_back(eventId)) {
FATAL_ERROR_OOM();
}
+
+ return true;
}
-void Nanoapp::unregisterForBroadcastEvent(uint16_t eventType,
- uint16_t groupIdMask) {
- size_t foundIndex = registrationIndex(eventType);
- if (foundIndex < mRegisteredEvents.size()) {
- EventRegistration &reg = mRegisteredEvents[foundIndex];
- reg.groupIdMask &= ~groupIdMask;
- if (reg.groupIdMask == 0) {
- mRegisteredEvents.erase(foundIndex);
- }
+bool Nanoapp::unregisterForBroadcastEvent(uint16_t eventId) {
+ size_t registeredEventIndex = mRegisteredEvents.find(eventId);
+ if (registeredEventIndex == mRegisteredEvents.size()) {
+ return false;
}
+
+ mRegisteredEvents.erase(registeredEventIndex);
+ return true;
}
void Nanoapp::configureNanoappInfoEvents(bool enable) {
@@ -113,25 +98,12 @@ void Nanoapp::configureDebugDumpEvent(bool enable) {
}
}
-void Nanoapp::configureUserSettingEvent(uint8_t setting, bool enable) {
- if (enable) {
- registerForBroadcastEvent(CHRE_EVENT_SETTING_CHANGED_FIRST_EVENT + setting);
- } else {
- unregisterForBroadcastEvent(CHRE_EVENT_SETTING_CHANGED_FIRST_EVENT +
- setting);
- }
-}
-
Event *Nanoapp::processNextEvent() {
Event *event = mEventQueue.pop();
CHRE_ASSERT_LOG(event != nullptr, "Tried delivering event, but queue empty");
if (event != nullptr) {
- if (event->eventType == CHRE_EVENT_GNSS_DATA) {
- handleGnssMeasurementDataEvent(event);
- } else {
- handleEvent(event->senderInstanceId, event->eventType, event->eventData);
- }
+ handleEvent(event->senderInstanceId, event->eventType, event->eventData);
}
return event;
@@ -172,37 +144,4 @@ void Nanoapp::logStateToBuffer(DebugDumpWrapper &debugDump) const {
debugDump.print("%" PRIu16 " ]\n", mWakeupBuckets.front());
}
-bool Nanoapp::permitPermissionUse(uint32_t permission) const {
- return !supportsAppPermissions() ||
- ((getAppPermissions() & permission) == permission);
-}
-
-size_t Nanoapp::registrationIndex(uint16_t eventType) const {
- size_t foundIndex = 0;
- for (; foundIndex < mRegisteredEvents.size(); ++foundIndex) {
- const EventRegistration &reg = mRegisteredEvents[foundIndex];
- if (reg.eventType == eventType) {
- break;
- }
- }
- return foundIndex;
-}
-
-void Nanoapp::handleGnssMeasurementDataEvent(const Event *event) {
-#ifdef CHRE_GNSS_MEASUREMENT_BACK_COMPAT_ENABLED
- const struct chreGnssDataEvent *data =
- static_cast<const struct chreGnssDataEvent *>(event->eventData);
- if (getTargetApiVersion() < CHRE_API_VERSION_1_5 &&
- data->measurement_count > CHRE_GNSS_MAX_MEASUREMENT_PRE_1_5) {
- chreGnssDataEvent localEvent;
- memcpy(&localEvent, data, sizeof(struct chreGnssDataEvent));
- localEvent.measurement_count = CHRE_GNSS_MAX_MEASUREMENT_PRE_1_5;
- handleEvent(event->senderInstanceId, event->eventType, &localEvent);
- } else
-#endif // CHRE_GNSS_MEASUREMENT_BACK_COMPAT_ENABLED
- {
- handleEvent(event->senderInstanceId, event->eventType, event->eventData);
- }
-}
-
} // namespace chre
diff --git a/core/sensor.cc b/core/sensor.cc
index 48ae2f55..c9c9e811 100644
--- a/core/sensor.cc
+++ b/core/sensor.cc
@@ -20,7 +20,6 @@
#include "chre_api/chre/version.h"
namespace chre {
-Mutex Sensor::mSamplingStatusMutex;
Sensor::Sensor(Sensor &&other)
: PlatformSensor(std::move(other)), mFlushRequestPending(false) {
@@ -109,14 +108,12 @@ void Sensor::setLastEvent(ChreSensorData *event) {
bool Sensor::getSamplingStatus(struct chreSensorSamplingStatus *status) const {
CHRE_ASSERT(status != nullptr);
- LockGuard<Mutex> mLock(mSamplingStatusMutex);
memcpy(status, &mSamplingStatus, sizeof(*status));
return true;
}
void Sensor::setSamplingStatus(const struct chreSensorSamplingStatus &status) {
- LockGuard<Mutex> mLock(mSamplingStatusMutex);
mSamplingStatus = status;
}
diff --git a/core/sensor_request.cc b/core/sensor_request.cc
index a9e4599f..eb664ad3 100644
--- a/core/sensor_request.cc
+++ b/core/sensor_request.cc
@@ -63,14 +63,7 @@ SensorRequest::SensorRequest(uint32_t instanceId, SensorMode mode,
bool SensorRequest::isEquivalentTo(const SensorRequest &request) const {
return (mMode == request.mMode && mInterval == request.mInterval &&
- mLatency == request.mLatency &&
- mBiasUpdatesRequested == request.mBiasUpdatesRequested);
-}
-
-bool SensorRequest::onlyBiasRequestUpdated(const SensorRequest &request) const {
- return (mMode == request.mMode && mInterval == request.mInterval &&
- mLatency == request.mLatency &&
- mBiasUpdatesRequested != request.mBiasUpdatesRequested);
+ mLatency == request.mLatency);
}
bool SensorRequest::mergeWith(const SensorRequest &request) {
@@ -128,11 +121,6 @@ bool SensorRequest::mergeWith(const SensorRequest &request) {
mMode = maximalSensorMode;
attributesChanged = true;
}
-
- if (!mBiasUpdatesRequested && request.mBiasUpdatesRequested) {
- mBiasUpdatesRequested = true;
- attributesChanged = true;
- }
}
return attributesChanged;
diff --git a/core/sensor_request_manager.cc b/core/sensor_request_manager.cc
index 92b50ed2..88009d70 100644
--- a/core/sensor_request_manager.cc
+++ b/core/sensor_request_manager.cc
@@ -17,7 +17,6 @@
#include "chre/core/sensor_request_manager.h"
#include "chre/core/event_loop_manager.h"
-#include "chre/util/macros.h"
#include "chre/util/nested_data_ptr.h"
#include "chre/util/system/debug_dump.h"
#include "chre_api/chre/version.h"
@@ -57,7 +56,7 @@ bool isSensorRequestValid(const Sensor &sensor,
void updateLastEvent(void *eventData) {
CHRE_ASSERT(eventData);
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
+ auto callback = [](uint16_t /* type */, void *data) {
auto *sensorData = static_cast<ChreSensorData *>(data);
Sensor *sensor =
EventLoopManagerSingleton::get()->getSensorRequestManager().getSensor(
@@ -105,19 +104,28 @@ void postSamplingStatusEvent(uint32_t instanceId, uint32_t sensorHandle,
}
/**
- * Notifies all listening nanoapps of the latest sampling status update.
+ * Sets the latest sampling status for a given sensor and notifies all listening
+ * nanoapps of the latest update.
*
* @param sensorHandle The handle of the sensor.
- * @param status A reference of the sampling status to be posted.
+ * @param status A reference of the sampling status to be updated.
*/
-void postSamplingStatus(uint32_t sensorHandle,
- struct chreSensorSamplingStatus &status) {
- // Only post to Nanoapps with an open request.
- const DynamicVector<SensorRequest> &requests =
- EventLoopManagerSingleton::get()->getSensorRequestManager().getRequests(
+void updateSamplingStatus(uint32_t sensorHandle,
+ struct chreSensorSamplingStatus &status) {
+ Sensor *sensor =
+ EventLoopManagerSingleton::get()->getSensorRequestManager().getSensor(
sensorHandle);
- for (const auto &req : requests) {
- postSamplingStatusEvent(req.getInstanceId(), sensorHandle, status);
+
+ if (sensor != nullptr && !sensor->isOneShot()) {
+ sensor->setSamplingStatus(status);
+
+ // Only post to Nanoapps with an open request.
+ const DynamicVector<SensorRequest> &requests =
+ EventLoopManagerSingleton::get()->getSensorRequestManager().getRequests(
+ sensorHandle);
+ for (const auto &req : requests) {
+ postSamplingStatusEvent(req.getInstanceId(), sensorHandle, status);
+ }
}
}
@@ -139,16 +147,12 @@ void SensorRequestManager::init() {
}
bool SensorRequestManager::getSensorHandle(uint8_t sensorType,
- uint8_t sensorIndex,
- uint16_t targetGroupId,
uint32_t *sensorHandle) const {
CHRE_ASSERT(sensorHandle);
bool sensorHandleIsValid = false;
for (uint32_t i = 0; i < mSensors.size(); i++) {
- if ((mSensors[i].getSensorType() == sensorType) &&
- (mSensors[i].getSensorIndex() == sensorIndex) &&
- (BITMASK_HAS_VALUE(mSensors[i].getTargetGroupMask(), targetGroupId))) {
+ if (mSensors[i].getSensorType() == sensorType) {
sensorHandleIsValid = true;
*sensorHandle = i;
break;
@@ -171,14 +175,6 @@ bool SensorRequestManager::setSensorRequest(
} else {
Sensor &sensor = mSensors[sensorHandle];
if (isSensorRequestValid(sensor, sensorRequest)) {
- // Copy the request so it can be modified below.
- SensorRequest request = sensorRequest;
- if (sensor.isOneShot()) {
- // Always use a latency value of ASAP for one-shot sensors since
- // one-shot data is always expected to be delivered immediately.
- request.setLatency(Nanoseconds(CHRE_SENSOR_LATENCY_ASAP));
- }
-
size_t requestIndex;
uint8_t sensorType = sensor.getSensorType();
uint16_t eventType = getSampleEventTypeForSensorType(sensorType);
@@ -186,7 +182,7 @@ bool SensorRequestManager::setSensorRequest(
sensor.getRequestMultiplexer().findRequest(nanoapp->getInstanceId(),
&requestIndex) != nullptr;
- if (request.getMode() == SensorMode::Off) {
+ if (sensorRequest.getMode() == SensorMode::Off) {
if (nanoappHasRequest) {
// The request changes the mode to off and there was an existing
// request. The existing request is removed from the multiplexer. The
@@ -196,15 +192,13 @@ bool SensorRequestManager::setSensorRequest(
if (success) {
cancelFlushRequests(sensorHandle, nanoapp->getInstanceId());
- nanoapp->unregisterForBroadcastEvent(eventType,
- sensor.getTargetGroupMask());
+ nanoapp->unregisterForBroadcastEvent(eventType);
uint16_t biasEventType;
if (sensor.getBiasEventType(&biasEventType)) {
// Per API requirements, turn off bias reporting when
// unsubscribing from the sensor.
- nanoapp->unregisterForBroadcastEvent(biasEventType,
- sensor.getTargetGroupMask());
+ nanoapp->unregisterForBroadcastEvent(biasEventType);
}
}
} else {
@@ -218,21 +212,16 @@ bool SensorRequestManager::setSensorRequest(
// existing request. The request is newly created and added to the
// multiplexer. The nanoapp is registered for events if this request was
// successful.
- uint16_t biasEventType;
- if (sensor.getBiasEventType(&biasEventType) && sensor.isCalibrated()) {
- // Per API requirements, turn on bias reporting for calibrated sensors
- // by default when subscribed.
- request.setBiasUpdatesRequested(true);
- }
-
- success = addRequest(sensor, request, &requestChanged);
+ success = addRequest(sensor, sensorRequest, &requestChanged);
if (success) {
- nanoapp->registerForBroadcastEvent(eventType,
- sensor.getTargetGroupMask());
+ nanoapp->registerForBroadcastEvent(eventType);
- if (request.getBiasUpdatesRequested()) {
- nanoapp->registerForBroadcastEvent(biasEventType,
- sensor.getTargetGroupMask());
+ // Per API requirements, turn on bias reporting for calibrated sensors
+ // by default when subscribed.
+ uint16_t biasEventType;
+ if (sensor.getBiasEventType(&biasEventType) &&
+ sensor.isCalibrated()) {
+ nanoapp->registerForBroadcastEvent(biasEventType);
}
// Deliver last valid event to new clients of on-change sensors
@@ -243,15 +232,10 @@ bool SensorRequestManager::setSensorRequest(
}
}
} else {
- // Ensure bias events stay requested if they were previously enabled.
- const SensorRequest &previousRequest =
- sensor.getRequestMultiplexer().getRequests()[requestIndex];
- if (previousRequest.getBiasUpdatesRequested()) {
- request.setBiasUpdatesRequested(true);
- }
// The request changes the mode to the enabled state and there was an
// existing request. The existing request is updated.
- success = updateRequest(sensor, requestIndex, request, &requestChanged);
+ success =
+ updateRequest(sensor, requestIndex, sensorRequest, &requestChanged);
}
// TODO: Allow translating the sensor request
@@ -261,7 +245,8 @@ bool SensorRequestManager::setSensorRequest(
}
if (success) {
- addSensorRequestLog(nanoapp->getInstanceId(), sensorHandle, request);
+ addSensorRequestLog(nanoapp->getInstanceId(), sensorType,
+ sensorRequest);
}
}
}
@@ -299,8 +284,7 @@ bool SensorRequestManager::removeAllRequests(uint32_t sensorHandle) {
->getEventLoop()
.findNanoappByInstanceId(request.getInstanceId());
if (nanoapp != nullptr) {
- nanoapp->unregisterForBroadcastEvent(eventType,
- sensor.getTargetGroupMask());
+ nanoapp->unregisterForBroadcastEvent(eventType);
}
}
@@ -346,40 +330,27 @@ bool SensorRequestManager::configureBiasEvents(Nanoapp *nanoapp,
uint32_t sensorHandle,
bool enable) {
bool success = false;
- uint16_t eventType;
if (sensorHandle >= mSensors.size()) {
LOG_INVALID_HANDLE(sensorHandle);
} else if (enable && !mSensors[sensorHandle].isSensorEnabled()) {
LOGE("Bias events can't be configured for a disabled sensor!");
- } else if (mSensors[sensorHandle].getBiasEventType(&eventType)) {
+ } else {
+ uint16_t eventType;
Sensor &sensor = mSensors[sensorHandle];
- size_t requestIndex;
- bool nanoappHasRequest =
- sensor.getRequestMultiplexer().findRequest(nanoapp->getInstanceId(),
- &requestIndex) != nullptr;
- if (enable && !nanoappHasRequest) {
- LOGE("0x%" PRIx64
- " configuring bias events without an existing sensor request",
- nanoapp->getAppId());
- } else if (!enable && !nanoappHasRequest) {
- // Treat configuration request as a success since the nanoapp's request
- // already has been removed which would result in disabling bias event
- // updates
- success = true;
- } else {
- SensorRequest previousRequest =
- sensor.getRequestMultiplexer().getRequests()[requestIndex];
- previousRequest.setBiasUpdatesRequested(enable);
- bool requestChanged;
- success =
- updateRequest(sensor, requestIndex, previousRequest, &requestChanged);
+ if (sensor.getBiasEventType(&eventType)) {
+ uint64_t currentLatency = 0;
+ if (enable) {
+ currentLatency =
+ sensor.getMaximalRequest().getLatency().toRawNanoseconds();
+ }
+ success = mPlatformSensorManager.configureBiasEvents(sensor, enable,
+ currentLatency);
+
if (success) {
if (enable) {
- nanoapp->registerForBroadcastEvent(eventType,
- sensor.getTargetGroupMask());
+ nanoapp->registerForBroadcastEvent(eventType);
} else {
- nanoapp->unregisterForBroadcastEvent(eventType,
- sensor.getTargetGroupMask());
+ nanoapp->unregisterForBroadcastEvent(eventType);
}
}
}
@@ -435,7 +406,7 @@ void SensorRequestManager::releaseSensorDataEvent(uint16_t eventType,
mPlatformSensorManager.releaseSensorDataEvent(eventData);
uint8_t sensorType = getSensorTypeForSampleEventType(eventType);
uint32_t sensorHandle;
- if (getDefaultSensorHandle(sensorType, &sensorHandle) &&
+ if (getSensorHandle(sensorType, &sensorHandle) &&
mSensors[sensorHandle].isOneShot()) {
removeAllRequests(sensorHandle);
}
@@ -451,18 +422,30 @@ void SensorRequestManager::handleFlushCompleteEvent(uint32_t sensorHandle,
// has been received.
mSensors[sensorHandle].cancelPendingFlushRequestTimer();
- auto callback = [](uint16_t /*type*/, void *data, void *extraData) {
- uint8_t cbErrorCode = NestedDataPtr<uint8_t>(data);
- uint32_t cbSensorHandle = NestedDataPtr<uint32_t>(extraData);
- EventLoopManagerSingleton::get()
- ->getSensorRequestManager()
- .handleFlushCompleteEventSync(cbErrorCode, cbSensorHandle);
+ struct CallbackState {
+ uint8_t errorCode;
+ uint32_t sensorHandle;
};
- EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::SensorFlushComplete,
- NestedDataPtr<uint8_t>(errorCode), callback,
- NestedDataPtr<uint32_t>(sensorHandle));
+ auto *cbState = memoryAlloc<CallbackState>();
+ if (cbState == nullptr) {
+ LOG_OOM();
+ } else {
+ cbState->errorCode = errorCode;
+ cbState->sensorHandle = sensorHandle;
+
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ auto *cbState = static_cast<CallbackState *>(eventData);
+ EventLoopManagerSingleton::get()
+ ->getSensorRequestManager()
+ .handleFlushCompleteEventSync(cbState->errorCode,
+ cbState->sensorHandle);
+ memoryFree(cbState);
+ };
+
+ EventLoopManagerSingleton::get()->deferCallback(
+ SystemCallbackType::SensorFlushComplete, cbState, callback);
+ }
}
}
@@ -472,55 +455,52 @@ void SensorRequestManager::handleSensorDataEvent(uint32_t sensorHandle,
LOG_INVALID_HANDLE(sensorHandle);
mPlatformSensorManager.releaseSensorDataEvent(event);
} else {
- Sensor &sensor = mSensors[sensorHandle];
- if (sensor.isOnChange()) {
+ if (mSensors[sensorHandle].isOnChange()) {
updateLastEvent(event);
}
uint16_t eventType =
- getSampleEventTypeForSensorType(sensor.getSensorType());
+ getSampleEventTypeForSensorType(mSensors[sensorHandle].getSensorType());
// Only allow dropping continuous sensor events since losing one-shot or
// on-change events could result in nanoapps stuck in a bad state.
- if (sensor.isContinuous()) {
+ if (mSensors[sensorHandle].isContinuous()) {
EventLoopManagerSingleton::get()
->getEventLoop()
- .postLowPriorityEventOrFree(eventType, event, sensorDataEventFree,
- kSystemInstanceId, kBroadcastInstanceId,
- sensor.getTargetGroupMask());
+ .postLowPriorityEventOrFree(eventType, event, sensorDataEventFree);
} else {
EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- eventType, event, sensorDataEventFree, kBroadcastInstanceId,
- sensor.getTargetGroupMask());
+ eventType, event, sensorDataEventFree);
}
}
}
void SensorRequestManager::handleSamplingStatusUpdate(
uint32_t sensorHandle, struct chreSensorSamplingStatus *status) {
- Sensor *sensor =
- EventLoopManagerSingleton::get()->getSensorRequestManager().getSensor(
- sensorHandle);
- if (sensor == nullptr || sensor->isOneShot()) {
- releaseSamplingStatusUpdate(status);
+ struct StatusUpdate {
+ uint32_t sensorHandle;
+ struct chreSensorSamplingStatus *status;
+ };
+ auto *cbData = memoryAlloc<struct StatusUpdate>();
+ if (cbData == nullptr) {
+ LOG_OOM();
} else {
- sensor->setSamplingStatus(*status);
+ cbData->sensorHandle = sensorHandle;
+ cbData->status = status;
- auto callback = [](uint16_t /*type*/, void *data, void *extraData) {
- uint32_t cbSensorHandle = NestedDataPtr<uint32_t>(data);
- auto *cbStatus =
- static_cast<struct chreSensorSamplingStatus *>(extraData);
- postSamplingStatus(cbSensorHandle, *cbStatus);
+ auto callback = [](uint16_t /* type */, void *data) {
+ auto cbData = static_cast<struct StatusUpdate *>(data);
+ updateSamplingStatus(cbData->sensorHandle, *cbData->status);
EventLoopManagerSingleton::get()
->getSensorRequestManager()
- .releaseSamplingStatusUpdate(cbStatus);
+ .releaseSamplingStatusUpdate(cbData->status);
+ memoryFree(cbData);
};
// Schedule a deferred callback to handle sensor status change in the main
// thread.
EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::SensorStatusUpdate,
- NestedDataPtr<uint32_t>(sensorHandle), callback, status);
+ SystemCallbackType::SensorStatusUpdate, cbData, callback);
}
}
@@ -546,8 +526,7 @@ void SensorRequestManager::handleBiasEvent(uint32_t sensorHandle,
};
EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- eventType, biasData, freeCallback, kBroadcastInstanceId,
- sensor->getTargetGroupMask());
+ eventType, biasData, freeCallback);
}
}
}
@@ -560,7 +539,7 @@ void SensorRequestManager::logStateToBuffer(DebugDumpWrapper &debugDump) const {
// below
debugDump.print(
" %s: mode=%d int=%" PRIu64 " lat=%" PRIu64 " nappId=%" PRIu32 "\n",
- mSensors[i].getSensorTypeName(), static_cast<int>(request.getMode()),
+ mSensors[i].getSensorTypeName(), request.getMode(),
request.getInterval().toRawNanoseconds(),
request.getLatency().toRawNanoseconds(), request.getInstanceId());
}
@@ -571,12 +550,13 @@ void SensorRequestManager::logStateToBuffer(DebugDumpWrapper &debugDump) const {
for (int8_t i = static_cast<int8_t>(mSensorRequestLogs.size()) - 1; i >= 0;
i--) {
const auto &log = mSensorRequestLogs[static_cast<size_t>(i)];
- const Sensor &sensor = mSensors[log.sensorHandle];
- debugDump.print(" ts=%" PRIu64 " nappId=%" PRIu32 " type=%s idx=%" PRIu8
- " mask=%" PRIx16 " mode=%s",
- log.timestamp.toRawNanoseconds(), log.instanceId,
- sensor.getSensorTypeName(), sensor.getSensorIndex(),
- sensor.getTargetGroupMask(), getSensorModeName(log.mode));
+ uint32_t sensorHandle;
+ if (getSensorHandle(log.sensorType, &sensorHandle)) {
+ debugDump.print(" ts=%" PRIu64 " nappId=%" PRIu32 " sensType=%s mode=%s",
+ log.timestamp.toRawNanoseconds(), log.instanceId,
+ mSensors[sensorHandle].getSensorTypeName(),
+ getSensorModeName(log.mode));
+ }
if (sensorModeIsContinuous(log.mode)) {
debugDump.print(" int=%" PRIu64 " lat=%" PRIu64,
@@ -671,10 +651,10 @@ void SensorRequestManager::cancelFlushRequests(uint32_t sensorHandle,
}
void SensorRequestManager::addSensorRequestLog(
- uint32_t nanoappInstanceId, uint32_t sensorHandle,
+ uint32_t nanoappInstanceId, uint8_t sensorType,
const SensorRequest &sensorRequest) {
mSensorRequestLogs.kick_push(SensorRequestLog(
- SystemTime::getMonotonicTime(), nanoappInstanceId, sensorHandle,
+ SystemTime::getMonotonicTime(), nanoappInstanceId, sensorType,
sensorRequest.getMode(), sensorRequest.getInterval(),
sensorRequest.getLatency()));
}
@@ -687,13 +667,12 @@ bool SensorRequestManager::addRequest(Sensor &sensor,
size_t addIndex;
bool success = true;
SensorRequestMultiplexer &multiplexer = sensor.getRequestMultiplexer();
- SensorRequest prevRequest = sensor.getMaximalRequest();
if (!multiplexer.addRequest(request, &addIndex, requestChanged)) {
*requestChanged = false;
success = false;
LOG_OOM();
} else if (*requestChanged) {
- success = configurePlatformSensor(sensor, prevRequest);
+ success = configurePlatformSensor(sensor);
if (!success) {
// Remove the newly added request since the platform failed to handle
// it. The sensor is expected to maintain the existing request so there is
@@ -718,11 +697,9 @@ bool SensorRequestManager::updateRequest(Sensor &sensor, size_t updateIndex,
bool success = true;
SensorRequestMultiplexer &multiplexer = sensor.getRequestMultiplexer();
SensorRequest previousRequest = multiplexer.getRequests()[updateIndex];
- SensorRequest prevMaxRequest = sensor.getMaximalRequest();
-
multiplexer.updateRequest(updateIndex, request, requestChanged);
if (*requestChanged) {
- success = configurePlatformSensor(sensor, prevMaxRequest);
+ success = configurePlatformSensor(sensor);
if (!success) {
// Roll back the request since sending it to the sensor failed. The
// request will roll back to the previous maximal. The sensor is
@@ -744,10 +721,9 @@ bool SensorRequestManager::removeRequest(Sensor &sensor, size_t removeIndex,
CHRE_ASSERT(requestChanged != nullptr);
bool success = true;
- const SensorRequest prevRequest = sensor.getMaximalRequest();
sensor.getRequestMultiplexer().removeRequest(removeIndex, requestChanged);
if (*requestChanged) {
- success = configurePlatformSensor(sensor, prevRequest);
+ success = configurePlatformSensor(sensor);
if (!success) {
LOGE("SensorRequestManager failed to remove a request");
@@ -767,15 +743,14 @@ bool SensorRequestManager::removeRequest(Sensor &sensor, size_t removeIndex,
bool SensorRequestManager::removeAllRequests(Sensor &sensor) {
bool requestChanged;
- SensorRequest prevRequest = sensor.getMaximalRequest();
sensor.getRequestMultiplexer().removeAllRequests(&requestChanged);
bool success = true;
if (requestChanged) {
- success = configurePlatformSensor(sensor, prevRequest);
+ success = configurePlatformSensor(sensor);
if (!success) {
- LOGE("SensorRequestManager failed to remove all requests");
+ LOGE("SensorRequestManager failed to remove all request");
// If the platform fails to handle this request in a debug build there
// is likely an error in the platform. This is not strictly a programming
@@ -806,12 +781,15 @@ uint8_t SensorRequestManager::makeFlushRequest(FlushRequest &request) {
Nanoseconds delay = deadline - now;
request.isActive = true;
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- LOGE("Flush request timed out");
- NestedDataPtr<uint32_t> sensorHandle(data);
+ NestedDataPtr<uint32_t> index(request.sensorHandle);
+
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ LOGE("Flush request timed out.");
+ NestedDataPtr<uint32_t> nestedIndex;
+ nestedIndex.dataPtr = eventData;
EventLoopManagerSingleton::get()
->getSensorRequestManager()
- .onFlushTimeout(sensorHandle);
+ .onFlushTimeout(nestedIndex.data);
// Send a complete event, thus closing out this flush request. If the
// request that has just timed out receives a response later, this may
@@ -821,13 +799,13 @@ uint8_t SensorRequestManager::makeFlushRequest(FlushRequest &request) {
// responses can be properly dropped.
EventLoopManagerSingleton::get()
->getSensorRequestManager()
- .handleFlushCompleteEventSync(CHRE_ERROR_TIMEOUT, sensorHandle);
+ .handleFlushCompleteEventSync(CHRE_ERROR_TIMEOUT, nestedIndex.data);
};
sensor.setFlushRequestTimerHandle(
EventLoopManagerSingleton::get()->setDelayedCallback(
- SystemCallbackType::SensorFlushTimeout,
- NestedDataPtr<uint32_t>(request.sensorHandle), callback, delay));
+ SystemCallbackType::SensorFlushTimeout, index.dataPtr, callback,
+ delay));
}
} else {
// Flush request will be made once the pending request is completed.
@@ -851,35 +829,11 @@ bool SensorRequestManager::doMakeFlushRequest(Sensor &sensor) {
return success;
}
-bool SensorRequestManager::configurePlatformSensor(
- Sensor &sensor, const SensorRequest &prevSensorRequest) {
+bool SensorRequestManager::configurePlatformSensor(Sensor &sensor) {
bool success = false;
const SensorRequest &request = sensor.getMaximalRequest();
-
- // Ensures that only configureBiasEvents is invoked if that's the only value
- // that has changed since the previous request since CHRE shouldn't configure
- // the platform for data events if the sensor data request hasn't changed.
- bool biasChanged = (request.getBiasUpdatesRequested() !=
- prevSensorRequest.getBiasUpdatesRequested());
- bool onlyBiasChanged = request.onlyBiasRequestUpdated(prevSensorRequest);
- uint64_t currentLatency = 0;
- bool enable = (request.getMode() != SensorMode::Off);
- if (enable) {
- currentLatency = request.getLatency().toRawNanoseconds();
- }
-
- // Per platform API requirements, an active sensor subscription must exist
- // before any bias configuration can be done.
- if (!onlyBiasChanged &&
- !mPlatformSensorManager.configureSensor(sensor, request)) {
- LOGE("Failed to make platform sensor data request");
- } else if (biasChanged &&
- !mPlatformSensorManager.configureBiasEvents(
- sensor, request.getBiasUpdatesRequested(), currentLatency)) {
- LOGE("Failed to make platform sensor bias request");
- if (!onlyBiasChanged) {
- mPlatformSensorManager.configureSensor(sensor, prevSensorRequest);
- }
+ if (!mPlatformSensorManager.configureSensor(sensor, request)) {
+ LOGE("Failed to make platform sensor request");
} else {
success = true;
diff --git a/core/sensor_type_helpers.cc b/core/sensor_type_helpers.cc
index 2fef083e..3401ebdb 100644
--- a/core/sensor_type_helpers.cc
+++ b/core/sensor_type_helpers.cc
@@ -33,8 +33,6 @@ ReportingMode SensorTypeHelpers::getReportingMode(uint8_t sensorType) {
return ReportingMode::OneShot;
case CHRE_SENSOR_TYPE_LIGHT:
case CHRE_SENSOR_TYPE_PROXIMITY:
- case CHRE_SENSOR_TYPE_STEP_COUNTER:
- case CHRE_SENSOR_TYPE_HINGE_ANGLE:
return ReportingMode::OnChange;
default:
return ReportingMode::Continuous;
@@ -110,7 +108,6 @@ size_t SensorTypeHelpers::getLastEventSize(uint8_t sensorType) {
case CHRE_SENSOR_TYPE_ACCELEROMETER_TEMPERATURE:
case CHRE_SENSOR_TYPE_GYROSCOPE_TEMPERATURE:
case CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD_TEMPERATURE:
- case CHRE_SENSOR_TYPE_HINGE_ANGLE:
return sizeof(chreSensorFloatData);
case CHRE_SENSOR_TYPE_INSTANT_MOTION_DETECT:
case CHRE_SENSOR_TYPE_STATIONARY_DETECT:
@@ -118,8 +115,6 @@ size_t SensorTypeHelpers::getLastEventSize(uint8_t sensorType) {
return sizeof(chreSensorOccurrenceData);
case CHRE_SENSOR_TYPE_PROXIMITY:
return sizeof(chreSensorByteData);
- case CHRE_SENSOR_TYPE_STEP_COUNTER:
- return sizeof(chreSensorUint64Data);
default:
// Update implementation to prevent undefined from being used.
CHRE_ASSERT(false);
@@ -155,10 +150,6 @@ const char *SensorTypeHelpers::getSensorTypeName(uint8_t sensorType) {
return "Proximity";
case CHRE_SENSOR_TYPE_STEP_DETECT:
return "Step Detect";
- case CHRE_SENSOR_TYPE_STEP_COUNTER:
- return "Step Counter";
- case CHRE_SENSOR_TYPE_HINGE_ANGLE:
- return "Hinge Angle";
case CHRE_SENSOR_TYPE_ACCELEROMETER_TEMPERATURE:
return "Accelerometer Temp";
case CHRE_SENSOR_TYPE_GYROSCOPE_TEMPERATURE:
@@ -177,22 +168,6 @@ const char *SensorTypeHelpers::getSensorTypeName(uint8_t sensorType) {
}
}
-uint8_t SensorTypeHelpers::toUncalibratedSensorType(uint8_t sensorType) {
- switch (sensorType) {
- case CHRE_SENSOR_TYPE_ACCELEROMETER:
- return CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER;
- case CHRE_SENSOR_TYPE_GYROSCOPE:
- return CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE;
- case CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD:
- return CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD;
- default:
- /* empty */
- break;
- }
-
- return sensorType;
-}
-
void SensorTypeHelpers::getLastSample(uint8_t sensorType,
const ChreSensorData *event,
ChreSensorData *lastEvent) {
@@ -206,7 +181,6 @@ void SensorTypeHelpers::getLastSample(uint8_t sensorType,
} else {
switch (sensorType) {
case CHRE_SENSOR_TYPE_LIGHT:
- case CHRE_SENSOR_TYPE_HINGE_ANGLE:
copyLastSample<chreSensorFloatData>(&event->floatData,
&lastEvent->floatData);
break;
@@ -214,10 +188,6 @@ void SensorTypeHelpers::getLastSample(uint8_t sensorType,
copyLastSample<chreSensorByteData>(&event->byteData,
&lastEvent->byteData);
break;
- case CHRE_SENSOR_TYPE_STEP_COUNTER:
- copyLastSample<chreSensorUint64Data>(&event->uint64Data,
- &lastEvent->uint64Data);
- break;
default:
LOGE("Unhandled sensor type %" PRIu8, sensorType);
}
diff --git a/core/settings.cc b/core/settings.cc
index c044f5a3..c677544f 100644
--- a/core/settings.cc
+++ b/core/settings.cc
@@ -22,16 +22,12 @@
#include "chre/platform/log.h"
#include "chre/util/nested_data_ptr.h"
-#include "chre_api/chre/user_settings.h"
-
namespace chre {
namespace {
-constexpr size_t kNumSettings = static_cast<size_t>(Setting::SETTING_MAX);
-
//! The current state for each setting.
-SettingState gSettingStateList[kNumSettings];
+SettingState gSettingStateList[static_cast<size_t>(Setting::SETTING_MAX)];
/**
* @param setting The setting to get the index for.
@@ -51,14 +47,14 @@ bool getIndexForSetting(Setting setting, size_t *index) {
void setSettingState(Setting setting, SettingState state) {
size_t index;
if (!getIndexForSetting(setting, &index)) {
- LOGE("Unknown setting %" PRId8, static_cast<int8_t>(setting));
+ LOGE("Unknown setting %" PRIu8, static_cast<uint8_t>(setting));
} else {
gSettingStateList[index] = state;
}
}
const char *getSettingStateString(Setting setting) {
- switch (getSettingState(setting)) {
+ switch (getSettingState(Setting::LOCATION)) {
case SettingState::ENABLED:
return "enabled";
break;
@@ -72,53 +68,35 @@ const char *getSettingStateString(Setting setting) {
return "unknown";
}
-void sendSettingChangedNotification(Setting setting, SettingState state) {
- auto *eventData = memoryAlloc<struct chreUserSettingChangedEvent>();
- auto settingAsInt = static_cast<uint8_t>(setting);
- uint16_t eventType = CHRE_EVENT_SETTING_CHANGED_FIRST_EVENT + settingAsInt;
-
- if (eventData != nullptr) {
- eventData->setting = settingAsInt;
- eventData->settingState = static_cast<int8_t>(state);
-
- EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- eventType, eventData, freeEventDataCallback, kBroadcastInstanceId);
- } else {
- LOG_OOM();
- }
-}
-
-void settingChangedCallback(uint16_t /* type */, void *data, void *extraData) {
- Setting setting = NestedDataPtr<Setting>(data);
- SettingState settingState = NestedDataPtr<SettingState>(extraData);
-
- setSettingState(setting, settingState);
-
- LOGD("Setting changed callback called for setting %u state %u",
- static_cast<uint8_t>(setting), static_cast<uint8_t>(settingState));
-
-#ifdef CHRE_GNSS_SUPPORT_ENABLED
- EventLoopManagerSingleton::get()->getGnssManager().onSettingChanged(
- setting, settingState);
-#endif // CHRE_GNSS_SUPPORT_ENABLED
-
-#ifdef CHRE_AUDIO_SUPPORT_ENABLED
- EventLoopManagerSingleton::get()->getAudioRequestManager().onSettingChanged(
- setting, settingState);
-#endif // CHRE_AUDIO_SUPPORT_ENABLED
-
- sendSettingChangedNotification(setting, settingState);
-}
-
} // anonymous namespace
void postSettingChange(Setting setting, SettingState state) {
LOGD("Posting setting change: setting type %" PRIu8 " state %" PRIu8,
static_cast<uint8_t>(setting), static_cast<uint8_t>(state));
+ struct SettingChange {
+ Setting setting;
+ SettingState state;
+
+ SettingChange(Setting setting, SettingState state) {
+ this->setting = setting;
+ this->state = state;
+ }
+ };
+
+ NestedDataPtr<SettingChange> nestedPtr(SettingChange(setting, state));
+
+ auto callback = [](uint16_t /* type */, void *data) {
+ NestedDataPtr<SettingChange> setting;
+ setting.dataPtr = data;
+ setSettingState(setting.data.setting, setting.data.state);
+#ifdef CHRE_GNSS_SUPPORT_ENABLED
+ EventLoopManagerSingleton::get()->getGnssManager().onSettingChanged(
+ setting.data.setting, setting.data.state);
+#endif // CHRE_GNSS_SUPPORT_ENABLED
+ };
EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::SettingChangeEvent, NestedDataPtr<Setting>(setting),
- settingChangedCallback, NestedDataPtr<SettingState>(state));
+ SystemCallbackType::SettingChangeEvent, nestedPtr.dataPtr, callback);
}
SettingState getSettingState(Setting setting) {
@@ -128,27 +106,12 @@ SettingState getSettingState(Setting setting) {
}
LOGE("Unknown setting %" PRIu8, static_cast<uint8_t>(setting));
- return SettingState::UNKNOWN;
-}
-
-int8_t getSettingStateAsInt8(uint8_t setting) {
- int8_t state = CHRE_USER_SETTING_STATE_UNKNOWN;
- if (setting < static_cast<uint8_t>(Setting::SETTING_MAX)) {
- auto settingEnum = static_cast<Setting>(setting);
- state = static_cast<int8_t>(getSettingState(settingEnum));
- }
- return state;
+ return SettingState::SETTING_STATE_MAX;
}
void logSettingStateToBuffer(DebugDumpWrapper &debugDump) {
debugDump.print("\nSettings:");
debugDump.print("\n Location %s", getSettingStateString(Setting::LOCATION));
- debugDump.print("\n WiFi available %s",
- getSettingStateString(Setting::WIFI_AVAILABLE));
- debugDump.print("\n Airplane mode %s",
- getSettingStateString(Setting::AIRPLANE_MODE));
- debugDump.print("\n Microphone Access %s",
- getSettingStateString(Setting::MICROPHONE));
}
} // namespace chre
diff --git a/core/tests/audio_util_test.cc b/core/tests/audio_request_manager_test.cc
index 8d8ef102..170b6840 100644
--- a/core/tests/audio_util_test.cc
+++ b/core/tests/audio_request_manager_test.cc
@@ -16,43 +16,43 @@
#include "gtest/gtest.h"
-#include "chre/core/audio_util.h"
+#include "chre/core/audio_request_manager.h"
-using chre::AudioUtil;
+using chre::AudioRequestManager;
using chre::Nanoseconds;
TEST(AudioDurationFromSampleCountAndRate, HalfSecond) {
Nanoseconds duration =
- AudioUtil::getDurationFromSampleCountAndRate(8000, 16000);
- EXPECT_EQ(duration.toRawNanoseconds(), 500000000ull);
+ AudioRequestManager::getDurationFromSampleCountAndRate(8000, 16000);
+ EXPECT_EQ(duration.toRawNanoseconds(), 500000000);
}
TEST(AudioDurationFromSampleCountAndRate, OneSecond) {
Nanoseconds duration =
- AudioUtil::getDurationFromSampleCountAndRate(16000, 16000);
- EXPECT_EQ(duration.toRawNanoseconds(), 1000000000ull);
+ AudioRequestManager::getDurationFromSampleCountAndRate(16000, 16000);
+ EXPECT_EQ(duration.toRawNanoseconds(), 1000000000);
}
TEST(AudioDurationFromSampleCountAndRate, OneHundredSecond) {
Nanoseconds duration =
- AudioUtil::getDurationFromSampleCountAndRate(1600000, 16000);
- EXPECT_EQ(duration.toRawNanoseconds(), 100000000000ull);
+ AudioRequestManager::getDurationFromSampleCountAndRate(1600000, 16000);
+ EXPECT_EQ(duration.toRawNanoseconds(), 100000000000);
}
TEST(AudioSampleCountFromRateAndDuration, OneSample) {
- uint32_t sampleCount =
- AudioUtil::getSampleCountFromRateAndDuration(16000, Nanoseconds(62500));
- EXPECT_EQ(sampleCount, 1u);
+ uint32_t sampleCount = AudioRequestManager::getSampleCountFromRateAndDuration(
+ 16000, Nanoseconds(62500));
+ EXPECT_EQ(sampleCount, 1);
}
TEST(AudioSampleCountFromRateAndDuration, OneHundredSample) {
- uint32_t sampleCount =
- AudioUtil::getSampleCountFromRateAndDuration(16000, Nanoseconds(6250000));
- EXPECT_EQ(sampleCount, 100u);
+ uint32_t sampleCount = AudioRequestManager::getSampleCountFromRateAndDuration(
+ 16000, Nanoseconds(6250000));
+ EXPECT_EQ(sampleCount, 100);
}
TEST(AudioSampleCountFromRateAndDuration, OneThousandSample) {
- uint32_t sampleCount = AudioUtil::getSampleCountFromRateAndDuration(
+ uint32_t sampleCount = AudioRequestManager::getSampleCountFromRateAndDuration(
16000, Nanoseconds(62500000));
- EXPECT_EQ(sampleCount, 1000u);
+ EXPECT_EQ(sampleCount, 1000);
}
diff --git a/core/tests/memory_manager_test.cc b/core/tests/memory_manager_test.cc
index 69e07a08..69d3a360 100644
--- a/core/tests/memory_manager_test.cc
+++ b/core/tests/memory_manager_test.cc
@@ -31,36 +31,36 @@ struct node {
TEST(MemoryManager, DefaultTotalMemoryAllocatedIsZero) {
MemoryManager manager;
- EXPECT_EQ(manager.getTotalAllocatedBytes(), 0u);
+ EXPECT_EQ(manager.getTotalAllocatedBytes(), 0);
}
TEST(MemoryManager, BasicAllocationFree) {
MemoryManager manager;
Nanoapp app;
- void *ptr = manager.nanoappAlloc(&app, 1u);
+ void *ptr = manager.nanoappAlloc(&app, 1);
EXPECT_NE(ptr, nullptr);
- EXPECT_EQ(manager.getTotalAllocatedBytes(), 1u);
- EXPECT_EQ(manager.getAllocationCount(), 1u);
+ EXPECT_EQ(manager.getTotalAllocatedBytes(), 1);
+ EXPECT_EQ(manager.getAllocationCount(), 1);
manager.nanoappFree(&app, ptr);
- EXPECT_EQ(manager.getTotalAllocatedBytes(), 0u);
- EXPECT_EQ(manager.getAllocationCount(), 0u);
+ EXPECT_EQ(manager.getTotalAllocatedBytes(), 0);
+ EXPECT_EQ(manager.getAllocationCount(), 0);
}
TEST(MemoryManager, NullPointerFree) {
MemoryManager manager;
Nanoapp app;
manager.nanoappFree(&app, nullptr);
- EXPECT_EQ(manager.getTotalAllocatedBytes(), 0u);
- EXPECT_EQ(manager.getAllocationCount(), 0u);
+ EXPECT_EQ(manager.getTotalAllocatedBytes(), 0);
+ EXPECT_EQ(manager.getAllocationCount(), 0);
}
TEST(MemoryManager, ZeroAllocationFails) {
MemoryManager manager;
Nanoapp app;
- void *ptr = manager.nanoappAlloc(&app, 0u);
+ void *ptr = manager.nanoappAlloc(&app, 0);
EXPECT_EQ(ptr, nullptr);
- EXPECT_EQ(manager.getTotalAllocatedBytes(), 0u);
- EXPECT_EQ(manager.getAllocationCount(), 0u);
+ EXPECT_EQ(manager.getTotalAllocatedBytes(), 0);
+ EXPECT_EQ(manager.getAllocationCount(), 0);
}
TEST(MemoryManager, HugeAllocationFails) {
@@ -68,7 +68,7 @@ TEST(MemoryManager, HugeAllocationFails) {
Nanoapp app;
void *ptr = manager.nanoappAlloc(&app, manager.getMaxAllocationBytes() + 1);
EXPECT_EQ(ptr, nullptr);
- EXPECT_EQ(manager.getTotalAllocatedBytes(), 0u);
+ EXPECT_EQ(manager.getTotalAllocatedBytes(), 0);
}
TEST(MemoryManager, ManyAllocationsTest) {
@@ -85,7 +85,7 @@ TEST(MemoryManager, ManyAllocationsTest) {
}
EXPECT_EQ(manager.getTotalAllocatedBytes(), maxCount * sizeof(node));
EXPECT_EQ(manager.getAllocationCount(), maxCount);
- EXPECT_EQ(manager.nanoappAlloc(&app, 1u), nullptr);
+ EXPECT_EQ(manager.nanoappAlloc(&app, 1), nullptr);
curr = head;
for (size_t i = 0; i < maxCount; i++) {
@@ -93,15 +93,15 @@ TEST(MemoryManager, ManyAllocationsTest) {
manager.nanoappFree(&app, curr);
curr = temp;
}
- EXPECT_EQ(manager.getTotalAllocatedBytes(), 0u);
- EXPECT_EQ(manager.getAllocationCount(), 0u);
+ EXPECT_EQ(manager.getTotalAllocatedBytes(), 0);
+ EXPECT_EQ(manager.getAllocationCount(), 0);
}
TEST(MemoryManager, NegativeAllocationFails) {
MemoryManager manager;
Nanoapp app;
- void *ptr = manager.nanoappAlloc(&app, -1u);
+ void *ptr = manager.nanoappAlloc(&app, -1);
EXPECT_EQ(ptr, nullptr);
- EXPECT_EQ(manager.getTotalAllocatedBytes(), 0u);
- EXPECT_EQ(manager.getAllocationCount(), 0u);
+ EXPECT_EQ(manager.getTotalAllocatedBytes(), 0);
+ EXPECT_EQ(manager.getAllocationCount(), 0);
}
diff --git a/core/tests/request_multiplexer_test.cc b/core/tests/request_multiplexer_test.cc
index 5c0aca42..a738d68c 100644
--- a/core/tests/request_multiplexer_test.cc
+++ b/core/tests/request_multiplexer_test.cc
@@ -22,17 +22,17 @@
using chre::RequestMultiplexer;
-class FakeRequest {
+class DummyRequest {
public:
- FakeRequest() : FakeRequest(0) {}
+ DummyRequest() : DummyRequest(0) {}
- FakeRequest(int priority) : mPriority(priority) {}
+ DummyRequest(int priority) : mPriority(priority) {}
- bool isEquivalentTo(const FakeRequest &request) const {
+ bool isEquivalentTo(const DummyRequest &request) const {
return (mPriority == request.mPriority);
}
- bool mergeWith(const FakeRequest &request) {
+ bool mergeWith(const DummyRequest &request) {
bool newMaximal = false;
if (request.mPriority > mPriority) {
mPriority = request.mPriority;
@@ -51,8 +51,8 @@ class FakeRequest {
};
TEST(RequestMultiplexer, DefaultRequestDoesNotCauseNewMaximal) {
- RequestMultiplexer<FakeRequest> multiplexer;
- FakeRequest request;
+ RequestMultiplexer<DummyRequest> multiplexer;
+ DummyRequest request;
size_t index;
bool maximalRequestChanged;
ASSERT_TRUE(multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -61,8 +61,8 @@ TEST(RequestMultiplexer, DefaultRequestDoesNotCauseNewMaximal) {
}
TEST(RequestMultiplexer, FirstHighPriorityRequestCausesNewMaximal) {
- RequestMultiplexer<FakeRequest> multiplexer;
- FakeRequest request(10);
+ RequestMultiplexer<DummyRequest> multiplexer;
+ DummyRequest request(10);
size_t index;
bool maximalRequestChanged;
ASSERT_TRUE(multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -71,11 +71,11 @@ TEST(RequestMultiplexer, FirstHighPriorityRequestCausesNewMaximal) {
}
TEST(RequestMultiplexer, NewLowerPriorityRequestDoesNotCauseNewMaximal) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
size_t index;
{
- FakeRequest request(10);
+ DummyRequest request(10);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -84,7 +84,7 @@ TEST(RequestMultiplexer, NewLowerPriorityRequestDoesNotCauseNewMaximal) {
}
{
- FakeRequest request(5);
+ DummyRequest request(5);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -94,8 +94,8 @@ TEST(RequestMultiplexer, NewLowerPriorityRequestDoesNotCauseNewMaximal) {
}
TEST(RequestMultiplexer, AddOneRemoveMaximal) {
- RequestMultiplexer<FakeRequest> multiplexer;
- FakeRequest request(10);
+ RequestMultiplexer<DummyRequest> multiplexer;
+ DummyRequest request(10);
size_t index;
bool maximalRequestChanged;
ASSERT_TRUE(multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -103,7 +103,7 @@ TEST(RequestMultiplexer, AddOneRemoveMaximal) {
EXPECT_EQ(multiplexer.getRequests()[index].getPriority(), 10);
EXPECT_EQ(multiplexer.getCurrentMaximalRequest().getPriority(), 10);
- FakeRequest defaultRequest;
+ DummyRequest defaultRequest;
multiplexer.removeRequest(0, &maximalRequestChanged);
EXPECT_TRUE(maximalRequestChanged);
EXPECT_TRUE(
@@ -112,11 +112,11 @@ TEST(RequestMultiplexer, AddOneRemoveMaximal) {
}
TEST(RequestMultiplexer, AddManyRemoveMaximal) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
size_t index;
{
- FakeRequest request(10);
+ DummyRequest request(10);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -126,7 +126,7 @@ TEST(RequestMultiplexer, AddManyRemoveMaximal) {
}
{
- FakeRequest request(5);
+ DummyRequest request(5);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -136,7 +136,7 @@ TEST(RequestMultiplexer, AddManyRemoveMaximal) {
}
{
- FakeRequest request(10);
+ DummyRequest request(10);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -154,11 +154,11 @@ TEST(RequestMultiplexer, AddManyRemoveMaximal) {
}
TEST(RequestMultiplexer, AddManyRemoveBeforeMaximalThenRemoveMaximal) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
size_t index;
{
- FakeRequest request(1);
+ DummyRequest request(1);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -168,7 +168,7 @@ TEST(RequestMultiplexer, AddManyRemoveBeforeMaximalThenRemoveMaximal) {
}
{
- FakeRequest request(5);
+ DummyRequest request(5);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -178,7 +178,7 @@ TEST(RequestMultiplexer, AddManyRemoveBeforeMaximalThenRemoveMaximal) {
}
{
- FakeRequest request(10);
+ DummyRequest request(10);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -201,11 +201,11 @@ TEST(RequestMultiplexer, AddManyRemoveBeforeMaximalThenRemoveMaximal) {
}
TEST(RequestMultiplexer, AddManyRemoveAfterMaximalThenRemoveMaximal) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
size_t index;
{
- FakeRequest request(1);
+ DummyRequest request(1);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -215,7 +215,7 @@ TEST(RequestMultiplexer, AddManyRemoveAfterMaximalThenRemoveMaximal) {
}
{
- FakeRequest request(5);
+ DummyRequest request(5);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -225,7 +225,7 @@ TEST(RequestMultiplexer, AddManyRemoveAfterMaximalThenRemoveMaximal) {
}
{
- FakeRequest request(10);
+ DummyRequest request(10);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -235,7 +235,7 @@ TEST(RequestMultiplexer, AddManyRemoveAfterMaximalThenRemoveMaximal) {
}
{
- FakeRequest request(5);
+ DummyRequest request(5);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -260,11 +260,11 @@ TEST(RequestMultiplexer, AddManyRemoveAfterMaximalThenRemoveMaximal) {
}
TEST(RequestMultiplexer, AddManyUpdateWithLowerPriority) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
size_t index;
{
- FakeRequest request(1);
+ DummyRequest request(1);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -274,7 +274,7 @@ TEST(RequestMultiplexer, AddManyUpdateWithLowerPriority) {
}
{
- FakeRequest request(5);
+ DummyRequest request(5);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -284,7 +284,7 @@ TEST(RequestMultiplexer, AddManyUpdateWithLowerPriority) {
}
{
- FakeRequest request(10);
+ DummyRequest request(10);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -294,7 +294,7 @@ TEST(RequestMultiplexer, AddManyUpdateWithLowerPriority) {
}
{
- FakeRequest request(8);
+ DummyRequest request(8);
bool maximalRequestChanged;
multiplexer.updateRequest(1, request, &maximalRequestChanged);
EXPECT_FALSE(maximalRequestChanged);
@@ -304,11 +304,11 @@ TEST(RequestMultiplexer, AddManyUpdateWithLowerPriority) {
}
TEST(RequestMultiplexer, AddManyUpdateWithNewMaximalLowerPriority) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
size_t index;
{
- FakeRequest request(1);
+ DummyRequest request(1);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -318,7 +318,7 @@ TEST(RequestMultiplexer, AddManyUpdateWithNewMaximalLowerPriority) {
}
{
- FakeRequest request(5);
+ DummyRequest request(5);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -328,7 +328,7 @@ TEST(RequestMultiplexer, AddManyUpdateWithNewMaximalLowerPriority) {
}
{
- FakeRequest request(10);
+ DummyRequest request(10);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -338,7 +338,7 @@ TEST(RequestMultiplexer, AddManyUpdateWithNewMaximalLowerPriority) {
}
{
- FakeRequest request(8);
+ DummyRequest request(8);
bool maximalRequestChanged;
multiplexer.updateRequest(2, request, &maximalRequestChanged);
EXPECT_TRUE(maximalRequestChanged);
@@ -348,11 +348,11 @@ TEST(RequestMultiplexer, AddManyUpdateWithNewMaximalLowerPriority) {
}
TEST(RequestMultiplexer, AddManyUpdateNewMaximal) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
size_t index;
{
- FakeRequest request(1);
+ DummyRequest request(1);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -362,7 +362,7 @@ TEST(RequestMultiplexer, AddManyUpdateNewMaximal) {
}
{
- FakeRequest request(5);
+ DummyRequest request(5);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -372,7 +372,7 @@ TEST(RequestMultiplexer, AddManyUpdateNewMaximal) {
}
{
- FakeRequest request(10);
+ DummyRequest request(10);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
@@ -382,7 +382,7 @@ TEST(RequestMultiplexer, AddManyUpdateNewMaximal) {
}
{
- FakeRequest request(20);
+ DummyRequest request(20);
bool maximalRequestChanged;
multiplexer.updateRequest(1, request, &maximalRequestChanged);
EXPECT_TRUE(maximalRequestChanged);
@@ -392,7 +392,7 @@ TEST(RequestMultiplexer, AddManyUpdateNewMaximal) {
}
TEST(RequestMultiplexer, RemoveAllRequestsEmpty) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
bool maximalRequestChanged;
multiplexer.removeAllRequests(&maximalRequestChanged);
@@ -402,11 +402,11 @@ TEST(RequestMultiplexer, RemoveAllRequestsEmpty) {
}
TEST(RequestMultiplexer, RemoveAllRequestsNonEmpty) {
- RequestMultiplexer<FakeRequest> multiplexer;
+ RequestMultiplexer<DummyRequest> multiplexer;
size_t index;
{
- FakeRequest request(1);
+ DummyRequest request(1);
bool maximalRequestChanged;
ASSERT_TRUE(
multiplexer.addRequest(request, &index, &maximalRequestChanged));
diff --git a/core/tests/sensor_request_test.cc b/core/tests/sensor_request_test.cc
index 1b355ede..50c44df6 100644
--- a/core/tests/sensor_request_test.cc
+++ b/core/tests/sensor_request_test.cc
@@ -236,49 +236,3 @@ TEST(SensorRequest, LowRateHighLatencyAndHighRateLowLatency) {
EXPECT_EQ(mergedRequest.getLatency(), Nanoseconds(90));
EXPECT_EQ(mergedRequest.getMode(), SensorMode::ActiveContinuous);
}
-
-TEST(SensorRequest, MergeWithOnlyBiasChanges) {
- SensorRequest Request0(SensorMode::ActiveContinuous, Nanoseconds(100),
- Nanoseconds(100));
- SensorRequest Request1(SensorMode::ActiveContinuous, Nanoseconds(100),
- Nanoseconds(100));
- Request1.setBiasUpdatesRequested(true);
- SensorRequest mergedRequest;
-
- EXPECT_TRUE(mergedRequest.mergeWith(Request0));
- EXPECT_FALSE(mergedRequest.getBiasUpdatesRequested());
-
- EXPECT_TRUE(mergedRequest.mergeWith(Request1));
- EXPECT_TRUE(mergedRequest.getBiasUpdatesRequested());
-}
-
-TEST(SensorRequest, MergeWithBiasUpdatesUnchanged) {
- SensorRequest Request0(SensorMode::ActiveContinuous, Nanoseconds(100),
- Nanoseconds(100));
- Request0.setBiasUpdatesRequested(true);
- SensorRequest Request1(SensorMode::ActiveContinuous, Nanoseconds(100),
- Nanoseconds(100));
- Request1.setBiasUpdatesRequested(true);
-
- EXPECT_FALSE(Request0.mergeWith(Request1));
-}
-
-TEST(SensorRequest, MergeWithBiasUpdatesChanged) {
- SensorRequest Request0(SensorMode::ActiveContinuous, Nanoseconds(100),
- Nanoseconds(100));
- Request0.setBiasUpdatesRequested(true);
- SensorRequest Request1(SensorMode::ActiveContinuous, Nanoseconds(100),
- Nanoseconds(100));
-
- EXPECT_FALSE(Request0.mergeWith(Request1));
-}
-
-TEST(SensorRequest, OnlyBiasRequestUpdated) {
- SensorRequest Request0(SensorMode::ActiveContinuous, Nanoseconds(100),
- Nanoseconds(100));
- SensorRequest Request1(SensorMode::ActiveContinuous, Nanoseconds(100),
- Nanoseconds(100));
- Request1.setBiasUpdatesRequested(true);
-
- EXPECT_TRUE(Request0.onlyBiasRequestUpdated(Request1));
-} \ No newline at end of file
diff --git a/core/tests/wifi_scan_request_test.cc b/core/tests/wifi_scan_request_test.cc
index 8b7f92b5..274e2950 100644
--- a/core/tests/wifi_scan_request_test.cc
+++ b/core/tests/wifi_scan_request_test.cc
@@ -24,6 +24,6 @@ using chre::WifiScanType;
TEST(WifiScanRequest, DefaultWithMinimalPriority) {
WifiScanRequest request;
EXPECT_EQ(request.getScanType(), WifiScanType::Invalid);
- EXPECT_EQ(request.getFrequencies().size(), 0u);
- EXPECT_EQ(request.getSsids().size(), 0u);
+ EXPECT_EQ(request.getFrequencies().size(), 0);
+ EXPECT_EQ(request.getSsids().size(), 0);
}
diff --git a/core/timer_pool.cc b/core/timer_pool.cc
index 95eb9228..04ed0744 100644
--- a/core/timer_pool.cc
+++ b/core/timer_pool.cc
@@ -30,13 +30,12 @@ TimerPool::TimerPool() {
}
TimerHandle TimerPool::setSystemTimer(Nanoseconds duration,
- SystemEventCallbackFunction *callback,
+ SystemCallbackFunction *callback,
SystemCallbackType callbackType,
- void *data) {
- CHRE_ASSERT(callback != nullptr);
- TimerHandle timerHandle =
- setTimer(kSystemInstanceId, duration, data, callback, callbackType,
- true /* isOneShot */);
+ const void *cookie) {
+ TimerHandle timerHandle = setTimer(kSystemInstanceId, duration, callback,
+ static_cast<uint16_t>(callbackType),
+ cookie, true /* isOneShot */);
if (timerHandle == CHRE_TIMER_INVALID) {
FATAL_ERROR("Failed to set system timer");
@@ -46,9 +45,8 @@ TimerHandle TimerPool::setSystemTimer(Nanoseconds duration,
}
TimerHandle TimerPool::setTimer(uint32_t instanceId, Nanoseconds duration,
- const void *cookie,
- SystemEventCallbackFunction *systemCallback,
- SystemCallbackType callbackType,
+ SystemCallbackFunction *callback,
+ uint16_t eventType, const void *cookie,
bool isOneShot) {
LockGuard<Mutex> lock(mMutex);
@@ -57,10 +55,10 @@ TimerHandle TimerPool::setTimer(uint32_t instanceId, Nanoseconds duration,
timerRequest.timerHandle = generateTimerHandleLocked();
timerRequest.expirationTime = SystemTime::getMonotonicTime() + duration;
timerRequest.duration = duration;
- timerRequest.cookie = cookie;
- timerRequest.systemCallback = systemCallback;
- timerRequest.callbackType = callbackType;
timerRequest.isOneShot = isOneShot;
+ timerRequest.callback = callback;
+ timerRequest.eventType = eventType;
+ timerRequest.cookie = cookie;
bool newTimerExpiresEarliest =
(!mTimerRequests.empty() && mTimerRequests.top() > timerRequest);
@@ -219,25 +217,16 @@ bool TimerPool::handleExpiredTimersAndScheduleNext() {
}
bool TimerPool::handleExpiredTimersAndScheduleNextLocked() {
- bool handledExpiredTimer = false;
-
+ bool success = false;
while (!mTimerRequests.empty()) {
Nanoseconds currentTime = SystemTime::getMonotonicTime();
TimerRequest &currentTimerRequest = mTimerRequests.top();
if (currentTime >= currentTimerRequest.expirationTime) {
- // This timer has expired, so post an event if it is a nanoapp timer, or
- // submit a deferred callback if it's a system timer.
- if (currentTimerRequest.instanceId == kSystemInstanceId) {
- EventLoopManagerSingleton::get()->deferCallback(
- currentTimerRequest.callbackType,
- const_cast<void *>(currentTimerRequest.cookie),
- currentTimerRequest.systemCallback);
- } else {
- EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- CHRE_EVENT_TIMER, const_cast<void *>(currentTimerRequest.cookie),
- nullptr /*freeCallback*/, currentTimerRequest.instanceId);
- }
- handledExpiredTimer = true;
+ // Post an event for an expired timer.
+ success = EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
+ currentTimerRequest.eventType,
+ const_cast<void *>(currentTimerRequest.cookie),
+ currentTimerRequest.callback, currentTimerRequest.instanceId);
// Reschedule the timer if needed, and release the current request.
if (!currentTimerRequest.isOneShot) {
@@ -253,27 +242,26 @@ bool TimerPool::handleExpiredTimersAndScheduleNextLocked() {
popTimerRequestLocked();
}
} else {
- // Update the system timer to reflect the duration until the closest
- // expiry (mTimerRequests is sorted by expiry, so we just do this for the
- // first timer found which has not expired yet)
Nanoseconds duration = currentTimerRequest.expirationTime - currentTime;
mSystemTimer.set(handleSystemTimerCallback, this, duration);
+
+ // Assign success to true here to handle timers that tick before their
+ // expiration time. This should be rarely required, but for systems where
+ // a timer may tick earlier than requested the request is rescheduled with
+ // the remaining time as computed above.
+ success = true;
break;
}
}
- return handledExpiredTimer;
+ return success;
}
void TimerPool::handleSystemTimerCallback(void *timerPoolPtr) {
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- auto *timerPool = static_cast<TimerPool *>(data);
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ auto *timerPool = static_cast<TimerPool *>(eventData);
if (!timerPool->handleExpiredTimersAndScheduleNext()) {
- // Means that the system timer invoked our callback before the next timer
- // expired. Possible in rare race conditions with time removal, but could
- // indicate a faulty SystemTimer implementation if this happens often. Not
- // a major problem - we'll just reset the timer to the next expiration.
- LOGW("Timer callback invoked prior to expiry");
+ LOGE("Timer callback invoked with no outstanding timers");
}
};
diff --git a/core/wifi_request_manager.cc b/core/wifi_request_manager.cc
index e7080f47..0b0f0f77 100644
--- a/core/wifi_request_manager.cc
+++ b/core/wifi_request_manager.cc
@@ -24,7 +24,6 @@
#include "chre/platform/fatal_error.h"
#include "chre/platform/log.h"
#include "chre/platform/system_time.h"
-#include "chre/util/nested_data_ptr.h"
#include "chre/util/system/debug_dump.h"
#include "chre_api/chre/version.h"
@@ -153,22 +152,18 @@ bool WifiRequestManager::requestScan(Nanoapp *nanoapp,
bool success = false;
if (mScanRequestingNanoappInstanceId.has_value()) {
LOGE("Active wifi scan request made while a request is in flight");
- } else if (getSettingState(Setting::WIFI_AVAILABLE) ==
- SettingState::DISABLED) {
- // Treat as success, but send an async failure per API contract.
- success = true;
- handleScanResponse(false /* pending */, CHRE_ERROR_FUNCTION_DISABLED);
} else {
success = mPlatformWifi.requestScan(params);
if (!success) {
LOGE("Wifi scan request failed");
+ } else {
+ mScanRequestingNanoappInstanceId = nanoapp->getInstanceId();
+ mScanRequestingNanoappCookie = cookie;
+ mLastScanRequestTime = SystemTime::getMonotonicTime();
}
}
if (success) {
- mScanRequestingNanoappInstanceId = nanoapp->getInstanceId();
- mScanRequestingNanoappCookie = cookie;
- mLastScanRequestTime = SystemTime::getMonotonicTime();
addWifiScanRequestLog(nanoapp->getInstanceId(), params);
}
@@ -182,19 +177,24 @@ void WifiRequestManager::handleScanMonitorStateChange(bool enabled,
uint8_t errorCode;
};
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- CallbackState cbState = NestedDataPtr<CallbackState>(data);
- EventLoopManagerSingleton::get()
- ->getWifiRequestManager()
- .handleScanMonitorStateChangeSync(cbState.enabled, cbState.errorCode);
- };
-
- CallbackState cbState = {};
- cbState.enabled = enabled;
- cbState.errorCode = errorCode;
- EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::WifiScanMonitorStateChange,
- NestedDataPtr<CallbackState>(cbState), callback);
+ auto *cbState = memoryAlloc<CallbackState>();
+ if (cbState == nullptr) {
+ LOG_OOM();
+ } else {
+ cbState->enabled = enabled;
+ cbState->errorCode = errorCode;
+
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ auto *state = static_cast<CallbackState *>(eventData);
+ EventLoopManagerSingleton::get()
+ ->getWifiRequestManager()
+ .handleScanMonitorStateChangeSync(state->enabled, state->errorCode);
+ memoryFree(state);
+ };
+
+ EventLoopManagerSingleton::get()->deferCallback(
+ SystemCallbackType::WifiScanMonitorStateChange, cbState, callback);
+ }
}
void WifiRequestManager::handleScanResponse(bool pending, uint8_t errorCode) {
@@ -203,39 +203,66 @@ void WifiRequestManager::handleScanResponse(bool pending, uint8_t errorCode) {
uint8_t errorCode;
};
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- CallbackState cbState = NestedDataPtr<CallbackState>(data);
- EventLoopManagerSingleton::get()
- ->getWifiRequestManager()
- .handleScanResponseSync(cbState.pending, cbState.errorCode);
- };
-
- CallbackState cbState = {};
- cbState.pending = pending;
- cbState.errorCode = errorCode;
- EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::WifiRequestScanResponse,
- NestedDataPtr<CallbackState>(cbState), callback);
+ auto *cbState = memoryAlloc<CallbackState>();
+ if (cbState == nullptr) {
+ LOG_OOM();
+ } else {
+ cbState->pending = pending;
+ cbState->errorCode = errorCode;
+
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ auto *state = static_cast<CallbackState *>(eventData);
+ EventLoopManagerSingleton::get()
+ ->getWifiRequestManager()
+ .handleScanResponseSync(state->pending, state->errorCode);
+ memoryFree(state);
+ };
+
+ EventLoopManagerSingleton::get()->deferCallback(
+ SystemCallbackType::WifiRequestScanResponse, cbState, callback);
+ }
}
void WifiRequestManager::handleRangingEvent(
uint8_t errorCode, struct chreWifiRangingEvent *event) {
- auto callback = [](uint16_t /*type*/, void *data, void *extraData) {
- uint8_t cbErrorCode = NestedDataPtr<uint8_t>(extraData);
- EventLoopManagerSingleton::get()
- ->getWifiRequestManager()
- .handleRangingEventSync(
- cbErrorCode, static_cast<struct chreWifiRangingEvent *>(data));
- };
-
- EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::WifiHandleRangingEvent, event, callback,
- NestedDataPtr<uint8_t>(errorCode));
+ // Use two different callbacks to avoid needing a temporary allocation to
+ // carry the error code into the event loop context
+ if (errorCode != CHRE_ERROR_NONE) {
+ // Enables passing the error code through the event data pointer to avoid
+ // allocating memory
+ union NestedErrorCode {
+ void *eventData;
+ uint8_t errorCode;
+ };
+
+ auto errorCb = [](uint16_t /* eventType */, void *eventData) {
+ NestedErrorCode cbErrorCode;
+ cbErrorCode.eventData = eventData;
+ EventLoopManagerSingleton::get()
+ ->getWifiRequestManager()
+ .handleRangingEventSync(cbErrorCode.errorCode, nullptr);
+ };
+
+ NestedErrorCode error = {};
+ error.errorCode = errorCode;
+ EventLoopManagerSingleton::get()->deferCallback(
+ SystemCallbackType::WifiHandleFailedRanging, error.eventData, errorCb);
+ } else {
+ auto successCb = [](uint16_t /* eventType */, void *eventData) {
+ auto *rttEvent = static_cast<struct chreWifiRangingEvent *>(eventData);
+ EventLoopManagerSingleton::get()
+ ->getWifiRequestManager()
+ .handleRangingEventSync(CHRE_ERROR_NONE, rttEvent);
+ };
+
+ EventLoopManagerSingleton::get()->deferCallback(
+ SystemCallbackType::WifiHandleRangingEvent, event, successCb);
+ }
}
-void WifiRequestManager::handleScanEvent(struct chreWifiScanEvent *event) {
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- auto *scanEvent = static_cast<struct chreWifiScanEvent *>(data);
+void WifiRequestManager::handleScanEvent(chreWifiScanEvent *event) {
+ auto callback = [](uint16_t eventType, void *eventData) {
+ chreWifiScanEvent *scanEvent = static_cast<chreWifiScanEvent *>(eventData);
EventLoopManagerSingleton::get()
->getWifiRequestManager()
.postScanEventFatal(scanEvent);
@@ -251,7 +278,7 @@ void WifiRequestManager::logStateToBuffer(DebugDumpWrapper &debugDump) const {
if (scanMonitorIsEnabled()) {
debugDump.print(" Wifi scan monitor enabled nanoapps:\n");
- for (uint32_t instanceId : mScanMonitorNanoapps) {
+ for (const auto &instanceId : mScanMonitorNanoapps) {
debugDump.print(" nappId=%" PRIu32 "\n", instanceId);
}
}
@@ -380,10 +407,14 @@ bool WifiRequestManager::postScanMonitorAsyncResultEvent(
event->reserved = 0;
event->cookie = cookie;
- EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- CHRE_EVENT_WIFI_ASYNC_RESULT, event, freeEventDataCallback,
- nanoappInstanceId);
- eventPosted = true;
+ // Post the event.
+ eventPosted =
+ EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
+ CHRE_EVENT_WIFI_ASYNC_RESULT, event, freeEventDataCallback,
+ nanoappInstanceId);
+ if (!eventPosted) {
+ memoryFree(event);
+ }
}
}
@@ -402,9 +433,6 @@ void WifiRequestManager::postScanMonitorAsyncResultEventFatal(
bool WifiRequestManager::postScanRequestAsyncResultEvent(
uint32_t nanoappInstanceId, bool success, uint8_t errorCode,
const void *cookie) {
- // TODO: the body of this function can be extracted to a common helper for use
- // across this function, postScanMonitorAsyncResultEvent,
- // postRangingAsyncResult, and GnssSession::postAsyncResultEvent
bool eventPosted = false;
chreAsyncResult *event = memoryAlloc<chreAsyncResult>();
if (event == nullptr) {
@@ -416,10 +444,11 @@ bool WifiRequestManager::postScanRequestAsyncResultEvent(
event->reserved = 0;
event->cookie = cookie;
- EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- CHRE_EVENT_WIFI_ASYNC_RESULT, event, freeEventDataCallback,
- nanoappInstanceId);
- eventPosted = true;
+ // Post the event.
+ eventPosted =
+ EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
+ CHRE_EVENT_WIFI_ASYNC_RESULT, event, freeEventDataCallback,
+ nanoappInstanceId);
}
return eventPosted;
@@ -560,10 +589,13 @@ bool WifiRequestManager::postRangingAsyncResult(uint8_t errorCode) {
event->reserved = 0;
event->cookie = req.cookie;
- EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- CHRE_EVENT_WIFI_ASYNC_RESULT, event, freeEventDataCallback,
- req.nanoappInstanceId);
- eventPosted = true;
+ eventPosted =
+ EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
+ CHRE_EVENT_WIFI_ASYNC_RESULT, event, freeEventDataCallback,
+ req.nanoappInstanceId);
+ if (!eventPosted) {
+ memoryFree(event);
+ }
}
}
@@ -657,15 +689,15 @@ void WifiRequestManager::addWifiScanRequestLog(
static_cast<Milliseconds>(params->maxScanAgeMs)));
}
-void WifiRequestManager::freeWifiScanEventCallback(uint16_t /* eventType */,
+void WifiRequestManager::freeWifiScanEventCallback(uint16_t eventType,
void *eventData) {
- auto *scanEvent = static_cast<struct chreWifiScanEvent *>(eventData);
+ chreWifiScanEvent *scanEvent = static_cast<chreWifiScanEvent *>(eventData);
EventLoopManagerSingleton::get()
->getWifiRequestManager()
.handleFreeWifiScanEvent(scanEvent);
}
-void WifiRequestManager::freeWifiRangingEventCallback(uint16_t /* eventType */,
+void WifiRequestManager::freeWifiRangingEventCallback(uint16_t eventType,
void *eventData) {
auto *event = static_cast<struct chreWifiRangingEvent *>(eventData);
EventLoopManagerSingleton::get()
diff --git a/core/wwan_request_manager.cc b/core/wwan_request_manager.cc
index 2c982f77..d973b2fd 100644
--- a/core/wwan_request_manager.cc
+++ b/core/wwan_request_manager.cc
@@ -49,10 +49,9 @@ bool WwanRequestManager::requestCellInfo(Nanoapp *nanoapp, const void *cookie) {
return success;
}
-void WwanRequestManager::handleCellInfoResult(
- struct chreWwanCellInfoResult *result) {
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- auto *cellInfoResult = static_cast<chreWwanCellInfoResult *>(data);
+void WwanRequestManager::handleCellInfoResult(chreWwanCellInfoResult *result) {
+ auto callback = [](uint16_t /* eventType */, void *eventData) {
+ auto *cellInfoResult = static_cast<chreWwanCellInfoResult *>(eventData);
EventLoopManagerSingleton::get()
->getWwanRequestManager()
.handleCellInfoResultSync(cellInfoResult);
diff --git a/doc/porting_guide.md b/doc/porting_guide.md
index 7c4469f4..72d3b1d9 100644
--- a/doc/porting_guide.md
+++ b/doc/porting_guide.md
@@ -227,7 +227,7 @@ the various PAL APIs and verify the CHRE API requirements are being met
2. Assuming the platform PAL implementations utilize CHPP and can communicate
from the host machine to the target chipset, execute `run_pal_impl_tests.sh` to
-run basic consistency checks on the PAL
+run basic sanity checks on the PAL
3. Execute tests (see Testing section for details)
diff --git a/external/flatbuffers/flatbuffers.mk b/external/flatbuffers/flatbuffers.mk
index f5fd761d..e2eb6097 100644
--- a/external/flatbuffers/flatbuffers.mk
+++ b/external/flatbuffers/flatbuffers.mk
@@ -7,5 +7,3 @@ FLATBUFFERS_PATH = external/flatbuffers
FLATBUFFERS_CFLAGS := -I$(FLATBUFFERS_PATH)/include
FLATBUFFERS_CFLAGS += -DFLATBUFFERS_CHRE
-FLATBUFFERS_CFLAGS += -DFLATBUFFERS_ASSERT=CHRE_ASSERT
-FLATBUFFERS_CFLAGS += -DFLATBUFFERS_ASSERT_INCLUDE=\"chre/util/container_support.h\"
diff --git a/external/flatbuffers/include/flatbuffers/flatbuffers.h b/external/flatbuffers/include/flatbuffers/flatbuffers.h
index 7b59fa06..5ca119e4 100644
--- a/external/flatbuffers/include/flatbuffers/flatbuffers.h
+++ b/external/flatbuffers/include/flatbuffers/flatbuffers.h
@@ -22,19 +22,20 @@
* A customized version of the FlatBuffers implementation header file targeted
* for use within CHRE. This file differs from the mainline FlatBuffers release
* via the introduction of the feature flag FLATBUFFERS_CHRE. When defined,
- * standard library features not used in CHRE are removed. This includes
- * removing most support for strings and std::vector, removal of std::function,
- * etc.
- *
- * Any user of this header, including CHRE, must make use of a custom Allocator
- * class when using the FlatBufferBuilder. This ensures that alloc / free
- * functions specific to the platform are used as new / delete are not
- * supported, but are used by the DefaultAllocator. Additionally,
- * FLATBUFFERS_ASSERT must be defined to be the assert function that flatbuffers
- * should use and FLATBUFFERS_ASSERT_INCLUDE must be the include path to the
- * file that defines that assert function.
+ * standard library features not used in CHRE are removed or remapped to their
+ * CHRE-specific alternatives. This includes removing support for strings,
+ * replacing std::vector with chre::DynamicVector, use of CHRE_ASSERT, removal
+ * of uses of std::function, etc.
*/
+#ifdef FLATBUFFERS_CHRE
+#include "chre/util/container_support.h"
+#include "chre/util/dynamic_vector.h"
+
+// Before the flatbuffers/base.h include where it's used
+#define FLATBUFFERS_ASSERT CHRE_ASSERT
+#endif
+
#include "flatbuffers/base.h"
#if defined(FLATBUFFERS_NAN_DEFAULTS)
@@ -249,7 +250,9 @@ struct VectorReverseIterator : public std::reverse_iterator<Iterator> {
}
};
+#ifndef FLATBUFFERS_CHRE
struct String;
+#endif
// This is used as a helper type for accessing vectors.
// Vector::data() assumes the vector elements start after the length field.
@@ -564,6 +567,7 @@ template<typename T, uint16_t length> class Array<Offset<T>, length> {
uint8_t data_[1];
};
+#ifndef FLATBUFFERS_CHRE
// Lexicographically compare two strings (possibly containing nulls), and
// return true if the first is less than the second.
static inline bool StringLessThan(const char *a_data, uoffset_t a_size,
@@ -574,9 +578,7 @@ static inline bool StringLessThan(const char *a_data, uoffset_t a_size,
struct String : public Vector<char> {
const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
- #ifndef FLATBUFFERS_CHRE
std::string str() const { return std::string(c_str(), size()); }
- #endif // !FLATBUFFERS_CHRE
// clang-format off
#ifdef FLATBUFFERS_HAS_STRING_VIEW
@@ -591,19 +593,18 @@ struct String : public Vector<char> {
}
};
-#ifndef FLATBUFFERS_CHRE
// Convenience function to get std::string from a String returning an empty
// string on null pointer.
static inline std::string GetString(const String *str) {
return str ? str->str() : "";
}
-#endif // !FLATBUFFERS_CHRE
// Convenience function to get char* from a String returning an empty string on
// null pointer.
static inline const char *GetCstring(const String *str) {
return str ? str->c_str() : "";
}
+#endif // !FLATBUFFERS_CHRE
// Allocator interface. This is flatbuffers-specific and meant only for
// `vector_downward` usage.
@@ -647,73 +648,51 @@ class Allocator {
}
};
-#ifndef FLATBUFFERS_CHRE
// DefaultAllocator uses new/delete to allocate memory regions
class DefaultAllocator : public Allocator {
public:
uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE {
- return new uint8_t[size];
+ #ifndef FLATBUFFERS_CHRE
+ return new uint8_t[size];
+ #else
+ return static_cast<uint8_t *>(chre::memoryAlloc(size));
+ #endif
}
void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE {
- delete[] p;
+ #ifndef FLATBUFFERS_CHRE
+ delete[] p;
+ #else
+ return chre::memoryFree(p);
+ #endif
}
- static void dealloc(void *p, size_t) {
- delete[] static_cast<uint8_t *>(p);
- }
+ static void dealloc(void *p, size_t) { delete[] static_cast<uint8_t *>(p); }
};
-#endif
// These functions allow for a null allocator to mean use the default allocator,
// as used by DetachedBuffer and vector_downward below.
// This is to avoid having a statically or dynamically allocated default
// allocator, or having to move it between the classes that may own it.
inline uint8_t *Allocate(Allocator *allocator, size_t size) {
- #ifndef FLATBUFFERS_CHRE
- return allocator ? allocator->allocate(size)
- : DefaultAllocator().allocate(size);
- #else
- if (allocator)
- return allocator->allocate(size);
- else {
- FLATBUFFERS_ASSERT(false);
- return nullptr;
- }
- #endif // FLATBUFFERS_CHRE
+ return allocator ? allocator->allocate(size)
+ : DefaultAllocator().allocate(size);
}
inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) {
- #ifndef FLATBUFFERS_CHRE
- if (allocator)
- allocator->deallocate(p, size);
- else
- DefaultAllocator().deallocate(p, size);
- #else
- if (allocator)
- allocator->deallocate(p, size);
- else
- FLATBUFFERS_ASSERT(false);
- #endif // FLATBUFFERS_CHRE
+ if (allocator)
+ allocator->deallocate(p, size);
+ else
+ DefaultAllocator().deallocate(p, size);
}
inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p,
size_t old_size, size_t new_size,
size_t in_use_back, size_t in_use_front) {
- #ifndef FLATBUFFERS_CHRE
- return allocator ? allocator->reallocate_downward(old_p, old_size, new_size,
- in_use_back, in_use_front)
- : DefaultAllocator().reallocate_downward(
- old_p, old_size, new_size, in_use_back, in_use_front);
- #else
- if (allocator)
- return allocator->reallocate_downward(old_p, old_size, new_size,
- in_use_back, in_use_front);
- else {
- FLATBUFFERS_ASSERT(false);
- return nullptr;
- }
- #endif // FLATBUFFERS_CHRE
+ return allocator ? allocator->reallocate_downward(old_p, old_size, new_size,
+ in_use_back, in_use_front)
+ : DefaultAllocator().reallocate_downward(
+ old_p, old_size, new_size, in_use_back, in_use_front);
}
// DetachedBuffer is a finished flatbuffer memory region, detached from its
@@ -1515,6 +1494,7 @@ class FlatBufferBuilder {
}
/// @endcond
+ #ifndef FLATBUFFERS_CHRE
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const char pointer to the data to be stored as a string.
/// @param[in] len The number of bytes that should be stored from `str`.
@@ -1542,7 +1522,6 @@ class FlatBufferBuilder {
return CreateString(str, strlen(str));
}
- #ifndef FLATBUFFERS_CHRE
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const reference to a std::string to store in the buffer.
/// @return Returns the offset in the buffer where the string starts.
@@ -1725,6 +1704,17 @@ class FlatBufferBuilder {
FLATBUFFERS_ASSERT(false);
return 0;
}
+
+ /// @brief Serialize a `chre::DynamicVector` into a FlatBuffer `vector`.
+ /// @tparam T The data type of the `chre::DynamicVector` elements.
+ /// @param v A const reference to the `chre::DynamicVector` to serialize into
+ /// the buffer as a `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T> Offset<Vector<T>> CreateVector(
+ const chre::DynamicVector<T> &v) {
+ return CreateVector(v.data(), v.size());
+ }
#endif // FLATBUFFERS_CHRE
// clang-format off
@@ -2299,6 +2289,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
}
+ #ifndef FLATBUFFERS_CHRE
// Verify a pointer (may be NULL) to string.
bool VerifyString(const String *str) const {
size_t end;
@@ -2307,6 +2298,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
Verify(end, 1) && // Must have terminator
Check(buf_[end] == '\0')); // Terminating byte must be 0.
}
+ #endif
// Common code between vectors and strings.
bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size,
diff --git a/external/kiss_fft/_kiss_fft_guts.h b/external/kiss_fft/_kiss_fft_guts.h
index 6aa102df..e83771f0 100644
--- a/external/kiss_fft/_kiss_fft_guts.h
+++ b/external/kiss_fft/_kiss_fft_guts.h
@@ -55,13 +55,9 @@ struct kiss_fft_state{
#define SAMP_MIN -SAMP_MAX
#if defined(CHECK_OVERFLOW)
-#ifdef CHRE_KISS_FFT_CAN_USE_STDIO
# define CHECK_OVERFLOW_OP(a,op,b) \
if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \
fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); }
-#else
-#define CHECK_OVERFLOW(a, op, b) {}
-#endif
#endif
@@ -149,13 +145,10 @@ struct kiss_fft_state{
}while(0)
-#ifdef CHRE_KISS_FFT_CAN_USE_STDIO
/* a debugging function */
#define pcpx(c)\
fprintf(stderr,"%g + %gi\n",(double)((c)->r),(double)((c)->i) )
-#else
-#define pcpx(c) {}
-#endif
+
#ifdef KISS_FFT_USE_ALLOCA
// define this to allow use of alloca instead of malloc for temporary buffers
diff --git a/external/kiss_fft/kiss_fft.c b/external/kiss_fft/kiss_fft.c
index c1ea7e32..7f439c2e 100644
--- a/external/kiss_fft/kiss_fft.c
+++ b/external/kiss_fft/kiss_fft.c
@@ -18,14 +18,6 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
fixed or floating point complex numbers. It also delares the kf_ internal functions.
*/
-// CHRE modifications begin
-#if defined(__clang__)
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wcast-align"
-#pragma clang diagnostic ignored "-Wbad-function-cast"
-#endif
-// CHRE modifications end
-
static void kf_bfly2(
kiss_fft_cpx * Fout,
const size_t fstride,
@@ -414,9 +406,3 @@ int kiss_fft_next_fast_size(int n)
}
return n;
}
-
-// CHRE modifications begin
-#if defined(__clang__)
-#pragma clang diagnostic pop
-#endif
-// CHRE modifications end
diff --git a/external/kiss_fft/kiss_fftr.c b/external/kiss_fft/kiss_fftr.c
index 0dad8a24..f31f23ec 100644
--- a/external/kiss_fft/kiss_fftr.c
+++ b/external/kiss_fft/kiss_fftr.c
@@ -15,14 +15,6 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#include "kiss_fftr.h"
#include "_kiss_fft_guts.h"
-// CHRE modifications begin
-#if defined(__clang__)
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wcast-align"
-#pragma clang diagnostic ignored "-Wbad-function-cast"
-#endif
-// CHRE modifications end
-
struct kiss_fftr_state{
kiss_fft_cfg substate;
kiss_fft_cpx * tmpbuf;
@@ -39,9 +31,7 @@ kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem,size_t * lenme
size_t subsize, memneeded;
if (nfft & 1) {
-#if CHRE_KISS_FFT_CAN_USE_STDIO
fprintf(stderr,"Real FFT optimization must be even.\n");
-#endif
return NULL;
}
nfft >>= 1;
@@ -81,12 +71,8 @@ void kiss_fftr(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_cpx *fr
kiss_fft_cpx fpnk,fpk,f1k,f2k,tw,tdc;
if ( st->substate->inverse) {
-#if CHRE_KISS_FFT_CAN_USE_STDIO
fprintf(stderr,"kiss fft usage error: improper alloc\n");
exit(1);
-#else
- return;
-#endif
}
ncfft = st->substate->nfft;
@@ -140,12 +126,8 @@ void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_cpx *freqdata,kiss_fft_scalar *t
int k, ncfft;
if (st->substate->inverse == 0) {
-#if CHRE_KISS_FFT_CAN_USE_STDIO
fprintf (stderr, "kiss fft usage error: improper alloc\n");
exit (1);
-#else
- return;
-#endif
}
ncfft = st->substate->nfft;
@@ -175,9 +157,3 @@ void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_cpx *freqdata,kiss_fft_scalar *t
}
kiss_fft (st->substate, st->tmpbuf, (kiss_fft_cpx *) timedata);
}
-
-// CHRE modifications begin
-#if defined(__clang__)
-#pragma clang diagnostic pop
-#endif
-// CHRE modifications end
diff --git a/host/common/audio_stress_test/audio_stress_test.cc b/host/common/audio_stress_test/audio_stress_test.cc
index 00737188..f8247866 100644
--- a/host/common/audio_stress_test/audio_stress_test.cc
+++ b/host/common/audio_stress_test/audio_stress_test.cc
@@ -15,7 +15,6 @@
*/
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_header_utils.h"
#include "chre_host/host_protocol_host.h"
#include "chre_host/log.h"
#include "chre_host/socket_client.h"
@@ -93,15 +92,12 @@ void sendLoadNanoappRequest(SocketClient &client, const char *filename,
return;
}
- // All loaded nanoapps must be signed currently.
- uint32_t appFlags = CHRE_NAPP_HEADER_SIGNED;
-
// Perform loading with 1 fragment for simplicity
FlatBufferBuilder builder(size + 128);
FragmentedLoadTransaction transaction =
FragmentedLoadTransaction(1 /* transactionId */, appId, appVersion,
- appFlags, 0x01000000 /* targetApiVersion */,
- buffer, buffer.size() /* fragmentSize */);
+ 0x01000000 /* targetApiVersion */, buffer,
+ buffer.size() /* fragmentSize */);
HostProtocolHost::encodeFragmentedLoadNanoappRequest(
builder, transaction.getNextRequest());
diff --git a/host/common/daemon_base.cc b/host/common/daemon_base.cc
deleted file mode 100644
index 976cfba1..00000000
--- a/host/common/daemon_base.cc
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <cstdlib>
-#include <fstream>
-
-#include "chre_host/daemon_base.h"
-#include "chre_host/log.h"
-#include "chre_host/napp_header.h"
-
-#include <json/json.h>
-
-// Aliased for consistency with the way these symbols are referenced in
-// CHRE-side code
-namespace fbs = ::chre::fbs;
-
-namespace android {
-namespace chre {
-
-void ChreDaemonBase::loadPreloadedNanoapps() {
- constexpr char kPreloadedNanoappsConfigPath[] =
- "/vendor/etc/chre/preloaded_nanoapps.json";
- std::ifstream configFileStream(kPreloadedNanoappsConfigPath);
-
- Json::CharReaderBuilder builder;
- Json::Value config;
- if (!configFileStream) {
- LOGE("Failed to open config file '%s': %d (%s)",
- kPreloadedNanoappsConfigPath, errno, strerror(errno));
- } else if (!Json::parseFromStream(builder, configFileStream, &config,
- /* errorMessage = */ nullptr)) {
- LOGE("Failed to parse nanoapp config file");
- } else if (!config.isMember("nanoapps") || !config.isMember("source_dir")) {
- LOGE("Malformed preloaded nanoapps config");
- } else {
- const Json::Value &directory = config["source_dir"];
- for (Json::ArrayIndex i = 0; i < config["nanoapps"].size(); i++) {
- const Json::Value &nanoapp = config["nanoapps"][i];
- loadPreloadedNanoapp(directory.asString(), nanoapp.asString(),
- static_cast<uint32_t>(i));
- }
- }
-}
-
-void ChreDaemonBase::loadPreloadedNanoapp(const std::string &directory,
- const std::string &name,
- uint32_t transactionId) {
- std::vector<uint8_t> headerBuffer;
-
- std::string headerFile = directory + "/" + name + ".napp_header";
-
- // Only create the nanoapp filename as the CHRE framework will load from
- // within the directory its own binary resides in.
- std::string nanoappFilename = name + ".so";
-
- if (readFileContents(headerFile.c_str(), &headerBuffer) &&
- !loadNanoapp(headerBuffer, nanoappFilename, transactionId)) {
- LOGE("Failed to load nanoapp: '%s'", name.c_str());
- }
-}
-
-bool ChreDaemonBase::loadNanoapp(const std::vector<uint8_t> &header,
- const std::string &nanoappName,
- uint32_t transactionId) {
- bool success = false;
- if (header.size() != sizeof(NanoAppBinaryHeader)) {
- LOGE("Header size mismatch");
- } else {
- // The header blob contains the struct above.
- const auto *appHeader =
- reinterpret_cast<const NanoAppBinaryHeader *>(header.data());
-
- // Build the target API version from major and minor.
- uint32_t targetApiVersion = (appHeader->targetChreApiMajorVersion << 24) |
- (appHeader->targetChreApiMinorVersion << 16);
-
- success = sendNanoappLoad(appHeader->appId, appHeader->appVersion,
- targetApiVersion, nanoappName, transactionId);
- }
-
- return success;
-}
-
-bool ChreDaemonBase::sendNanoappLoad(uint64_t appId, uint32_t appVersion,
- uint32_t appTargetApiVersion,
- const std::string &appBinaryName,
- uint32_t transactionId) {
- flatbuffers::FlatBufferBuilder builder;
- HostProtocolHost::encodeLoadNanoappRequestForFile(
- builder, transactionId, appId, appVersion, appTargetApiVersion,
- appBinaryName.c_str());
-
- bool success = sendMessageToChre(
- kHostClientIdDaemon, builder.GetBufferPointer(), builder.GetSize());
-
- if (!success) {
- LOGE("Failed to send nanoapp filename.");
- } else {
- mPreloadedNanoappPendingTransactionIds.push(transactionId);
- }
-
- return success;
-}
-
-bool ChreDaemonBase::sendTimeSync(bool logOnError) {
- bool success = false;
- int64_t timeOffset = getTimeOffset(&success);
-
- if (success) {
- flatbuffers::FlatBufferBuilder builder(64);
- HostProtocolHost::encodeTimeSyncMessage(builder, timeOffset);
- success = sendMessageToChre(kHostClientIdDaemon, builder.GetBufferPointer(),
- builder.GetSize());
-
- if (!success && logOnError) {
- LOGE("Failed to deliver time sync message from host to CHRE");
- }
- }
-
- return success;
-}
-
-bool ChreDaemonBase::sendTimeSyncWithRetry(size_t numRetries,
- useconds_t retryDelayUs,
- bool logOnError) {
- bool success = false;
- while (!success && (numRetries-- != 0)) {
- success = sendTimeSync(logOnError);
- if (!success) {
- usleep(retryDelayUs);
- }
- }
- return success;
-}
-
-bool ChreDaemonBase::sendMessageToChre(uint16_t clientId, void *data,
- size_t length) {
- bool success = false;
- if (!HostProtocolHost::mutateHostClientId(data, length, clientId)) {
- LOGE("Couldn't set host client ID in message container!");
- } else {
- LOGV("Delivering message from host (size %zu)", length);
- getLogger()->dump(static_cast<const uint8_t *>(data), length);
- success = doSendMessage(data, length);
- }
-
- return success;
-}
-
-void ChreDaemonBase::onMessageReceived(const unsigned char *messageBuffer,
- size_t messageLen) {
- getLogger()->dump(messageBuffer, messageLen);
-
- uint16_t hostClientId;
- fbs::ChreMessage messageType;
- if (!HostProtocolHost::extractHostClientIdAndType(
- messageBuffer, messageLen, &hostClientId, &messageType)) {
- LOGW("Failed to extract host client ID from message - sending broadcast");
- hostClientId = ::chre::kHostClientIdUnspecified;
- }
-
- if (messageType == fbs::ChreMessage::LogMessage) {
- std::unique_ptr<fbs::MessageContainerT> container =
- fbs::UnPackMessageContainer(messageBuffer);
- const auto *logMessage = container->message.AsLogMessage();
- const std::vector<int8_t> &logData = logMessage->buffer;
-
- getLogger()->log(reinterpret_cast<const uint8_t *>(logData.data()),
- logData.size());
- } else if (messageType == fbs::ChreMessage::LogMessageV2) {
- std::unique_ptr<fbs::MessageContainerT> container =
- fbs::UnPackMessageContainer(messageBuffer);
- const auto *logMessage = container->message.AsLogMessageV2();
- const std::vector<int8_t> &logData = logMessage->buffer;
- uint32_t numLogsDropped = logMessage->num_logs_dropped;
-
- getLogger()->logV2(reinterpret_cast<const uint8_t *>(logData.data()),
- logData.size(), numLogsDropped);
- } else if (messageType == fbs::ChreMessage::TimeSyncRequest) {
- sendTimeSync(true /* logOnError */);
- } else if (messageType == fbs::ChreMessage::LowPowerMicAccessRequest) {
- configureLpma(true /* enabled */);
- } else if (messageType == fbs::ChreMessage::LowPowerMicAccessRelease) {
- configureLpma(false /* enabled */);
- } else if (hostClientId == kHostClientIdDaemon) {
- handleDaemonMessage(messageBuffer);
- } else if (hostClientId == ::chre::kHostClientIdUnspecified) {
- mServer.sendToAllClients(messageBuffer, static_cast<size_t>(messageLen));
- } else {
- mServer.sendToClientById(messageBuffer, static_cast<size_t>(messageLen),
- hostClientId);
- }
-}
-
-bool ChreDaemonBase::readFileContents(const char *filename,
- std::vector<uint8_t> *buffer) {
- bool success = false;
- std::ifstream file(filename, std::ios::binary | std::ios::ate);
- if (!file) {
- LOGE("Couldn't open file '%s': %d (%s)", filename, errno, strerror(errno));
- } else {
- ssize_t size = file.tellg();
- file.seekg(0, std::ios::beg);
-
- buffer->resize(size);
- if (!file.read(reinterpret_cast<char *>(buffer->data()), size)) {
- LOGE("Couldn't read from file '%s': %d (%s)", filename, errno,
- strerror(errno));
- } else {
- success = true;
- }
- }
-
- return success;
-}
-
-void ChreDaemonBase::handleDaemonMessage(const uint8_t *message) {
- std::unique_ptr<fbs::MessageContainerT> container =
- fbs::UnPackMessageContainer(message);
- if (container->message.type != fbs::ChreMessage::LoadNanoappResponse) {
- LOGE("Invalid message from CHRE directed to daemon");
- } else {
- const auto *response = container->message.AsLoadNanoappResponse();
- if (mPreloadedNanoappPendingTransactionIds.empty()) {
- LOGE("Received nanoapp load response with no pending load");
- } else if (mPreloadedNanoappPendingTransactionIds.front() !=
- response->transaction_id) {
- LOGE("Received nanoapp load response with ID %" PRIu32
- " expected transaction id %" PRIu32,
- response->transaction_id,
- mPreloadedNanoappPendingTransactionIds.front());
- } else {
- if (!response->success) {
- LOGE("Received unsuccessful nanoapp load response with ID %" PRIu32,
- mPreloadedNanoappPendingTransactionIds.front());
- }
- mPreloadedNanoappPendingTransactionIds.pop();
- }
- }
-}
-
-} // namespace chre
-} // namespace android
diff --git a/host/common/fragmented_load_transaction.cc b/host/common/fragmented_load_transaction.cc
index c3c26d33..cf1f637f 100644
--- a/host/common/fragmented_load_transaction.cc
+++ b/host/common/fragmented_load_transaction.cc
@@ -48,8 +48,8 @@ inline std::vector<uint8_t> getSubVector(const std::vector<uint8_t> &source,
FragmentedLoadTransaction::FragmentedLoadTransaction(
uint32_t transactionId, uint64_t appId, uint32_t appVersion,
- uint32_t appFlags, uint32_t targetApiVersion,
- const std::vector<uint8_t> &appBinary, size_t fragmentSize) {
+ uint32_t targetApiVersion, const std::vector<uint8_t> &appBinary,
+ size_t fragmentSize) {
mTransactionId = transactionId;
// Start with fragmentId at 1 since 0 is used to indicate
@@ -59,9 +59,8 @@ FragmentedLoadTransaction::FragmentedLoadTransaction(
do {
if (fragmentId == 1) {
mFragmentRequests.emplace_back(
- fragmentId++, transactionId, appId, appVersion, appFlags,
- targetApiVersion, appBinary.size(),
- getSubVector(appBinary, byteIndex, fragmentSize));
+ fragmentId++, transactionId, appId, appVersion, targetApiVersion,
+ appBinary.size(), getSubVector(appBinary, byteIndex, fragmentSize));
} else {
mFragmentRequests.emplace_back(
fragmentId++, transactionId,
diff --git a/host/common/host_protocol_host.cc b/host/common/host_protocol_host.cc
index 9d61d473..21904f58 100644
--- a/host/common/host_protocol_host.cc
+++ b/host/common/host_protocol_host.cc
@@ -83,10 +83,6 @@ bool HostProtocolHost::decodeMessageFromChre(const void *message,
handlers.handleDebugDumpResponse(*msg.AsDebugDumpResponse());
break;
- case fbs::ChreMessage::SelfTestResponse:
- handlers.handleSelfTestResponse(*msg.AsSelfTestResponse());
- break;
-
default:
LOGW("Got invalid/unexpected message type %" PRIu8,
static_cast<uint8_t>(msg.type));
@@ -104,11 +100,11 @@ void HostProtocolHost::encodeHubInfoRequest(FlatBufferBuilder &builder) {
void HostProtocolHost::encodeFragmentedLoadNanoappRequest(
flatbuffers::FlatBufferBuilder &builder,
- const FragmentedLoadRequest &request, bool respondBeforeStart) {
+ const FragmentedLoadRequest &request) {
encodeLoadNanoappRequestForBinary(
builder, request.transactionId, request.appId, request.appVersion,
- request.appFlags, request.targetApiVersion, request.binary,
- request.fragmentId, request.appTotalSizeBytes, respondBeforeStart);
+ request.targetApiVersion, request.binary, request.fragmentId,
+ request.appTotalSizeBytes);
}
void HostProtocolHost::encodeNanoappListRequest(FlatBufferBuilder &builder) {
@@ -174,14 +170,13 @@ bool HostProtocolHost::mutateHostClientId(void *message, size_t messageLen,
void HostProtocolHost::encodeLoadNanoappRequestForBinary(
FlatBufferBuilder &builder, uint32_t transactionId, uint64_t appId,
- uint32_t appVersion, uint32_t appFlags, uint32_t targetApiVersion,
+ uint32_t appVersion, uint32_t targetApiVersion,
const std::vector<uint8_t> &nanoappBinary, uint32_t fragmentId,
- size_t appTotalSizeBytes, bool respondBeforeStart) {
+ size_t appTotalSizeBytes) {
auto appBinary = builder.CreateVector(nanoappBinary);
auto request = fbs::CreateLoadNanoappRequest(
builder, transactionId, appId, appVersion, targetApiVersion, appBinary,
- fragmentId, appTotalSizeBytes, 0 /* app_binary_file_name */, appFlags,
- respondBeforeStart);
+ fragmentId, appTotalSizeBytes);
finalize(builder, fbs::ChreMessage::LoadNanoappRequest, request.Union());
}
@@ -207,11 +202,5 @@ void HostProtocolHost::encodeSettingChangeNotification(
notification.Union());
}
-void HostProtocolHost::encodeSelfTestRequest(
- flatbuffers::FlatBufferBuilder &builder) {
- auto request = fbs::CreateSelfTestRequest(builder);
- finalize(builder, fbs::ChreMessage::SelfTestRequest, request.Union());
-}
-
} // namespace chre
} // namespace android
diff --git a/host/common/include/chre_host/daemon_base.h b/host/common/include/chre_host/daemon_base.h
deleted file mode 100644
index 7d29ca45..00000000
--- a/host/common/include/chre_host/daemon_base.h
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 CHRE_DAEMON_H_
-#define CHRE_DAEMON_H_
-
-#include <atomic>
-#include <cstdint>
-#include <map>
-#include <queue>
-#include <string>
-
-#include "chre_host/host_protocol_host.h"
-#include "chre_host/log_message_parser_base.h"
-#include "chre_host/socket_server.h"
-
-namespace android {
-namespace chre {
-
-class ChreDaemonBase {
- public:
- ChreDaemonBase() : mChreShutdownRequested(false) {}
- virtual ~ChreDaemonBase() {}
-
- /**
- * Initialize the CHRE daemon. We're expected to fail here and not start
- * the daemon if we don't get all the resources we're hoping to.
- * Any resources claimed by this function should be released in the
- * destructor
- *
- * @return true on successful initialization
- */
- virtual bool init() = 0;
-
- /**
- * Start the CHRE Daemon. This method must be called after @ref init() has
- * been called.
- */
- virtual void run() = 0;
-
- /**
- * Send a message to CHRE
- *
- * @param clientId The client ID that this message originates from.
- * @param data The data to pass down.
- * @param length The size of the data to send.
- * @return true if successful, false otherwise.
- */
- bool sendMessageToChre(uint16_t clientId, void *data, size_t dataLen);
-
- /**
- * Function to query if a graceful shutdown of CHRE was requested
- *
- * @return true if a graceful shutdown was requested
- */
- bool wasShutdownRequested() const {
- return mChreShutdownRequested;
- }
-
- /**
- * Loads the supplied file into the provided buffer.
- *
- * @param filename The name of the file to load.
- * @param buffer The buffer to load into.
- * @return true if successful, false otherwise.
- */
- static bool readFileContents(const char *filename,
- std::vector<uint8_t> *buffer);
-
- protected:
- //! The host ID to use when preloading nanoapps. This is used before the
- //! server is started and is sufficiently high enough so as to not collide
- //! with any clients after the server starts.
- static constexpr uint16_t kHostClientIdDaemon = UINT16_MAX;
-
- void setShutdownRequested(bool request) {
- mChreShutdownRequested = request;
- }
-
- /**
- * Attempts to load all preloaded nanoapps from a config file. The config file
- * is expected to be valid JSON with the following structure:
- *
- * { "nanoapps": [
- * "/path/to/nanoapp_1",
- * "/path/to/nanoapp_2"
- * ]}
- *
- * The napp_header and so files will both be loaded. All errors are logged.
- *
- * TODO: This is SLPI specific right now, and needs to be revisited to
- * implement platform specific loading.
- */
- void loadPreloadedNanoapps();
-
- /**
- * Loads a preloaded nanoapp given a filename to load from. Allows the
- * transaction to complete before the nanoapp starts so the server can start
- * serving requests as soon as possible.
- *
- * @param directory The directory to load the nanoapp from.
- * @param name The filename of the nanoapp to load.
- * @param transactionId The transaction ID to use when loading the app.
- */
- virtual void loadPreloadedNanoapp(const std::string &directory,
- const std::string &name,
- uint32_t transactionId);
-
- /**
- * Sends a preloaded nanoapp filename / metadata to CHRE.
- *
- * @param header The nanoapp header binary blob.
- * @param nanoappName The filename of the nanoapp to be loaded.
- * @param transactionId The transaction ID to use when loading the app.
- * @return true if successful, false otherwise.
- */
- bool loadNanoapp(const std::vector<uint8_t> &header,
- const std::string &nanoappName, uint32_t transactionId);
-
- /**
- * Loads a nanoapp by sending the nanoapp filename to the CHRE framework. This
- * method will return after sending the request so no guarantee is made that
- * the nanoapp is loaded until after the response is received.
- *
- * @param appId The ID of the nanoapp to load.
- * @param appVersion The version of the nanoapp to load.
- * @param appTargetApiVersion The version of the CHRE API that the app
- * targets.
- * @param appBinaryName The name of the binary as stored in the filesystem.
- * This will be used to load the nanoapp into CHRE.
- * @param transactionId The transaction ID to use when loading.
- * @return true if a request was successfully sent, false otherwise.
- */
- bool sendNanoappLoad(uint64_t appId, uint32_t appVersion,
- uint32_t appTargetApiVersion,
- const std::string &appBinaryName,
- uint32_t transactionId);
-
- /**
- * Send a time sync message to CHRE
- *
- * @param logOnError If true, logs an error message on failure.
- *
- * @return true if the time sync message was successfully sent to CHRE.
- */
- bool sendTimeSync(bool logOnError);
-
- /**
- * Sends a time sync message to CHRE, retrying a specified time until success.
- *
- * @param maxNumRetries The number of times to retry sending the message
- *
- * @return true if the time sync message was successfully sent to CHRE.
- */
- bool sendTimeSyncWithRetry(size_t numRetries, useconds_t retryDelayUs,
- bool logOnError);
-
- /**
- * Interface to a callback that is called when the Daemon receives a message.
- *
- * @param message A buffer containing the message
- * @param messageLen size of the message buffer in bytes
- */
- void onMessageReceived(const unsigned char *message, size_t messageLen);
-
- /**
- * Handles a message that is directed towards the daemon.
- *
- * @param message The message sent to the daemon.
- */
- virtual void handleDaemonMessage(const uint8_t *message);
-
- /**
- * Platform-specific method to actually do the message sending requested by
- * sendMessageToChre.
- */
- virtual bool doSendMessage(void *data, size_t dataLen) = 0;
-
- /**
- * Enables or disables LPMA (low power microphone access).
- */
- virtual void configureLpma(bool enabled) = 0;
-
- /**
- * @return logger used by the underlying platform.
- */
- virtual ChreLogMessageParserBase *getLogger() = 0;
-
- //! Server used to communicate with daemon clients
- SocketServer mServer;
-
- private:
- //! Set to true when we request a graceful shutdown of CHRE
- std::atomic<bool> mChreShutdownRequested;
-
- //! Contains a set of transaction IDs used to load the preloaded nanoapps.
- //! The IDs are stored in the order they are sent.
- std::queue<uint32_t> mPreloadedNanoappPendingTransactionIds;
-
- /**
- * Computes and returns the clock drift between the system clock
- * and the processor timer registers
- *
- * @return offset in nanoseconds
- */
- virtual int64_t getTimeOffset(bool *success) = 0;
-};
-
-} // namespace chre
-} // namespace android
-
-#endif // CHRE_DAEMON_H
diff --git a/host/common/include/chre_host/fragmented_load_transaction.h b/host/common/include/chre_host/fragmented_load_transaction.h
index 22f54879..98a4e562 100644
--- a/host/common/include/chre_host/fragmented_load_transaction.h
+++ b/host/common/include/chre_host/fragmented_load_transaction.h
@@ -20,12 +20,6 @@
#include <cinttypes>
#include <vector>
-#ifndef CHRE_HOST_DEFAULT_FRAGMENT_SIZE
-// Use 30KB fragment size to fit within 32KB memory fragments at the kernel
-// for most devices.
-#define CHRE_HOST_DEFAULT_FRAGMENT_SIZE (30 * 1024)
-#endif
-
namespace android {
namespace chre {
@@ -40,25 +34,22 @@ struct FragmentedLoadRequest {
uint32_t transactionId;
uint64_t appId;
uint32_t appVersion;
- uint32_t appFlags;
uint32_t targetApiVersion;
size_t appTotalSizeBytes;
std::vector<uint8_t> binary;
FragmentedLoadRequest(size_t fragmentId, uint32_t transactionId,
const std::vector<uint8_t> &binary)
- : FragmentedLoadRequest(fragmentId, transactionId, 0, 0, 0, 0, 0,
- binary) {}
+ : FragmentedLoadRequest(fragmentId, transactionId, 0, 0, 0, 0, binary) {}
FragmentedLoadRequest(size_t fragmentId, uint32_t transactionId,
- uint64_t appId, uint32_t appVersion, uint32_t appFlags,
+ uint64_t appId, uint32_t appVersion,
uint32_t targetApiVersion, size_t appTotalSizeBytes,
const std::vector<uint8_t> &binary)
: fragmentId(fragmentId),
transactionId(transactionId),
appId(appId),
appVersion(appVersion),
- appFlags(appFlags),
targetApiVersion(targetApiVersion),
appTotalSizeBytes(appTotalSizeBytes),
binary(binary) {}
@@ -78,14 +69,12 @@ class FragmentedLoadTransaction {
* @param transactionId the unique ID of the unfragmented load transaction
* @param appId the unique ID of the nanoapp
* @param appVersion the version of the nanoapp
- * @param appFlags the flags specified by the nanoapp to be loaded.
* @param targetApiVersion the API version this nanoapp is targeted for
* @param appBinary the nanoapp binary data
* @param fragmentSize the size of each fragment in bytes
*/
FragmentedLoadTransaction(uint32_t transactionId, uint64_t appId,
- uint32_t appVersion, uint32_t appFlags,
- uint32_t targetApiVersion,
+ uint32_t appVersion, uint32_t targetApiVersion,
const std::vector<uint8_t> &appBinary,
size_t fragmentSize = kDefaultFragmentSize);
@@ -116,8 +105,7 @@ class FragmentedLoadTransaction {
size_t mCurrentRequestIndex = 0;
uint32_t mTransactionId;
- static constexpr size_t kDefaultFragmentSize =
- CHRE_HOST_DEFAULT_FRAGMENT_SIZE;
+ static constexpr size_t kDefaultFragmentSize = 30 * 1024;
};
} // namespace chre
diff --git a/host/common/include/chre_host/generated/host_messages_generated.h b/host/common/include/chre_host/generated/host_messages_generated.h
index f68d8b9e..4e280b60 100644
--- a/host/common/include/chre_host/generated/host_messages_generated.h
+++ b/host/common/include/chre_host/generated/host_messages_generated.h
@@ -85,18 +85,6 @@ struct SettingChangeMessage;
struct SettingChangeMessageBuilder;
struct SettingChangeMessageT;
-struct LogMessageV2;
-struct LogMessageV2Builder;
-struct LogMessageV2T;
-
-struct SelfTestRequest;
-struct SelfTestRequestBuilder;
-struct SelfTestRequestT;
-
-struct SelfTestResponse;
-struct SelfTestResponseBuilder;
-struct SelfTestResponseT;
-
struct HostAddress;
struct MessageContainer;
@@ -106,36 +94,27 @@ struct MessageContainerT;
/// An enum describing the setting type.
enum class Setting : int8_t {
LOCATION = 0,
- WIFI_AVAILABLE = 1,
- AIRPLANE_MODE = 2,
- MICROPHONE = 3,
MIN = LOCATION,
- MAX = MICROPHONE
+ MAX = LOCATION
};
-inline const Setting (&EnumValuesSetting())[4] {
+inline const Setting (&EnumValuesSetting())[1] {
static const Setting values[] = {
- Setting::LOCATION,
- Setting::WIFI_AVAILABLE,
- Setting::AIRPLANE_MODE,
- Setting::MICROPHONE
+ Setting::LOCATION
};
return values;
}
inline const char * const *EnumNamesSetting() {
- static const char * const names[5] = {
+ static const char * const names[2] = {
"LOCATION",
- "WIFI_AVAILABLE",
- "AIRPLANE_MODE",
- "MICROPHONE",
nullptr
};
return names;
}
inline const char *EnumNameSetting(Setting e) {
- if (flatbuffers::IsOutRange(e, Setting::LOCATION, Setting::MICROPHONE)) return "";
+ if (flatbuffers::IsOutRange(e, Setting::LOCATION, Setting::LOCATION)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesSetting()[index];
}
@@ -193,14 +172,11 @@ enum class ChreMessage : uint8_t {
LowPowerMicAccessRequest = 16,
LowPowerMicAccessRelease = 17,
SettingChangeMessage = 18,
- LogMessageV2 = 19,
- SelfTestRequest = 20,
- SelfTestResponse = 21,
MIN = NONE,
- MAX = SelfTestResponse
+ MAX = SettingChangeMessage
};
-inline const ChreMessage (&EnumValuesChreMessage())[22] {
+inline const ChreMessage (&EnumValuesChreMessage())[19] {
static const ChreMessage values[] = {
ChreMessage::NONE,
ChreMessage::NanoappMessage,
@@ -220,16 +196,13 @@ inline const ChreMessage (&EnumValuesChreMessage())[22] {
ChreMessage::TimeSyncRequest,
ChreMessage::LowPowerMicAccessRequest,
ChreMessage::LowPowerMicAccessRelease,
- ChreMessage::SettingChangeMessage,
- ChreMessage::LogMessageV2,
- ChreMessage::SelfTestRequest,
- ChreMessage::SelfTestResponse
+ ChreMessage::SettingChangeMessage
};
return values;
}
inline const char * const *EnumNamesChreMessage() {
- static const char * const names[23] = {
+ static const char * const names[20] = {
"NONE",
"NanoappMessage",
"HubInfoRequest",
@@ -249,16 +222,13 @@ inline const char * const *EnumNamesChreMessage() {
"LowPowerMicAccessRequest",
"LowPowerMicAccessRelease",
"SettingChangeMessage",
- "LogMessageV2",
- "SelfTestRequest",
- "SelfTestResponse",
nullptr
};
return names;
}
inline const char *EnumNameChreMessage(ChreMessage e) {
- if (flatbuffers::IsOutRange(e, ChreMessage::NONE, ChreMessage::SelfTestResponse)) return "";
+ if (flatbuffers::IsOutRange(e, ChreMessage::NONE, ChreMessage::SettingChangeMessage)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesChreMessage()[index];
}
@@ -339,18 +309,6 @@ template<> struct ChreMessageTraits<chre::fbs::SettingChangeMessage> {
static const ChreMessage enum_value = ChreMessage::SettingChangeMessage;
};
-template<> struct ChreMessageTraits<chre::fbs::LogMessageV2> {
- static const ChreMessage enum_value = ChreMessage::LogMessageV2;
-};
-
-template<> struct ChreMessageTraits<chre::fbs::SelfTestRequest> {
- static const ChreMessage enum_value = ChreMessage::SelfTestRequest;
-};
-
-template<> struct ChreMessageTraits<chre::fbs::SelfTestResponse> {
- static const ChreMessage enum_value = ChreMessage::SelfTestResponse;
-};
-
struct ChreMessageUnion {
ChreMessage type;
void *value;
@@ -527,30 +485,6 @@ struct ChreMessageUnion {
return type == ChreMessage::SettingChangeMessage ?
reinterpret_cast<const chre::fbs::SettingChangeMessageT *>(value) : nullptr;
}
- chre::fbs::LogMessageV2T *AsLogMessageV2() {
- return type == ChreMessage::LogMessageV2 ?
- reinterpret_cast<chre::fbs::LogMessageV2T *>(value) : nullptr;
- }
- const chre::fbs::LogMessageV2T *AsLogMessageV2() const {
- return type == ChreMessage::LogMessageV2 ?
- reinterpret_cast<const chre::fbs::LogMessageV2T *>(value) : nullptr;
- }
- chre::fbs::SelfTestRequestT *AsSelfTestRequest() {
- return type == ChreMessage::SelfTestRequest ?
- reinterpret_cast<chre::fbs::SelfTestRequestT *>(value) : nullptr;
- }
- const chre::fbs::SelfTestRequestT *AsSelfTestRequest() const {
- return type == ChreMessage::SelfTestRequest ?
- reinterpret_cast<const chre::fbs::SelfTestRequestT *>(value) : nullptr;
- }
- chre::fbs::SelfTestResponseT *AsSelfTestResponse() {
- return type == ChreMessage::SelfTestResponse ?
- reinterpret_cast<chre::fbs::SelfTestResponseT *>(value) : nullptr;
- }
- const chre::fbs::SelfTestResponseT *AsSelfTestResponse() const {
- return type == ChreMessage::SelfTestResponse ?
- reinterpret_cast<const chre::fbs::SelfTestResponseT *>(value) : nullptr;
- }
};
bool VerifyChreMessage(flatbuffers::Verifier &verifier, const void *obj, ChreMessage type);
@@ -582,14 +516,10 @@ struct NanoappMessageT : public flatbuffers::NativeTable {
uint32_t message_type;
uint16_t host_endpoint;
std::vector<uint8_t> message;
- uint32_t message_permissions;
- uint32_t permissions;
NanoappMessageT()
: app_id(0),
message_type(0),
- host_endpoint(65534),
- message_permissions(0),
- permissions(0) {
+ host_endpoint(65534) {
}
};
@@ -601,9 +531,7 @@ struct NanoappMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_APP_ID = 4,
VT_MESSAGE_TYPE = 6,
VT_HOST_ENDPOINT = 8,
- VT_MESSAGE = 10,
- VT_MESSAGE_PERMISSIONS = 12,
- VT_PERMISSIONS = 14
+ VT_MESSAGE = 10
};
uint64_t app_id() const {
return GetField<uint64_t>(VT_APP_ID, 0);
@@ -633,25 +561,6 @@ struct NanoappMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
flatbuffers::Vector<uint8_t> *mutable_message() {
return GetPointer<flatbuffers::Vector<uint8_t> *>(VT_MESSAGE);
}
- /// List of Android permissions that cover the contents of a message from a
- /// nanoapp to the host.
- /// These permissions are used to record and attribute access to
- /// permissions-controlled resources.
- uint32_t message_permissions() const {
- return GetField<uint32_t>(VT_MESSAGE_PERMISSIONS, 0);
- }
- bool mutate_message_permissions(uint32_t _message_permissions) {
- return SetField<uint32_t>(VT_MESSAGE_PERMISSIONS, _message_permissions, 0);
- }
- /// List of Android permissions declared by the nanoapp / granted to the host.
- /// For messages from a nanoaapp to the host, this must be a superset of
- /// message_permissions.
- uint32_t permissions() const {
- return GetField<uint32_t>(VT_PERMISSIONS, 0);
- }
- bool mutate_permissions(uint32_t _permissions) {
- return SetField<uint32_t>(VT_PERMISSIONS, _permissions, 0);
- }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint64_t>(verifier, VT_APP_ID) &&
@@ -659,8 +568,6 @@ struct NanoappMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VerifyField<uint16_t>(verifier, VT_HOST_ENDPOINT) &&
VerifyOffsetRequired(verifier, VT_MESSAGE) &&
verifier.VerifyVector(message()) &&
- VerifyField<uint32_t>(verifier, VT_MESSAGE_PERMISSIONS) &&
- VerifyField<uint32_t>(verifier, VT_PERMISSIONS) &&
verifier.EndTable();
}
NanoappMessageT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -684,12 +591,6 @@ struct NanoappMessageBuilder {
void add_message(flatbuffers::Offset<flatbuffers::Vector<uint8_t>> message) {
fbb_.AddOffset(NanoappMessage::VT_MESSAGE, message);
}
- void add_message_permissions(uint32_t message_permissions) {
- fbb_.AddElement<uint32_t>(NanoappMessage::VT_MESSAGE_PERMISSIONS, message_permissions, 0);
- }
- void add_permissions(uint32_t permissions) {
- fbb_.AddElement<uint32_t>(NanoappMessage::VT_PERMISSIONS, permissions, 0);
- }
explicit NanoappMessageBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -708,13 +609,9 @@ inline flatbuffers::Offset<NanoappMessage> CreateNanoappMessage(
uint64_t app_id = 0,
uint32_t message_type = 0,
uint16_t host_endpoint = 65534,
- flatbuffers::Offset<flatbuffers::Vector<uint8_t>> message = 0,
- uint32_t message_permissions = 0,
- uint32_t permissions = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<uint8_t>> message = 0) {
NanoappMessageBuilder builder_(_fbb);
builder_.add_app_id(app_id);
- builder_.add_permissions(permissions);
- builder_.add_message_permissions(message_permissions);
builder_.add_message(message);
builder_.add_message_type(message_type);
builder_.add_host_endpoint(host_endpoint);
@@ -726,18 +623,14 @@ inline flatbuffers::Offset<NanoappMessage> CreateNanoappMessageDirect(
uint64_t app_id = 0,
uint32_t message_type = 0,
uint16_t host_endpoint = 65534,
- const std::vector<uint8_t> *message = nullptr,
- uint32_t message_permissions = 0,
- uint32_t permissions = 0) {
+ const std::vector<uint8_t> *message = nullptr) {
auto message__ = message ? _fbb.CreateVector<uint8_t>(*message) : 0;
return chre::fbs::CreateNanoappMessage(
_fbb,
app_id,
message_type,
host_endpoint,
- message__,
- message_permissions,
- permissions);
+ message__);
}
flatbuffers::Offset<NanoappMessage> CreateNanoappMessage(flatbuffers::FlatBufferBuilder &_fbb, const NanoappMessageT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
@@ -1099,13 +992,11 @@ struct NanoappListEntryT : public flatbuffers::NativeTable {
uint32_t version;
bool enabled;
bool is_system;
- uint32_t permissions;
NanoappListEntryT()
: app_id(0),
version(0),
enabled(true),
- is_system(false),
- permissions(0) {
+ is_system(false) {
}
};
@@ -1116,8 +1007,7 @@ struct NanoappListEntry FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_APP_ID = 4,
VT_VERSION = 6,
VT_ENABLED = 8,
- VT_IS_SYSTEM = 10,
- VT_PERMISSIONS = 12
+ VT_IS_SYSTEM = 10
};
uint64_t app_id() const {
return GetField<uint64_t>(VT_APP_ID, 0);
@@ -1147,21 +1037,12 @@ struct NanoappListEntry FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
bool mutate_is_system(bool _is_system) {
return SetField<uint8_t>(VT_IS_SYSTEM, static_cast<uint8_t>(_is_system), 0);
}
- /// Nanoapp permissions, if supported. Nanoapp permissions are required on
- /// CHRE API v1.5+, and are defined in chre/util/system/napp_permissions.h
- uint32_t permissions() const {
- return GetField<uint32_t>(VT_PERMISSIONS, 0);
- }
- bool mutate_permissions(uint32_t _permissions) {
- return SetField<uint32_t>(VT_PERMISSIONS, _permissions, 0);
- }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint64_t>(verifier, VT_APP_ID) &&
VerifyField<uint32_t>(verifier, VT_VERSION) &&
VerifyField<uint8_t>(verifier, VT_ENABLED) &&
VerifyField<uint8_t>(verifier, VT_IS_SYSTEM) &&
- VerifyField<uint32_t>(verifier, VT_PERMISSIONS) &&
verifier.EndTable();
}
NanoappListEntryT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -1185,9 +1066,6 @@ struct NanoappListEntryBuilder {
void add_is_system(bool is_system) {
fbb_.AddElement<uint8_t>(NanoappListEntry::VT_IS_SYSTEM, static_cast<uint8_t>(is_system), 0);
}
- void add_permissions(uint32_t permissions) {
- fbb_.AddElement<uint32_t>(NanoappListEntry::VT_PERMISSIONS, permissions, 0);
- }
explicit NanoappListEntryBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -1205,11 +1083,9 @@ inline flatbuffers::Offset<NanoappListEntry> CreateNanoappListEntry(
uint64_t app_id = 0,
uint32_t version = 0,
bool enabled = true,
- bool is_system = false,
- uint32_t permissions = 0) {
+ bool is_system = false) {
NanoappListEntryBuilder builder_(_fbb);
builder_.add_app_id(app_id);
- builder_.add_permissions(permissions);
builder_.add_version(version);
builder_.add_is_system(is_system);
builder_.add_enabled(enabled);
@@ -1298,17 +1174,13 @@ struct LoadNanoappRequestT : public flatbuffers::NativeTable {
uint32_t fragment_id;
uint32_t total_app_size;
std::vector<int8_t> app_binary_file_name;
- uint32_t app_flags;
- bool respond_before_start;
LoadNanoappRequestT()
: transaction_id(0),
app_id(0),
app_version(0),
target_api_version(0),
fragment_id(0),
- total_app_size(0),
- app_flags(0),
- respond_before_start(false) {
+ total_app_size(0) {
}
};
@@ -1361,9 +1233,7 @@ struct LoadNanoappRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_APP_BINARY = 12,
VT_FRAGMENT_ID = 14,
VT_TOTAL_APP_SIZE = 16,
- VT_APP_BINARY_FILE_NAME = 18,
- VT_APP_FLAGS = 20,
- VT_RESPOND_BEFORE_START = 22
+ VT_APP_BINARY_FILE_NAME = 18
};
uint32_t transaction_id() const {
return GetField<uint32_t>(VT_TRANSACTION_ID, 0);
@@ -1419,24 +1289,6 @@ struct LoadNanoappRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
flatbuffers::Vector<int8_t> *mutable_app_binary_file_name() {
return GetPointer<flatbuffers::Vector<int8_t> *>(VT_APP_BINARY_FILE_NAME);
}
- /// The nanoapp flag values from the nanoapp header defined in
- /// build/build_template.mk. Refer to that file for more details.
- uint32_t app_flags() const {
- return GetField<uint32_t>(VT_APP_FLAGS, 0);
- }
- bool mutate_app_flags(uint32_t _app_flags) {
- return SetField<uint32_t>(VT_APP_FLAGS, _app_flags, 0);
- }
- /// If true and fragmented loading is requested, the LoadNanoappResponse
- /// for the last fragment will be sent after the fragment was confirmed
- /// to be placed in memory and no additional response will be sent after
- /// the nanoapp is linked and started in the framework.
- bool respond_before_start() const {
- return GetField<uint8_t>(VT_RESPOND_BEFORE_START, 0) != 0;
- }
- bool mutate_respond_before_start(bool _respond_before_start) {
- return SetField<uint8_t>(VT_RESPOND_BEFORE_START, static_cast<uint8_t>(_respond_before_start), 0);
- }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint32_t>(verifier, VT_TRANSACTION_ID) &&
@@ -1449,8 +1301,6 @@ struct LoadNanoappRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VerifyField<uint32_t>(verifier, VT_TOTAL_APP_SIZE) &&
VerifyOffset(verifier, VT_APP_BINARY_FILE_NAME) &&
verifier.VerifyVector(app_binary_file_name()) &&
- VerifyField<uint32_t>(verifier, VT_APP_FLAGS) &&
- VerifyField<uint8_t>(verifier, VT_RESPOND_BEFORE_START) &&
verifier.EndTable();
}
LoadNanoappRequestT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -1486,12 +1336,6 @@ struct LoadNanoappRequestBuilder {
void add_app_binary_file_name(flatbuffers::Offset<flatbuffers::Vector<int8_t>> app_binary_file_name) {
fbb_.AddOffset(LoadNanoappRequest::VT_APP_BINARY_FILE_NAME, app_binary_file_name);
}
- void add_app_flags(uint32_t app_flags) {
- fbb_.AddElement<uint32_t>(LoadNanoappRequest::VT_APP_FLAGS, app_flags, 0);
- }
- void add_respond_before_start(bool respond_before_start) {
- fbb_.AddElement<uint8_t>(LoadNanoappRequest::VT_RESPOND_BEFORE_START, static_cast<uint8_t>(respond_before_start), 0);
- }
explicit LoadNanoappRequestBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -1514,12 +1358,9 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequest(
flatbuffers::Offset<flatbuffers::Vector<uint8_t>> app_binary = 0,
uint32_t fragment_id = 0,
uint32_t total_app_size = 0,
- flatbuffers::Offset<flatbuffers::Vector<int8_t>> app_binary_file_name = 0,
- uint32_t app_flags = 0,
- bool respond_before_start = false) {
+ flatbuffers::Offset<flatbuffers::Vector<int8_t>> app_binary_file_name = 0) {
LoadNanoappRequestBuilder builder_(_fbb);
builder_.add_app_id(app_id);
- builder_.add_app_flags(app_flags);
builder_.add_app_binary_file_name(app_binary_file_name);
builder_.add_total_app_size(total_app_size);
builder_.add_fragment_id(fragment_id);
@@ -1527,7 +1368,6 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequest(
builder_.add_target_api_version(target_api_version);
builder_.add_app_version(app_version);
builder_.add_transaction_id(transaction_id);
- builder_.add_respond_before_start(respond_before_start);
return builder_.Finish();
}
@@ -1540,9 +1380,7 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequestDirect(
const std::vector<uint8_t> *app_binary = nullptr,
uint32_t fragment_id = 0,
uint32_t total_app_size = 0,
- const std::vector<int8_t> *app_binary_file_name = nullptr,
- uint32_t app_flags = 0,
- bool respond_before_start = false) {
+ const std::vector<int8_t> *app_binary_file_name = nullptr) {
auto app_binary__ = app_binary ? _fbb.CreateVector<uint8_t>(*app_binary) : 0;
auto app_binary_file_name__ = app_binary_file_name ? _fbb.CreateVector<int8_t>(*app_binary_file_name) : 0;
return chre::fbs::CreateLoadNanoappRequest(
@@ -1554,9 +1392,7 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequestDirect(
app_binary__,
fragment_id,
total_app_size,
- app_binary_file_name__,
- app_flags,
- respond_before_start);
+ app_binary_file_name__);
}
flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequest(flatbuffers::FlatBufferBuilder &_fbb, const LoadNanoappRequestT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
@@ -2365,208 +2201,6 @@ inline flatbuffers::Offset<SettingChangeMessage> CreateSettingChangeMessage(
flatbuffers::Offset<SettingChangeMessage> CreateSettingChangeMessage(flatbuffers::FlatBufferBuilder &_fbb, const SettingChangeMessageT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-struct LogMessageV2T : public flatbuffers::NativeTable {
- typedef LogMessageV2 TableType;
- std::vector<int8_t> buffer;
- uint32_t num_logs_dropped;
- LogMessageV2T()
- : num_logs_dropped(0) {
- }
-};
-
-/// Represents V2 log messages from CHRE.
-struct LogMessageV2 FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
- typedef LogMessageV2T NativeTableType;
- typedef LogMessageV2Builder Builder;
- enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
- VT_BUFFER = 4,
- VT_NUM_LOGS_DROPPED = 6
- };
- /// A buffer containing formatted log data. A flat array is used here to avoid
- /// overhead in serializing and deserializing. The format is as follows:
- ///
- /// uint8_t - LogBuffer log level (1 = error, 2 = warn,
- /// 3 = info, 4 = debug,
- /// 5 = verbose)
- /// uint32_t, little-endian - timestamp in milliseconds
- /// char[] - message to log
- /// char, \0 - null-terminator
- ///
- /// This pattern repeats until the end of the buffer for multiple log
- /// messages. The last byte will always be a null-terminator. There are no
- /// padding bytes between these fields. Treat this like a packed struct and be
- /// cautious with unaligned access when reading/writing this buffer.
- const flatbuffers::Vector<int8_t> *buffer() const {
- return GetPointer<const flatbuffers::Vector<int8_t> *>(VT_BUFFER);
- }
- flatbuffers::Vector<int8_t> *mutable_buffer() {
- return GetPointer<flatbuffers::Vector<int8_t> *>(VT_BUFFER);
- }
- /// The number of logs dropped since CHRE started
- uint32_t num_logs_dropped() const {
- return GetField<uint32_t>(VT_NUM_LOGS_DROPPED, 0);
- }
- bool mutate_num_logs_dropped(uint32_t _num_logs_dropped) {
- return SetField<uint32_t>(VT_NUM_LOGS_DROPPED, _num_logs_dropped, 0);
- }
- bool Verify(flatbuffers::Verifier &verifier) const {
- return VerifyTableStart(verifier) &&
- VerifyOffset(verifier, VT_BUFFER) &&
- verifier.VerifyVector(buffer()) &&
- VerifyField<uint32_t>(verifier, VT_NUM_LOGS_DROPPED) &&
- verifier.EndTable();
- }
- LogMessageV2T *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
- void UnPackTo(LogMessageV2T *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
- static flatbuffers::Offset<LogMessageV2> Pack(flatbuffers::FlatBufferBuilder &_fbb, const LogMessageV2T* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-};
-
-struct LogMessageV2Builder {
- typedef LogMessageV2 Table;
- flatbuffers::FlatBufferBuilder &fbb_;
- flatbuffers::uoffset_t start_;
- void add_buffer(flatbuffers::Offset<flatbuffers::Vector<int8_t>> buffer) {
- fbb_.AddOffset(LogMessageV2::VT_BUFFER, buffer);
- }
- void add_num_logs_dropped(uint32_t num_logs_dropped) {
- fbb_.AddElement<uint32_t>(LogMessageV2::VT_NUM_LOGS_DROPPED, num_logs_dropped, 0);
- }
- explicit LogMessageV2Builder(flatbuffers::FlatBufferBuilder &_fbb)
- : fbb_(_fbb) {
- start_ = fbb_.StartTable();
- }
- LogMessageV2Builder &operator=(const LogMessageV2Builder &);
- flatbuffers::Offset<LogMessageV2> Finish() {
- const auto end = fbb_.EndTable(start_);
- auto o = flatbuffers::Offset<LogMessageV2>(end);
- return o;
- }
-};
-
-inline flatbuffers::Offset<LogMessageV2> CreateLogMessageV2(
- flatbuffers::FlatBufferBuilder &_fbb,
- flatbuffers::Offset<flatbuffers::Vector<int8_t>> buffer = 0,
- uint32_t num_logs_dropped = 0) {
- LogMessageV2Builder builder_(_fbb);
- builder_.add_num_logs_dropped(num_logs_dropped);
- builder_.add_buffer(buffer);
- return builder_.Finish();
-}
-
-inline flatbuffers::Offset<LogMessageV2> CreateLogMessageV2Direct(
- flatbuffers::FlatBufferBuilder &_fbb,
- const std::vector<int8_t> *buffer = nullptr,
- uint32_t num_logs_dropped = 0) {
- auto buffer__ = buffer ? _fbb.CreateVector<int8_t>(*buffer) : 0;
- return chre::fbs::CreateLogMessageV2(
- _fbb,
- buffer__,
- num_logs_dropped);
-}
-
-flatbuffers::Offset<LogMessageV2> CreateLogMessageV2(flatbuffers::FlatBufferBuilder &_fbb, const LogMessageV2T *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-
-struct SelfTestRequestT : public flatbuffers::NativeTable {
- typedef SelfTestRequest TableType;
- SelfTestRequestT() {
- }
-};
-
-struct SelfTestRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
- typedef SelfTestRequestT NativeTableType;
- typedef SelfTestRequestBuilder Builder;
- bool Verify(flatbuffers::Verifier &verifier) const {
- return VerifyTableStart(verifier) &&
- verifier.EndTable();
- }
- SelfTestRequestT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
- void UnPackTo(SelfTestRequestT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
- static flatbuffers::Offset<SelfTestRequest> Pack(flatbuffers::FlatBufferBuilder &_fbb, const SelfTestRequestT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-};
-
-struct SelfTestRequestBuilder {
- typedef SelfTestRequest Table;
- flatbuffers::FlatBufferBuilder &fbb_;
- flatbuffers::uoffset_t start_;
- explicit SelfTestRequestBuilder(flatbuffers::FlatBufferBuilder &_fbb)
- : fbb_(_fbb) {
- start_ = fbb_.StartTable();
- }
- SelfTestRequestBuilder &operator=(const SelfTestRequestBuilder &);
- flatbuffers::Offset<SelfTestRequest> Finish() {
- const auto end = fbb_.EndTable(start_);
- auto o = flatbuffers::Offset<SelfTestRequest>(end);
- return o;
- }
-};
-
-inline flatbuffers::Offset<SelfTestRequest> CreateSelfTestRequest(
- flatbuffers::FlatBufferBuilder &_fbb) {
- SelfTestRequestBuilder builder_(_fbb);
- return builder_.Finish();
-}
-
-flatbuffers::Offset<SelfTestRequest> CreateSelfTestRequest(flatbuffers::FlatBufferBuilder &_fbb, const SelfTestRequestT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-
-struct SelfTestResponseT : public flatbuffers::NativeTable {
- typedef SelfTestResponse TableType;
- bool success;
- SelfTestResponseT()
- : success(false) {
- }
-};
-
-struct SelfTestResponse FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
- typedef SelfTestResponseT NativeTableType;
- typedef SelfTestResponseBuilder Builder;
- enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
- VT_SUCCESS = 4
- };
- bool success() const {
- return GetField<uint8_t>(VT_SUCCESS, 0) != 0;
- }
- bool mutate_success(bool _success) {
- return SetField<uint8_t>(VT_SUCCESS, static_cast<uint8_t>(_success), 0);
- }
- bool Verify(flatbuffers::Verifier &verifier) const {
- return VerifyTableStart(verifier) &&
- VerifyField<uint8_t>(verifier, VT_SUCCESS) &&
- verifier.EndTable();
- }
- SelfTestResponseT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
- void UnPackTo(SelfTestResponseT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
- static flatbuffers::Offset<SelfTestResponse> Pack(flatbuffers::FlatBufferBuilder &_fbb, const SelfTestResponseT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-};
-
-struct SelfTestResponseBuilder {
- typedef SelfTestResponse Table;
- flatbuffers::FlatBufferBuilder &fbb_;
- flatbuffers::uoffset_t start_;
- void add_success(bool success) {
- fbb_.AddElement<uint8_t>(SelfTestResponse::VT_SUCCESS, static_cast<uint8_t>(success), 0);
- }
- explicit SelfTestResponseBuilder(flatbuffers::FlatBufferBuilder &_fbb)
- : fbb_(_fbb) {
- start_ = fbb_.StartTable();
- }
- SelfTestResponseBuilder &operator=(const SelfTestResponseBuilder &);
- flatbuffers::Offset<SelfTestResponse> Finish() {
- const auto end = fbb_.EndTable(start_);
- auto o = flatbuffers::Offset<SelfTestResponse>(end);
- return o;
- }
-};
-
-inline flatbuffers::Offset<SelfTestResponse> CreateSelfTestResponse(
- flatbuffers::FlatBufferBuilder &_fbb,
- bool success = false) {
- SelfTestResponseBuilder builder_(_fbb);
- builder_.add_success(success);
- return builder_.Finish();
-}
-
-flatbuffers::Offset<SelfTestResponse> CreateSelfTestResponse(flatbuffers::FlatBufferBuilder &_fbb, const SelfTestResponseT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-
struct MessageContainerT : public flatbuffers::NativeTable {
typedef MessageContainer TableType;
chre::fbs::ChreMessageUnion message;
@@ -2647,15 +2281,6 @@ struct MessageContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const chre::fbs::SettingChangeMessage *message_as_SettingChangeMessage() const {
return message_type() == chre::fbs::ChreMessage::SettingChangeMessage ? static_cast<const chre::fbs::SettingChangeMessage *>(message()) : nullptr;
}
- const chre::fbs::LogMessageV2 *message_as_LogMessageV2() const {
- return message_type() == chre::fbs::ChreMessage::LogMessageV2 ? static_cast<const chre::fbs::LogMessageV2 *>(message()) : nullptr;
- }
- const chre::fbs::SelfTestRequest *message_as_SelfTestRequest() const {
- return message_type() == chre::fbs::ChreMessage::SelfTestRequest ? static_cast<const chre::fbs::SelfTestRequest *>(message()) : nullptr;
- }
- const chre::fbs::SelfTestResponse *message_as_SelfTestResponse() const {
- return message_type() == chre::fbs::ChreMessage::SelfTestResponse ? static_cast<const chre::fbs::SelfTestResponse *>(message()) : nullptr;
- }
void *mutable_message() {
return GetPointer<void *>(VT_MESSAGE);
}
@@ -2756,18 +2381,6 @@ template<> inline const chre::fbs::SettingChangeMessage *MessageContainer::messa
return message_as_SettingChangeMessage();
}
-template<> inline const chre::fbs::LogMessageV2 *MessageContainer::message_as<chre::fbs::LogMessageV2>() const {
- return message_as_LogMessageV2();
-}
-
-template<> inline const chre::fbs::SelfTestRequest *MessageContainer::message_as<chre::fbs::SelfTestRequest>() const {
- return message_as_SelfTestRequest();
-}
-
-template<> inline const chre::fbs::SelfTestResponse *MessageContainer::message_as<chre::fbs::SelfTestResponse>() const {
- return message_as_SelfTestResponse();
-}
-
struct MessageContainerBuilder {
typedef MessageContainer Table;
flatbuffers::FlatBufferBuilder &fbb_;
@@ -2822,8 +2435,6 @@ inline void NanoappMessage::UnPackTo(NanoappMessageT *_o, const flatbuffers::res
{ auto _e = message_type(); _o->message_type = _e; }
{ auto _e = host_endpoint(); _o->host_endpoint = _e; }
{ auto _e = message(); if (_e) { _o->message.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->message[_i] = _e->Get(_i); } } }
- { auto _e = message_permissions(); _o->message_permissions = _e; }
- { auto _e = permissions(); _o->permissions = _e; }
}
inline flatbuffers::Offset<NanoappMessage> NanoappMessage::Pack(flatbuffers::FlatBufferBuilder &_fbb, const NanoappMessageT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -2838,16 +2449,12 @@ inline flatbuffers::Offset<NanoappMessage> CreateNanoappMessage(flatbuffers::Fla
auto _message_type = _o->message_type;
auto _host_endpoint = _o->host_endpoint;
auto _message = _fbb.CreateVector(_o->message);
- auto _message_permissions = _o->message_permissions;
- auto _permissions = _o->permissions;
return chre::fbs::CreateNanoappMessage(
_fbb,
_app_id,
_message_type,
_host_endpoint,
- _message,
- _message_permissions,
- _permissions);
+ _message);
}
inline HubInfoRequestT *HubInfoRequest::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
@@ -2968,7 +2575,6 @@ inline void NanoappListEntry::UnPackTo(NanoappListEntryT *_o, const flatbuffers:
{ auto _e = version(); _o->version = _e; }
{ auto _e = enabled(); _o->enabled = _e; }
{ auto _e = is_system(); _o->is_system = _e; }
- { auto _e = permissions(); _o->permissions = _e; }
}
inline flatbuffers::Offset<NanoappListEntry> NanoappListEntry::Pack(flatbuffers::FlatBufferBuilder &_fbb, const NanoappListEntryT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -2983,14 +2589,12 @@ inline flatbuffers::Offset<NanoappListEntry> CreateNanoappListEntry(flatbuffers:
auto _version = _o->version;
auto _enabled = _o->enabled;
auto _is_system = _o->is_system;
- auto _permissions = _o->permissions;
return chre::fbs::CreateNanoappListEntry(
_fbb,
_app_id,
_version,
_enabled,
- _is_system,
- _permissions);
+ _is_system);
}
inline NanoappListResponseT *NanoappListResponse::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
@@ -3036,8 +2640,6 @@ inline void LoadNanoappRequest::UnPackTo(LoadNanoappRequestT *_o, const flatbuff
{ auto _e = fragment_id(); _o->fragment_id = _e; }
{ auto _e = total_app_size(); _o->total_app_size = _e; }
{ auto _e = app_binary_file_name(); if (_e) { _o->app_binary_file_name.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->app_binary_file_name[_i] = _e->Get(_i); } } }
- { auto _e = app_flags(); _o->app_flags = _e; }
- { auto _e = respond_before_start(); _o->respond_before_start = _e; }
}
inline flatbuffers::Offset<LoadNanoappRequest> LoadNanoappRequest::Pack(flatbuffers::FlatBufferBuilder &_fbb, const LoadNanoappRequestT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -3056,8 +2658,6 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequest(flatbuff
auto _fragment_id = _o->fragment_id;
auto _total_app_size = _o->total_app_size;
auto _app_binary_file_name = _o->app_binary_file_name.size() ? _fbb.CreateVector(_o->app_binary_file_name) : 0;
- auto _app_flags = _o->app_flags;
- auto _respond_before_start = _o->respond_before_start;
return chre::fbs::CreateLoadNanoappRequest(
_fbb,
_transaction_id,
@@ -3067,9 +2667,7 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequest(flatbuff
_app_binary,
_fragment_id,
_total_app_size,
- _app_binary_file_name,
- _app_flags,
- _respond_before_start);
+ _app_binary_file_name);
}
inline LoadNanoappResponseT *LoadNanoappResponse::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
@@ -3393,84 +2991,6 @@ inline flatbuffers::Offset<SettingChangeMessage> CreateSettingChangeMessage(flat
_state);
}
-inline LogMessageV2T *LogMessageV2::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- std::unique_ptr<chre::fbs::LogMessageV2T> _o = std::unique_ptr<chre::fbs::LogMessageV2T>(new LogMessageV2T());
- UnPackTo(_o.get(), _resolver);
- return _o.release();
-}
-
-inline void LogMessageV2::UnPackTo(LogMessageV2T *_o, const flatbuffers::resolver_function_t *_resolver) const {
- (void)_o;
- (void)_resolver;
- { auto _e = buffer(); if (_e) { _o->buffer.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->buffer[_i] = _e->Get(_i); } } }
- { auto _e = num_logs_dropped(); _o->num_logs_dropped = _e; }
-}
-
-inline flatbuffers::Offset<LogMessageV2> LogMessageV2::Pack(flatbuffers::FlatBufferBuilder &_fbb, const LogMessageV2T* _o, const flatbuffers::rehasher_function_t *_rehasher) {
- return CreateLogMessageV2(_fbb, _o, _rehasher);
-}
-
-inline flatbuffers::Offset<LogMessageV2> CreateLogMessageV2(flatbuffers::FlatBufferBuilder &_fbb, const LogMessageV2T *_o, const flatbuffers::rehasher_function_t *_rehasher) {
- (void)_rehasher;
- (void)_o;
- struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const LogMessageV2T* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
- auto _buffer = _o->buffer.size() ? _fbb.CreateVector(_o->buffer) : 0;
- auto _num_logs_dropped = _o->num_logs_dropped;
- return chre::fbs::CreateLogMessageV2(
- _fbb,
- _buffer,
- _num_logs_dropped);
-}
-
-inline SelfTestRequestT *SelfTestRequest::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- std::unique_ptr<chre::fbs::SelfTestRequestT> _o = std::unique_ptr<chre::fbs::SelfTestRequestT>(new SelfTestRequestT());
- UnPackTo(_o.get(), _resolver);
- return _o.release();
-}
-
-inline void SelfTestRequest::UnPackTo(SelfTestRequestT *_o, const flatbuffers::resolver_function_t *_resolver) const {
- (void)_o;
- (void)_resolver;
-}
-
-inline flatbuffers::Offset<SelfTestRequest> SelfTestRequest::Pack(flatbuffers::FlatBufferBuilder &_fbb, const SelfTestRequestT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
- return CreateSelfTestRequest(_fbb, _o, _rehasher);
-}
-
-inline flatbuffers::Offset<SelfTestRequest> CreateSelfTestRequest(flatbuffers::FlatBufferBuilder &_fbb, const SelfTestRequestT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
- (void)_rehasher;
- (void)_o;
- struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const SelfTestRequestT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
- return chre::fbs::CreateSelfTestRequest(
- _fbb);
-}
-
-inline SelfTestResponseT *SelfTestResponse::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- std::unique_ptr<chre::fbs::SelfTestResponseT> _o = std::unique_ptr<chre::fbs::SelfTestResponseT>(new SelfTestResponseT());
- UnPackTo(_o.get(), _resolver);
- return _o.release();
-}
-
-inline void SelfTestResponse::UnPackTo(SelfTestResponseT *_o, const flatbuffers::resolver_function_t *_resolver) const {
- (void)_o;
- (void)_resolver;
- { auto _e = success(); _o->success = _e; }
-}
-
-inline flatbuffers::Offset<SelfTestResponse> SelfTestResponse::Pack(flatbuffers::FlatBufferBuilder &_fbb, const SelfTestResponseT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
- return CreateSelfTestResponse(_fbb, _o, _rehasher);
-}
-
-inline flatbuffers::Offset<SelfTestResponse> CreateSelfTestResponse(flatbuffers::FlatBufferBuilder &_fbb, const SelfTestResponseT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
- (void)_rehasher;
- (void)_o;
- struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const SelfTestResponseT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
- auto _success = _o->success;
- return chre::fbs::CreateSelfTestResponse(
- _fbb,
- _success);
-}
-
inline MessageContainerT *MessageContainer::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
std::unique_ptr<chre::fbs::MessageContainerT> _o = std::unique_ptr<chre::fbs::MessageContainerT>(new MessageContainerT());
UnPackTo(_o.get(), _resolver);
@@ -3580,18 +3100,6 @@ inline bool VerifyChreMessage(flatbuffers::Verifier &verifier, const void *obj,
auto ptr = reinterpret_cast<const chre::fbs::SettingChangeMessage *>(obj);
return verifier.VerifyTable(ptr);
}
- case ChreMessage::LogMessageV2: {
- auto ptr = reinterpret_cast<const chre::fbs::LogMessageV2 *>(obj);
- return verifier.VerifyTable(ptr);
- }
- case ChreMessage::SelfTestRequest: {
- auto ptr = reinterpret_cast<const chre::fbs::SelfTestRequest *>(obj);
- return verifier.VerifyTable(ptr);
- }
- case ChreMessage::SelfTestResponse: {
- auto ptr = reinterpret_cast<const chre::fbs::SelfTestResponse *>(obj);
- return verifier.VerifyTable(ptr);
- }
default: return true;
}
}
@@ -3682,18 +3190,6 @@ inline void *ChreMessageUnion::UnPack(const void *obj, ChreMessage type, const f
auto ptr = reinterpret_cast<const chre::fbs::SettingChangeMessage *>(obj);
return ptr->UnPack(resolver);
}
- case ChreMessage::LogMessageV2: {
- auto ptr = reinterpret_cast<const chre::fbs::LogMessageV2 *>(obj);
- return ptr->UnPack(resolver);
- }
- case ChreMessage::SelfTestRequest: {
- auto ptr = reinterpret_cast<const chre::fbs::SelfTestRequest *>(obj);
- return ptr->UnPack(resolver);
- }
- case ChreMessage::SelfTestResponse: {
- auto ptr = reinterpret_cast<const chre::fbs::SelfTestResponse *>(obj);
- return ptr->UnPack(resolver);
- }
default: return nullptr;
}
}
@@ -3772,18 +3268,6 @@ inline flatbuffers::Offset<void> ChreMessageUnion::Pack(flatbuffers::FlatBufferB
auto ptr = reinterpret_cast<const chre::fbs::SettingChangeMessageT *>(value);
return CreateSettingChangeMessage(_fbb, ptr, _rehasher).Union();
}
- case ChreMessage::LogMessageV2: {
- auto ptr = reinterpret_cast<const chre::fbs::LogMessageV2T *>(value);
- return CreateLogMessageV2(_fbb, ptr, _rehasher).Union();
- }
- case ChreMessage::SelfTestRequest: {
- auto ptr = reinterpret_cast<const chre::fbs::SelfTestRequestT *>(value);
- return CreateSelfTestRequest(_fbb, ptr, _rehasher).Union();
- }
- case ChreMessage::SelfTestResponse: {
- auto ptr = reinterpret_cast<const chre::fbs::SelfTestResponseT *>(value);
- return CreateSelfTestResponse(_fbb, ptr, _rehasher).Union();
- }
default: return 0;
}
}
@@ -3862,18 +3346,6 @@ inline ChreMessageUnion::ChreMessageUnion(const ChreMessageUnion &u) : type(u.ty
value = new chre::fbs::SettingChangeMessageT(*reinterpret_cast<chre::fbs::SettingChangeMessageT *>(u.value));
break;
}
- case ChreMessage::LogMessageV2: {
- value = new chre::fbs::LogMessageV2T(*reinterpret_cast<chre::fbs::LogMessageV2T *>(u.value));
- break;
- }
- case ChreMessage::SelfTestRequest: {
- value = new chre::fbs::SelfTestRequestT(*reinterpret_cast<chre::fbs::SelfTestRequestT *>(u.value));
- break;
- }
- case ChreMessage::SelfTestResponse: {
- value = new chre::fbs::SelfTestResponseT(*reinterpret_cast<chre::fbs::SelfTestResponseT *>(u.value));
- break;
- }
default:
break;
}
@@ -3971,21 +3443,6 @@ inline void ChreMessageUnion::Reset() {
delete ptr;
break;
}
- case ChreMessage::LogMessageV2: {
- auto ptr = reinterpret_cast<chre::fbs::LogMessageV2T *>(value);
- delete ptr;
- break;
- }
- case ChreMessage::SelfTestRequest: {
- auto ptr = reinterpret_cast<chre::fbs::SelfTestRequestT *>(value);
- delete ptr;
- break;
- }
- case ChreMessage::SelfTestResponse: {
- auto ptr = reinterpret_cast<chre::fbs::SelfTestResponseT *>(value);
- delete ptr;
- break;
- }
default: break;
}
value = nullptr;
diff --git a/host/common/include/chre_host/host_protocol_host.h b/host/common/include/chre_host/host_protocol_host.h
index 16ef2359..ba04c14d 100644
--- a/host/common/include/chre_host/host_protocol_host.h
+++ b/host/common/include/chre_host/host_protocol_host.h
@@ -71,9 +71,6 @@ class IChreMessageHandlers {
virtual void handleDebugDumpResponse(
const ::chre::fbs::DebugDumpResponseT & /*response*/){};
-
- virtual void handleSelfTestResponse(
- const ::chre::fbs::SelfTestResponseT & /*response*/){};
};
/**
@@ -114,12 +111,10 @@ class HostProtocolHost : public ::chre::HostProtocolCommon {
* construct the message
* @param request The FragmentedLoadRequest object with the binary and the
* metadata
- * @param respondBeforeStart See LoadNanoappRequest.respond_before_start in
- * flatbuffers message.
*/
static void encodeFragmentedLoadNanoappRequest(
flatbuffers::FlatBufferBuilder &builder,
- const FragmentedLoadRequest &request, bool respondBeforeStart = false);
+ const FragmentedLoadRequest &request);
/**
* Encodes a message requesting the list of loaded nanoapps from CHRE
@@ -201,9 +196,9 @@ class HostProtocolHost : public ::chre::HostProtocolCommon {
*/
static void encodeLoadNanoappRequestForBinary(
flatbuffers::FlatBufferBuilder &builder, uint32_t transactionId,
- uint64_t appId, uint32_t appVersion, uint32_t appFlags,
- uint32_t targetApiVersion, const std::vector<uint8_t> &nanoappBinary,
- uint32_t fragmentId, size_t appTotalSizeBytes, bool respondBeforeStart);
+ uint64_t appId, uint32_t appVersion, uint32_t targetApiVersion,
+ const std::vector<uint8_t> &nanoappBinary, uint32_t fragmentId,
+ size_t appTotalSizeBytes);
/**
* Encodes a message requesting to load a nanoapp specified by the included
@@ -228,11 +223,6 @@ class HostProtocolHost : public ::chre::HostProtocolCommon {
static void encodeSettingChangeNotification(
flatbuffers::FlatBufferBuilder &builder, ::chre::fbs::Setting setting,
::chre::fbs::SettingState newState);
-
- /**
- * Encodes a message to request CHRE to perform a self test.
- */
- static void encodeSelfTestRequest(flatbuffers::FlatBufferBuilder &builder);
};
} // namespace chre
diff --git a/host/common/include/chre_host/log_message_parser_base.h b/host/common/include/chre_host/log_message_parser_base.h
deleted file mode 100644
index f2a9ffe3..00000000
--- a/host/common/include/chre_host/log_message_parser_base.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_LOG_MESSAGE_PARSER_BASE_H_
-#define CHRE_LOG_MESSAGE_PARSER_BASE_H_
-
-#include <cinttypes>
-#include <cstdint>
-
-#include "chre_host/log.h"
-
-#include <android-base/logging.h>
-
-namespace android {
-namespace chre {
-
-// TODO: Since nanoapp logging won't use tokenized logging, refactor this
-// to have the base class handle normal log messages, and a subclass
-// that could extend to handle log messages of other types (eg: tokenized
-// logging), and can then invoke the parent class methods if they receive
-// a log of the 'normal' type.
-class ChreLogMessageParserBase {
- public:
- ChreLogMessageParserBase();
-
- virtual ~ChreLogMessageParserBase() {}
-
- virtual bool init() {
- return true;
- };
-
- virtual bool deinit() {
- return true;
- };
-
- //! Logs from a log buffer containing one or more log messages (version 1)
- virtual void log(const uint8_t *logBuffer, size_t logBufferSize);
-
- //! Logs from a log buffer containing one or more log messages (version 2)
- virtual void logV2(const uint8_t *logBuffer, size_t logBufferSize,
- uint32_t numLogsDropped);
-
- /**
- * With verbose logging enabled (via enableVerbose()), dump a
- * binary log buffer to a human-readable string
- *
- * @param logBuffer buffer to be output as a string
- * @param logBufferSize size of the buffer being output
- */
- virtual void dump(const uint8_t *logBuffer, size_t logBufferSize);
-
- void enableVerbose(bool enable) {
- mVerboseLoggingEnabled = enable;
- }
-
- protected:
- static constexpr char kHubLogFormatStr[] = "@ %3" PRIu32 ".%03" PRIu32 ": %s";
-
- bool mVerboseLoggingEnabled;
-
- static android_LogPriority chreLogLevelToAndroidLogPriority(uint8_t level);
-
- void emitLogMessage(uint8_t level, uint32_t timestampMillis,
- const char *logMessage);
-
- private:
- enum LogLevel : uint8_t {
- ERROR = 1,
- WARNING = 2,
- INFO = 3,
- DEBUG = 4,
- VERBOSE = 5,
- };
-
- //! See host_messages.fbs for the definition of this struct.
- struct LogMessage {
- enum LogLevel logLevel;
- uint64_t timestampNanos;
- char logMessage[];
- } __attribute__((packed));
-
- //! See host_messages.fbs for the definition of this struct.
- struct LogMessageV2 {
- enum LogLevel logLevel;
- uint32_t timestampMillis;
- char logMessage[];
- } __attribute__((packed));
-
- //! The number of logs dropped since CHRE start
- uint32_t mNumLogsDropped = 0;
-};
-
-} // namespace chre
-} // namespace android
-
-#endif // CHRE_LOG_MESSAGE_PARSER_BASE_H_
diff --git a/host/common/include/chre_host/napp_header.h b/host/common/include/chre_host/napp_header.h
deleted file mode 100644
index 83ac9eaa..00000000
--- a/host/common/include/chre_host/napp_header.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 CHRE_HOST_NAPP_HEADER_H_
-#define CHRE_HOST_NAPP_HEADER_H_
-
-namespace android {
-namespace chre {
-
-// This struct comes from build/build_template.mk and must not be modified.
-// Refer to that file for more details.
-struct NanoAppBinaryHeader {
- uint32_t headerVersion;
- uint32_t magic;
- uint64_t appId;
- uint32_t appVersion;
- uint32_t flags;
- uint64_t hwHubType;
- uint8_t targetChreApiMajorVersion;
- uint8_t targetChreApiMinorVersion;
- uint8_t reserved[6];
-} __attribute__((packed));
-
-} // namespace chre
-} // namespace android
-
-#endif // CHRE_HOST_NAPP_HEADER_H_
diff --git a/host/common/include/chre_host/socket_server.h b/host/common/include/chre_host/socket_server.h
index 2aeecd27..57c858ec 100644
--- a/host/common/include/chre_host/socket_server.h
+++ b/host/common/include/chre_host/socket_server.h
@@ -84,9 +84,8 @@ class SocketServer {
private:
DISALLOW_COPY_AND_ASSIGN(SocketServer);
- static constexpr size_t kMaxActiveClients = 8;
- static constexpr int kMaxPendingConnectionRequests =
- static_cast<int>(kMaxActiveClients);
+ static constexpr int kMaxPendingConnectionRequests = 4;
+ static constexpr size_t kMaxActiveClients = 4;
static constexpr size_t kMaxPacketSize = 1024 * 1024;
int mSockFd = INVALID_SOCKET;
diff --git a/host/common/include/chre_host/st_hal_lpma_handler.h b/host/common/include/chre_host/st_hal_lpma_handler.h
deleted file mode 100644
index 4210802f..00000000
--- a/host/common/include/chre_host/st_hal_lpma_handler.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 ST_HAL_LPMA_HANDLER_H_
-#define ST_HAL_LPMA_HANDLER_H_
-
-#include <condition_variable>
-#include <cstdio>
-#include <functional>
-#include <mutex>
-#include <thread>
-
-#include "chre_host/log.h"
-
-#include <android/hardware/soundtrigger/2.0/ISoundTriggerHw.h>
-#include <hardware_legacy/power.h>
-
-using android::hardware::hidl_death_recipient;
-using android::hardware::Return;
-using android::hardware::soundtrigger::V2_0::ISoundTriggerHw;
-using android::hardware::soundtrigger::V2_0::SoundModelHandle;
-using android::hardware::soundtrigger::V2_0::SoundModelType;
-using android::hidl::base::V1_0::IBase;
-
-namespace android {
-namespace chre {
-
-/**
- * Handles interactions with the SoundTrigger (ST) HAL, to issue configuration
- * requests for the always-on audio hardware to enable Low Power Microphone
- * Access (LPMA) in CHRE. Typically, this class is used when the CHRE audio
- * implementation for a given system requires notifying the ST HAL when audio
- * is requested/released within CHRE
- */
-class StHalLpmaHandler {
- public:
- //! Class to handle when a connected ST HAL service dies
- class StHalDeathRecipient : public hidl_death_recipient {
- public:
- StHalDeathRecipient() = delete;
- explicit StHalDeathRecipient(std::function<void()> cb) : mCallback(cb) {}
-
- /**
- * Callback that is called when a connected service dies. It mainly
- * resets the LPMA Enabled flag, and unblocks the LPMA processing thread.
- * It is to be used in conjunction with linkToDeath(), which we do
- * in checkConnectionToStHalServiceLocked().
- */
- virtual void serviceDied(uint64_t /* cookie */,
- const wp<IBase> & /* who */) override {
- mCallback();
- }
-
- private:
- std::function<void()> mCallback;
- };
-
- StHalLpmaHandler() = delete;
-
- explicit StHalLpmaHandler(bool allowed);
-
- ~StHalLpmaHandler() {
- if (mThread.has_value()) {
- // TODO: Change this to join after adding proper handler
- mThread->detach();
- }
- }
-
- /**
- * If LPMA is enabled, starts a worker thread to load/unload models.
- */
- void init();
-
- /**
- * Sets the target state for LPMA to be enabled. This triggers another thread
- * to perform the async operation of enabling or disabling the LPMA use case.
- *
- * @param enabled Whether LPMA is to be enabled or disabled.
- */
- void enable(bool enabled);
-
- /**
- * Loads the LPMA use case via the SoundTrigger HAL HIDL service.
- *
- * @return true if LPMA was enabled successfully, false otherwise.
- */
- bool load();
-
- /**
- * Unloads the LPMA use case via the SoundTrigger HAL HIDL service. This
- * function does not indicate success/failure as it is expected that even in
- * the event of a failure to unload, the use case will be unloaded. As long as
- * the sound trigger HAL received the request we can be assured that the use
- * case will be unloaded (even if it means reseting the codec or otherwise).
- */
- void unload();
-
- /**
- * Entry point for the thread that loads/unloads sound models from the
- * ST HAL
- */
- void StHalLpmaHandlerThreadEntry();
-
- private:
- const bool mIsLpmaAllowed;
- bool mCurrentLpmaEnabled;
- bool mTargetLpmaEnabled;
- bool mCondVarPredicate;
- SoundModelHandle mLpmaHandle = 0;
-
- int mRetryCount;
- useconds_t mRetryDelay;
-
- std::optional<std::thread> mThread;
- std::mutex mMutex;
- std::condition_variable mCondVar;
-
- sp<StHalDeathRecipient> mDeathRecipient;
- sp<ISoundTriggerHw> mStHalService;
-
- /**
- * Checks for a valid connection to the ST HAL service, reconnects if not
- * already connected. This method should only be invoked after acquiring the
- * class mutex has been locked.
- */
- void checkConnectionToStHalServiceLocked();
-
- /**
- * Invoked by the HAL service death callback. see
- * StHalDeathRecipient::ServiceDied()
- */
- void onStHalServiceDeath();
-
- /**
- * This function blocks on a condition variable and when notified, based
- * on its current state and as notified by enable(), performs a load or
- * unload. The function also resets the delay and retry counts if the current
- * and next states match
- *
- * @return true if the state update succeeded, and we don't need to retry with
- * a delay
- */
- bool waitOnStHalRequestAndProcess();
-
- /**
- * Delay retrying a load if a state update failed
- */
- void delay();
-};
-
-} // namespace chre
-} // namespace android
-
-#endif // ST_HAL_LPMA_HANDLER_H_
diff --git a/host/common/include/chre_host/tokenized_log_message_parser.h b/host/common/include/chre_host/tokenized_log_message_parser.h
deleted file mode 100644
index ce380887..00000000
--- a/host/common/include/chre_host/tokenized_log_message_parser.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_TOKENIZED_LOG_MESSAGE_PARSER_H_
-#define CHRE_TOKENIZED_LOG_MESSAGE_PARSER_H_
-
-#include <memory>
-#include "chre_host/daemon_base.h"
-#include "chre_host/log_message_parser_base.h"
-
-#include "pw_tokenizer/detokenize.h"
-
-using pw::tokenizer::DetokenizedString;
-using pw::tokenizer::Detokenizer;
-
-namespace android {
-namespace chre {
-
-class ChreTokenizedLogMessageParser : public ChreLogMessageParserBase {
- public:
- virtual bool init() override final {
- mDetokenizer = logDetokenizerInit();
- return mDetokenizer != nullptr;
- }
-
- virtual void log(const uint8_t *logBuffer,
- size_t logBufferSize) override final {
- parseAndEmitTokenizedLogMessages(logBuffer, logBufferSize,
- mDetokenizer.get());
- }
-
- void logV2(const uint8_t *logBuffer, size_t logBufferSize) override {
- // TODO(b/172654554): Modify tokenized logging to only support v2 logs.
- }
-
- private:
- std::unique_ptr<Detokenizer> mDetokenizer;
-
- /**
- * Initialize the Log Detokenizer
- *
- * The log detokenizer reads a binary database file that contains key value
- * pairs of hash-keys <--> Decoded log messages, and creates an instance
- * of the Detokenizer.
- *
- * @return an instance of the Detokenizer
- */
- std::unique_ptr<Detokenizer> logDetokenizerInit() {
- constexpr const char kLogDatabaseFilePath[] =
- "/vendor/etc/chre/libchre_log_database.bin";
- std::vector<uint8_t> tokenData;
- if (ChreDaemonBase::readFileContents(kLogDatabaseFilePath, &tokenData)) {
- pw::tokenizer::TokenDatabase database =
- pw::tokenizer::TokenDatabase::Create(tokenData);
- if (database.ok()) {
- return std::make_unique<Detokenizer>(database);
- } else {
- LOGE("CHRE Token database creation not OK");
- }
- } else {
- LOGE("Failed to read CHRE Token database file");
- }
- return std::unique_ptr<Detokenizer>(nullptr);
- }
-
- // Log messages are routed through ashLog if tokenized logging
- // is disabled, so only parse tokenized log messages here.
- void parseAndEmitTokenizedLogMessages(const uint8_t *message,
- unsigned int messageLen,
- const Detokenizer *detokenizer) {
- if (detokenizer != nullptr) {
- // TODO: Pull out common code from the tokenized/standard log
- // parser functions when we implement batching for tokenized
- // logs (b/148873804)
- constexpr size_t kLogMessageHeaderSize =
- 1 /*logLevel*/ + sizeof(uint64_t) /*timestamp*/;
- uint8_t level = *message;
- ++message;
-
- uint64_t timestampNanos;
- memcpy(&timestampNanos, message, sizeof(uint64_t));
- timestampNanos = le64toh(timestampNanos);
- message += sizeof(uint64_t);
-
- DetokenizedString detokenizedLog =
- detokenizer->Detokenize(message, messageLen - kLogMessageHeaderSize);
- std::string decodedLog = detokenizedLog.BestStringWithErrors();
- uint32_t timestampMillis =
- timestampNanos / chre::kOneMillisecondInNanoseconds;
- emitLogMessage(level, timestampNanos, decodedLog.c_str());
- } else {
- // log an error and risk log spam? fail silently? log once?
- }
- }
-};
-
-} // namespace chre
-} // namespace android
-
-#endif // CHRE_TOKENIZED_LOG_MESSAGE_PARSER_H_ \ No newline at end of file
diff --git a/host/common/log_message_parser_base.cc b/host/common/log_message_parser_base.cc
deleted file mode 100644
index 56d88684..00000000
--- a/host/common/log_message_parser_base.cc
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <endian.h>
-#include <cstdio>
-
-#include "chre/util/time.h"
-#include "chre_host/log_message_parser_base.h"
-
-using chre::kOneMillisecondInNanoseconds;
-using chre::kOneSecondInMilliseconds;
-
-namespace android {
-namespace chre {
-
-namespace {
-#if defined(LOG_NDEBUG) || LOG_NDEBUG != 0
-constexpr bool kVerboseLoggingEnabled = true;
-#else
-constexpr bool kVerboseLoggingEnabled = false;
-#endif
-} // anonymous namespace
-
-ChreLogMessageParserBase::ChreLogMessageParserBase()
- : mVerboseLoggingEnabled(kVerboseLoggingEnabled) {}
-
-void ChreLogMessageParserBase::dump(const uint8_t *buffer, size_t size) {
- if (mVerboseLoggingEnabled) {
- char line[32];
- char lineChars[32];
- int offset = 0;
- int offsetChars = 0;
-
- size_t orig_size = size;
- if (size > 128) {
- size = 128;
- LOGV("Dumping first 128 bytes of buffer of size %zu", orig_size);
- } else {
- LOGV("Dumping buffer of size %zu bytes", size);
- }
- for (size_t i = 1; i <= size; ++i) {
- offset += snprintf(&line[offset], sizeof(line) - offset, "%02x ",
- buffer[i - 1]);
- offsetChars +=
- snprintf(&lineChars[offsetChars], sizeof(lineChars) - offsetChars,
- "%c", (isprint(buffer[i - 1])) ? buffer[i - 1] : '.');
- if ((i % 8) == 0) {
- LOGV(" %s\t%s", line, lineChars);
- offset = 0;
- offsetChars = 0;
- } else if ((i % 4) == 0) {
- offset += snprintf(&line[offset], sizeof(line) - offset, " ");
- }
- }
-
- if (offset > 0) {
- char tabs[8];
- char *pos = tabs;
- while (offset < 28) {
- *pos++ = '\t';
- offset += 8;
- }
- *pos = '\0';
- LOGV(" %s%s%s", line, tabs, lineChars);
- }
- }
-}
-
-android_LogPriority ChreLogMessageParserBase::chreLogLevelToAndroidLogPriority(
- uint8_t level) {
- switch (level) {
- case LogLevel::ERROR:
- return ANDROID_LOG_ERROR;
- case LogLevel::WARNING:
- return ANDROID_LOG_WARN;
- case LogLevel::INFO:
- return ANDROID_LOG_INFO;
- case LogLevel::DEBUG:
- return ANDROID_LOG_DEBUG;
- default:
- return ANDROID_LOG_SILENT;
- }
-}
-
-void ChreLogMessageParserBase::log(const uint8_t *logBuffer,
- size_t logBufferSize) {
- size_t bufferIndex = 0;
- while (bufferIndex < logBufferSize) {
- const LogMessage *message =
- reinterpret_cast<const LogMessage *>(&logBuffer[bufferIndex]);
- uint64_t timeNs = le64toh(message->timestampNanos);
- emitLogMessage(message->logLevel, timeNs / kOneMillisecondInNanoseconds,
- message->logMessage);
- bufferIndex += sizeof(LogMessage) +
- strnlen(message->logMessage, logBufferSize - bufferIndex) +
- 1;
- }
-}
-
-void ChreLogMessageParserBase::logV2(const uint8_t *logBuffer,
- size_t logBufferSize,
- uint32_t numLogsDropped) {
- size_t bufferIndex = 0;
- if (numLogsDropped < mNumLogsDropped) {
- LOGE(
- "The numLogsDropped value received from CHRE is less than the last "
- "value received. Received: %" PRIu32 " Last value: %" PRIu32,
- numLogsDropped, mNumLogsDropped);
- }
- // Log the number of logs dropped once before logging remaining logs from CHRE
- uint32_t diffLogsDropped = numLogsDropped - mNumLogsDropped;
- mNumLogsDropped = numLogsDropped;
- if (diffLogsDropped > 0) {
- LOGI("# logs dropped: %" PRIu32, diffLogsDropped);
- }
- while (bufferIndex < logBufferSize) {
- const LogMessageV2 *message =
- reinterpret_cast<const LogMessageV2 *>(&logBuffer[bufferIndex]);
- emitLogMessage(message->logLevel, le32toh(message->timestampMillis),
- message->logMessage);
- bufferIndex += sizeof(LogMessageV2) +
- strnlen(message->logMessage, logBufferSize - bufferIndex) +
- 1;
- }
-}
-
-void ChreLogMessageParserBase::emitLogMessage(uint8_t level,
- uint32_t timestampMillis,
- const char *logMessage) {
- constexpr const char kLogTag[] = "CHRE";
- uint32_t timeSec = timestampMillis / kOneSecondInMilliseconds;
- uint32_t timeMsRemainder = timestampMillis % kOneSecondInMilliseconds;
- android_LogPriority priority = chreLogLevelToAndroidLogPriority(level);
- LOG_PRI(priority, kLogTag, kHubLogFormatStr, timeSec, timeMsRemainder,
- logMessage);
-}
-
-} // namespace chre
-} // namespace android
diff --git a/host/common/socket_client.cc b/host/common/socket_client.cc
index ba13adce..d000d094 100644
--- a/host/common/socket_client.cc
+++ b/host/common/socket_client.cc
@@ -228,26 +228,9 @@ bool SocketClient::tryConnect(bool suppressErrorLogs) {
// Set the send buffer size to 2MB to allow plenty of room for nanoapp
// loading
int sndbuf = 2 * 1024 * 1024;
- // Normally, send() should effectively return immediately, but in the event
- // that we get blocked due to flow control, don't stay blocked for more than
- // 3 seconds
- struct timeval timeout = {
- .tv_sec = 3,
- .tv_usec = 0,
- };
- int ret;
-
- if ((ret = setsockopt(sockFd, SOL_SOCKET, SO_SNDBUF, &sndbuf,
- sizeof(sndbuf))) != 0) {
- if (!suppressErrorLogs) {
- LOGE("Failed to set SO_SNDBUF to %d: %s", sndbuf, strerror(errno));
- }
- } else if ((ret = setsockopt(sockFd, SOL_SOCKET, SO_SNDTIMEO, &timeout,
- sizeof(timeout))) != 0) {
- if (!suppressErrorLogs) {
- LOGE("Failed to set SO_SNDTIMEO: %s", strerror(errno));
- }
- } else {
+ int ret =
+ setsockopt(sockFd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
+ if (ret == 0) {
mSockFd = socket_local_client_connect(sockFd, mSocketName,
ANDROID_SOCKET_NAMESPACE_RESERVED,
SOCK_SEQPACKET);
@@ -257,6 +240,8 @@ bool SocketClient::tryConnect(bool suppressErrorLogs) {
LOGE("Couldn't connect client socket to '%s': %s", mSocketName,
strerror(errno));
}
+ } else if (!suppressErrorLogs) {
+ LOGE("Failed to set SO_SNDBUF to %d: %s", sndbuf, strerror(errno));
}
if (!success) {
diff --git a/host/common/st_hal_lpma_handler.cc b/host/common/st_hal_lpma_handler.cc
deleted file mode 100644
index 29e0e51c..00000000
--- a/host/common/st_hal_lpma_handler.cc
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <cinttypes>
-
-#include "chre_host/st_hal_lpma_handler.h"
-
-namespace android {
-namespace chre {
-
-namespace {
-
-constexpr char kChreWakeLockName[] = "chre_daemon";
-
-void acquireWakeLock() {
- int rc;
- if ((rc = acquire_wake_lock(PARTIAL_WAKE_LOCK, kChreWakeLockName)) != 0) {
- LOGE("Failed to acquire wakelock (err %d)", rc);
- }
-}
-
-void releaseWakeLock() {
- int rc;
- static bool wakeLockInitialRelease = true;
-
- // It's expected to get an error when we first try to release the
- // wakelock
- // as it won't exist unless it was leaked previously - don't output a
- // false warning for this case
- if (((rc = release_wake_lock(kChreWakeLockName)) != 0) &&
- !wakeLockInitialRelease) {
- LOGE("Failed to release wakelock (err %d)", rc);
- }
-
- wakeLockInitialRelease = false;
-}
-
-} // anonymous namespace
-
-StHalLpmaHandler::StHalLpmaHandler(bool allowed) : mIsLpmaAllowed(allowed) {
- auto cb = [&]() { onStHalServiceDeath(); };
- mDeathRecipient = new StHalDeathRecipient(cb);
-}
-
-void StHalLpmaHandler::init() {
- if (mIsLpmaAllowed) {
- mThread = std::thread(&StHalLpmaHandler::StHalLpmaHandlerThreadEntry, this);
- }
-}
-
-void StHalLpmaHandler::enable(bool enabled) {
- if (mIsLpmaAllowed) {
- std::lock_guard<std::mutex> lock(mMutex);
- mTargetLpmaEnabled = enabled;
- mCondVarPredicate = true;
- mCondVar.notify_one();
- } else {
- LOGE("Trying to modify LPMA state when LPMA is disabled");
- }
-}
-
-bool StHalLpmaHandler::load() {
- constexpr uint8_t kUuidNode[] = {0x2E, 0x95, 0xA2, 0x31, 0x3A, 0xEE};
-
- LOGV("Loading LPMA");
-
- ISoundTriggerHw::SoundModel soundModel;
- soundModel.type = SoundModelType::GENERIC;
- soundModel.vendorUuid.timeLow = 0x57CADDB1;
- soundModel.vendorUuid.timeMid = 0xACDB;
- soundModel.vendorUuid.versionAndTimeHigh = 0x4DCE;
- soundModel.vendorUuid.variantAndClockSeqHigh = 0x8CB0;
-
- memcpy(&soundModel.vendorUuid.node[0], kUuidNode, sizeof(kUuidNode));
- soundModel.data.resize(1); // Insert an empty byte to bypass HAL NULL checks.
-
- bool loaded = false;
- checkConnectionToStHalServiceLocked();
- int32_t loadResult;
- Return<void> hidlResult = mStHalService->loadSoundModel(
- soundModel, nullptr /* callback */, 0 /* cookie */,
- [&](int32_t retval, SoundModelHandle handle) {
- loadResult = retval;
- mLpmaHandle = handle;
- });
-
- if (hidlResult.isOk()) {
- if (loadResult == 0) {
- LOGD("Loaded LPMA");
- loaded = true;
- } else {
- LOGE("Failed to load LPMA with %" PRId32, loadResult);
- }
- } else {
- LOGE("Failed to load LPMA due to hidl error %s",
- hidlResult.description().c_str());
- }
-
- return loaded;
-}
-
-void StHalLpmaHandler::unload() {
- checkConnectionToStHalServiceLocked();
- Return<int32_t> hidlResult = mStHalService->unloadSoundModel(mLpmaHandle);
- mLpmaHandle = 0;
-
- if (hidlResult.isOk()) {
- if (hidlResult != 0) {
- LOGE("Failed to unload LPMA with %" PRId32, int32_t(hidlResult));
- }
- } else {
- LOGE("Failed to unload LPMA due to hidl error %s",
- hidlResult.description().c_str());
- }
-}
-
-void StHalLpmaHandler::checkConnectionToStHalServiceLocked() {
- if (mStHalService == nullptr) {
- mStHalService = ISoundTriggerHw::getService();
- if (mStHalService != nullptr) {
- LOGI("Connected to ST HAL service");
- mStHalService->linkToDeath(mDeathRecipient, 0 /* flags */);
- }
- }
-}
-
-bool StHalLpmaHandler::waitOnStHalRequestAndProcess() {
- bool noDelayNeeded = true;
- std::unique_lock<std::mutex> lock(mMutex);
-
- if (mCurrentLpmaEnabled == mTargetLpmaEnabled) {
- mRetryDelay = 0;
- mRetryCount = 0;
- releaseWakeLock(); // Allow the system to suspend while waiting.
- mCondVar.wait(lock, [this] { return mCondVarPredicate; });
- mCondVarPredicate = false;
- acquireWakeLock(); // Ensure the system stays up while retrying.
- } else if (mTargetLpmaEnabled && load()) {
- mCurrentLpmaEnabled = mTargetLpmaEnabled;
- } else if (!mTargetLpmaEnabled) {
- // Regardless of whether the use case fails to unload, set the
- // currentLpmaEnabled to the targetLpmaEnabled. This will allow the next
- // enable request to proceed. After a failure to unload occurs, the
- // supplied handle is invalid and should not be unloaded again.
- unload();
- mCurrentLpmaEnabled = mTargetLpmaEnabled;
- } else {
- noDelayNeeded = false;
- }
-
- return noDelayNeeded;
-}
-
-void StHalLpmaHandler::delay() {
- constexpr useconds_t kInitialRetryDelayUs = 500000;
- constexpr int kRetryGrowthFactor = 2;
- constexpr int kRetryGrowthLimit = 5; // Terminates at 8s retry interval.
- constexpr int kRetryWakeLockLimit = 10; // Retry with a wakelock 10 times.
-
- if (mRetryDelay == 0) {
- mRetryDelay = kInitialRetryDelayUs;
- } else if (mRetryCount < kRetryGrowthLimit) {
- mRetryDelay *= kRetryGrowthFactor;
- }
- usleep(mRetryDelay);
- mRetryCount++;
- if (mRetryCount > kRetryWakeLockLimit) {
- releaseWakeLock();
- }
-}
-
-void StHalLpmaHandler::StHalLpmaHandlerThreadEntry() {
- LOGD("Starting LPMA thread");
-
- while (true) {
- if (!waitOnStHalRequestAndProcess()) {
- // processing an LPMA state update failed, retry after a little while
- delay();
- }
- }
-}
-
-void StHalLpmaHandler::onStHalServiceDeath() {
- LOGE("ST HAL Service Died");
- std::lock_guard<std::mutex> lock(mMutex);
- mStHalService = nullptr;
- if (mTargetLpmaEnabled) {
- // ST HAL has died, so assume that the sound model is no longer active,
- // and trigger a reload of the sound model.
- mCurrentLpmaEnabled = false;
- mCondVarPredicate = true;
- mCondVar.notify_one();
- }
-}
-
-} // namespace chre
-} // namespace android
diff --git a/host/common/test/chre_test_client.cc b/host/common/test/chre_test_client.cc
index 304ea6bc..d651cb88 100644
--- a/host/common/test/chre_test_client.cc
+++ b/host/common/test/chre_test_client.cc
@@ -15,10 +15,8 @@
*/
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_header_utils.h"
#include "chre_host/host_protocol_host.h"
#include "chre_host/log.h"
-#include "chre_host/napp_header.h"
#include "chre_host/socket_client.h"
#include <inttypes.h>
@@ -26,7 +24,6 @@
#include <sys/types.h>
#include <fstream>
-#include <future>
#include <sstream>
#include <thread>
@@ -39,9 +36,8 @@
* processor of MSM chipsets, which is used to help test basic functionality.
*
* Usage:
- * chre_test_client load <nanoapp-id> <nanoapp-so-path> \
- * [app-version] [api-version] [tcm-capable] [nanoapp-header-path]
- * chre_test_client load_with_header <nanoapp-header-path> <nanoapp-so-path>
+ * chre_test_client load <nanoapp-id> <nanoapp-path> \
+ * [app-version] [api-version]
* chre_test_client unload <nanoapp-id>
*/
@@ -50,7 +46,6 @@ using android::chre::FragmentedLoadTransaction;
using android::chre::getStringFromByteVector;
using android::chre::HostProtocolHost;
using android::chre::IChreMessageHandlers;
-using android::chre::NanoAppBinaryHeader;
using android::chre::SocketClient;
using flatbuffers::FlatBufferBuilder;
@@ -117,9 +112,10 @@ class SocketCallbacks : public SocketClient::ICallbacks,
for (const std::unique_ptr<fbs::NanoappListEntryT> &nanoapp :
response.nanoapps) {
LOGI(" App ID 0x%016" PRIx64 " version 0x%" PRIx32
- " permissions 0x%" PRIx32 " enabled %d system %d",
- nanoapp->app_id, nanoapp->version, nanoapp->permissions,
- nanoapp->enabled, nanoapp->is_system);
+ " enabled %d system "
+ "%d",
+ nanoapp->app_id, nanoapp->version, nanoapp->enabled,
+ nanoapp->is_system);
}
}
@@ -134,18 +130,6 @@ class SocketCallbacks : public SocketClient::ICallbacks,
LOGI("Got unload nanoapp response, transaction ID 0x%" PRIx32 " result %d",
response.transaction_id, response.success);
}
-
- void handleSelfTestResponse(const ::chre::fbs::SelfTestResponseT &response) {
- LOGI("Got self test response with success %d", response.success);
- mResultPromise.set_value(response.success);
- }
-
- std::future<bool> getResultFuture() {
- return mResultPromise.get_future();
- }
-
- private:
- std::promise<bool> mResultPromise;
};
void requestHubInfo(SocketClient &client) {
@@ -182,85 +166,40 @@ void sendMessageToNanoapp(SocketClient &client) {
}
}
-bool readFileContents(const char *filename, std::vector<uint8_t> *buffer) {
- bool success = false;
+void sendLoadNanoappRequest(SocketClient &client, const char *filename,
+ uint64_t appId, uint32_t appVersion,
+ uint32_t apiVersion) {
std::ifstream file(filename, std::ios::binary | std::ios::ate);
if (!file) {
- LOGE("Couldn't open file '%s': %d (%s)", filename, errno, strerror(errno));
- } else {
- ssize_t size = file.tellg();
- file.seekg(0, std::ios::beg);
-
- buffer->resize(size);
- if (!file.read(reinterpret_cast<char *>(buffer->data()), size)) {
- LOGE("Couldn't read from file '%s': %d (%s)", filename, errno,
- strerror(errno));
- } else {
- success = true;
- }
+ LOGE("Couldn't open file '%s': %s", filename, strerror(errno));
+ return;
}
+ ssize_t size = file.tellg();
+ file.seekg(0, std::ios::beg);
- return success;
-}
+ std::vector<uint8_t> buffer(size);
+ if (!file.read(reinterpret_cast<char *>(buffer.data()), size)) {
+ LOGE("Couldn't read from file: %s", strerror(errno));
+ return;
+ }
-void sendNanoappLoad(SocketClient &client, uint64_t appId, uint32_t appVersion,
- uint32_t apiVersion, uint32_t appFlags,
- const std::vector<uint8_t> &binary) {
// Perform loading with 1 fragment for simplicity
- FlatBufferBuilder builder(binary.size() + 128);
+ FlatBufferBuilder builder(size + 128);
FragmentedLoadTransaction transaction = FragmentedLoadTransaction(
- 1 /* transactionId */, appId, appVersion, appFlags, apiVersion, binary,
- binary.size() /* fragmentSize */);
+ 1 /* transactionId */, appId, appVersion, apiVersion, buffer,
+ buffer.size() /* fragmentSize */);
HostProtocolHost::encodeFragmentedLoadNanoappRequest(
builder, transaction.getNextRequest());
LOGI("Sending load nanoapp request (%" PRIu32
" bytes total w/%zu bytes of "
"payload)",
- builder.GetSize(), binary.size());
+ builder.GetSize(), buffer.size());
if (!client.sendMessage(builder.GetBufferPointer(), builder.GetSize())) {
LOGE("Failed to send message");
}
}
-void sendLoadNanoappRequest(SocketClient &client, const char *headerPath,
- const char *binaryPath) {
- std::vector<uint8_t> headerBuffer;
- std::vector<uint8_t> binaryBuffer;
- if (readFileContents(headerPath, &headerBuffer) &&
- readFileContents(binaryPath, &binaryBuffer)) {
- if (headerBuffer.size() != sizeof(NanoAppBinaryHeader)) {
- LOGE("Header size mismatch");
- } else {
- // The header blob contains the struct above.
- const auto *appHeader =
- reinterpret_cast<const NanoAppBinaryHeader *>(headerBuffer.data());
-
- // Build the target API version from major and minor.
- uint32_t targetApiVersion = (appHeader->targetChreApiMajorVersion << 24) |
- (appHeader->targetChreApiMinorVersion << 16);
-
- sendNanoappLoad(client, appHeader->appId, appHeader->appVersion,
- targetApiVersion, appHeader->flags, binaryBuffer);
- }
- }
-}
-
-void sendLoadNanoappRequest(SocketClient &client, const char *filename,
- uint64_t appId, uint32_t appVersion,
- uint32_t apiVersion, bool tcmApp) {
- std::vector<uint8_t> buffer;
- if (readFileContents(filename, &buffer)) {
- // All loaded nanoapps must be signed currently.
- uint32_t appFlags = CHRE_NAPP_HEADER_SIGNED;
- if (tcmApp) {
- appFlags |= CHRE_NAPP_HEADER_TCM_CAPABLE;
- }
-
- sendNanoappLoad(client, appId, appVersion, apiVersion, appFlags, buffer);
- }
-}
-
void sendUnloadNanoappRequest(SocketClient &client, uint64_t appId) {
FlatBufferBuilder builder(48);
constexpr uint32_t kTransactionId = 4321;
@@ -274,16 +213,6 @@ void sendUnloadNanoappRequest(SocketClient &client, uint64_t appId) {
}
}
-void sendSelfTestRequest(SocketClient &client) {
- FlatBufferBuilder builder(48);
- HostProtocolHost::encodeSelfTestRequest(builder);
-
- LOGI("Sending self test");
- if (!client.sendMessage(builder.GetBufferPointer(), builder.GetSize())) {
- LOGE("Failed to send message");
- }
-}
-
} // anonymous namespace
static void usage(const std::string &name) {
@@ -293,9 +222,9 @@ static void usage(const std::string &name) {
"\n"
"Usage:\n " +
name +
- " load <nanoapp-id> <nanoapp-so-path> [app-version] [api-version]\n " +
- name + " load_with_header <nanoapp-header-path> <nanoapp-so-path>\n " +
- name + " unload <nanoapp-id>\n " + name + " self_test\n";
+ " load <nanoapp-id> <nanoapp-path> "
+ "[app-version] [api-version]\n " +
+ name + " unload <nanoapp-id>\n";
LOGI("%s", output.c_str());
}
@@ -304,94 +233,63 @@ int main(int argc, char *argv[]) {
int argi = 0;
const std::string name{argv[argi++]};
const std::string cmd{argi < argc ? argv[argi++] : ""};
+ const std::string idstr{argi < argc ? argv[argi++] : ""};
+ const std::string path{argi < argc ? argv[argi++] : ""};
+ const std::string appVerStr{argi < argc ? argv[argi++] : ""};
+ const std::string apiVerStr{argi < argc ? argv[argi++] : ""};
SocketClient client;
sp<SocketCallbacks> callbacks = new SocketCallbacks();
- bool success = true;
if (!client.connect("chre", callbacks)) {
LOGE("Couldn't connect to socket");
- success = false;
- } else if (cmd.empty()) {
+ return -1;
+ }
+
+ if (cmd.empty()) {
requestHubInfo(client);
requestNanoappList(client);
sendMessageToNanoapp(client);
sendLoadNanoappRequest(client, "/data/activity.so",
0x476f6f676c00100b /* appId */, 0 /* appVersion */,
- 0x01000000 /* targetApiVersion */,
- false /* tcmCapable */);
+ 0x01000000 /* targetApiVersion */);
sendUnloadNanoappRequest(client, 0x476f6f676c00100b /* appId */);
LOGI("Sleeping, waiting on responses");
std::this_thread::sleep_for(std::chrono::seconds(5));
- } else if (cmd == "load_with_header") {
- const std::string headerPath{argi < argc ? argv[argi++] : ""};
- const std::string binaryPath{argi < argc ? argv[argi++] : ""};
-
- if (headerPath.empty() || binaryPath.empty()) {
- LOGE("Arguments not provided!");
- usage(name);
- success = false;
- } else {
- sendLoadNanoappRequest(client, headerPath.c_str(), binaryPath.c_str());
- }
} else if (cmd == "load") {
- const std::string idstr{argi < argc ? argv[argi++] : ""};
- const std::string path{argi < argc ? argv[argi++] : ""};
- const std::string appVerStr{argi < argc ? argv[argi++] : ""};
- const std::string apiVerStr{argi < argc ? argv[argi++] : ""};
- const std::string tcmCapStr{argi < argc ? argv[argi++] : ""};
-
uint64_t id = 0;
uint32_t appVersion = kDefaultAppVersion;
uint32_t apiVersion = kDefaultApiVersion;
- bool tcmApp = false;
if (idstr.empty() || path.empty()) {
LOGE("Arguments not provided!");
usage(name);
- success = false;
- } else {
- std::istringstream(idstr) >> std::setbase(0) >> id;
- if (!appVerStr.empty()) {
- std::istringstream(appVerStr) >> std::setbase(0) >> appVersion;
- }
- if (!apiVerStr.empty()) {
- std::istringstream(apiVerStr) >> std::setbase(0) >> apiVersion;
- }
- if (!tcmCapStr.empty()) {
- std::istringstream(tcmCapStr) >> tcmApp;
- }
- sendLoadNanoappRequest(client, path.c_str(), id, appVersion, apiVersion,
- tcmApp);
+ return -1;
}
+ std::istringstream(idstr) >> std::setbase(0) >> id;
+ if (!appVerStr.empty()) {
+ std::istringstream(appVerStr) >> std::setbase(0) >> appVersion;
+ }
+ if (!apiVerStr.empty()) {
+ std::istringstream(apiVerStr) >> std::setbase(0) >> apiVersion;
+ }
+ sendLoadNanoappRequest(client, path.c_str(), id, appVersion, apiVersion);
} else if (cmd == "unload") {
- const std::string idstr{argi < argc ? argv[argi++] : ""};
uint64_t id = 0;
if (idstr.empty()) {
LOGE("Arguments not provided!");
usage(name);
- success = false;
- } else {
- std::istringstream(idstr) >> std::setbase(0) >> id;
- sendUnloadNanoappRequest(client, id);
- }
- } else if (cmd == "self_test") {
- sendSelfTestRequest(client);
-
- std::future<bool> future = callbacks->getResultFuture();
- std::future_status status = future.wait_for(std::chrono::seconds(5));
-
- if (status != std::future_status::ready) {
- LOGE("Self test timed out");
- } else {
- success = future.get();
+ return -1;
}
+ std::istringstream(idstr) >> std::setbase(0) >> id;
+ sendUnloadNanoappRequest(client, id);
} else {
LOGE("Invalid command provided!");
usage(name);
+ return -1;
}
- return success ? 0 : -1;
+ return 0;
}
diff --git a/host/common/test/power_test/chre_power_test_client.cc b/host/common/test/power_test/chre_power_test_client.cc
index c3a6779c..a3091b9b 100644
--- a/host/common/test/power_test/chre_power_test_client.cc
+++ b/host/common/test/power_test/chre_power_test_client.cc
@@ -16,7 +16,6 @@
#include <cutils/sockets.h>
#include <sys/socket.h>
-#include <sys/stat.h>
#include <sys/types.h>
#include <utils/StrongPointer.h>
@@ -33,7 +32,6 @@
#include <vector>
#include "chre/util/nanoapp/app_id.h"
-#include "chre/util/system/napp_header_utils.h"
#include "chre/version.h"
#include "chre_host/host_protocol_host.h"
#include "chre_host/log.h"
@@ -51,9 +49,6 @@
* chre_power_test_client unloadall
* chre_power_test_client timer <optional: tcm> <enable> <interval_ns>
* chre_power_test_client wifi <optional: tcm> <enable> <interval_ns>
- * <optional: wifi_scan_type>
- * <optional: wifi_radio_chain>
- * <optional: wifi_channel_set>
* chre_power_test_client gnss <optional: tcm> <enable> <interval_ms>
* <optional: next_fix_ms>
* chre_power_test_client cell <optional: tcm> <enable> <interval_ns>
@@ -61,7 +56,6 @@
* chre_power_test_client sensor <optional: tcm> <enable> <sensor_type>
* <interval_ns> <optional: latency_ns>
* chre_power_test_client breakit <optional: tcm> <enable>
- * chre_power_test_client gnss_meas <optional: tcm> <enable> <interval_ms>
*
* Command:
* load: load power test nanoapp to CHRE
@@ -74,7 +68,6 @@
* audio: start/stop periodic audio capture
* sensor: start/stop periodic sensor sampling
* breakit: start/stop all action for stress tests
- * gnss_meas: start/stop periodic GNSS measurement
*
* <optional: tcm>: tcm for micro image, default for big image
* <enable>: enable/disable
@@ -91,7 +84,6 @@
* light
* proximity
* step
- * step_counter
* uncalibrated_accelerometer
* accelerometer_temperature
* gyroscope_temperature
@@ -99,22 +91,6 @@
*
* For instant_motion and stationary sensor, it is not necessary to provide the
* interval and latency
- *
- * <wifi_scan_type>:
- * active
- * active_passive_dfs
- * passive
- * no_preference (default when omitted)
- *
- * <wifi_radio_chain>:
- * default (default when omitted)
- * low_latency
- * low_power
- * high_accuracy
- *
- * <wifi_channel_set>:
- * non_dfs (default when omitted)
- * all
*/
using android::sp;
@@ -125,9 +101,6 @@ using android::chre::IChreMessageHandlers;
using android::chre::SocketClient;
using chre::power_test::MessageType;
using chre::power_test::SensorType;
-using chre::power_test::WifiChannelSet;
-using chre::power_test::WifiRadioChain;
-using chre::power_test::WifiScanType;
using flatbuffers::FlatBufferBuilder;
using std::string;
@@ -140,7 +113,7 @@ namespace {
constexpr uint16_t kHostEndpoint = 0xfffd;
-constexpr uint32_t kAppVersion = 0x00020000;
+constexpr uint32_t kAppVersion = 1;
constexpr uint32_t kApiVersion = CHRE_API_VERSION;
constexpr uint64_t kPowerTestAppId = 0x012345678900000f;
constexpr uint64_t kPowerTestTcmAppId = 0x0123456789000010;
@@ -148,8 +121,8 @@ constexpr uint64_t kUint64Max = std::numeric_limits<uint64_t>::max();
constexpr auto kTimeout = std::chrono::seconds(10);
-const string kPowerTestName = "power_test.so";
-const string kPowerTestTcmName = "power_test_tcm.so";
+const char *kPowerTestPath = "/vendor/dsp/sdsp/power_test.so";
+const char *kPowerTestTcmPath = "/vendor/dsp/sdsp/power_test_tcm.so";
std::condition_variable kReadyCond;
std::mutex kReadyMutex;
std::unique_lock<std::mutex> kReadyCondLock(kReadyMutex);
@@ -164,8 +137,7 @@ enum class Command : uint32_t {
kCell,
kAudio,
kSensor,
- kBreakIt,
- kGnssMeas
+ kBreakIt
};
std::unordered_map<string, Command> commandMap{
@@ -173,8 +145,7 @@ std::unordered_map<string, Command> commandMap{
{"unload", Command::kUnload}, {"timer", Command::kTimer},
{"wifi", Command::kWifi}, {"gnss", Command::kGnss},
{"cell", Command::kCell}, {"audio", Command::kAudio},
- {"sensor", Command::kSensor}, {"breakit", Command::kBreakIt},
- {"gnss_meas", Command::kGnssMeas}};
+ {"sensor", Command::kSensor}, {"breakit", Command::kBreakIt}};
std::unordered_map<string, MessageType> messageTypeMap{
{"timer", MessageType::TIMER_TEST},
@@ -183,8 +154,7 @@ std::unordered_map<string, MessageType> messageTypeMap{
{"cell", MessageType::CELL_QUERY_TEST},
{"audio", MessageType::AUDIO_REQUEST_TEST},
{"sensor", MessageType::SENSOR_REQUEST_TEST},
- {"breakit", MessageType::BREAK_IT_TEST},
- {"gnss_meas", MessageType::GNSS_MEASUREMENT_TEST}};
+ {"breakit", MessageType::BREAK_IT_TEST}};
std::unordered_map<string, SensorType> sensorTypeMap{
{"accelerometer", SensorType::ACCELEROMETER},
@@ -198,51 +168,11 @@ std::unordered_map<string, SensorType> sensorTypeMap{
{"light", SensorType::LIGHT},
{"proximity", SensorType::PROXIMITY},
{"step", SensorType::STEP_DETECT},
- {"step_counter", SensorType::STEP_COUNTER},
{"uncalibrated_accelerometer", SensorType::UNCALIBRATED_ACCELEROMETER},
{"accelerometer_temperature", SensorType::ACCELEROMETER_TEMPERATURE},
{"gyroscope_temperature", SensorType::GYROSCOPE_TEMPERATURE},
{"geomagnetic_temperature", SensorType::GEOMAGNETIC_FIELD_TEMPERATURE}};
-std::unordered_map<string, WifiScanType> wifiScanTypeMap{
- {"active", WifiScanType::ACTIVE},
- {"active_passive_dfs", WifiScanType::ACTIVE_PLUS_PASSIVE_DFS},
- {"passive", WifiScanType::PASSIVE},
- {"no_preference", WifiScanType::NO_PREFERENCE}};
-
-std::unordered_map<string, WifiRadioChain> wifiRadioChainMap{
- {"default", WifiRadioChain::DEFAULT},
- {"low_latency", WifiRadioChain::LOW_LATENCY},
- {"low_power", WifiRadioChain::LOW_POWER},
- {"high_accuracy", WifiRadioChain::HIGH_ACCURACY}};
-
-std::unordered_map<string, WifiChannelSet> wifiChannelSetMap{
- {"non_dfs", WifiChannelSet::NON_DFS}, {"all", WifiChannelSet::ALL}};
-
-bool wifiScanTypeMatch(const string &name, WifiScanType *scanType) {
- if (wifiScanTypeMap.find(name) != wifiScanTypeMap.end()) {
- *scanType = wifiScanTypeMap[name];
- return true;
- }
- return false;
-}
-
-bool wifiRadioChainMatch(const string &name, WifiRadioChain *radioChain) {
- if (wifiRadioChainMap.find(name) != wifiRadioChainMap.end()) {
- *radioChain = wifiRadioChainMap[name];
- return true;
- }
- return false;
-}
-
-bool wifiChannelSetMatch(const string &name, WifiChannelSet *channelSet) {
- if (wifiChannelSetMap.find(name) != wifiChannelSetMap.end()) {
- *channelSet = wifiChannelSetMap[name];
- return true;
- }
- return false;
-}
-
class SocketCallbacks : public SocketClient::ICallbacks,
public IChreMessageHandlers {
public:
@@ -292,10 +222,9 @@ class SocketCallbacks : public SocketClient::ICallbacks,
LOGI("Got nanoapp list response with %zu apps:", response.nanoapps.size());
mAppIdVector.clear();
for (const auto &nanoapp : response.nanoapps) {
- LOGI("App ID 0x%016" PRIx64 " version 0x%" PRIx32
- " permissions 0x%" PRIx32 " enabled %d system %d",
- nanoapp->app_id, nanoapp->version, nanoapp->permissions,
- nanoapp->enabled, nanoapp->is_system);
+ LOGI("App ID 0x%016" PRIx64 " version 0x%" PRIx32 " enabled %d system %d",
+ nanoapp->app_id, nanoapp->version, nanoapp->enabled,
+ nanoapp->is_system);
mAppIdVector.push_back(nanoapp->app_id);
}
mConditionVariable.notify_all();
@@ -345,7 +274,7 @@ bool requestNanoappList(SocketClient &client) {
bool sendLoadNanoappRequest(SocketClient &client, const char *filename,
uint64_t appId, uint32_t appVersion,
- uint32_t apiVersion, bool tcmApp) {
+ uint32_t apiVersion) {
std::ifstream file(filename, std::ios::binary | std::ios::ate);
if (!file) {
LOGE("Couldn't open file '%s': %s", filename, strerror(errno));
@@ -361,16 +290,10 @@ bool sendLoadNanoappRequest(SocketClient &client, const char *filename,
return false;
}
- // All loaded nanoapps must be signed currently.
- uint32_t appFlags = CHRE_NAPP_HEADER_SIGNED;
- if (tcmApp) {
- appFlags |= CHRE_NAPP_HEADER_TCM_CAPABLE;
- }
-
// Perform loading with 1 fragment for simplicity
FlatBufferBuilder builder(size + 128);
FragmentedLoadTransaction transaction = FragmentedLoadTransaction(
- 1 /* transactionId */, appId, appVersion, appFlags, apiVersion, buffer,
+ 1 /* transactionId */, appId, appVersion, apiVersion, buffer,
buffer.size() /* fragmentSize */);
HostProtocolHost::encodeFragmentedLoadNanoappRequest(
builder, transaction.getNextRequest());
@@ -388,9 +311,9 @@ bool sendLoadNanoappRequest(SocketClient &client, const char *filename,
bool loadNanoapp(SocketClient &client, sp<SocketCallbacks> callbacks,
const char *filename, uint64_t appId, uint32_t appVersion,
- uint32_t apiVersion, bool tcmApp) {
- if (!sendLoadNanoappRequest(client, filename, appId, appVersion, apiVersion,
- tcmApp)) {
+ uint32_t apiVersion) {
+ if (!sendLoadNanoappRequest(client, filename, appId, appVersion,
+ apiVersion)) {
return false;
}
auto status = kReadyCond.wait_for(kReadyCondLock, kTimeout);
@@ -454,27 +377,11 @@ bool unloadAllNanoapps(SocketClient &client, sp<SocketCallbacks> callbacks) {
return true;
}
-bool isTcmArgSpecified(std::vector<string> &args) {
- return !args.empty() && args[0] == "tcm";
-}
-
inline uint64_t getId(std::vector<string> &args) {
- return isTcmArgSpecified(args) ? kPowerTestTcmAppId : kPowerTestAppId;
-}
-
-const string searchPath(const string &name) {
- const string kAdspPath = "vendor/dsp/adsp/" + name;
- const string kSdspPath = "vendor/dsp/sdsp/" + name;
- const string kEtcPath = "vendor/etc/chre/" + name;
-
- struct stat buf;
- if (stat(kAdspPath.c_str(), &buf) == 0) {
- return kAdspPath;
- } else if (stat(kSdspPath.c_str(), &buf) == 0) {
- return kSdspPath;
- } else {
- return kEtcPath;
+ if (!args.empty() && args[0] == "tcm") {
+ return kPowerTestTcmAppId;
}
+ return kPowerTestAppId;
}
/**
@@ -483,17 +390,17 @@ const string searchPath(const string &name) {
* for non-tcm mode, the args[0] is the path.
*/
-inline const string getPath(std::vector<string> &args) {
+inline const char *getPath(std::vector<string> &args) {
if (args.empty()) {
- return searchPath(kPowerTestName);
+ return kPowerTestPath;
}
if (args[0] == "tcm") {
if (args.size() > 1) {
- return args[1];
+ return args[1].c_str();
}
- return searchPath(kPowerTestTcmName);
+ return kPowerTestTcmPath;
}
- return args[0];
+ return args[0].c_str();
}
inline uint64_t getNanoseconds(std::vector<string> &args, size_t index) {
@@ -520,69 +427,8 @@ bool isLoaded(SocketClient &client, sp<SocketCallbacks> callbacks,
return false;
}
-bool validateSensorArguments(std::vector<string> &args) {
- if (args.size() < 3) {
- LOGE("Sensor type is required");
- return false;
- }
-
- if (sensorTypeMap.find(args[2]) == sensorTypeMap.end()) {
- LOGE("Invalid sensor type");
- return false;
- }
-
- SensorType sensorType = sensorTypeMap[args[2]];
- if (sensorType == SensorType::STATIONARY_DETECT ||
- sensorType == SensorType::INSTANT_MOTION_DETECT)
- return true;
-
- uint64_t intervalNanoseconds = getNanoseconds(args, 3);
- uint64_t latencyNanoseconds = getNanoseconds(args, 4);
- if (intervalNanoseconds == 0) {
- LOGE("Non zero sensor sampling interval is required when enable");
- return false;
- }
- if (latencyNanoseconds != 0 && latencyNanoseconds < intervalNanoseconds) {
- LOGE("The latency is not zero and smaller than the interval");
- return false;
- }
- return true;
-}
-
-bool validateWifiArguments(std::vector<string> &args) {
- if (args.size() < 3) {
- LOGE("The interval is required");
- return false;
- }
-
- bool valid = true;
- WifiScanType scanType;
- WifiRadioChain radioChain;
- WifiChannelSet channelSet;
- for (int i = 3; i < 6 && args.size() > i && valid; i++) {
- valid = wifiScanTypeMatch(args[i], &scanType) ||
- wifiRadioChainMatch(args[i], &radioChain) ||
- wifiChannelSetMatch(args[i], &channelSet);
- if (!valid) {
- LOGE("Invalid WiFi scan parameters: %s", args[i].c_str());
- return false;
- }
- }
-
- uint64_t intervalNanoseconds = getNanoseconds(args, 2);
- if (intervalNanoseconds == 0) {
- LOGE("Non-zero WiFi request interval is required");
- return false;
- }
-
- return true;
-}
-
bool validateArguments(Command commandEnum, std::vector<string> &args) {
- // Commands: unloadall, load, unload
if (static_cast<uint32_t>(commandEnum) < 3) return true;
-
- // The other commands.
if (args.empty()) {
LOGE("Not enough parameters");
return false;
@@ -612,11 +458,7 @@ bool validateArguments(Command commandEnum, std::vector<string> &args) {
}
// Case of "enable":
- if (commandEnum == Command::kSensor) {
- return validateSensorArguments(args);
- } else if (commandEnum == Command::kWifi) {
- return validateWifiArguments(args);
- } else {
+ if (commandEnum != Command::kSensor) {
if (args.size() < 3) {
LOGE("The interval or duration was not provided");
return false;
@@ -630,6 +472,34 @@ bool validateArguments(Command commandEnum, std::vector<string> &args) {
}
return true;
}
+
+ // Case of enable sensor request
+ if (args.size() < 3) {
+ LOGE("Sensor type is required");
+ return false;
+ }
+
+ if (sensorTypeMap.find(args[2]) == sensorTypeMap.end()) {
+ LOGE("Invalid sensor type");
+ return false;
+ }
+
+ SensorType sensorType = sensorTypeMap[args[2]];
+ if (sensorType == SensorType::STATIONARY_DETECT ||
+ sensorType == SensorType::INSTANT_MOTION_DETECT)
+ return true;
+
+ uint64_t intervalNanoseconds = getNanoseconds(args, 3);
+ uint64_t latencyNanoseconds = getNanoseconds(args, 4);
+ if (intervalNanoseconds == 0) {
+ LOGE("Non zero sensor sampling interval is required when enable");
+ return false;
+ }
+ if (latencyNanoseconds != 0 && latencyNanoseconds < intervalNanoseconds) {
+ LOGE("The latency is not zero and smaller than the interval");
+ return false;
+ }
+ return true;
}
void createTimerMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
@@ -643,24 +513,9 @@ void createTimerMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
void createWifiMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
bool enable = (args[1] == "enable");
uint64_t intervalNanoseconds = getNanoseconds(args, 2);
- WifiScanType scanType = WifiScanType::NO_PREFERENCE;
- WifiRadioChain radioChain = WifiRadioChain::DEFAULT;
- WifiChannelSet channelSet = WifiChannelSet::NON_DFS;
-
- // Check for the 3 optional parameters.
- bool valid = true;
- for (int i = 3; i < 6 && args.size() > i && valid; i++) {
- valid = wifiScanTypeMatch(args[i], &scanType) ||
- wifiRadioChainMatch(args[i], &radioChain) ||
- wifiChannelSetMatch(args[i], &channelSet);
- }
-
- fbb.Finish(ptest::CreateWifiScanMessage(fbb, enable, intervalNanoseconds,
- scanType, radioChain, channelSet));
- LOGI("Created WifiScanMessage, enable %d, scan interval ns %" PRIu64
- " scan type %" PRIu8 " radio chain %" PRIu8 " channel set %" PRIu8,
- enable, intervalNanoseconds, static_cast<uint8_t>(scanType),
- static_cast<uint8_t>(radioChain), static_cast<uint8_t>(channelSet));
+ fbb.Finish(ptest::CreateWifiScanMessage(fbb, enable, intervalNanoseconds));
+ LOGI("Created WifiScanMessage, enable %d, scan interval ns %" PRIu64, enable,
+ intervalNanoseconds);
}
void createGnssMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
@@ -716,15 +571,6 @@ void createBreakItMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
LOGI("Created BreakItMessage, enable %d", enable);
}
-void createGnssMeasMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
- bool enable = (args[1] == "enable");
- uint32_t intervalMilliseconds = getMilliseconds(args, 2);
- fbb.Finish(
- ptest::CreateGnssMeasurementMessage(fbb, enable, intervalMilliseconds));
- LOGI("Created GnssMeasurementMessage, enable %d, interval ms %" PRIu32,
- enable, intervalMilliseconds);
-}
-
bool sendMessageToNanoapp(SocketClient &client, sp<SocketCallbacks> callbacks,
FlatBufferBuilder &fbb, uint64_t appId,
MessageType messageType) {
@@ -760,17 +606,14 @@ static void usage() {
" chre_power_test_client unload <optional: tcm>\n"
" chre_power_test_client unloadall\n"
" chre_power_test_client timer <optional: tcm> <enable> <interval_ns>\n"
- " chre_power_test_client wifi <optional: tcm> <enable> <interval_ns>"
- " <optional: wifi_scan_type> <optional: wifi_radio_chain>"
- " <optional: wifi_channel_set>\n"
+ " chre_power_test_client wifi <optional: tcm> <enable> <interval_ns>\n"
" chre_power_test_client gnss <optional: tcm> <enable> <interval_ms>"
" <next_fix_ms>\n"
" chre_power_test_client cell <optional: tcm> <enable> <interval_ns>\n"
" chre_power_test_client audio <optional: tcm> <enable> <duration_ns>\n"
" chre_power_test_client sensor <optional: tcm> <enable> <sensor_type>"
" <interval_ns> <optional: latency_ns>\n"
- " chre_power_test_client breakit <optional: tcm> <enable>\n"
- " chre_power_test_client gnss_meas <optional: tcm> <enable> <interval_ms>"
+ " chre_power_test_client <optional: tcm> <enable>\n"
"\n"
"Command:\n"
"load: load power test nanoapp to CHRE\n"
@@ -783,7 +626,6 @@ static void usage() {
"audio: start/stop periodic audio capture\n"
"sensor: start/stop periodic sensor sampling\n"
"breakit: start/stop all action for stress tests\n"
- "gnss_meas: start/stop periodic GNSS measurement\n"
"\n"
"<optional: tcm>: tcm for micro image, default for big image\n"
"<enable>: enable/disable\n"
@@ -806,23 +648,7 @@ static void usage() {
" geomanetic_temperature\n"
"\n"
" For instant_montion and stationary sersor, it is not necessary to"
- " provide the interval and latency.\n"
- "\n"
- "<wifi_scan_type>:\n"
- " active\n"
- " active_passive_dfs\n"
- " passive\n"
- " no_preference (default when omitted)\n"
- "\n"
- "<wifi_radio_chain>:\n"
- " default (default when omitted)\n"
- " low_latency\n"
- " low_power\n"
- " high_accuracy\n"
- "\n"
- "<wifi_channel_set>:\n"
- " non_dfs (default when omitted)\n"
- " all\n");
+ " provide the interval and latency");
}
void createRequestMessage(Command commandEnum, FlatBufferBuilder &fbb,
@@ -856,10 +682,6 @@ void createRequestMessage(Command commandEnum, FlatBufferBuilder &fbb,
createBreakItMessage(fbb, args);
break;
}
- case Command::kGnssMeas: {
- createGnssMeasMessage(fbb, args);
- break;
- }
default: {
usage();
}
@@ -916,10 +738,8 @@ int main(int argc, char *argv[]) {
break;
}
case Command::kLoad: {
- LOGI("Loading nanoapp from %s", getPath(args).c_str());
- success =
- loadNanoapp(client, callbacks, getPath(args).c_str(), getId(args),
- kAppVersion, kApiVersion, isTcmArgSpecified(args));
+ success = loadNanoapp(client, callbacks, getPath(args), getId(args),
+ kAppVersion, kApiVersion);
break;
}
default: {
diff --git a/host/hal_generic/V1_1/generic_context_hub_v1_1.cc b/host/hal_generic/V1_1/generic_context_hub_v1_1.cc
index 1bab8c73..4a911061 100644
--- a/host/hal_generic/V1_1/generic_context_hub_v1_1.cc
+++ b/host/hal_generic/V1_1/generic_context_hub_v1_1.cc
@@ -19,8 +19,6 @@
#include "generic_context_hub_v1_1.h"
-#include "context_hub_settings_util.h"
-
#include <chrono>
#include <cinttypes>
#include <vector>
@@ -36,20 +34,56 @@ namespace implementation {
using ::android::chre::HostProtocolHost;
using ::android::hardware::Return;
-using ::android::hardware::contexthub::common::implementation::getFbsSetting;
-using ::android::hardware::contexthub::common::implementation::
- getFbsSettingValue;
using ::flatbuffers::FlatBufferBuilder;
// Aliased for consistency with the way these symbols are referenced in
// CHRE-side code
namespace fbs = ::chre::fbs;
+namespace {
+
+bool getFbsSetting(Setting setting, fbs::Setting *fbsSetting) {
+ bool foundSetting = true;
+
+ switch (setting) {
+ case Setting::LOCATION:
+ *fbsSetting = fbs::Setting::LOCATION;
+ break;
+ default:
+ foundSetting = false;
+ ALOGE("Setting update with invalid enum value %hhu", setting);
+ break;
+ }
+
+ return foundSetting;
+}
+
+bool getFbsSettingValue(SettingValue newValue, fbs::SettingState *fbsState) {
+ bool foundSettingValue = true;
+
+ switch (newValue) {
+ case SettingValue::ENABLED:
+ *fbsState = fbs::SettingState::ENABLED;
+ break;
+ case SettingValue::DISABLED:
+ *fbsState = fbs::SettingState::DISABLED;
+ break;
+ default:
+ foundSettingValue = false;
+ ALOGE("Setting value update with invalid enum value %hhu", newValue);
+ break;
+ }
+
+ return foundSettingValue;
+}
+
+} // namespace
+
Return<void> GenericContextHubV1_1::onSettingChanged(Setting setting,
SettingValue newValue) {
fbs::Setting fbsSetting;
fbs::SettingState fbsState;
- if (getFbsSetting(reinterpret_cast<V1_2::Setting &>(setting), &fbsSetting) &&
+ if (getFbsSetting(setting, &fbsSetting) &&
getFbsSettingValue(newValue, &fbsState)) {
FlatBufferBuilder builder(64);
HostProtocolHost::encodeSettingChangeNotification(builder, fbsSetting,
diff --git a/host/hal_generic/V1_2/android.hardware.contexthub@1.2-generic.xml b/host/hal_generic/V1_2/android.hardware.contexthub@1.2-generic.xml
deleted file mode 100644
index ec6c6849..00000000
--- a/host/hal_generic/V1_2/android.hardware.contexthub@1.2-generic.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<manifest version="1.0" type="device">
- <hal format="hidl">
- <name>android.hardware.contexthub</name>
- <transport>hwbinder</transport>
- <version>1.2</version>
- <interface>
- <name>IContexthub</name>
- <instance>default</instance>
- </interface>
- </hal>
-</manifest>
diff --git a/host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-generic.rc b/host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-generic.rc
deleted file mode 100644
index c6253604..00000000
--- a/host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-generic.rc
+++ /dev/null
@@ -1,7 +0,0 @@
-service vendor.contexthub-hal-1-2 /vendor/bin/hw/android.hardware.contexthub@1.2-service.generic
- interface android.hardware.contexthub@1.0::IContexthub default
- interface android.hardware.contexthub@1.1::IContexthub default
- interface android.hardware.contexthub@1.2::IContexthub default
- class hal
- user context_hub
- group context_hub
diff --git a/host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-small_fragments.rc b/host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-small_fragments.rc
deleted file mode 100644
index 8df42de6..00000000
--- a/host/hal_generic/V1_2/android.hardware.contexthub@1.2-service-small_fragments.rc
+++ /dev/null
@@ -1,7 +0,0 @@
-service vendor.contexthub-hal-1-2 /vendor/bin/hw/android.hardware.contexthub@1.2-service.small_fragments
- interface android.hardware.contexthub@1.0::IContexthub default
- interface android.hardware.contexthub@1.1::IContexthub default
- interface android.hardware.contexthub@1.2::IContexthub default
- class hal
- user context_hub
- group context_hub
diff --git a/host/hal_generic/V1_2/generic_context_hub_v1_2.cc b/host/hal_generic/V1_2/generic_context_hub_v1_2.cc
deleted file mode 100644
index 2503ad28..00000000
--- a/host/hal_generic/V1_2/generic_context_hub_v1_2.cc
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-#define LOG_TAG "ContextHubHal"
-#define LOG_NDEBUG 0
-
-#include "generic_context_hub_v1_2.h"
-
-#include "context_hub_settings_util.h"
-#include "permissions_util.h"
-
-#include <chrono>
-#include <cinttypes>
-#include <vector>
-
-#include <log/log.h>
-#include <unistd.h>
-
-namespace android {
-namespace hardware {
-namespace contexthub {
-namespace V1_2 {
-namespace implementation {
-
-using ::android::chre::HostProtocolHost;
-using ::android::hardware::Return;
-using ::android::hardware::contexthub::common::implementation::getFbsSetting;
-using ::android::hardware::contexthub::common::implementation::
- getFbsSettingValue;
-using ::android::hardware::contexthub::common::implementation::
- kSupportedPermissions;
-using ::android::hardware::contexthub::V1_X::implementation::
- IContextHubCallbackWrapperBase;
-using ::android::hardware::contexthub::V1_X::implementation::
- IContextHubCallbackWrapperV1_2;
-using ::flatbuffers::FlatBufferBuilder;
-
-using V1_0::ContextHub;
-using V1_1::SettingValue;
-using V1_2::IContexthub;
-
-// Aliased for consistency with the way these symbols are referenced in
-// CHRE-side code
-namespace fbs = ::chre::fbs;
-
-Return<void> GenericContextHubV1_2::getHubs_1_2(
- IContexthub::getHubs_1_2_cb _hidl_cb) {
- std::vector<ContextHub> retHubs;
- getHubs([&retHubs](std::vector<ContextHub> hubs) { retHubs = hubs; });
- _hidl_cb(retHubs, kSupportedPermissions);
-
- return Void();
-}
-
-Return<Result> GenericContextHubV1_2::registerCallback_1_2(
- uint32_t hubId, const sp<IContexthubCallback> &cb) {
- sp<IContextHubCallbackWrapperBase> wrappedCallback;
- if (cb != nullptr) {
- wrappedCallback = new IContextHubCallbackWrapperV1_2(cb);
- }
- return registerCallbackCommon(hubId, wrappedCallback);
-}
-
-Return<void> GenericContextHubV1_2::onSettingChanged(V1_1::Setting setting,
- SettingValue newValue) {
- return onSettingChanged_1_2(reinterpret_cast<V1_2::Setting &>(setting),
- newValue);
-}
-
-Return<void> GenericContextHubV1_2::onSettingChanged_1_2(
- Setting setting, SettingValue newValue) {
- fbs::Setting fbsSetting;
- fbs::SettingState fbsState;
- if (getFbsSetting(setting, &fbsSetting) &&
- getFbsSettingValue(newValue, &fbsState)) {
- FlatBufferBuilder builder(64);
- HostProtocolHost::encodeSettingChangeNotification(builder, fbsSetting,
- fbsState);
- mClient.sendMessage(builder.GetBufferPointer(), builder.GetSize());
- }
-
- return Void();
-}
-
-} // namespace implementation
-} // namespace V1_2
-} // namespace contexthub
-} // namespace hardware
-} // namespace android
diff --git a/host/hal_generic/V1_2/generic_context_hub_v1_2.h b/host/hal_generic/V1_2/generic_context_hub_v1_2.h
deleted file mode 100644
index 6f6f4155..00000000
--- a/host/hal_generic/V1_2/generic_context_hub_v1_2.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 ANDROID_HARDWARE_CONTEXTHUB_V1_2_CONTEXTHUB_H
-#define ANDROID_HARDWARE_CONTEXTHUB_V1_2_CONTEXTHUB_H
-
-#include "generic_context_hub_base.h"
-
-#include <condition_variable>
-#include <functional>
-#include <mutex>
-#include <optional>
-
-#include <android/hardware/contexthub/1.2/IContexthub.h>
-#include <hidl/MQDescriptor.h>
-#include <hidl/Status.h>
-
-#include "chre_host/fragmented_load_transaction.h"
-#include "chre_host/host_protocol_host.h"
-#include "chre_host/socket_client.h"
-
-namespace android {
-namespace hardware {
-namespace contexthub {
-namespace V1_2 {
-namespace implementation {
-
-using ::android::hardware::contexthub::common::implementation::
- GenericContextHubBase;
-using ::android::hardware::contexthub::V1_0::Result;
-
-class GenericContextHubV1_2 : public GenericContextHubBase<V1_2::IContexthub> {
- public:
- Return<void> getHubs_1_2(V1_2::IContexthub::getHubs_1_2_cb _hidl_cb) override;
-
- Return<Result> registerCallback_1_2(
- uint32_t hubId, const sp<IContexthubCallback> &cb) override;
-
- Return<void> onSettingChanged(V1_1::Setting setting,
- V1_1::SettingValue newValue) override;
-
- Return<void> onSettingChanged_1_2(V1_2::Setting setting,
- V1_1::SettingValue newValue) override;
-};
-
-} // namespace implementation
-} // namespace V1_2
-} // namespace contexthub
-} // namespace hardware
-} // namespace android
-
-#endif // ANDROID_HARDWARE_CONTEXTHUB_V1_2_CONTEXTHUB_H
diff --git a/host/hal_generic/V1_2/service.cc b/host/hal_generic/V1_2/service.cc
deleted file mode 100644
index 334511da..00000000
--- a/host/hal_generic/V1_2/service.cc
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-#define LOG_TAG "android.hardware.contexthub@1.2-service"
-
-#include <android/hardware/contexthub/1.2/IContexthub.h>
-#include <hidl/HidlTransportSupport.h>
-#include <log/log.h>
-#include <utils/StrongPointer.h>
-#include "generic_context_hub_v1_2.h"
-
-using android::hardware::configureRpcThreadpool;
-using android::hardware::joinRpcThreadpool;
-using android::hardware::contexthub::V1_2::IContexthub;
-using android::hardware::contexthub::V1_2::implementation::
- GenericContextHubV1_2;
-
-int main() {
- configureRpcThreadpool(1, true);
-
- android::sp<IContexthub> contexthub = new GenericContextHubV1_2();
- if (contexthub->registerAsService() != ::android::OK) {
- ALOGE("Failed to register Contexthub HAL instance");
- return 1;
- }
-
- joinRpcThreadpool();
- return 1;
-}
diff --git a/host/hal_generic/common/context_hub_settings_util.cc b/host/hal_generic/common/context_hub_settings_util.cc
deleted file mode 100644
index c3f48989..00000000
--- a/host/hal_generic/common/context_hub_settings_util.cc
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-#define LOG_TAG "ContextHubHal"
-#define LOG_NDEBUG 0
-
-#include "context_hub_settings_util.h"
-
-#include <log/log.h>
-#include <unistd.h>
-
-namespace android {
-namespace hardware {
-namespace contexthub {
-namespace common {
-namespace implementation {
-
-// Aliased for consistency with the way these symbols are referenced in
-// CHRE-side code
-namespace fbs = ::chre::fbs;
-
-using ::android::hardware::contexthub::V1_1::SettingValue;
-using ::android::hardware::contexthub::V1_2::Setting;
-
-static_assert(sizeof(::android::hardware::contexthub::V1_1::Setting) ==
- sizeof(Setting),
- "New and old Setting types must have the same size");
-
-bool getFbsSetting(const Setting &setting, fbs::Setting *fbsSetting) {
- bool foundSetting = true;
-
- switch (setting) {
- case Setting::LOCATION:
- *fbsSetting = fbs::Setting::LOCATION;
- break;
- case Setting::WIFI_AVAILABLE:
- *fbsSetting = fbs::Setting::WIFI_AVAILABLE;
- break;
- case Setting::AIRPLANE_MODE:
- *fbsSetting = fbs::Setting::AIRPLANE_MODE;
- break;
- case Setting::MICROPHONE:
- *fbsSetting = fbs::Setting::MICROPHONE;
- break;
- default:
- foundSetting = false;
- ALOGE("Setting update with invalid enum value %hhu", setting);
- break;
- }
-
- return foundSetting;
-}
-
-bool getFbsSettingValue(const SettingValue &newValue,
- fbs::SettingState *fbsState) {
- bool foundSettingValue = true;
-
- switch (newValue) {
- case SettingValue::ENABLED:
- *fbsState = fbs::SettingState::ENABLED;
- break;
- case SettingValue::DISABLED:
- *fbsState = fbs::SettingState::DISABLED;
- break;
- default:
- foundSettingValue = false;
- ALOGE("Setting value update with invalid enum value %hhu", newValue);
- break;
- }
-
- return foundSettingValue;
-}
-
-} // namespace implementation
-} // namespace common
-} // namespace contexthub
-} // namespace hardware
-} // namespace android
diff --git a/host/hal_generic/common/context_hub_settings_util.h b/host/hal_generic/common/context_hub_settings_util.h
deleted file mode 100644
index cffc8184..00000000
--- a/host/hal_generic/common/context_hub_settings_util.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 ANDROID_HARDWARE_CONTEXTHUB_COMMON_CONTEXT_HUB_SETTINGS_UTIL_H
-#define ANDROID_HARDWARE_CONTEXTHUB_COMMON_CONTEXT_HUB_SETTINGS_UTIL_H
-
-#include <cinttypes>
-
-#include <android/hardware/contexthub/1.1/IContexthub.h>
-#include <android/hardware/contexthub/1.2/IContexthub.h>
-
-#include "chre_host/host_protocol_host.h"
-
-namespace android {
-namespace hardware {
-namespace contexthub {
-namespace common {
-namespace implementation {
-
-/**
- * @param setting The HAL Setting (<= v1.2).
- * @param fbsSetting A non-null pointer where the corresponding flatbuffers
- * settings value will be stored.
- *
- * @return true if the flatbuffers setting value was found and populated.
- */
-bool getFbsSetting(
- const ::android::hardware::contexthub::V1_2::Setting &setting,
- ::chre::fbs::Setting *fbsSetting);
-
-/**
- * @param setting The HAL v1.1 SettingValue.
- * @param fbsSetting A non-null pointer where the corresponding flatbuffers
- * setting state value will be stored.
- *
- * @return true if the flatbuffers setting state value was found and populated.
- */
-bool getFbsSettingValue(
- const ::android::hardware::contexthub::V1_1::SettingValue &newValue,
- ::chre::fbs::SettingState *fbsState);
-
-} // namespace implementation
-} // namespace common
-} // namespace contexthub
-} // namespace hardware
-} // namespace android
-
-#endif // ANDROID_HARDWARE_CONTEXTHUB_COMMON_CONTEXT_HUB_SETTINGS_UTIL_H
diff --git a/host/hal_generic/common/generic_context_hub_base.h b/host/hal_generic/common/generic_context_hub_base.h
index 572561e6..81514e55 100644
--- a/host/hal_generic/common/generic_context_hub_base.h
+++ b/host/hal_generic/common/generic_context_hub_base.h
@@ -27,11 +27,9 @@
#include <hidl/Status.h>
#include <log/log.h>
-#include "IContextHubCallbackWrapper.h"
#include "chre_host/fragmented_load_transaction.h"
#include "chre_host/host_protocol_host.h"
#include "chre_host/socket_client.h"
-#include "permissions_util.h"
namespace android {
namespace hardware {
@@ -48,20 +46,14 @@ using ::android::hardware::hidl_handle;
using ::android::hardware::hidl_string;
using ::android::hardware::hidl_vec;
using ::android::hardware::Return;
-using ::android::hardware::contexthub::common::implementation::
- chreToAndroidPermissions;
using ::android::hardware::contexthub::V1_0::AsyncEventType;
using ::android::hardware::contexthub::V1_0::ContextHub;
+using ::android::hardware::contexthub::V1_0::ContextHubMsg;
+using ::android::hardware::contexthub::V1_0::HubAppInfo;
using ::android::hardware::contexthub::V1_0::IContexthubCallback;
using ::android::hardware::contexthub::V1_0::NanoAppBinary;
using ::android::hardware::contexthub::V1_0::Result;
using ::android::hardware::contexthub::V1_0::TransactionResult;
-using ::android::hardware::contexthub::V1_2::ContextHubMsg;
-using ::android::hardware::contexthub::V1_2::HubAppInfo;
-using ::android::hardware::contexthub::V1_X::implementation::
- IContextHubCallbackWrapperBase;
-using ::android::hardware::contexthub::V1_X::implementation::
- IContextHubCallbackWrapperV1_0;
using ::flatbuffers::FlatBufferBuilder;
constexpr uint32_t kDefaultHubId = 0;
@@ -180,16 +172,6 @@ class GenericContextHubBase : public IContexthubT {
Return<Result> registerCallback(uint32_t hubId,
const sp<IContexthubCallback> &cb) override {
- sp<IContextHubCallbackWrapperBase> wrappedCallback;
- if (cb != nullptr) {
- wrappedCallback = new IContextHubCallbackWrapperV1_0(cb);
- }
- return registerCallbackCommon(hubId, wrappedCallback);
- }
-
- // Common logic shared between pre-V1.2 and V1.2 HALs.
- Return<Result> registerCallbackCommon(
- uint32_t hubId, const sp<IContextHubCallbackWrapperBase> &cb) {
Result result;
ALOGV("%s", __func__);
@@ -218,7 +200,7 @@ class GenericContextHubBase : public IContexthubT {
}
Return<Result> sendMessageToHub(uint32_t hubId,
- const V1_0::ContextHubMsg &msg) override {
+ const ContextHubMsg &msg) override {
Result result;
ALOGV("%s", __func__);
@@ -257,8 +239,8 @@ class GenericContextHubBase : public IContexthubT {
uint32_t targetApiVersion = (appBinary.targetChreApiMajorVersion << 24) |
(appBinary.targetChreApiMinorVersion << 16);
mPendingLoadTransaction = FragmentedLoadTransaction(
- transactionId, appBinary.appId, appBinary.appVersion, appBinary.flags,
- targetApiVersion, appBinary.customBinary);
+ transactionId, appBinary.appId, appBinary.appVersion,
+ targetApiVersion, appBinary.customBinary, kLoadFragmentSizeBytes);
result =
sendFragmentedLoadNanoAppRequest(mPendingLoadTransaction.value());
@@ -337,7 +319,7 @@ class GenericContextHubBase : public IContexthubT {
protected:
::android::chre::SocketClient mClient;
- sp<IContextHubCallbackWrapperBase> mCallbacks;
+ sp<IContexthubCallback> mCallbacks;
std::mutex mCallbacksLock;
class SocketCallbacks : public ::android::chre::SocketClient::ICallbacks,
@@ -368,20 +350,13 @@ class GenericContextHubBase : public IContexthubT {
void handleNanoappMessage(
const ::chre::fbs::NanoappMessageT &message) override {
ContextHubMsg msg;
- msg.msg_1_0.appName = message.app_id;
- msg.msg_1_0.hostEndPoint = message.host_endpoint;
- msg.msg_1_0.msgType = message.message_type;
- msg.msg_1_0.msg = message.message;
- // Set of nanoapp permissions required to communicate with this nanoapp.
- msg.permissions = chreToAndroidPermissions(message.permissions);
- // Set of permissions required to consume this message and what will be
- // attributed when the host endpoint consumes this on the Android side.
- hidl_vec<hidl_string> msgContentPerms =
- chreToAndroidPermissions(message.message_permissions);
+ msg.appName = message.app_id;
+ msg.hostEndPoint = message.host_endpoint;
+ msg.msgType = message.message_type;
+ msg.msg = message.message;
- invokeClientCallback([&]() {
- return mParent.mCallbacks->handleClientMsg(msg, msgContentPerms);
- });
+ invokeClientCallback(
+ [&]() { return mParent.mCallbacks->handleClientMsg(msg); });
}
void handleHubInfoResponse(
@@ -434,17 +409,15 @@ class GenericContextHubBase : public IContexthubT {
continue;
}
- ALOGV("App 0x%016" PRIx64 " ver 0x%" PRIx32 " permissions 0x%" PRIx32
- " enabled %d system %d",
- nanoapp->app_id, nanoapp->version, nanoapp->permissions,
- nanoapp->enabled, nanoapp->is_system);
+ ALOGV("App 0x%016" PRIx64 " ver 0x%" PRIx32 " enabled %d system %d",
+ nanoapp->app_id, nanoapp->version, nanoapp->enabled,
+ nanoapp->is_system);
if (!nanoapp->is_system) {
HubAppInfo appInfo;
- appInfo.info_1_0.appId = nanoapp->app_id;
- appInfo.info_1_0.version = nanoapp->version;
- appInfo.info_1_0.enabled = nanoapp->enabled;
- appInfo.permissions = chreToAndroidPermissions(nanoapp->permissions);
+ appInfo.appId = nanoapp->app_id;
+ appInfo.version = nanoapp->version;
+ appInfo.enabled = nanoapp->enabled;
appInfoList.push_back(appInfo);
}
@@ -596,6 +569,9 @@ class GenericContextHubBase : public IContexthubT {
std::optional<FragmentedLoadTransaction> mPendingLoadTransaction;
std::mutex mPendingLoadTransactionMutex;
+ // Use 30KB fragment size to fit within 32KB memory fragments at the kernel
+ static constexpr size_t kLoadFragmentSizeBytes = 30 * 1024;
+
// Write a string to mDebugFd
void writeToDebugFile(const char *str) {
writeToDebugFile(str, strlen(str));
diff --git a/host/hal_generic/common/permissions_util.cc b/host/hal_generic/common/permissions_util.cc
deleted file mode 100644
index 31b987bd..00000000
--- a/host/hal_generic/common/permissions_util.cc
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 "permissions_util.h"
-
-#include "chre/util/macros.h"
-#include "chre/util/system/napp_permissions.h"
-
-namespace android {
-namespace hardware {
-namespace contexthub {
-namespace common {
-namespace implementation {
-
-hidl_vec<hidl_string> chreToAndroidPermissions(uint32_t chrePermissions) {
- std::vector<hidl_string> androidPermissions;
- if (BITMASK_HAS_VALUE(chrePermissions,
- ::chre::NanoappPermissions::CHRE_PERMS_AUDIO)) {
- androidPermissions.push_back(kRecordAudioPerm);
- }
-
- if (BITMASK_HAS_VALUE(chrePermissions,
- ::chre::NanoappPermissions::CHRE_PERMS_GNSS) ||
- BITMASK_HAS_VALUE(chrePermissions,
- ::chre::NanoappPermissions::CHRE_PERMS_WIFI) ||
- BITMASK_HAS_VALUE(chrePermissions,
- ::chre::NanoappPermissions::CHRE_PERMS_WWAN)) {
- androidPermissions.push_back(kFineLocationPerm);
- androidPermissions.push_back(kBackgroundLocationPerm);
- }
-
- return hidl_vec(androidPermissions);
-}
-
-} // namespace implementation
-} // namespace common
-} // namespace contexthub
-} // namespace hardware
-} // namespace android
diff --git a/host/hal_generic/common/permissions_util.h b/host/hal_generic/common/permissions_util.h
deleted file mode 100644
index 3b19fc0e..00000000
--- a/host/hal_generic/common/permissions_util.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 ANDROID_HARDWARE_CONTEXTHUB_COMMON_PERMISSIONS_UTIL_H
-#define ANDROID_HARDWARE_CONTEXTHUB_COMMON_PERMISSIONS_UTIL_H
-
-#include <hidl/HidlSupport.h>
-
-namespace android {
-namespace hardware {
-namespace contexthub {
-namespace common {
-namespace implementation {
-
-// List of permissions supported by this HAL.
-const hidl_string kBackgroundLocationPerm =
- "android.permission.ACCESS_BACKGROUND_LOCATION";
-const hidl_string kFineLocationPerm = "android.permission.ACCESS_FINE_LOCATION";
-const hidl_string kRecordAudioPerm = "android.permission.RECORD_AUDIO";
-const hidl_vec<hidl_string> kSupportedPermissions = {
- kBackgroundLocationPerm, kFineLocationPerm, kRecordAudioPerm};
-
-//! Converts the CHRE permissions bitmask to a list of CHRE permissions.
-hidl_vec<hidl_string> chreToAndroidPermissions(uint32_t chrePermissions);
-
-} // namespace implementation
-} // namespace common
-} // namespace contexthub
-} // namespace hardware
-} // namespace android
-
-#endif // ANDROID_HARDWARE_CONTEXTHUB_COMMON_PERMISSIONS_UTIL_H
diff --git a/host/msm/daemon/chre_daemon.cc b/host/msm/daemon/chre_daemon.cc
new file mode 100644
index 00000000..f4b72102
--- /dev/null
+++ b/host/msm/daemon/chre_daemon.cc
@@ -0,0 +1,1067 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * 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.
+ */
+
+/**
+ * @file
+ * The daemon that hosts CHRE on a hexagon DSP via FastRPC. This is typically
+ * the SLPI but could be the ADSP or another DSP that supports FastRPC.
+ *
+ * Several threads are required for this functionality:
+ * - Main thread: blocked waiting on SIGINT/SIGTERM, and requests graceful
+ * shutdown of CHRE when caught
+ * - Monitor thread: persistently blocked in a FastRPC call to the DSP that
+ * only returns when CHRE exits or the DSP crashes
+ * - TODO: see whether we can merge this with the RX thread
+ * - Reverse monitor thread: after initializing the DSP-side monitor for this
+ * process, blocks on a condition variable. If this thread exits, CHRE on
+ * the DSP side will be notified and shut down (this is only possible if
+ * this thread is not blocked in a FastRPC call).
+ * - TODO: confirm this and see whether we can merge this responsibility
+ * into the TX thread
+ * - Message to host (RX) thread: blocks in FastRPC call, waiting on incoming
+ * message from CHRE
+ * - Message to CHRE (TX) thread: blocks waiting on outbound queue, delivers
+ * messages to CHRE over FastRPC
+ *
+ * TODO: This file originated from an implementation for another device, and was
+ * written in C, but then it was converted to C++ when adding socket support. It
+ * should be fully converted to C++.
+ */
+
+// Disable verbose logging
+// TODO: use property_get_bool to make verbose logging runtime configurable
+// #define LOG_NDEBUG 0
+
+#include <ctype.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <fstream>
+#include <queue>
+#include <string>
+
+#include "chre/platform/slpi/fastrpc.h"
+#include "chre_host/host_protocol_host.h"
+#include "chre_host/log.h"
+#include "chre_host/socket_server.h"
+#include "generated/chre_slpi.h"
+
+#include <android-base/logging.h>
+#include <json/json.h>
+#include <utils/SystemClock.h>
+
+#ifdef CHRE_USE_TOKENIZED_LOGGING
+#include "pw_tokenizer/detokenize.h"
+using pw::tokenizer::DetokenizedString;
+using pw::tokenizer::Detokenizer;
+#endif
+
+#ifdef CHRE_DAEMON_LOAD_INTO_SENSORSPD
+#include "remote.h"
+
+#define ITRANSPORT_PREFIX "'\":;./\\"
+#endif // CHRE_DAEMON_LOAD_INTO_SENSORSPD
+
+//! The format string to use for logs from the CHRE implementation.
+#define HUB_LOG_FORMAT_STR "@ %3" PRIu32 ".%03" PRIu32 ": [CHRE] %s"
+
+#ifndef UNUSED_VAR
+#define UNUSED_VAR(var) ((void)(var))
+#endif
+
+#ifdef CHRE_DAEMON_LPMA_ENABLED
+#include <android/hardware/soundtrigger/2.0/ISoundTriggerHw.h>
+#include <hardware_legacy/power.h>
+
+using android::sp;
+using android::wp;
+using android::hardware::Return;
+using android::hardware::soundtrigger::V2_0::ISoundTriggerHw;
+using android::hardware::soundtrigger::V2_0::SoundModelHandle;
+using android::hardware::soundtrigger::V2_0::SoundModelType;
+#endif // CHRE_DAEMON_LPMA_ENABLED
+
+using android::elapsedRealtimeNano;
+using android::chre::FragmentedLoadTransaction;
+using android::chre::HostProtocolHost;
+
+// Aliased for consistency with the way these symbols are referenced in
+// CHRE-side code
+namespace fbs = ::chre::fbs;
+
+typedef void *(thread_entry_point_f)(void *);
+
+struct reverse_monitor_thread_data {
+ pthread_t thread;
+ pthread_mutex_t mutex;
+ pthread_cond_t cond;
+};
+
+static void *chre_message_to_host_thread(void *arg);
+static void *chre_monitor_thread(void *arg);
+static bool start_thread(pthread_t *thread_handle,
+ thread_entry_point_f *thread_entry, void *arg);
+
+#ifdef CHRE_DAEMON_LPMA_ENABLED
+//! The name of the wakelock to use for the CHRE daemon.
+static const char kWakeLockName[] = "chre_daemon";
+
+//! Forward declarations
+static void onStHalServiceDeath();
+
+//! Class to handle when a connected ST HAL service dies.
+class StHalDeathRecipient : public android::hardware::hidl_death_recipient {
+ virtual void serviceDied(
+ uint64_t /* cookie */,
+ const wp<::android::hidl::base::V1_0::IBase> & /* who */) override {
+ LOGE("ST HAL service died.");
+ onStHalServiceDeath();
+ }
+};
+
+struct LpmaEnableThreadData {
+ pthread_t thread;
+ pthread_mutex_t mutex;
+ pthread_cond_t cond;
+ bool currentLpmaEnabled;
+ bool targetLpmaEnabled;
+ bool connectedToService;
+ sp<StHalDeathRecipient> deathRecipient = new StHalDeathRecipient();
+ sp<ISoundTriggerHw> stHalService;
+};
+
+static LpmaEnableThreadData lpmaEnableThread;
+
+#endif // CHRE_DAEMON_LPMA_ENABLED
+
+//! The host ID to use when preloading nanoapps. This is used before the server
+//! is started and is sufficiently high enough so as to not collide with any
+//! clients after the server starts.
+static const uint16_t kHostClientIdDaemon = UINT16_MAX;
+
+//! Contains a set of transaction IDs used to load the preloaded nanoapps.
+//! The IDs are stored in the order they are sent.
+static std::queue<uint32_t> gPreloadedNanoappPendingTransactionIds;
+
+//! Set to true when we request a graceful shutdown of CHRE
+static volatile bool chre_shutdown_requested = false;
+
+#if !defined(LOG_NDEBUG) || LOG_NDEBUG != 0
+static void log_buffer(const uint8_t * /*buffer*/, size_t /*size*/) {}
+#else
+static void log_buffer(const uint8_t *buffer, size_t size) {
+ char line[32];
+ int offset = 0;
+ char line_chars[32];
+ int offset_chars = 0;
+
+ size_t orig_size = size;
+ if (size > 128) {
+ size = 128;
+ LOGV("Dumping first 128 bytes of buffer of size %zu", orig_size);
+ } else {
+ LOGV("Dumping buffer of size %zu bytes", size);
+ }
+ for (size_t i = 1; i <= size; ++i) {
+ offset +=
+ snprintf(&line[offset], sizeof(line) - offset, "%02x ", buffer[i - 1]);
+ offset_chars +=
+ snprintf(&line_chars[offset_chars], sizeof(line_chars) - offset_chars,
+ "%c", (isprint(buffer[i - 1])) ? buffer[i - 1] : '.');
+ if ((i % 8) == 0) {
+ LOGV(" %s\t%s", line, line_chars);
+ offset = 0;
+ offset_chars = 0;
+ } else if ((i % 4) == 0) {
+ offset += snprintf(&line[offset], sizeof(line) - offset, " ");
+ }
+ }
+
+ if (offset > 0) {
+ char tabs[8];
+ char *pos = tabs;
+ while (offset < 28) {
+ *pos++ = '\t';
+ offset += 8;
+ }
+ *pos = '\0';
+ LOGV(" %s%s%s", line, tabs, line_chars);
+ }
+}
+#endif
+
+#ifdef CHRE_USE_TOKENIZED_LOGGING
+static android_LogPriority chreLogLevelToAndroidLogPriority(uint8_t level) {
+ switch (level) {
+ case CHRE_LOG_LEVEL_ERROR:
+ return ANDROID_LOG_ERROR;
+ case CHRE_LOG_LEVEL_WARN:
+ return ANDROID_LOG_WARN;
+ case CHRE_LOG_LEVEL_INFO:
+ return ANDROID_LOG_INFO;
+ case CHRE_LOG_LEVEL_DEBUG:
+ return ANDROID_LOG_DEBUG;
+ default:
+ return ANDROID_LOG_SILENT;
+ }
+}
+
+void emitLogMessage(uint8_t level, uint64_t timestampNanos, const char *log) {
+ constexpr const char kLogTag[] = "CHRE";
+ constexpr const uint64_t kNanosPerSec = 1e9;
+ constexpr const uint64_t kNanosPerMsec = 1e6;
+
+ uint32_t timeSec = timestampNanos / kNanosPerSec;
+ timestampNanos -= (timeSec * kNanosPerSec);
+
+ uint32_t timeMsec = timestampNanos / kNanosPerMsec;
+
+ android_LogPriority priority = chreLogLevelToAndroidLogPriority(level);
+ LOG_PRI(priority, kLogTag, HUB_LOG_FORMAT_STR, timeSec, timeMsec, log);
+}
+
+void parseAndEmitTokenizedLogMessages(unsigned char *message,
+ unsigned int messageLen,
+ const Detokenizer *detokenizer) {
+ if (detokenizer != nullptr) {
+ // TODO: Pull out common code from the tokenized/standard log
+ // parser functions when we implement batching for tokenized
+ // logs (b/148873804)
+ constexpr size_t kLogMessageHeaderSize =
+ 1 /*logLevel*/ + sizeof(uint64_t) /*timestamp*/;
+
+ const fbs::MessageContainer *container = fbs::GetMessageContainer(message);
+ const auto *logMessage =
+ static_cast<const fbs::LogMessage *>(container->message());
+
+ const flatbuffers::Vector<int8_t> &logData = *logMessage->buffer();
+ const uint8_t *log = reinterpret_cast<const uint8_t *>(logData.data());
+ uint8_t level = *log;
+ ++log;
+
+ uint64_t timestampNanos;
+ memcpy(&timestampNanos, log, sizeof(uint64_t));
+ timestampNanos = le64toh(timestampNanos);
+ log += sizeof(uint64_t);
+
+ DetokenizedString detokenizedLog =
+ detokenizer->Detokenize(log, messageLen - kLogMessageHeaderSize);
+ std::string decodedLog = detokenizedLog.BestStringWithErrors();
+ emitLogMessage(level, timestampNanos, decodedLog.c_str());
+ } else {
+ // log an error and risk log spam? fail silently? log once?
+ }
+}
+
+#endif
+
+static int64_t getTimeOffset(bool *success) {
+ int64_t timeOffset = 0;
+
+#if defined(__aarch64__)
+ // Reads the system time counter (CNTVCT) and its frequency (CNTFRQ)
+ // CNTVCT is used in the sensors HAL for time synchronization.
+ // More information can be found in the ARM reference manual
+ // (http://infocenter.arm.com/help/index.jsp?topic=
+ // /com.arm.doc.100048_0002_05_en/jfa1406793266982.html)
+ // Use uint64_t to store since the MRS instruction uses 64 bit (X) registers
+ // (http://infocenter.arm.com/help/topic/
+ // com.arm.doc.den0024a/ch06s05s02.html)
+ uint64_t qTimerCount = 0, qTimerFreq = 0;
+ uint64_t hostTimeNano = elapsedRealtimeNano();
+ asm volatile("mrs %0, cntvct_el0" : "=r"(qTimerCount));
+ asm volatile("mrs %0, cntfrq_el0" : "=r"(qTimerFreq));
+
+ constexpr uint64_t kOneSecondInNanoseconds = 1000000000;
+ if (qTimerFreq != 0) {
+ // Get the seconds part first, then convert the remainder to prevent
+ // overflow
+ uint64_t qTimerNanos = (qTimerCount / qTimerFreq);
+ if (qTimerNanos > UINT64_MAX / kOneSecondInNanoseconds) {
+ LOGE(
+ "CNTVCT_EL0 conversion to nanoseconds overflowed during time sync."
+ " Aborting time sync.");
+ *success = false;
+ } else {
+ qTimerNanos *= kOneSecondInNanoseconds;
+
+ // Round the remainder portion to the nearest nanosecond
+ uint64_t remainder = (qTimerCount % qTimerFreq);
+ qTimerNanos +=
+ (remainder * kOneSecondInNanoseconds + qTimerFreq / 2) / qTimerFreq;
+
+ timeOffset = hostTimeNano - qTimerNanos;
+ *success = true;
+ }
+ } else {
+ LOGE("CNTFRQ_EL0 had 0 value. Aborting time sync.");
+ *success = false;
+ }
+#else
+#error "Unsupported CPU architecture type"
+#endif
+
+ return timeOffset;
+}
+
+/**
+ * @param logOnError If true, logs an error message on failure.
+ *
+ * @return true if the time sync message was successfully sent to CHRE.
+ */
+static bool sendTimeSyncMessage(bool logOnError) {
+ bool timeSyncSuccess = true;
+ int64_t timeOffset = getTimeOffset(&timeSyncSuccess);
+
+ if (timeSyncSuccess) {
+ flatbuffers::FlatBufferBuilder builder(64);
+ HostProtocolHost::encodeTimeSyncMessage(builder, timeOffset);
+ int success = chre_slpi_deliver_message_from_host(
+ static_cast<const unsigned char *>(builder.GetBufferPointer()),
+ static_cast<int>(builder.GetSize()));
+
+ if (success != 0) {
+ if (logOnError) {
+ LOGE("Failed to deliver time sync message from host to CHRE: %d",
+ success);
+ }
+ timeSyncSuccess = false;
+ }
+ }
+
+ return timeSyncSuccess;
+}
+
+/**
+ * Sends a time sync message to CHRE, retrying a specified time until success.
+ *
+ * @param maxNumRetries The number of times to retry sending the message
+ *
+ * @return true if the time sync message was successfully sent to CHRE.
+ */
+static bool sendTimeSyncMessageRetry(size_t maxNumRetries) {
+ size_t numRetries = 0;
+ useconds_t retryDelayUs = 50000; // 50 ms initially
+ bool success = sendTimeSyncMessage(numRetries == maxNumRetries);
+ while (!success && numRetries < maxNumRetries) {
+ usleep(retryDelayUs);
+ numRetries++;
+ retryDelayUs *= 2;
+ success = sendTimeSyncMessage(numRetries == maxNumRetries);
+ }
+
+ return success;
+}
+
+#ifdef CHRE_DAEMON_LPMA_ENABLED
+
+static void acquireWakeLock() {
+ if (acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLockName) != 0) {
+ LOGE("Failed to acquire wakelock");
+ }
+}
+
+static void releaseWakeLock() {
+ static bool initialRelease = true;
+
+ // It's expected to get an error when we first try to release the wakelock
+ // as it won't exist unless it was leaked previously - don't output a
+ // false warning for this case
+ if (release_wake_lock(kWakeLockName) != 0 && !initialRelease) {
+ LOGE("Failed to release wakelock");
+ }
+
+ initialRelease = false;
+}
+
+/**
+ * Sets the target state for LPMA to be enabled. This triggers another thread to
+ * perform the async operation of enabling or disabling the LPMA use case.
+ *
+ * @param enabled Whether LPMA is to be enabled or disabled.
+ */
+static void setLpmaState(bool enabled) {
+ pthread_mutex_lock(&lpmaEnableThread.mutex);
+ lpmaEnableThread.targetLpmaEnabled = enabled;
+ pthread_mutex_unlock(&lpmaEnableThread.mutex);
+ pthread_cond_signal(&lpmaEnableThread.cond);
+}
+
+static void onStHalServiceDeath() {
+ pthread_mutex_lock(&lpmaEnableThread.mutex);
+ lpmaEnableThread.connectedToService = false;
+ if (lpmaEnableThread.targetLpmaEnabled) {
+ // ST HAL has died, so assume that the sound model is no longer active,
+ // and trigger a reload of the sound model.
+ lpmaEnableThread.currentLpmaEnabled = false;
+ pthread_cond_signal(&lpmaEnableThread.cond);
+ }
+ pthread_mutex_unlock(&lpmaEnableThread.mutex);
+}
+
+/**
+ * Connects to the ST HAL service, if not already. This method should only
+ * be invoked after acquiring the lpmaEnableThread.mutex lock.
+ *
+ * @return true if successfully connected to the HAL.
+ */
+static bool connectToStHalServiceLocked() {
+ if (!lpmaEnableThread.connectedToService) {
+ lpmaEnableThread.stHalService = ISoundTriggerHw::getService();
+ if (lpmaEnableThread.stHalService != nullptr) {
+ LOGI("Connected to ST HAL service");
+ lpmaEnableThread.connectedToService = true;
+ lpmaEnableThread.stHalService->linkToDeath(
+ lpmaEnableThread.deathRecipient, 0 /* flags */);
+ }
+ }
+
+ return lpmaEnableThread.connectedToService;
+}
+
+/**
+ * Loads the LPMA use case via the SoundTrigger HAL HIDL service.
+ *
+ * @param lpmaHandle The handle that was generated as a result of enabling
+ * the LPMA use case successfully.
+ * @return true if LPMA was enabled successfully, false otherwise.
+ */
+static bool loadLpma(SoundModelHandle *lpmaHandle) {
+ LOGD("Loading LPMA");
+
+ ISoundTriggerHw::SoundModel soundModel;
+ soundModel.type = SoundModelType::GENERIC;
+ soundModel.vendorUuid.timeLow = 0x57CADDB1;
+ soundModel.vendorUuid.timeMid = 0xACDB;
+ soundModel.vendorUuid.versionAndTimeHigh = 0x4DCE;
+ soundModel.vendorUuid.variantAndClockSeqHigh = 0x8CB0;
+
+ const uint8_t uuidNode[6] = {0x2E, 0x95, 0xA2, 0x31, 0x3A, 0xEE};
+ memcpy(&soundModel.vendorUuid.node[0], uuidNode, sizeof(uuidNode));
+ soundModel.data.resize(1); // Insert a dummy byte to bypass HAL NULL checks.
+
+ bool loaded = false;
+ if (!connectToStHalServiceLocked()) {
+ LOGE("Failed to get ST HAL service for LPMA load");
+ } else {
+ int32_t loadResult;
+ Return<void> hidlResult = lpmaEnableThread.stHalService->loadSoundModel(
+ soundModel, NULL /* callback */, 0 /* cookie */,
+ [&](int32_t retval, SoundModelHandle handle) {
+ loadResult = retval;
+ *lpmaHandle = handle;
+ });
+
+ if (hidlResult.isOk()) {
+ if (loadResult == 0) {
+ LOGI("Loaded LPMA");
+ loaded = true;
+ } else {
+ LOGE("Failed to load LPMA with %" PRId32, loadResult);
+ }
+ } else {
+ LOGE("Failed to load LPMA due to hidl error %s",
+ hidlResult.description().c_str());
+ }
+ }
+
+ return loaded;
+}
+
+/**
+ * Unloads the LPMA use case via the SoundTrigger HAL HIDL service. This
+ * function does not indicate success/failure as it is expected that even in the
+ * event of a failure to unload, the use case will be unloaded. As long as the
+ * sound trigger HAL received the request we can be assured that the use case
+ * will be unloaded (even if it means reseting the codec or otherwise).
+ *
+ * @param lpmaHandle A handle that was previously produced by the setLpmaEnabled
+ * function. This is the handle that is unloaded from the ST HAL to
+ * disable LPMA.
+ */
+static void unloadLpma(SoundModelHandle lpmaHandle) {
+ LOGD("Unloading LPMA");
+
+ if (!connectToStHalServiceLocked()) {
+ LOGE("Failed to get ST HAL service for LPMA unload");
+ } else {
+ Return<int32_t> hidlResult =
+ lpmaEnableThread.stHalService->unloadSoundModel(lpmaHandle);
+
+ if (hidlResult.isOk()) {
+ if (hidlResult == 0) {
+ LOGI("Unloaded LPMA");
+ } else {
+ LOGE("Failed to unload LPMA with %" PRId32, int32_t(hidlResult));
+ }
+ } else {
+ LOGE("Failed to unload LPMA due to hidl error %s",
+ hidlResult.description().c_str());
+ }
+ }
+}
+
+static void *chreLpmaEnableThread(void *arg) {
+ auto *state = static_cast<LpmaEnableThreadData *>(arg);
+
+ const useconds_t kInitialRetryDelayUs = 500000;
+ const int kRetryGrowthFactor = 2;
+ const int kRetryGrowthLimit = 5; // Terminates at 8s retry interval.
+ const int kRetryWakeLockLimit = 10; // Retry with a wakelock 10 times.
+
+ int retryCount = 0;
+ useconds_t retryDelay = 0;
+ SoundModelHandle lpmaHandle;
+
+ while (true) {
+ pthread_mutex_lock(&state->mutex);
+ if (state->currentLpmaEnabled == state->targetLpmaEnabled) {
+ retryCount = 0;
+ retryDelay = 0;
+ releaseWakeLock(); // Allow the system to suspend while waiting.
+ pthread_cond_wait(&state->cond, &state->mutex);
+ acquireWakeLock(); // Ensure the system stays up while retrying.
+ } else if (state->targetLpmaEnabled && loadLpma(&lpmaHandle)) {
+ state->currentLpmaEnabled = state->targetLpmaEnabled;
+ } else if (!state->targetLpmaEnabled) {
+ // Regardless of whether the use case fails to unload, set the
+ // currentLpmaEnabled to the targetLpmaEnabled. This will allow the next
+ // enable request to proceed. After a failure to unload occurs, the
+ // supplied handle is invalid and should not be unloaded again.
+ unloadLpma(lpmaHandle);
+ state->currentLpmaEnabled = state->targetLpmaEnabled;
+ } else {
+ // Unlock while delaying to avoid blocking the client thread. No shared
+ // state is modified here.
+ pthread_mutex_unlock(&state->mutex);
+
+ if (retryDelay == 0) {
+ retryDelay = kInitialRetryDelayUs;
+ } else if (retryCount < kRetryGrowthLimit) {
+ retryDelay *= kRetryGrowthFactor;
+ }
+
+ LOGD("Delaying retry %d for %uus", retryCount, retryDelay);
+ usleep(retryDelay);
+
+ retryCount++;
+ if (retryCount > kRetryWakeLockLimit) {
+ releaseWakeLock();
+ }
+
+ pthread_mutex_lock(&state->mutex);
+ }
+
+ pthread_mutex_unlock(&state->mutex);
+ }
+
+ LOGV("LPMA enable thread exited");
+ return NULL;
+}
+
+/**
+ * Initializes the data shared with the LPMA enable thread and starts the
+ * thread.
+ *
+ * @param data Pointer to structure containing the (uninitialized) condition
+ * variable and associated data passed to the LPMA enable thread.
+ * @return true on success, false otherwise.
+ */
+static bool initLpmaEnableThread(LpmaEnableThreadData *data) {
+ bool success = false;
+ int ret;
+
+ if ((ret = pthread_mutex_init(&data->mutex, NULL)) != 0) {
+ LOG_ERROR("Failed to initialize lpma enable mutex", ret);
+ } else if ((ret = pthread_cond_init(&data->cond, NULL)) != 0) {
+ LOG_ERROR("Failed to initialize lpma enable condition variable", ret);
+ } else if (!start_thread(&data->thread, chreLpmaEnableThread, data)) {
+ LOGE("Couldn't start lpma enable thread");
+ } else {
+ data->currentLpmaEnabled = false;
+ data->targetLpmaEnabled = false;
+ success = true;
+ }
+
+ return success;
+}
+
+#endif // CHRE_DAEMON_LPMA_ENABLED
+
+/**
+ * Sends a message to CHRE.
+ *
+ * @param clientId The client ID that this message originates from.
+ * @param data The data to pass down.
+ * @param length The size of the data to send.
+ * @return true if successful, false otherwise.
+ */
+static bool sendMessageToChre(uint16_t clientId, void *data, size_t length) {
+ constexpr size_t kMaxPayloadSize = 1024 * 1024; // 1 MiB
+
+ // This limitation is due to FastRPC, but there's no case where we should come
+ // close to this limit...
+ static_assert(kMaxPayloadSize <= INT32_MAX,
+ "DSP uses 32-bit signed integers to represent message size");
+
+ bool success = false;
+ if (length > kMaxPayloadSize) {
+ LOGE("Message too large (got %zu, max %zu bytes)", length, kMaxPayloadSize);
+ } else if (!HostProtocolHost::mutateHostClientId(data, length, clientId)) {
+ LOGE("Couldn't set host client ID in message container!");
+ } else {
+ LOGV("Delivering message from host (size %zu)", length);
+ log_buffer(static_cast<const uint8_t *>(data), length);
+ int ret = chre_slpi_deliver_message_from_host(
+ static_cast<const unsigned char *>(data), static_cast<int>(length));
+ if (ret != 0) {
+ LOGE("Failed to deliver message from host to CHRE: %d", ret);
+ } else {
+ success = true;
+ }
+ }
+
+ return success;
+}
+
+/**
+ * Loads a nanoapp by sending the nanoapp filename to the CHRE framework. This
+ * method will return after sending the request so no guarantee is made that
+ * the nanoapp is loaded until after the response is received.
+ *
+ * @param appId The ID of the nanoapp to load.
+ * @param appVersion The version of the nanoapp to load.
+ * @param appTargetApiVersion The version of the CHRE API that the app targets.
+ * @param appBinaryName The name of the binary as stored in the filesystem. This
+ * will be used to load the nanoapp into CHRE.
+ * @param transactionId The transaction ID to use when loading.
+ * @return true if a request was successfully sent, false otherwise.
+ */
+static bool sendNanoappLoad(uint64_t appId, uint32_t appVersion,
+ uint32_t appTargetApiVersion,
+ const std::string &appBinaryName,
+ uint32_t transactionId) {
+ flatbuffers::FlatBufferBuilder builder;
+ HostProtocolHost::encodeLoadNanoappRequestForFile(
+ builder, transactionId, appId, appVersion, appTargetApiVersion,
+ appBinaryName.c_str());
+
+ bool success = sendMessageToChre(
+ kHostClientIdDaemon, builder.GetBufferPointer(), builder.GetSize());
+
+ if (!success) {
+ LOGE("Failed to send nanoapp filename.");
+ } else {
+ gPreloadedNanoappPendingTransactionIds.push(transactionId);
+ }
+
+ return success;
+}
+
+/**
+ * Sends a preloaded nanoapp filename / metadata to CHRE.
+ *
+ * @param header The nanoapp header binary blob.
+ * @param nanoappName The filename of the nanoapp to be loaded.
+ * @param transactionId The transaction ID to use when loading the app.
+ * @return true if successful, false otherwise.
+ */
+static bool loadNanoapp(const std::vector<uint8_t> &header,
+ const std::string &nanoappName,
+ uint32_t transactionId) {
+ // This struct comes from build/build_template.mk and must not be modified.
+ // Refer to that file for more details.
+ struct NanoAppBinaryHeader {
+ uint32_t headerVersion;
+ uint32_t magic;
+ uint64_t appId;
+ uint32_t appVersion;
+ uint32_t flags;
+ uint64_t hwHubType;
+ uint8_t targetChreApiMajorVersion;
+ uint8_t targetChreApiMinorVersion;
+ uint8_t reserved[6];
+ } __attribute__((packed));
+
+ bool success = false;
+ if (header.size() != sizeof(NanoAppBinaryHeader)) {
+ LOGE("Header size mismatch");
+ } else {
+ // The header blob contains the struct above.
+ const auto *appHeader =
+ reinterpret_cast<const NanoAppBinaryHeader *>(header.data());
+
+ // Build the target API version from major and minor.
+ uint32_t targetApiVersion = (appHeader->targetChreApiMajorVersion << 24) |
+ (appHeader->targetChreApiMinorVersion << 16);
+
+ success = sendNanoappLoad(appHeader->appId, appHeader->appVersion,
+ targetApiVersion, nanoappName, transactionId);
+ }
+
+ return success;
+}
+
+/**
+ * Loads the supplied file into the provided buffer.
+ *
+ * @param filename The name of the file to load.
+ * @param buffer The buffer to load into.
+ * @return true if successful, false otherwise.
+ */
+static bool readFileContents(const char *filename,
+ std::vector<uint8_t> *buffer) {
+ bool success = false;
+ std::ifstream file(filename, std::ios::binary | std::ios::ate);
+ if (!file) {
+ LOGE("Couldn't open file '%s': %d (%s)", filename, errno, strerror(errno));
+ } else {
+ ssize_t size = file.tellg();
+ file.seekg(0, std::ios::beg);
+
+ buffer->resize(size);
+ if (!file.read(reinterpret_cast<char *>(buffer->data()), size)) {
+ LOGE("Couldn't read from file '%s': %d (%s)", filename, errno,
+ strerror(errno));
+ } else {
+ success = true;
+ }
+ }
+
+ return success;
+}
+
+/**
+ * Loads a preloaded nanoapp given a filename to load from. Allows the
+ * transaction to complete before the nanoapp starts so the server can start
+ * serving requests as soon as possible.
+ *
+ * @param directory The directory to load the nanoapp from.
+ * @param name The filename of the nanoapp to load.
+ * @param transactionId The transaction ID to use when loading the app.
+ */
+static void loadPreloadedNanoapp(const std::string &directory,
+ const std::string &name,
+ uint32_t transactionId) {
+ std::vector<uint8_t> headerBuffer;
+
+ std::string headerFile = directory + "/" + name + ".napp_header";
+
+ // Only create the nanoapp filename as the CHRE framework will load from
+ // within the directory its own binary resides in.
+ std::string nanoappFilename = name + ".so";
+
+ if (readFileContents(headerFile.c_str(), &headerBuffer) &&
+ !loadNanoapp(headerBuffer, nanoappFilename, transactionId)) {
+ LOGE("Failed to load nanoapp: '%s'", name.c_str());
+ }
+}
+
+/**
+ * Attempts to load all preloaded nanoapps from a config file. The config file
+ * is expected to be valid JSON with the following structure:
+ *
+ * { "nanoapps": [
+ * "/path/to/nanoapp_1",
+ * "/path/to/nanoapp_2"
+ * ]}
+ *
+ * The napp_header and so files will both be loaded. All errors are logged.
+ */
+static void loadPreloadedNanoapps() {
+ constexpr char kPreloadedNanoappsConfigPath[] =
+ "/vendor/etc/chre/preloaded_nanoapps.json";
+ std::ifstream configFileStream(kPreloadedNanoappsConfigPath);
+
+ Json::Reader reader;
+ Json::Value config;
+ if (!configFileStream) {
+ LOGE("Failed to open config file '%s': %d (%s)",
+ kPreloadedNanoappsConfigPath, errno, strerror(errno));
+ } else if (!reader.parse(configFileStream, config)) {
+ LOGE("Failed to parse nanoapp config file");
+ } else if (!config.isMember("nanoapps") || !config.isMember("source_dir")) {
+ LOGE("Malformed preloaded nanoapps config");
+ } else {
+ const Json::Value &directory = config["source_dir"];
+ for (Json::ArrayIndex i = 0; i < config["nanoapps"].size(); i++) {
+ const Json::Value &nanoapp = config["nanoapps"][i];
+ loadPreloadedNanoapp(directory.asString(), nanoapp.asString(),
+ static_cast<uint32_t>(i));
+ }
+ }
+}
+
+/**
+ * Handles a message that is directed towards the daemon.
+ *
+ * @param message The message sent to the daemon.
+ */
+static void handleDaemonMessage(const uint8_t *message) {
+ std::unique_ptr<fbs::MessageContainerT> container =
+ fbs::UnPackMessageContainer(message);
+ if (container->message.type != fbs::ChreMessage::LoadNanoappResponse) {
+ LOGE("Invalid message from CHRE directed to daemon");
+ } else {
+ const auto *response = container->message.AsLoadNanoappResponse();
+ if (gPreloadedNanoappPendingTransactionIds.empty()) {
+ LOGE("Received nanoapp load response with no pending load");
+ } else if (gPreloadedNanoappPendingTransactionIds.front() !=
+ response->transaction_id) {
+ LOGE("Received nanoapp load response with ID %" PRIu32
+ " expected transaction id %" PRIu32,
+ response->transaction_id,
+ gPreloadedNanoappPendingTransactionIds.front());
+ } else {
+ if (!response->success) {
+ LOGE("Received unsuccessful nanoapp load response with ID %" PRIu32,
+ gPreloadedNanoappPendingTransactionIds.front());
+ }
+ gPreloadedNanoappPendingTransactionIds.pop();
+ }
+ }
+}
+
+#ifdef CHRE_USE_TOKENIZED_LOGGING
+/**
+ * Initialize the Log Detokenizer
+ *
+ * The log detokenizer reads a binary database file that contains key value
+ * pairs of hash-keys <--> Decoded log messages, and creates an instance
+ * of the Detokenizer.
+ *
+ * @return an instance of the Detokenizer
+ */
+static std::unique_ptr<Detokenizer> logDetokenizerInit() {
+ constexpr const char kLogDatabaseFilePath[] =
+ "/vendor/etc/chre/libchre_log_database.bin";
+ std::vector<uint8_t> tokenData;
+ if (readFileContents(kLogDatabaseFilePath, &tokenData)) {
+ pw::tokenizer::TokenDatabase database =
+ pw::tokenizer::TokenDatabase::Create(tokenData);
+ if (database.ok()) {
+ return std::make_unique<Detokenizer>(database);
+ } else {
+ LOGE("CHRE Token database creation not OK");
+ }
+ } else {
+ LOGE("Failed to read CHRE Token database file");
+ }
+ return std::unique_ptr<Detokenizer>(nullptr);
+}
+#endif
+
+/**
+ * Entry point for the thread that receives messages sent by CHRE.
+ *
+ * @return always returns NULL
+ */
+static void *chre_message_to_host_thread(void *arg) {
+ unsigned char messageBuffer[4096];
+ unsigned int messageLen;
+ int result = 0;
+ auto *server = static_cast<::android::chre::SocketServer *>(arg);
+
+#ifdef CHRE_USE_TOKENIZED_LOGGING
+ std::unique_ptr<Detokenizer> detokenizer = logDetokenizerInit();
+#endif
+
+ while (true) {
+ messageLen = 0;
+ LOGV("Calling into chre_slpi_get_message_to_host");
+ result = chre_slpi_get_message_to_host(messageBuffer, sizeof(messageBuffer),
+ &messageLen);
+ LOGV("Got message from CHRE with size %u (result %d)", messageLen, result);
+
+ if (result == CHRE_FASTRPC_ERROR_SHUTTING_DOWN) {
+ LOGD("CHRE shutting down, exiting CHRE->Host message thread");
+ break;
+ } else if (result == CHRE_FASTRPC_SUCCESS && messageLen > 0) {
+ log_buffer(messageBuffer, messageLen);
+ uint16_t hostClientId;
+ fbs::ChreMessage messageType;
+ if (!HostProtocolHost::extractHostClientIdAndType(
+ messageBuffer, messageLen, &hostClientId, &messageType)) {
+ LOGW(
+ "Failed to extract host client ID from message - sending "
+ "broadcast");
+ hostClientId = chre::kHostClientIdUnspecified;
+ }
+
+ if (messageType == fbs::ChreMessage::LogMessage) {
+ // Log messages are routed through ashLog if tokenized logging
+ // is disabled, so only parse tokenized log messages here.
+#ifdef CHRE_USE_TOKENIZED_LOGGING
+ parseAndEmitTokenizedLogMessages(messageBuffer, messageLen,
+ detokenizer.get());
+#endif
+ } else if (messageType == fbs::ChreMessage::TimeSyncRequest) {
+ sendTimeSyncMessage(true /* logOnError */);
+#ifdef CHRE_DAEMON_LPMA_ENABLED
+ } else if (messageType == fbs::ChreMessage::LowPowerMicAccessRequest) {
+ setLpmaState(true);
+ } else if (messageType == fbs::ChreMessage::LowPowerMicAccessRelease) {
+ setLpmaState(false);
+#endif // CHRE_DAEMON_LPMA_ENABLED
+ } else if (hostClientId == kHostClientIdDaemon) {
+ handleDaemonMessage(messageBuffer);
+ } else if (hostClientId == chre::kHostClientIdUnspecified) {
+ server->sendToAllClients(messageBuffer,
+ static_cast<size_t>(messageLen));
+ } else {
+ server->sendToClientById(messageBuffer, static_cast<size_t>(messageLen),
+ hostClientId);
+ }
+ } else if (!chre_shutdown_requested) {
+ LOGE(
+ "Received an unknown result (%d) and no shutdown was requested. "
+ "Quitting",
+ result);
+ exit(-1);
+ } else {
+ // Received an unknown result but a shutdown was requested. Break from the
+ // loop to allow the daemon to cleanup.
+ break;
+ }
+ }
+
+ LOGV("Message to host thread exited");
+ return NULL;
+}
+
+/**
+ * Entry point for the thread that blocks in a FastRPC call to monitor for
+ * abnormal exit of CHRE or reboot of the DSP.
+ *
+ * @return always returns NULL
+ */
+static void *chre_monitor_thread(void *arg) {
+ (void)arg;
+ int ret = chre_slpi_wait_on_thread_exit();
+ if (!chre_shutdown_requested) {
+ LOGE("Detected unexpected CHRE thread exit (%d)\n", ret);
+ exit(EXIT_FAILURE);
+ }
+
+ LOGV("Monitor thread exited");
+ return NULL;
+}
+
+/**
+ * Start a thread with default attributes, or log an error on failure
+ *
+ * @return bool true if the thread was successfully started
+ */
+static bool start_thread(pthread_t *thread_handle,
+ thread_entry_point_f *thread_entry, void *arg) {
+ int ret = pthread_create(thread_handle, NULL, thread_entry, arg);
+ if (ret != 0) {
+ LOG_ERROR("pthread_create failed", ret);
+ }
+ return (ret == 0);
+}
+
+namespace {
+
+void onMessageReceivedFromClient(uint16_t clientId, void *data, size_t length) {
+ sendMessageToChre(clientId, data, length);
+}
+
+} // anonymous namespace
+
+int main() {
+ int ret = -1;
+ pthread_t monitor_thread;
+ pthread_t msg_to_host_thread;
+
+ ::android::chre::SocketServer server;
+
+#ifdef CHRE_DAEMON_LOAD_INTO_SENSORSPD
+ remote_handle remote_handle_fd = 0xFFFFFFFF;
+ if (remote_handle_open(ITRANSPORT_PREFIX "createstaticpd:sensorspd",
+ &remote_handle_fd)) {
+ LOGE("Failed to open remote handle for sensorspd");
+ } else {
+ LOGV("Successfully opened remote handle for sensorspd");
+ }
+#endif // CHRE_DAEMON_LOAD_INTO_SENSORSPD
+
+ // Send time sync message before nanoapps start, retrying a few times
+ // in case the SLPI is not ready yet. This retry logic must be placed before
+ // any of the other FastRPC method invocations.
+ constexpr size_t kMaxNumRetries = 5;
+ if (!sendTimeSyncMessageRetry(kMaxNumRetries)) {
+ LOGE("Failed to send initial time sync message");
+ // Reverse monitor invokes a FastRPC method to allow the code running in
+ // CHRE to detect abnormal shutdown of the host-side daemon and perform a
+ // gracefull cleanup.
+ // ToDo: consolidate the chre_slpi_initialize_reverse_monitor() logic into
+ // an always-running daemon thread to eliminate the FastRPC call and save
+ // space in the CHRE framework.
+ } else if ((ret = chre_slpi_initialize_reverse_monitor()) !=
+ CHRE_FASTRPC_SUCCESS) {
+ LOGE("Failed to initialize reverse monitor: %d", ret);
+#ifdef CHRE_DAEMON_LPMA_ENABLED
+ } else if (!initLpmaEnableThread(&lpmaEnableThread)) {
+ LOGE("Couldn't initialize LPMA enable thread");
+#endif // CHRE_DAEMON_LPMA_ENABLED
+ } else {
+ if ((ret = chre_slpi_start_thread()) != CHRE_FASTRPC_SUCCESS) {
+ LOGE("Failed to start CHRE: %d", ret);
+ } else {
+ if (!start_thread(&monitor_thread, chre_monitor_thread, NULL)) {
+ LOGE("Couldn't start monitor thread");
+ } else if (!start_thread(&msg_to_host_thread, chre_message_to_host_thread,
+ &server)) {
+ LOGE("Couldn't start CHRE->Host message thread");
+ } else {
+ LOGI("CHRE started");
+ loadPreloadedNanoapps();
+
+ // TODO: take 2nd argument as command-line parameter
+ server.run("chre", true, onMessageReceivedFromClient);
+ }
+
+ chre_shutdown_requested = true;
+ ret = chre_slpi_stop_thread();
+ if (ret != CHRE_FASTRPC_SUCCESS) {
+ LOGE("Failed to stop CHRE: %d", ret);
+ } else {
+ // TODO: don't call pthread_join if the thread failed to start
+ LOGV("Joining monitor thread");
+ ret = pthread_join(monitor_thread, NULL);
+ if (ret != 0) {
+ LOG_ERROR("Join on monitor thread failed", ret);
+ }
+
+ LOGV("Joining message to host thread");
+ ret = pthread_join(msg_to_host_thread, NULL);
+ if (ret != 0) {
+ LOG_ERROR("Join on monitor thread failed", ret);
+ }
+
+ LOGI("Shutdown complete");
+ }
+ }
+ }
+
+ return ret;
+}
diff --git a/host/msm/daemon/fastrpc_daemon.cc b/host/msm/daemon/fastrpc_daemon.cc
deleted file mode 100644
index 5f48e8d5..00000000
--- a/host/msm/daemon/fastrpc_daemon.cc
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * 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.
- */
-
-// Disable verbose logging
-// TODO: use property_get_bool to make verbose logging runtime configurable
-// #define LOG_NDEBUG 0
-
-#include "fastrpc_daemon.h"
-
-#include "generated/chre_slpi.h"
-
-// TODO: The following conditional compilation needs to be removed, and done
-// for all platforms after verifying that it works on older devices where
-// we're currently not defining this macro
-#ifdef CHRE_DAEMON_LOAD_INTO_SENSORSPD
-#include "remote.h"
-
-#define ITRANSPORT_PREFIX "'\":;./\\"
-#endif // CHRE_DAEMON_LOAD_INTO_SENSORSPD
-
-// Aliased for consistency with the way these symbols are referenced in
-// CHRE-side code
-namespace fbs = ::chre::fbs;
-
-namespace android {
-namespace chre {
-
-namespace {
-
-#ifdef CHRE_DAEMON_LPMA_ENABLED
-constexpr bool kLpmaAllowed = true;
-#else
-constexpr bool kLpmaAllowed = false;
-#endif // CHRE_DAEMON_LPMA_ENABLED
-
-} // namespace
-
-FastRpcChreDaemon::FastRpcChreDaemon() : mLpmaHandler(kLpmaAllowed) {}
-
-bool FastRpcChreDaemon::init() {
- constexpr size_t kMaxTimeSyncRetries = 5;
- constexpr useconds_t kTimeSyncRetryDelayUs = 50000; // 50 ms
-
- int rc = -1;
-
-#ifdef CHRE_USE_TOKENIZED_LOGGING
- mLogger = ChreTokenizedLogMessageParser();
-#else
- // Logging is being routed through ashLog
- mLogger = ChreLogMessageParserBase();
-#endif
-
-#ifdef CHRE_DAEMON_LOAD_INTO_SENSORSPD
- remote_handle remote_handle_fd = 0xFFFFFFFF;
- if (remote_handle_open(ITRANSPORT_PREFIX "createstaticpd:sensorspd",
- &remote_handle_fd)) {
- LOGE("Failed to open remote handle for sensorspd");
- } else {
- LOGD("Successfully opened remote handle for sensorspd");
- }
-#endif // CHRE_DAEMON_LOAD_INTO_SENSORSPD
-
- mLpmaHandler.init();
-
- if (!sendTimeSyncWithRetry(kMaxTimeSyncRetries, kTimeSyncRetryDelayUs,
- true /* logOnError */)) {
- LOGE("Failed to send initial time sync message");
- } else if ((rc = chre_slpi_initialize_reverse_monitor()) !=
- CHRE_FASTRPC_SUCCESS) {
- LOGE("Failed to initialize reverse monitor: (err) %d", rc);
- } else if ((rc = chre_slpi_start_thread()) != CHRE_FASTRPC_SUCCESS) {
- LOGE("Failed to start CHRE: (err) %d", rc);
- } else {
- mMonitorThread = std::thread(&FastRpcChreDaemon::monitorThreadEntry, this);
- mMsgToHostThread =
- std::thread(&FastRpcChreDaemon::msgToHostThreadEntry, this);
- loadPreloadedNanoapps();
- LOGI("CHRE started");
- }
-
- return (rc == CHRE_FASTRPC_SUCCESS);
-}
-
-void FastRpcChreDaemon::deinit() {
- int rc;
-
- setShutdownRequested(true);
-
- if ((rc = chre_slpi_stop_thread()) != CHRE_FASTRPC_SUCCESS) {
- LOGE("Failed to stop CHRE: (err) %d", rc);
- }
-
- if (mMonitorThread.has_value()) {
- mMonitorThread->join();
- }
- if (mMsgToHostThread.has_value()) {
- mMsgToHostThread->join();
- }
-}
-
-void FastRpcChreDaemon::run() {
- constexpr char kChreSocketName[] = "chre";
- auto serverCb = [&](uint16_t clientId, void *data, size_t len) {
- if (mCrashDetected) {
- LOGW("Dropping data, CHRE restart in process...");
- } else {
- sendMessageToChre(clientId, data, len);
- }
- };
-
- // TODO: take 2nd argument as command-line parameter
- mServer.run(kChreSocketName, true /* allowSocketCreation */, serverCb);
-}
-
-bool FastRpcChreDaemon::doSendMessage(void *data, size_t length) {
- // This limitation is due to FastRPC, but there's no case
- // where we should come close to this limit
- constexpr size_t kMaxPayloadSize = 1024 * 1024; // 1 MiB
- static_assert(kMaxPayloadSize <= INT32_MAX,
- "DSP uses 32-bit signed integers to represent message size");
-
- bool success = false;
- if (length > kMaxPayloadSize) {
- LOGE("Message too large (got %zu, max %zu bytes)", length, kMaxPayloadSize);
- } else {
- int ret = chre_slpi_deliver_message_from_host(
- static_cast<const unsigned char *>(data), static_cast<int>(length));
- if (ret != CHRE_FASTRPC_SUCCESS) {
- LOGE("Failed to deliver message from host to CHRE: %d", ret);
- } else {
- success = true;
- }
- }
-
- return success;
-}
-
-void FastRpcChreDaemon::monitorThreadEntry() {
- LOGD("Monitor thread started");
-
- int ret = chre_slpi_wait_on_thread_exit();
- if (!wasShutdownRequested()) {
- LOGE("Monitor detected unexpected CHRE thread exit (%d)", ret);
- onRemoteCrashDetected();
- }
- LOGD("Monitor thread exited");
-}
-
-void FastRpcChreDaemon::msgToHostThreadEntry() {
- unsigned char messageBuffer[4096];
- unsigned int messageLen;
- int result = 0;
-
- LOGD("MsgToHost thread started");
-
- while (true) {
- messageLen = 0;
- LOGV("Calling into chre_slpi_get_message_to_host");
- result = chre_slpi_get_message_to_host(messageBuffer, sizeof(messageBuffer),
- &messageLen);
- LOGV("Got message from CHRE with size %u (result %d)", messageLen, result);
-
- if (result == CHRE_FASTRPC_ERROR_SHUTTING_DOWN) {
- LOGD("CHRE shutting down, exiting CHRE->Host message thread");
- break;
- } else if (result == CHRE_FASTRPC_SUCCESS && messageLen > 0) {
- onMessageReceived(messageBuffer, messageLen);
- } else if (!wasShutdownRequested()) {
- LOGE("get_message_to_host returned unexpected error (%d)", result);
- onRemoteCrashDetected();
- } else {
- // Received an unknown result but a shutdown was requested. Break from
- // the loop to allow the daemon to cleanup.
- break;
- }
- }
- LOGD("Message to host thread exited");
-}
-
-int64_t FastRpcChreDaemon::getTimeOffset(bool *success) {
- int64_t timeOffset = 0;
-
-#if defined(__aarch64__)
- // Reads the system time counter (CNTVCT) and its frequency (CNTFRQ)
- // CNTVCT is used in the sensors HAL for time synchronization.
- // More information can be found in the ARM reference manual
- // (http://infocenter.arm.com/help/index.jsp?topic=
- // /com.arm.doc.100048_0002_05_en/jfa1406793266982.html)
- // Use uint64_t to store since the MRS instruction uses 64 bit (X) registers
- // (http://infocenter.arm.com/help/topic/
- // com.arm.doc.den0024a/ch06s05s02.html)
- uint64_t qTimerCount = 0, qTimerFreq = 0;
- uint64_t hostTimeNano = elapsedRealtimeNano();
- asm volatile("mrs %0, cntvct_el0" : "=r"(qTimerCount));
- asm volatile("mrs %0, cntfrq_el0" : "=r"(qTimerFreq));
-
- constexpr uint64_t kOneSecondInNanoseconds = 1000000000;
- if (qTimerFreq != 0) {
- // Get the seconds part first, then convert the remainder to prevent
- // overflow
- uint64_t qTimerNanos = (qTimerCount / qTimerFreq);
- if (qTimerNanos > UINT64_MAX / kOneSecondInNanoseconds) {
- LOGE(
- "CNTVCT_EL0 conversion to nanoseconds overflowed during time sync. "
- "Aborting time sync.");
- *success = false;
- } else {
- qTimerNanos *= kOneSecondInNanoseconds;
-
- // Round the remainder portion to the nearest nanosecond
- uint64_t remainder = (qTimerCount % qTimerFreq);
- qTimerNanos +=
- (remainder * kOneSecondInNanoseconds + qTimerFreq / 2) / qTimerFreq;
-
- timeOffset = hostTimeNano - qTimerNanos;
- *success = true;
- }
- } else {
- LOGE("CNTFRQ_EL0 had 0 value. Aborting time sync.");
- *success = false;
- }
-#else
-#error "Unsupported CPU architecture type"
-#endif
-
- return timeOffset;
-}
-
-void FastRpcChreDaemon::onRemoteCrashDetected() {
- // After a DSP crash, we delay a short period of time before exiting. This is
- // primarily to avoid any potential race conditions arising from trying to
- // initialize CHRE very early in the DSP boot flow. Normally the firmware is
- // reloaded within a second or so, but we use a longer time here to have some
- // padding to handle cases where the system is slower than usual, etc.
- constexpr auto kDelayAfterCrash = std::chrono::seconds(3);
-
- // It's technically fine if multiple threads race here, but to avoid duplicate
- // logs, give the first one to reach this point a shorter delay than others
- bool firstDetection = !mCrashDetected.exchange(true);
- auto delay = (firstDetection) ? kDelayAfterCrash : kDelayAfterCrash * 2;
- std::this_thread::sleep_for(delay);
- LOGE("Exiting daemon");
- std::exit(EXIT_FAILURE);
-}
-
-} // namespace chre
-} // namespace android
diff --git a/host/msm/daemon/fastrpc_daemon.h b/host/msm/daemon/fastrpc_daemon.h
deleted file mode 100644
index fe3b0473..00000000
--- a/host/msm/daemon/fastrpc_daemon.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-/**
- * @file
- * The daemon that hosts CHRE on a hexagon DSP via FastRPC. This is typically
- * the SLPI but could be the ADSP or another DSP that supports FastRPC.
- */
-
-#ifndef CHRE_FASTRPC_DAEMON_H_
-#define CHRE_FASTRPC_DAEMON_H_
-
-#include "chre/platform/slpi/fastrpc.h"
-#include "chre_host/daemon_base.h"
-#include "chre_host/st_hal_lpma_handler.h"
-
-#include <utils/SystemClock.h>
-#include <atomic>
-#include <optional>
-#include <thread>
-
-#ifdef CHRE_USE_TOKENIZED_LOGGING
-#include "chre_host/tokenized_log_message_parser.h"
-#else
-#include "chre_host/log_message_parser_base.h"
-#endif
-
-namespace android {
-namespace chre {
-
-class FastRpcChreDaemon : public ChreDaemonBase {
- public:
- FastRpcChreDaemon();
-
- ~FastRpcChreDaemon() {
- deinit();
- }
-
- /**
- * Initializes and starts the monitoring and message handling threads,
- * then proceeds to load any preloaded nanoapps. Also starts LPMA if
- * it's enabled.
- *
- * @return true on successful init
- */
- bool init();
-
- /**
- * Starts a socket server receive loop for inbound messages.
- */
- void run();
-
- protected:
- bool doSendMessage(void *data, size_t length) override;
-
- void configureLpma(bool enabled) override {
- mLpmaHandler.enable(enabled);
- }
-
- ChreLogMessageParserBase *getLogger() override {
- return &mLogger;
- }
-
- private:
- std::optional<std::thread> mMonitorThread;
- std::optional<std::thread> mMsgToHostThread;
- std::atomic_bool mCrashDetected = false;
- ChreLogMessageParserBase mLogger;
- StHalLpmaHandler mLpmaHandler;
-
- /**
- * Shutsdown the daemon, stops all the worker threads created in init()
- * Since this is to be invoked at exit, it's mostly best effort, and is
- * invoked by the class destructor
- */
- void deinit();
-
- /**
- * Platform specific getTimeOffset for the FastRPC daemon
- *
- * @return clock drift offset in nanoseconds
- */
- int64_t getTimeOffset(bool *success);
-
- /**
- * Entry point for the thread that blocks in a FastRPC call to monitor for
- * abnormal exit of CHRE or reboot of the DSP.
- */
- void monitorThreadEntry();
-
- /**
- * Entry point for the thread that receives messages sent by CHRE.
- */
- void msgToHostThreadEntry();
-
- /**
- * Handles the case where the remote end (SLPI, ADSP, etc) has crashed.
- */
- void onRemoteCrashDetected();
-};
-
-} // namespace chre
-} // namespace android
-
-#endif // CHRE_FASTRPC_DAEMON_H_
diff --git a/host/msm/daemon/main.cc b/host/msm/daemon/main.cc
deleted file mode 100644
index 046f2593..00000000
--- a/host/msm/daemon/main.cc
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "fastrpc_daemon.h"
-
-int main() {
- android::chre::FastRpcChreDaemon daemon;
-
- if (!daemon.init()) {
- LOGE("failed to init the daemon");
- } else {
- daemon.run();
- }
-
- return 0;
-}
diff --git a/java/test/audio_concurrency/Android.bp b/java/test/audio_concurrency/Android.bp
index 462f7216..f9ef1323 100644
--- a/java/test/audio_concurrency/Android.bp
+++ b/java/test/audio_concurrency/Android.bp
@@ -1,4 +1,4 @@
-// Copyright (C) 2020 The Android Open Source Project
+// Copyright (C) 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -12,15 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
java_library {
name: "context-hub-audio-concurrency-test",
diff --git a/java/test/audio_concurrency/src/com/google/android/chre/test/audioconcurrency/ContextHubAudioConcurrencyTestExecutor.java b/java/test/audio_concurrency/src/com/google/android/chre/test/audioconcurrency/ContextHubAudioConcurrencyTestExecutor.java
index c82b19a1..63777b20 100644
--- a/java/test/audio_concurrency/src/com/google/android/chre/test/audioconcurrency/ContextHubAudioConcurrencyTestExecutor.java
+++ b/java/test/audio_concurrency/src/com/google/android/chre/test/audioconcurrency/ContextHubAudioConcurrencyTestExecutor.java
@@ -15,6 +15,7 @@
*/
package com.google.android.chre.test.audioconcurrency;
+import android.app.UiAutomation;
import android.hardware.location.ContextHubClient;
import android.hardware.location.ContextHubClientCallback;
import android.hardware.location.ContextHubInfo;
@@ -27,6 +28,8 @@ import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
+import androidx.test.InstrumentationRegistry;
+
import com.google.android.chre.nanoapp.proto.ChreAudioConcurrencyTest;
import com.google.android.chre.nanoapp.proto.ChreTestCommon;
import com.google.android.utils.chre.ChreTestUtil;
@@ -177,6 +180,10 @@ public class ContextHubAudioConcurrencyTestExecutor extends ContextHubClientCall
* Records audio from the mic.
*/
private void recordAudio() {
+ UiAutomation automation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+ Assert.assertTrue("Failed to get UI automation", automation != null);
+ automation.adoptShellPermissionIdentity(AUDIO_PERMISSION);
+
// Hold the mic for 1 second
int samplingRateHz = 16000; // 16 KHz
int durationSeconds = 1;
@@ -194,6 +201,8 @@ public class ContextHubAudioConcurrencyTestExecutor extends ContextHubClientCall
record.read(buf, 0 /* offsetInBytes */, size);
Log.d(TAG, "AP read audio for " + 1000 * size / samplingRateHz + " ms");
record.release();
+
+ automation.dropShellPermissionIdentity();
}
/**
diff --git a/java/test/chqts/Android.bp b/java/test/chqts/Android.bp
deleted file mode 100644
index 398b98bb..00000000
--- a/java/test/chqts/Android.bp
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (C) 2020 The Android Open Source Project
-//
-// 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.
-
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
-java_library {
- name: "chqts",
-
- srcs: ["src/**/*.java"],
-
- static_libs: [
- "androidx.test.rules",
- "chre-test-utils",
- ],
-
- sdk_version: "system_current",
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubBadNanoAppsTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubBadNanoAppsTestExecutor.java
deleted file mode 100644
index 54b5e596..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubBadNanoAppsTestExecutor.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-import com.google.android.utils.chre.ChreTestUtil;
-
-import org.junit.Assert;
-
-import java.util.Arrays;
-
-/**
- * These are a series of tests which attempt to load various invalid NanoApps.
- *
- * We want to make sure these fail to load, and the system doesn't throw
- * unexpected exceptions or crash while attempting this.
- *
- * TODO (b/151159967): Adapt this test for < P builds.
- */
-public class ContextHubBadNanoAppsTestExecutor {
- private final ContextHubManager mContextHubManager;
-
- private final ContextHubInfo mContextHubInfo;
-
- public ContextHubBadNanoAppsTestExecutor(ContextHubManager manager, ContextHubInfo info) {
- mContextHubManager = manager;
- mContextHubInfo = info;
- }
-
- public void noAppBinaryTest() {
- // TODO (b/151159967): Implement this test
- }
-
- public void noAppIdTest() {
- // TODO (b/151159967): Implement this test
- }
-
- public void emptyAppBinaryTest() {
- runInvalidBinaryTest(0 /* numBytes */);
- }
-
- public void smallInvalidAppBinaryTest() {
- runInvalidBinaryTest(64 /* numBytes */);
- }
-
- public void largeInvalidAppBinaryTest() {
- runInvalidBinaryTest(8192 /* numBytes */);
- }
-
- private void runInvalidBinaryTest(int numBytes) {
- byte[] buffer = new byte[numBytes];
- Arrays.fill(buffer, (byte) 0xFF);
-
- NanoAppBinary binary = new NanoAppBinary(buffer);
- Assert.assertFalse("Invalid nanoapp binary (" + numBytes
- + " bytes) returns true for hasValidHeader()", binary.hasValidHeader());
-
- boolean success = ChreTestUtil.loadNanoApp(mContextHubManager, mContextHubInfo, binary);
- Assert.assertFalse("Invalid nanoapp binary (" + numBytes + " bytes) successfully loaded",
- success);
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubBusyStartupTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubBusyStartupTestExecutor.java
deleted file mode 100644
index 204ff693..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubBusyStartupTestExecutor.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-/**
- * Executes the busy startup nanoapp test, which confirms that nanoappStart() can properly call
- * various methods. See the busy_startup.cc nanoapp code for details.
- *
- * Note that this nanoapp is not a general_test nanoapp, but uses the same protocol, so we use
- * the ContextHubGeneralTestExecutor class.
- */
-public class ContextHubBusyStartupTestExecutor extends ContextHubGeneralTestExecutor {
-
- public ContextHubBusyStartupTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary) {
- // busy_startup nanoapp does not require a start message, since it does all the work during
- // nanoappStart().
- super(manager, info,
- new GeneralTestNanoApp(binary, ContextHubTestConstants.TestNames.INVALID_TEST,
- true /* loadAtInit */,
- false /* sendStartMessage */));
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- // No specific messages for busy startup test.
- fail("Unexpected message type " + type);
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubEstimatedHostTimeTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubEstimatedHostTimeTestExecutor.java
deleted file mode 100644
index e067940a..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubEstimatedHostTimeTestExecutor.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-import android.os.SystemClock;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * Verify estimated host time from nanoapp.
- *
- * Protocol:
- * host to app: ESTIMATED_HOST_TIME, no data
- * app to host: CONTINUE
- * host to app: CONTINUE, 64-bit time
- * app to host: SUCCESS
- */
-public class ContextHubEstimatedHostTimeTestExecutor extends ContextHubGeneralTestExecutor {
-
- public ContextHubEstimatedHostTimeTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary) {
- super(manager, info, new GeneralTestNanoApp(binary,
- ContextHubTestConstants.TestNames.ESTIMATED_HOST_TIME));
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- if (type != ContextHubTestConstants.MessageType.CONTINUE) {
- fail("Unexpected message type " + type);
- } else {
- ByteBuffer buffer = ByteBuffer.allocate(8)
- .order(ByteOrder.LITTLE_ENDIAN)
- .putLong(SystemClock.elapsedRealtimeNanos());
-
- sendMessageToNanoAppOrFail(nanoAppId,
- ContextHubTestConstants.MessageType.CONTINUE.asInt(),
- buffer.array());
- }
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubEventBetweenAppsTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubEventBetweenAppsTestExecutor.java
deleted file mode 100644
index a36f6b06..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubEventBetweenAppsTestExecutor.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * Verify sending a CHRE event between two nanoapps.
- *
- * We also check that we get the correct nanoApp IDs and sane nanoApp instance IDs.
- *
- * Protocol:
- * There are two nanoapps here, so we'll talk in term of app0 and app1.
- * All data involving the host is sent little endian.
- *
- * Host to app0: EVENT_BETWEEN_APPS0, no data
- * Host to app1: EVENT_BETWEEN_APPS1, no data
- * app0 to host: CONTINUE, 64-bit app ID, 32-bit instance ID
- * app1 to host: CONTINUE, 64-bit app ID, 32-bit instance ID
- * Host to app1: CONTINUE, app0's 32-bit instance ID
- * Host to app0: CONTINUE, app1's 32-bit instance ID
- * [app0 sends message to app1]
- * app1 to host: SUCCESS
- */
-public class ContextHubEventBetweenAppsTestExecutor extends ContextHubGeneralTestExecutor {
- /**
- * A container class to store information supplied by the nanoapps.
- */
- private class AppInfo {
- public long appId;
- public int instanceId;
- public boolean haveInfo = false;
- }
-
- private final long mNanoAppId0;
- private final long mNanoAppId1;
- private AppInfo[] mAppInfo = new AppInfo[]{new AppInfo(), new AppInfo()};
-
- public ContextHubEventBetweenAppsTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary0, NanoAppBinary binary1) {
- super(manager, info, new GeneralTestNanoApp(binary0,
- ContextHubTestConstants.TestNames.EVENT_BETWEEN_APPS0),
- new GeneralTestNanoApp(binary1,
- ContextHubTestConstants.TestNames.EVENT_BETWEEN_APPS1));
- mNanoAppId0 = binary0.getNanoAppId();
- mNanoAppId1 = binary1.getNanoAppId();
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- if (type != ContextHubTestConstants.MessageType.CONTINUE) {
- fail("Unexpected message type " + type);
- return;
- }
-
- int index = (nanoAppId == mNanoAppId0) ? 0 : 1;
- assertFalse("Multiple CONTINUE messages from app 0x" + Long.toHexString(nanoAppId),
- mAppInfo[index].haveInfo);
-
- ByteBuffer buffer = ByteBuffer.wrap(data)
- .order(ByteOrder.LITTLE_ENDIAN);
- try {
- mAppInfo[index].appId = buffer.getLong();
- mAppInfo[index].instanceId = buffer.getInt();
- mAppInfo[index].haveInfo = true;
- } catch (BufferUnderflowException e) {
- fail("Not enough data provided in CONTINUE message from 0x" + Long.toHexString(
- nanoAppId));
- }
- assertFalse(
- "Too much data provided in CONTINUE message from 0x" + Long.toHexString(nanoAppId),
- buffer.hasRemaining());
-
- int otherIndex = 1 - index;
- if (!mAppInfo[otherIndex].haveInfo) {
- // We need to wait to get the info from the other app.
- return;
- }
-
- assertEquals("Incorrect app ID given for 0x" + Long.toHexString(mNanoAppId0),
- mNanoAppId0,
- mAppInfo[0].appId);
- assertEquals("Incorrect app ID given for 0x" + Long.toHexString(mNanoAppId1),
- mNanoAppId1,
- mAppInfo[1].appId);
- assertTrue("Both nanoapps given identical instance IDs",
- mAppInfo[0].instanceId != mAppInfo[1].instanceId);
-
- // Consistency checks pass. We'll send the data down.
- buffer = ByteBuffer.allocate(4)
- .order(ByteOrder.LITTLE_ENDIAN)
- .putInt(mAppInfo[0].instanceId);
- sendMessageToNanoAppOrFail(mNanoAppId1,
- ContextHubTestConstants.MessageType.CONTINUE.asInt(), buffer.array());
-
- buffer.clear();
- buffer.putInt(mAppInfo[1].instanceId);
- sendMessageToNanoAppOrFail(mNanoAppId0,
- ContextHubTestConstants.MessageType.CONTINUE.asInt(), buffer.array());
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubGeneralTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubGeneralTestExecutor.java
deleted file mode 100644
index 07b6f696..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubGeneralTestExecutor.java
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubClient;
-import android.hardware.location.ContextHubClientCallback;
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.ContextHubTransaction;
-import android.hardware.location.NanoAppBinary;
-import android.hardware.location.NanoAppMessage;
-import android.util.Log;
-
-import com.google.android.utils.chre.ChreTestUtil;
-
-import org.junit.Assert;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * A class that can execute the CHQTS "general" tests. Nanoapps using this "general" test framework
- * have the name "general_test".
- *
- * A test successfully passes in one of two ways:
- * - MessageType.SUCCESS received from the Nanoapp by this infrastructure.
- * - A call to ContextHubGeneralTestExecutor.pass() by the test code.
- *
- * NOTE: A test must extend this class and define the handleNanoappMessage() function to handle
- * specific messages for the test.
- *
- * TODO: Refactor this class to be able to be invoked for < P builds.
- */
-public abstract class ContextHubGeneralTestExecutor extends ContextHubClientCallback {
- public static final String TAG = "ContextHubGeneralTestExecutor";
-
- private final List<GeneralTestNanoApp> mGeneralTestNanoAppList;
-
- private final Set<Long> mNanoAppIdSet;
-
- private ContextHubClient mContextHubClient;
-
- private final ContextHubManager mContextHubManager;
-
- private final ContextHubInfo mContextHubInfo;
-
- private CountDownLatch mCountDownLatch;
-
- private boolean mInitialized = false;
-
- private AtomicReference<String> mErrorString = new AtomicReference<>(null);
-
- private long mThreadId;
-
- /**
- * A container class to describe a general_test nanoapp.
- */
- public static class GeneralTestNanoApp {
- private final NanoAppBinary mNanoAppBinary;
- private final ContextHubTestConstants.TestNames mTestName;
-
- // Set to false if the nanoapp should not be loaded at init. An example of why this may be
- // needed are for nanoapps that are loaded in the middle of the test execution, but still
- // needs to be included in this test executor (e.g. deliver messages from it).
- private final boolean mLoadAtInit;
-
- // Set to false if the nanoapp should not send a start message at init. An example of where
- // this is not needed is for test nanoapps that use the general_test protocol, but do not
- // require a start message (e.g. starts on load like the busy_startup nanoapp).
- private final boolean mSendStartMessage;
-
- public GeneralTestNanoApp(NanoAppBinary nanoAppBinary,
- ContextHubTestConstants.TestNames testName) {
- mTestName = testName;
- mNanoAppBinary = nanoAppBinary;
- mLoadAtInit = true;
- mSendStartMessage = true;
- }
-
- public GeneralTestNanoApp(NanoAppBinary nanoAppBinary,
- ContextHubTestConstants.TestNames testName, boolean loadAtInit) {
- mTestName = testName;
- mNanoAppBinary = nanoAppBinary;
- mLoadAtInit = loadAtInit;
- mSendStartMessage = true;
- }
-
- public GeneralTestNanoApp(NanoAppBinary nanoAppBinary,
- ContextHubTestConstants.TestNames testName,
- boolean loadAtInit, boolean sendStartMessage) {
- mTestName = testName;
- mNanoAppBinary = nanoAppBinary;
- mLoadAtInit = loadAtInit;
- mSendStartMessage = sendStartMessage;
- }
-
- public NanoAppBinary getNanoAppBinary() {
- return mNanoAppBinary;
- }
-
- public ContextHubTestConstants.TestNames getTestName() {
- return mTestName;
- }
-
- public boolean loadAtInit() {
- return mLoadAtInit;
- }
-
- public boolean sendStartMessage() {
- return mSendStartMessage;
- }
- }
-
- /**
- * Note that this constructor accepts multiple general_test nanoapps to test.
- */
- public ContextHubGeneralTestExecutor(ContextHubManager manager, ContextHubInfo info,
- GeneralTestNanoApp... tests) {
- mContextHubManager = manager;
- mContextHubInfo = info;
- mGeneralTestNanoAppList = new ArrayList<>(Arrays.asList(tests));
- mNanoAppIdSet = new HashSet<>();
- for (GeneralTestNanoApp test : mGeneralTestNanoAppList) {
- mNanoAppIdSet.add(test.getNanoAppBinary().getNanoAppId());
- }
- }
-
- @Override
- public void onMessageFromNanoApp(ContextHubClient client, NanoAppMessage message) {
- if (mNanoAppIdSet.contains(message.getNanoAppId())) {
- NanoAppMessage realMessage = hackMessageFromNanoApp(message);
-
- int messageType = realMessage.getMessageType();
- ContextHubTestConstants.MessageType messageEnum =
- ContextHubTestConstants.MessageType.fromInt(messageType, "");
- byte[] data = realMessage.getMessageBody();
-
- switch (messageEnum) {
- case INVALID_MESSAGE_TYPE: // fall-through
- case FAILURE: // fall-through
- case INTERNAL_FAILURE:
- // These are univeral failure conditions for all tests.
- // If they have data, it's expected to be an ASCII string.
- String errorString = new String(data, Charset.forName("US-ASCII"));
- fail(errorString);
- break;
-
- case SKIPPED:
- // TODO: Use junit Assume
- String reason = new String(data, Charset.forName("US-ASCII"));
- Log.w(TAG, "SKIPPED " + ":" + reason);
- pass();
- break;
-
- case SUCCESS:
- // This is a universal success for the test. We ignore
- // 'data'.
- pass();
- break;
-
- default:
- handleMessageFromNanoApp(message.getNanoAppId(), messageEnum, data);
- }
- }
- }
-
- /**
- * Should be invoked before run() is invoked to set up the test, e.g. in a @Before method.
- */
- public void init() {
- Assert.assertFalse("init() must not be invoked when already initialized", mInitialized);
-
- mInitialized = true;
-
- // Initialize the CountDownLatch before run() since some nanoapps will start on load.
- mCountDownLatch = new CountDownLatch(1);
-
- mContextHubClient = mContextHubManager.createClient(mContextHubInfo, this);
- Assert.assertTrue(mContextHubClient != null);
-
- for (GeneralTestNanoApp test : mGeneralTestNanoAppList) {
- if (test.loadAtInit()) {
- ChreTestUtil.loadNanoAppAssertSuccess(mContextHubManager, mContextHubInfo,
- test.getNanoAppBinary());
- }
- }
-
- mErrorString.set(null);
- }
-
- /**
- * Run the test.
- */
- public void run(long timeoutSeconds) {
- mThreadId = Thread.currentThread().getId();
-
- for (GeneralTestNanoApp test : mGeneralTestNanoAppList) {
- if (test.loadAtInit() && test.sendStartMessage()) {
- sendMessageToNanoAppOrFail(test.getNanoAppBinary().getNanoAppId(),
- test.getTestName().asInt(), new byte[0] /* data */);
- }
- }
-
- boolean success = false;
- try {
- success = mCountDownLatch.await(timeoutSeconds, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
-
- Assert.assertTrue("Test timed out", success);
- }
-
- /**
- * Invoke to indicate that the test has passed.
- */
- public void pass() {
- mCountDownLatch.countDown();
- }
-
- /**
- * Cleans up the test, should be invoked in e.g. @After method.
- */
- public void deinit() {
- Assert.assertTrue("deinit() must be invoked after init()", mInitialized);
-
- // TODO: If the nanoapp aborted (i.e. test failed), wait for CHRE reset or nanoapp abort
- // callback, and otherwise assert unload success.
- for (GeneralTestNanoApp test : mGeneralTestNanoAppList) {
- ChreTestUtil.unloadNanoApp(mContextHubManager, mContextHubInfo,
- test.getNanoAppBinary().getNanoAppId());
- }
-
- mContextHubClient.close();
- mContextHubClient = null;
-
- mInitialized = false;
-
- if (mErrorString.get() != null) {
- Assert.fail(mErrorString.get());
- }
- }
-
- /**
- * Sends a message to the test nanoapp.
- *
- * @param nanoAppId The 64-bit ID of the nanoapp to send the message to.
- * @param type The message type.
- * @param data The message payload.
- */
- protected void sendMessageToNanoAppOrFail(long nanoAppId, int type, byte[] data) {
- NanoAppMessage message = NanoAppMessage.createMessageToNanoApp(
- nanoAppId, type, data);
-
- int result = mContextHubClient.sendMessageToNanoApp(hackMessageToNanoApp(message));
- if (result != ContextHubTransaction.RESULT_SUCCESS) {
- fail("Failed to send message: result = " + result);
- }
- }
-
- /**
- * @param errorMessage The error message to display
- */
- protected void fail(String errorMessage) {
- assertTrue(errorMessage, false /* condition */);
- }
-
- /**
- * Semantics the same as Assert.assertEquals.
- */
- protected <T> void assertEquals(String errorMessage, T expected, T actual) {
- if (Thread.currentThread().getId() == mThreadId) {
- Assert.assertEquals(errorMessage, expected, actual);
- } else if ((expected == null && actual != null) || (expected != null && !expected.equals(
- actual))) {
- mErrorString.set(errorMessage + ": " + expected + " != " + actual);
- mCountDownLatch.countDown();
- }
- }
-
- /**
- * Semantics the same as Assert.assertTrue.
- */
- protected void assertTrue(String errorMessage, boolean condition) {
- if (Thread.currentThread().getId() == mThreadId) {
- Assert.assertTrue(errorMessage, condition);
- } else if (!condition) {
- mErrorString.set(errorMessage);
- mCountDownLatch.countDown();
- }
- }
-
- /**
- * Semantics are the same as Assert.assertFalse.
- */
- protected void assertFalse(String errorMessage, boolean condition) {
- assertTrue(errorMessage, !condition);
- }
-
- protected ContextHubManager getContextHubManager() {
- return mContextHubManager;
- }
-
- protected ContextHubInfo getContextHubInfo() {
- return mContextHubInfo;
- }
-
- /**
- * Handles a message specific for a test.
- *
- * @param nanoAppId The 64-bit ID of the nanoapp sending the message.
- * @param type The message type.
- * @param data The message body.
- */
- protected abstract void handleMessageFromNanoApp(
- long nanoAppId, ContextHubTestConstants.MessageType type, byte[] data);
-
- // TODO: Remove this hack
- protected NanoAppMessage hackMessageToNanoApp(NanoAppMessage message) {
- // For NYC, we are not able to assume that the messageType correctly
- // makes it to the nanoapp. So we put it, in little endian, as the
- // first four bytes of the message.
- byte[] origData = message.getMessageBody();
- ByteBuffer newData = ByteBuffer.allocate(4 + origData.length);
- newData.order(ByteOrder.LITTLE_ENDIAN);
- newData.putInt(message.getMessageType());
- newData.put(origData);
- return NanoAppMessage.createMessageToNanoApp(
- message.getNanoAppId(), message.getMessageType(), newData.array());
- }
-
- // TODO: Remove this hack
- protected NanoAppMessage hackMessageFromNanoApp(NanoAppMessage message) {
- // For now, our nanohub HAL and JNI code end up not sending across the
- // message type of the user correctly. So our testing protocol hacks
- // around this by putting the message type in the first four bytes of
- // the data payload, in little endian.
- ByteBuffer origData = ByteBuffer.wrap(message.getMessageBody());
- origData.order(ByteOrder.LITTLE_ENDIAN);
- int newMessageType = origData.getInt();
- // The new data is the remainder of this array (which could be empty).
- byte[] newData = new byte[origData.remaining()];
- origData.get(newData);
- return NanoAppMessage.createMessageFromNanoApp(
- message.getNanoAppId(), newMessageType, newData,
- message.isBroadcastMessage());
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubGetTimeTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubGetTimeTestExecutor.java
deleted file mode 100644
index 059e4539..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubGetTimeTestExecutor.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.Timer;
-import java.util.TimerTask;
-
-/**
- * Checks that chreGetTime() is reasonable.
- *
- * We check that it's monotonically increasing, and mostly in line with
- * the application processor's notion of time passing.
- *
- * Protocol:
- * Host: GET_TIME, no data
- * Nanoapp: CONTINUE, 64-bit timestamp (little endian)
- * [2.5 second pause]
- * Host: CONTINUE, no data
- * Nanoapp: CONTINUE, 64-bit timestamp (little endian)
- * [Host declares pass]
- */
-public class ContextHubGetTimeTestExecutor extends ContextHubGeneralTestExecutor {
- private static final ContextHubTestConstants.TestNames TEST_NAME =
- ContextHubTestConstants.TestNames.GET_TIME;
-
- // Since the CHRE timestamps are in nanoseconds, we do most of our times
- // in nanoseconds here (although the Timer.schedule() only works with
- // milliseconds; we elect for the shorter naming for our more common unit).
-
- // 2.5 seconds
- private static final long SLEEP_DURATION_MILLISECONDS = 2500;
- private static final long SLEEP_DURATION_NS =
- SLEEP_DURATION_MILLISECONDS * 1000 * 1000;
-
- // We expect some degree of inconsistency between our host/CHRE
- // transaction overheads, so we allow a healthy amount of tolerance
- // here. This isn't a precision check, but should hopefully make
- // sure the CHRE is within the right ballpark.
- // 0.5 seconds
- private static final long TOLERANCE_NS = 500 * 1000 * 1000;
-
- private int mContinueCount = 0;
- private long mFirstTimestamp;
-
- private Timer mTimer = new Timer();
-
- public ContextHubGetTimeTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary) {
- super(manager, info,
- new GeneralTestNanoApp(binary, ContextHubTestConstants.TestNames.GET_TIME));
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- if (type != ContextHubTestConstants.MessageType.CONTINUE) {
- fail("Unexpected message type " + type);
- return;
- }
-
- assertEquals("Expected exactly 8 bytes with CONTINUE message.",
- 8, data.length);
- long timestamp = ByteBuffer.wrap(data)
- .order(ByteOrder.LITTLE_ENDIAN)
- .getLong();
-
- mContinueCount++;
- if (mContinueCount == 1) {
- mFirstTimestamp = timestamp;
- // We perform our delay before the next message in a separate
- // thread, so we're not stalling the ContextHubManager/Service
- // from servicing any other messages or events.
- mTimer.schedule(new TimerTask() {
- @Override
- public void run() {
- byte[] emptyData = new byte[0];
- sendMessageToNanoAppOrFail(nanoAppId,
- ContextHubTestConstants.MessageType.CONTINUE.asInt(),
- emptyData);
- }
- }, SLEEP_DURATION_MILLISECONDS);
- // We got our first timestamp and started the (delayed) send
- // message. Nothing more to do this time.
- return;
- }
- // This is our second call.
- long timeDifference = timestamp - mFirstTimestamp;
- assertTrue("Subsequent timestamps did not monotonically increase",
- timeDifference > 0);
- assertTrue("Expected timestamp difference around " + SLEEP_DURATION_NS
- + " nanoseconds, but got " + timeDifference,
- ((timeDifference > (SLEEP_DURATION_NS - TOLERANCE_NS))
- && (timeDifference
- < (SLEEP_DURATION_NS + TOLERANCE_NS))));
-
- // The CHRE gave us two reasonable timestamps. And the nanoapp didn't
- // signal any issues with its testing. We're good.
- pass();
- }
-
- @Override
- public void deinit() {
- // If our test aborted for another reason, we want to make sure
- // we cancel any timer that we might have set, so we don't send
- // a spurious message to the CHRE after this test has completed.
- mTimer.cancel();
-
- super.deinit();
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubInfoByIdTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubInfoByIdTestExecutor.java
deleted file mode 100644
index 47dca4d1..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubInfoByIdTestExecutor.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-import com.google.android.utils.chre.ChreTestUtil;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * Verify NanoApp info by appId/instanceId
- *
- * Protocol:
- * Host to App: mTestName, no data
- * App to Host: CONTINUE, no data
- * Host to App: CONTINUE, 32-bit app version
- * App to Host: SUCCESS, no data
- */
-public class ContextHubInfoByIdTestExecutor extends ContextHubGeneralTestExecutor {
- private boolean mFirstMessage = true;
-
- public ContextHubInfoByIdTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary, ContextHubTestConstants.TestNames testName) {
- super(manager, info, new GeneralTestNanoApp(binary, testName));
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- if (type != ContextHubTestConstants.MessageType.CONTINUE) {
- fail("Unexpected message type " + type);
- return;
- }
-
- int version =
- ChreTestUtil.getNanoAppVersion(getContextHubManager(), getContextHubInfo(),
- nanoAppId);
- ByteBuffer buffer = ByteBuffer.allocate(4)
- .order(ByteOrder.LITTLE_ENDIAN)
- .putInt(version);
-
- sendMessageToNanoAppOrFail(nanoAppId, ContextHubTestConstants.MessageType.CONTINUE.asInt(),
- buffer.array());
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubNanoAppInfoEventsTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubNanoAppInfoEventsTestExecutor.java
deleted file mode 100644
index 6aa1cd6b..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubNanoAppInfoEventsTestExecutor.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-import com.google.android.utils.chre.ChreTestUtil;
-
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * Verify chreConfigureNanoAppInfoEvents.
- *
- * Protocol:
- * There are two nanoapps here, so we'll talk in terms of the observer
- * and the performer. All data involving the host is sent little endian
- *
- * Host to observer: NANOAPP_INFO_EVENTS_OBSERVER, no data
- * observer to Host: CONTINUE
- * [Host starts performer]
- * performer to Host: CONTINUE, 64-bit app ID, 32-bit instance ID
- * [Host stops performer]
- * Host to observer: CONTINUE, performer's 32-bit instance ID
- * observer to host: SUCCESS
- */
-public class ContextHubNanoAppInfoEventsTestExecutor extends ContextHubGeneralTestExecutor {
- private final long mObserverNanoAppId;
- private final NanoAppBinary mPerformerNanoAppBinary;
-
- public ContextHubNanoAppInfoEventsTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary observerBinary, NanoAppBinary performerBinary) {
- // Note that the performer nanoapp is not loaded/started at init, since it will be loaded
- // via the message from the observer nanoapp.
- super(manager, info, new GeneralTestNanoApp(observerBinary,
- ContextHubTestConstants.TestNames.NANO_APP_INFO_EVENTS_OBSERVER),
- new GeneralTestNanoApp(performerBinary,
- ContextHubTestConstants.TestNames.NANO_APP_INFO_EVENTS_PERFORMER,
- false /* loadAtInit */));
- mObserverNanoAppId = observerBinary.getNanoAppId();
- mPerformerNanoAppBinary = performerBinary;
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- if (type != ContextHubTestConstants.MessageType.CONTINUE) {
- fail("Unexpected message type " + type);
- return;
- }
-
- if (nanoAppId == mObserverNanoAppId) {
- if (!ChreTestUtil.loadNanoApp(getContextHubManager(), getContextHubInfo(),
- mPerformerNanoAppBinary)) {
- fail("Failed to load performer nanoapp");
- return;
- }
-
- // Send message to have the PERFORMER actually start
- sendMessageToNanoAppOrFail(mPerformerNanoAppBinary.getNanoAppId(),
- ContextHubTestConstants.TestNames.NANO_APP_INFO_EVENTS_PERFORMER.asInt(),
- new byte[0] /* data */);
- } else {
- ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
-
- int performerInstanceId = 0;
-
- try {
- // Ignore the nanoApp ID
- buffer.getLong();
- performerInstanceId = buffer.getInt();
- } catch (BufferUnderflowException ex) {
- fail("Not enough data provided in CONTINUE message");
- }
-
- assertFalse("Too much data provided in CONTINUE message", buffer.hasRemaining());
-
- buffer = ByteBuffer.allocate(4)
- .order(ByteOrder.LITTLE_ENDIAN)
- .putInt(performerInstanceId);
-
- if (!ChreTestUtil.unloadNanoApp(getContextHubManager(), getContextHubInfo(),
- mPerformerNanoAppBinary.getNanoAppId())) {
- fail("Failed to unload performer nanoapp");
- }
-
- sendMessageToNanoAppOrFail(mObserverNanoAppId,
- ContextHubTestConstants.MessageType.CONTINUE.asInt(), buffer.array());
- }
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSendMessageToHostTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSendMessageToHostTestExecutor.java
deleted file mode 100644
index c8689940..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSendMessageToHostTestExecutor.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-import android.hardware.location.NanoAppMessage;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * Check chreSendMessageToHost() works, along with an empty message from the
- * host to the nanoapp.
- *
- * Much of the logic for this test takes place within the nanoapp. From
- * the Host side, we:
- * 1) Confirm we receive all of these message of various length
- * 2) Send one (edge-case) message after we've received everything
- * 3) Wait for the nanoapp to declare victory
- *
- * TODO(b/32114261): This code is a lot more complicated than it should
- * be. Specifically, the standard workaround for this bug involves
- * putting more data within the 'message' to/from host/nanoapp. But
- * since we're specifically testing that data, we can't use that
- * workaround. When that workaround is gone, we can make this test
- * much simpler.
- *
- * Protocol:
- * Host: SEND_MESSAGE_TO_HOST, no data
- * Nanoapp: <SMALL_DATA_LENGTH> bytes of <RAW_DATA_BYTE>
- * Nanoapp: <SMALL_DATA_LENGTH> bytes of <RAW_DATA_BYTE>
- * Nanoapp: <SMALL_DATA_LENGTH> bytes of <RAW_DATA_BYTE>
- * Nanoapp: <SMALL_DATA_LENGTH> bytes of <RAW_DATA_BYTE>
- * Nanoapp: 0 bytes
- * Nanoapp: CONTINUE, 4 bytes (little endian) with <MessageMaxSize>
- * Nanoapp: <MessageMaxSize> bytes of <RAW_DATA_BYTE>
- * Host: 0 bytes
- * Nanoapp: kSuccess
- */
-public class ContextHubSendMessageToHostTestExecutor extends ContextHubGeneralTestExecutor {
- private static final int SMALL_DATA_LENGTH = 3;
- private static final byte RAW_DATA_BYTE = (byte) 0xFE;
-
- boolean mSentStartMessage = false;
-
- // This stage count is tracking the stage used within the nanoapp. See
- // the nanoapp code for more details on this. That will also make it
- // clearer why we skip one stage.
- private int mStageCount = 0;
- // We'll get this value from the nanoapp.
- private int mMessageMaxSize = 0;
-
- public ContextHubSendMessageToHostTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary) {
- super(manager, info, new GeneralTestNanoApp(binary,
- ContextHubTestConstants.TestNames.SEND_MESSAGE_TO_HOST));
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- if (type != ContextHubTestConstants.MessageType.CONTINUE) {
- fail("Unexpected message type " + type);
- return;
- }
-
- switch (mStageCount) {
- case 0: // fall-through
- case 1: // fall-through
- case 2: // fall-through
- case 3:
- checkSmallData(data);
- break;
-
- case 4:
- assertEquals("Expected zero length data", 0, data.length);
- break;
-
- case 5:
- readMessageMaxSize(data);
- // Note that we don't receive a message for stage 6, so we
- // skip it here.
- mStageCount++;
- break;
-
- case 7:
- checkLargeData(data);
- sendEmptyMessage(nanoAppId);
- break;
-
- case 6: // fall-through
- default:
- fail("Unexpected stage " + mStageCount);
- break;
- }
- // We expect the next message to be at the next stage.
- mStageCount++;
- }
-
- private boolean isGeneralProtocolMessage(byte[] data) {
- if (data.length < 4) {
- return false;
- }
- for (int i = 0; i < 4; i++) {
- if (data[i] != RAW_DATA_BYTE) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- protected NanoAppMessage hackMessageToNanoApp(NanoAppMessage message) {
- if (!mSentStartMessage) {
- // Our start message, SEND_MESSAGE_TO_HOST, needs to
- // be sent via the standard workaround protocol.
- mSentStartMessage = true;
- return super.hackMessageToNanoApp(message);
- }
- // This should be our zero-length message, which we want to send raw.
- return NanoAppMessage.createMessageToNanoApp(
- message.getNanoAppId(), message.getMessageType(), message.getMessageBody());
- }
-
- @Override
- protected NanoAppMessage hackMessageFromNanoApp(NanoAppMessage message) {
- if (isGeneralProtocolMessage(message.getMessageBody())) {
- // This is going to be something like FAILURE or SUCCESS
- // which we want our standard infrastructure to handle.
- return super.hackMessageFromNanoApp(message);
- }
- // We'll use the CONTINUE message type for all messages from
- // the nanoapp, even though the nanoapp doesn't send that.
- return NanoAppMessage.createMessageFromNanoApp(
- message.getNanoAppId(), ContextHubTestConstants.MessageType.CONTINUE.asInt(),
- message.getMessageBody(), message.isBroadcastMessage());
- }
-
- private void checkSmallData(byte[] data) {
- assertEquals("Wrong small data length in stage " + mStageCount,
- SMALL_DATA_LENGTH, data.length);
- for (int i = 0; i < data.length; i++) {
- assertEquals("Bad data " + data[i] + " at index " + i
- + " in stage " + mStageCount,
- RAW_DATA_BYTE, data[i]);
- }
- }
-
- private void readMessageMaxSize(byte[] data) {
- mMessageMaxSize = ByteBuffer.wrap(data)
- .order(ByteOrder.LITTLE_ENDIAN)
- .getInt();
- assertTrue("Given bad max message size: " + mMessageMaxSize,
- mMessageMaxSize > 0);
- }
-
- private void checkLargeData(byte[] data) {
- assertTrue("checkLargeData called without mMessageMaxSize",
- mMessageMaxSize != 0);
- assertEquals("checkLargeData has bad data length",
- mMessageMaxSize, data.length);
- for (int i = 0; i < data.length; i++) {
- assertEquals("Failed raw data check at index " + i,
- RAW_DATA_BYTE, data[i]);
- }
- }
-
- private void sendEmptyMessage(long nanoAppId) {
- // Note that ContextHubManager/Client requires this to be non-null
- sendMessageToNanoAppOrFail(nanoAppId, ContextHubTestConstants.MessageType.CONTINUE.asInt(),
- new byte[0]);
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSimpleGeneralTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSimpleGeneralTestExecutor.java
deleted file mode 100644
index 9836616e..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSimpleGeneralTestExecutor.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-/**
- * A class that can execute the CHQTS simple "general" nanoapp tests.
- */
-public class ContextHubSimpleGeneralTestExecutor extends ContextHubGeneralTestExecutor {
-
- public ContextHubSimpleGeneralTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary, ContextHubTestConstants.TestNames testName) {
- super(manager, info, new GeneralTestNanoApp(binary, testName));
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- // No specific messages for simple "general" tests.
- fail("Unexpected message type " + type);
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSimpleHeapAllocTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSimpleHeapAllocTestExecutor.java
deleted file mode 100644
index 88b0934c..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubSimpleHeapAllocTestExecutor.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-/**
- * Performs simple allocation and freeing from the heap.
- *
- * Requires the host to send an additional message to tell us to free.
- *
- * Protocol:
- * Host: SIMPLE_HEAP_ALLOC
- * Nanoapp: CONTINUE, no data
- * Host: CONTINUE, no data
- * Nanoapp: SUCCESS, no data
- *
- * This is paired with general_test/simple_heap_alloc_test.h.
- */
-public class ContextHubSimpleHeapAllocTestExecutor extends ContextHubGeneralTestExecutor {
- private boolean mFirstMessage = true;
-
- public ContextHubSimpleHeapAllocTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary) {
- super(manager, info, new GeneralTestNanoApp(binary,
- ContextHubTestConstants.TestNames.SIMPLE_HEAP_ALLOC));
- }
-
- @Override
- protected void handleMessageFromNanoApp(long nanoAppId,
- ContextHubTestConstants.MessageType type, byte[] data) {
- if (type != ContextHubTestConstants.MessageType.CONTINUE) {
- fail("Unexpected message type " + type);
- return;
- }
-
- assertTrue("Multiple CONTINUE messages from nanoapp",
- mFirstMessage);
- mFirstMessage = false;
- assertEquals("Expected 0 bytes data from nanoapp CONTINUE; "
- + "got " + data.length + " bytes",
- 0, data.length);
-
- byte[] emptyData = new byte[0];
- sendMessageToNanoAppOrFail(nanoAppId, ContextHubTestConstants.MessageType.CONTINUE.asInt(),
- emptyData);
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubTestConstants.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubTestConstants.java
deleted file mode 100644
index b2fa1c34..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubTestConstants.java
+++ /dev/null
@@ -1,365 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import org.junit.Assert;
-
-/**
- * These values come from nanoapps/general_test/test_names.h and
- * nanoapps/shared/send_message.h.
- *
- * TODO: This is very fragile. We should try to automate keeping this
- * in sync. That's made mildly more challenging by different
- * language constructs and naming conventions.
- */
-public class ContextHubTestConstants {
- /**
- * Names of the tests we support.
- */
- public enum TestNames {
- /**
- * Value which should never be used.
- */
- INVALID_TEST(0x0400),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[HelloWorld]
- */
- HELLO_WORLD(0x0401),
-
- /**
- * Test: ContextHubSimpleHeapAllocNanoAppTest
- */
- SIMPLE_HEAP_ALLOC(0x0402),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[HeapAllocStress]
- */
- HEAP_ALLOC_STRESS(0x0403),
-
- /**
- * Test: ContextHubGetTimeNanoAppTest
- */
- GET_TIME(0x0404),
-
- /**
- * Test: ContextHubEventBetweenAppsNanoAppTest
- */
- EVENT_BETWEEN_APPS0(0x0405),
-
- /**
- * Test: ContextHubEventBetweenAppsNanoAppTest
- */
- EVENT_BETWEEN_APPS1(0x0406),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[SendEvent]
- */
- SEND_EVENT(0x0407),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicAccelerometer]
- */
- BASIC_ACCELEROMETER(0x0408),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicInstantMotionDetect]
- */
- BASIC_INSTANT_MOTION_DETECT(0x0409),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicStationaryDetect]
- */
- BASIC_STATIONARY_DETECT(0x040A),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicGyroscope]
- */
- BASIC_GYROSCOPE(0x040B),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicMagnetometer]
- */
- BASIC_MAGNETOMETER(0x040C),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicBarometer]
- */
- BASIC_BAROMETER(0x040D),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicLightSensor]
- */
- BASIC_LIGHT_SENSOR(0x040E),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicProximity]
- */
- BASIC_PROXIMITY(0x040F),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[VersionConsistency]
- */
- VERSION_CONSISTENCY(0x0410),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[LoggingConsistency]
- */
- LOGGING_CONSISTENCY(0x0411),
-
- /**
- * Test: ContextHubSendMessageToHostNanoAppTest
- */
- SEND_MESSAGE_TO_HOST(0x0412),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[TimerSet]
- */
- TIMER_SET(0x0413),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[TimerCancel]
- */
- TIMER_CANCEL(0x0414),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[TimerStress]
- */
- TIMER_STRESS(0x0415),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[SendEventStress]
- */
- SEND_EVENT_STRESS(0x0416),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[HeapExhaustionStability]
- */
- HEAP_EXHAUSTION_STABILITY(0x0417),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[GnssCapabilities]
- */
- GNSS_CAPABILITIES(0x0418),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[WifiCapabilities]
- */
- WIFI_CAPABILITIES(0x0419),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[WwanCapabilities]
- */
- WWAN_CAPABILITIES(0x041A),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[SensorInfoTest]
- */
- SENSOR_INFO(0x041B),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[WwanCellInfo]
- */
- WWAN_CELL_INFO(0x041C),
-
- /**
- * Test: ContextHubEstimatedHostTimeTest
- */
- ESTIMATED_HOST_TIME(0x041D),
-
- /**
- * Test: ContextHubNanoAppInfoByIdTests[NanoappInfoByAppId]
- */
- NANOAPP_INFO_BY_APP_ID(0x041E),
-
- /**
- * Test: ContextHubNanoAppInfoByIdTests[NanoappInfoByInstanceId]
- */
- NANOAPP_INFO_BY_INSTANCE_ID(0x041F),
-
- /**
- * Test: ContextHubNanoAppInfoEventsTest (Performer)
- */
- NANO_APP_INFO_EVENTS_PERFORMER(0x0420),
-
- /**
- * Test: ContextHubNanoAppInfoEventsTest (Observer)
- */
- NANO_APP_INFO_EVENTS_OBSERVER(0x0421),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicAudioTest]
- */
- BASIC_AUDIO_TEST(0x0422),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[HostAwakeSuspend]
- */
- HOST_AWAKE_SUSPEND(0x0423),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicGnssTest]
- */
- BASIC_GNSS_TEST(0x0424),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicWifiTest]
- */
- BASIC_WIFI_TEST(0x0425),
-
- /**
- * Test: ContextHubSimpleGeneralNanoAppTests[BasicSensorFlushAsyncTest]
- */
- BASIC_SENSOR_FLUSH_ASYNC_TEST(0x0426);
-
- private final int mValue;
- TestNames(int value) {
- this.mValue = value;
- }
-
- /**
- * Get the integer value for this TestNames.
- *
- * This is very efficient, O(1).
- *
- * @return integer value
- */
- public int asInt() {
- return mValue;
- }
- }
-
- /**
- * Messages types which are sent between Nanoapps and the Java Host testing
- * code.
- */
- public enum MessageType {
- /**
- * Value which should never be used.
- *
- * This type should never be sent by Host or Nanoapp code.
- */
- INVALID_MESSAGE_TYPE(0x0400),
-
- /**
- * Test has completed in success.
- *
- * Upon receiving this message type, the infrastructure considers
- * the test a success and concludes testing.
- *
- * This type should only be sent by the Nanoapp code.
- */
- SUCCESS(0x0401),
-
- /**
- * Test has failed.
- *
- * Upon receiving this message type, the infrastructure considers
- * the test to be a failure, and concludes testing. The presumption
- * is that the failure is due to an issue in the CHRE implementation
- * and/or Context Hub HAL implementation.
- *
- * This type should only be sent by the Nanoapp code.
- */
- FAILURE(0x0402),
-
- /**
- * Test has failed due to an issue within the testing framework.
- *
- * Upon receiving this message type, the infrastructure considers
- * the test to be a failure, and concludes testing. The presumption
- * is that the failure is due to an issue in the test itself, or
- * the testing framework code, and that the CHRE and/or Context Hub HAL
- * implementations may not have any issues.
- *
- * This type should only be sent by the Nanoapp code.
- */
- INTERNAL_FAILURE(0x0403),
-
- /**
- * Test is being skipped because it is not relevant.
- *
- * Upon receiving this message type, the infrastructure considers
- * the test to be "skipped". That is, this test is not considered
- * relevant, and shouldn't considered a failure, but it never
- * executed.
- *
- * This type should only be send by the Nanoapp code.
- */
- SKIPPED(0x0404),
-
- /**
- * A generic message indicating that the test should continue.
- *
- * The meaning of this generic message depends on the specific test.
- * In general, it means something along the lines of "The test is
- * successful thus far, please proceed to the next stage."
- *
- * This type can be sent by the Host or Nanoapp code.
- */
- CONTINUE(0x0405),
-
- /**
- * A message type to be used to test sending messages through the ContextHubClient.
- *
- * This message type should be used only for tests under the ContextHubServiceTestBase
- * framework.
- */
- SERVICE_MESSAGE(0x0406);
-
- private final int mValue;
- MessageType(int value) {
- this.mValue = value;
- }
-
- /**
- * Get the integer value for this message type.
- *
- * This is very efficient, O(1).
- *
- * @return integer value
- */
- public int asInt() {
- return mValue;
- }
-
- /**
- * Get the MessageType for a given integer value.
- *
- * This method will abort the running test if the given value does
- * not correspond to any MessageType.
- *
- * This is inefficient: O(N).
- *
- * @param value The value we're finding the MessageType for.
- * @param errorMessage In the case 'value' does not match any
- * MessageType, our test failure message will include this.
- * @return The matching MessageType.
- */
- public static MessageType fromInt(int value, String errorMessage) {
- for (MessageType type : MessageType.values()) {
- if (value == type.asInt()) {
- return type;
- }
- }
-
- Assert.fail("Unknown MessageType (" + value + ") from "
- + errorMessage);
- // Will never get here.
- return MessageType.INVALID_MESSAGE_TYPE;
- }
- }
-}
diff --git a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubTrivialNanoAppsTestExecutor.java b/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubTrivialNanoAppsTestExecutor.java
deleted file mode 100644
index 456fffe3..00000000
--- a/java/test/chqts/src/com/google/android/chre/test/chqts/ContextHubTrivialNanoAppsTestExecutor.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.chqts;
-
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.NanoAppBinary;
-
-import com.google.android.utils.chre.ChreTestUtil;
-
-import org.junit.Assert;
-
-/**
- * Tests of the absolutely most basic valid nanoapps.
- *
- * This tests that a nanoapp loads successfully/unsuccessfully, as intended. For instance,
- * the "do_nothing" nanoapp is expected to succeed, and "fail_startup" is expected to fail.
- */
-public class ContextHubTrivialNanoAppsTestExecutor {
- private final ContextHubManager mContextHubManager;
-
- private final ContextHubInfo mContextHubInfo;
-
- public ContextHubTrivialNanoAppsTestExecutor(ContextHubManager manager, ContextHubInfo info) {
- mContextHubManager = manager;
- mContextHubInfo = info;
- }
-
- /**
- * Run the test.
- */
- public void run(NanoAppBinary binary, boolean expectLoadSuccess) {
- boolean success = ChreTestUtil.loadNanoApp(mContextHubManager, mContextHubInfo, binary);
-
- if (success) {
- ChreTestUtil.unloadNanoAppAssertSuccess(mContextHubManager, mContextHubInfo,
- binary.getNanoAppId());
- }
-
- Assert.assertEquals("Unexpected load result", expectLoadSuccess, success);
- }
-}
diff --git a/java/test/cross_validation/Android.bp b/java/test/cross_validation/Android.bp
index e56416cf..ef60703c 100644
--- a/java/test/cross_validation/Android.bp
+++ b/java/test/cross_validation/Android.bp
@@ -1,4 +1,4 @@
-// Copyright (C) 2020 The Android Open Source Project
+// Copyright (C) 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -12,15 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
java_library {
name: "chre-cross-validation",
diff --git a/java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorSensor.java b/java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorSensor.java
index 87272008..4f8db722 100644
--- a/java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorSensor.java
+++ b/java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorSensor.java
@@ -329,7 +329,6 @@ public class ChreCrossValidatorSensor
map.put(Sensor.TYPE_PRESSURE, new CrossValidatorSensorConfig(1, 0.01f));
map.put(Sensor.TYPE_LIGHT, new CrossValidatorSensorConfig(1, 0.07f));
map.put(Sensor.TYPE_PROXIMITY, new CrossValidatorSensorConfig(1, 0.01f));
- map.put(Sensor.TYPE_STEP_COUNTER, new CrossValidatorSensorConfig(1, 0f));
return map;
}
@@ -347,7 +346,6 @@ public class ChreCrossValidatorSensor
map.put(Sensor.TYPE_PRESSURE, 10 /* CHRE_SENSOR_TYPE_PRESSURE */);
map.put(Sensor.TYPE_LIGHT, 12 /* CHRE_SENSOR_TYPE_LIGHT */);
map.put(Sensor.TYPE_PROXIMITY, 13 /* CHRE_SENSOR_TYPE_PROXIMITY */);
- map.put(Sensor.TYPE_STEP_COUNTER, 24 /* CHRE_SENSOR_TYPE_STEP_COUNTER */);
return map;
}
@@ -355,7 +353,6 @@ public class ChreCrossValidatorSensor
* Start collecting data from AP
*/
private void collectDataFromAp() {
- mCollectingData.set(true);
Assert.assertTrue(mSensorManager.registerListener(
this, mSensor, (int) TimeUnit.MILLISECONDS.toMicros(mSamplingIntervalInMs)));
}
@@ -386,6 +383,7 @@ public class ChreCrossValidatorSensor
* ms.
*/
private void waitForDataSampling() throws AssertionError {
+ mCollectingData.set(true);
try {
mAwaitDataLatch.await(getAwaitDataTimeoutInMs(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
diff --git a/java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorWifi.java b/java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorWifi.java
index a6cd0952..a9382888 100644
--- a/java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorWifi.java
+++ b/java/test/cross_validation/src/com/google/android/chre/test/crossvalidator/ChreCrossValidatorWifi.java
@@ -40,7 +40,7 @@ import com.google.protobuf.InvalidProtocolBufferException;
import org.junit.Assert;
import org.junit.Assume;
-import java.util.Collections;
+import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -48,8 +48,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class ChreCrossValidatorWifi extends ChreCrossValidatorBase {
- private static final long AWAIT_STEP_RESULT_MESSAGE_TIMEOUT_SEC = 7;
- private static final long AWAIT_WIFI_SCAN_RESULT_TIMEOUT_SEC = 30;
+ private static final long AWAIT_STEP_RESULT_MESSAGE_TIMEOUT_MS = 1000; // 1 sec
+ private static final long AWAIT_WIFI_SCAN_RESULT_TIMEOUT_MS = 3000; // 3 sec
private static final long NANO_APP_ID = 0x476f6f6754000005L;
@@ -60,8 +60,6 @@ public class ChreCrossValidatorWifi extends ChreCrossValidatorBase {
private static final int WIFI_CAPABILITIES_SCAN_MONITORING = 1;
private static final int WIFI_CAPABILITIES_ON_DEMAND_SCAN = 2;
- private static final int NUM_BYTES_IN_SCAN_RESULT_BSSID = 6;
-
AtomicReference<Step> mStep = new AtomicReference<Step>(Step.INIT);
AtomicBoolean mDidReceiveNanoAppMessage = new AtomicBoolean(false);
@@ -112,7 +110,6 @@ public class ChreCrossValidatorWifi extends ChreCrossValidatorBase {
mCollectingData.set(true);
sendStepStartMessage(Step.SETUP);
-
waitForMessageFromNanoapp();
mCollectingData.set(false);
@@ -166,7 +163,7 @@ public class ChreCrossValidatorWifi extends ChreCrossValidatorBase {
*/
private void waitForMessageFromNanoapp() {
try {
- mAwaitDataLatch.await(AWAIT_STEP_RESULT_MESSAGE_TIMEOUT_SEC, TimeUnit.SECONDS);
+ mAwaitDataLatch.await(AWAIT_STEP_RESULT_MESSAGE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Assert.fail("Interrupted while awaiting " + getCurrentStepName() + " step");
}
@@ -190,7 +187,7 @@ public class ChreCrossValidatorWifi extends ChreCrossValidatorBase {
private void waitForApScanResults() {
try {
- mAwaitApWifiSetupScan.await(AWAIT_WIFI_SCAN_RESULT_TIMEOUT_SEC, TimeUnit.SECONDS);
+ mAwaitApWifiSetupScan.await(AWAIT_WIFI_SCAN_RESULT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Assert.fail("Interrupted while awaiting ap wifi scan result");
}
@@ -288,42 +285,9 @@ public class ChreCrossValidatorWifi extends ChreCrossValidatorBase {
}
private static byte[] bssidToBytes(String bssid) {
- String expectedBssidFormat =
- String.join(":", Collections.nCopies(NUM_BYTES_IN_SCAN_RESULT_BSSID, "ff"));
- Assert.assertTrue(
- String.format("Bssid did not match expected format %s bssid = %s",
- expectedBssidFormat, bssid), verifyBssid(bssid));
- // the ScanResult.BSSID field comes in format ff:ff:ff:ff:ff:ff and needs to be converted to
+ // the ScanResult.BSSID field comes in format ff:ff:ff:ff:ff and needs to be converted to
// bytes in order to be compared to CHRE bssid
- String hexStringNoColon = bssid.replace(":" , "");
- byte[] bytes = new byte[NUM_BYTES_IN_SCAN_RESULT_BSSID];
- for (int i = 0; i < 6; i++) {
- // Shift first byte digit left bitwise to raise value than add second digit of byte.
- bytes[i] =
- (byte) ((Character.digit(hexStringNoColon.charAt(i * 2), 16) << 4)
- + Character.digit(hexStringNoColon.charAt(i * 2 + 1), 16));
- }
- return bytes;
- }
-
- /**
- * Verify that the BSSID field from AP Wifi scan results is of the format:
- * ff:ff:ff:.. where the number of bytes should equal to NUM_BYTES_IN_SCAN_RESULTS_BSSID
- * and there should be a ':' between each byte.
- *
- * @param bssid The bssid field to verify.
- */
- private static boolean verifyBssid(String bssid) {
- boolean passedVerification = (bssid.length() == NUM_BYTES_IN_SCAN_RESULT_BSSID * 3 - 1);
- for (int i = 0; passedVerification && i < bssid.length(); i += 3) {
- if ((Character.digit(bssid.charAt(i), 16) == -1)
- || (Character.digit(bssid.charAt(i + 1), 16) == -1)
- || ((i + 2 < bssid.length()) && (bssid.charAt(i + 2) != ':'))) {
- passedVerification = false;
- break;
- }
- }
- return passedVerification;
+ return (new BigInteger(bssid.replace(":" , ""), 16)).toByteArray();
}
// TODO: Implement this method
diff --git a/java/test/permissions/Android.bp b/java/test/permissions/Android.bp
deleted file mode 100644
index 6dd10bfc..00000000
--- a/java/test/permissions/Android.bp
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (C) 2021 The Android Open Source Project
-//
-// 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.
-
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
-java_library {
- name: "context-hub-permissions-test",
-
- srcs: ["src/**/*.java"],
-
- static_libs: [
- "androidx.test.rules",
- "permission_test_java_proto",
- "ping_test_java_proto",
- "chre_test_common_java_proto",
- "chre-test-utils",
- ],
-
- sdk_version: "system_current",
-}
diff --git a/java/test/permissions/src/com/google/android/chre/test/permissions/ContextHubChrePermissionsTestExecutor.java b/java/test/permissions/src/com/google/android/chre/test/permissions/ContextHubChrePermissionsTestExecutor.java
deleted file mode 100644
index 0d313f9e..00000000
--- a/java/test/permissions/src/com/google/android/chre/test/permissions/ContextHubChrePermissionsTestExecutor.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.permissions;
-
-import android.app.Instrumentation;
-import android.hardware.location.ContextHubClient;
-import android.hardware.location.ContextHubClientCallback;
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.ContextHubTransaction;
-import android.hardware.location.NanoAppBinary;
-import android.hardware.location.NanoAppMessage;
-import android.util.Log;
-
-import androidx.test.InstrumentationRegistry;
-
-import com.google.android.chre.nanoapp.proto.ChreTestCommon;
-import com.google.android.chre.nanoapp.proto.PermissionTest;
-import com.google.android.utils.chre.ChreTestUtil;
-
-import org.junit.Assert;
-
-import java.nio.charset.StandardCharsets;
-import java.util.concurrent.LinkedBlockingDeque;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * A class that can execute the permission gated API test.
- */
-public class ContextHubChrePermissionsTestExecutor extends ContextHubClientCallback {
- private static final String TAG = "ContextHubChrePermissionsTestExecutor";
-
- private final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
-
- private final NanoAppBinary mNanoAppBinary;
-
- private final long mNanoAppId;
-
- private final ContextHubClient mContextHubClient;
-
- private final ContextHubManager mContextHubManager;
-
- private final ContextHubInfo mContextHubInfo;
-
- private AtomicBoolean mHubResetDuringTest = new AtomicBoolean();
-
- private LinkedBlockingDeque<NanoAppMessage> mMessageQueue = new LinkedBlockingDeque<>();
-
- public ContextHubChrePermissionsTestExecutor(
- ContextHubManager manager, ContextHubInfo info, NanoAppBinary binary) {
- mContextHubManager = manager;
- mContextHubInfo = info;
- mNanoAppBinary = binary;
- mNanoAppId = mNanoAppBinary.getNanoAppId();
-
- mContextHubClient = mContextHubManager.createClient(mContextHubInfo, this);
- Assert.assertTrue(mContextHubClient != null);
- }
-
- @Override
- public void onMessageFromNanoApp(ContextHubClient client, NanoAppMessage message) {
- if (message.getNanoAppId() == mNanoAppId) {
- Log.d(TAG, "Got message from nanoapp: type " + message.getMessageType());
- mMessageQueue.add(message);
- }
- }
-
- @Override
- public void onHubReset(ContextHubClient client) {
- mHubResetDuringTest.set(true);
- }
-
- /**
- * Should be invoked before run() is invoked to set up the test, e.g. in a @Before method.
- */
- public void init() {
- ChreTestUtil.loadNanoAppAssertSuccess(mContextHubManager, mContextHubInfo, mNanoAppBinary);
- }
-
- /**
- * Runs the test where an app is forced to the denied authentication state.
- */
- public void checkPermissionGatedApisTest() throws Exception {
- NanoAppMessage message = NanoAppMessage.createMessageToNanoApp(
- mNanoAppId, PermissionTest.MessageType.TEST_COMMAND_VALUE,
- new byte[0] /* messageBody */);
- int result = mContextHubClient.sendMessageToNanoApp(message);
- if (result != ContextHubTransaction.RESULT_SUCCESS) {
- Assert.fail("Failed to send message: result = " + result);
- }
-
- NanoAppMessage rcvdMsg = null;
- try {
- rcvdMsg = mMessageQueue.poll(2, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
-
- Assert.assertNotNull("Timed out waiting for a message", rcvdMsg);
- Log.d(TAG, "Got message from nanoapp: " + rcvdMsg);
-
- Assert.assertEquals(PermissionTest.MessageType.TEST_RESULT_VALUE, rcvdMsg.getMessageType());
- ChreTestCommon.TestResult resultProto =
- ChreTestCommon.TestResult.parseFrom(rcvdMsg.getMessageBody());
- if (resultProto.hasErrorMessage()) {
- Assert.assertEquals(new String(resultProto.getErrorMessage().toByteArray(),
- StandardCharsets.UTF_8),
- ChreTestCommon.TestResult.Code.PASSED, resultProto.getCode());
- } else {
- Assert.assertEquals(ChreTestCommon.TestResult.Code.PASSED, resultProto.getCode());
- }
- }
-
- /**
- * Cleans up the test, should be invoked in e.g. @After method.
- */
- public void deinit() {
- ChreTestUtil.unloadNanoApp(mContextHubManager, mContextHubInfo, mNanoAppId);
- mContextHubClient.close();
- Assert.assertFalse(mHubResetDuringTest.get());
- }
-}
diff --git a/java/test/permissions/src/com/google/android/chre/test/permissions/ContextHubFrameworkPermissionsTestExecutor.java b/java/test/permissions/src/com/google/android/chre/test/permissions/ContextHubFrameworkPermissionsTestExecutor.java
deleted file mode 100644
index f0f9cd6f..00000000
--- a/java/test/permissions/src/com/google/android/chre/test/permissions/ContextHubFrameworkPermissionsTestExecutor.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.permissions;
-
-import android.app.Instrumentation;
-import android.content.Context;
-import android.hardware.location.ContextHubClient;
-import android.hardware.location.ContextHubClientCallback;
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.ContextHubTransaction;
-import android.hardware.location.NanoAppBinary;
-import android.hardware.location.NanoAppMessage;
-import android.util.Log;
-
-import androidx.test.InstrumentationRegistry;
-
-import com.google.android.chre.nanoapp.proto.PingTest;
-import com.google.android.utils.chre.ChreTestUtil;
-
-import org.junit.Assert;
-
-import java.util.concurrent.LinkedBlockingDeque;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * A class that can execute the Context Hub framework permissions test.
- */
-public class ContextHubFrameworkPermissionsTestExecutor extends ContextHubClientCallback {
- private static final String TAG = "ContextHubFrameworkPermissionsTestExecutor";
-
- private final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
-
- private final NanoAppBinary mNanoAppBinary;
-
- private final long mNanoAppId;
-
- private final ContextHubClient mContextHubClient;
-
- private final ContextHubManager mContextHubManager;
-
- private final ContextHubInfo mContextHubInfo;
-
- private final Context mContext;
-
- private final String mPackageName;
-
- private AtomicBoolean mHubResetDuringTest = new AtomicBoolean();
-
- private LinkedBlockingDeque<NanoAppMessage> mMessageQueue = new LinkedBlockingDeque<>();
-
- private LinkedBlockingDeque<Integer> mAuthorizationUpdateQueue = new LinkedBlockingDeque<>();
-
- public ContextHubFrameworkPermissionsTestExecutor(
- ContextHubManager manager, ContextHubInfo info, NanoAppBinary binary) {
- mContextHubManager = manager;
- mContextHubInfo = info;
- mNanoAppBinary = binary;
- mNanoAppId = mNanoAppBinary.getNanoAppId();
- mContext = mInstrumentation.getTargetContext();
- mPackageName = mContext.getPackageName();
-
- mContextHubClient = mContextHubManager.createClient(mContextHubInfo, this);
- Assert.assertTrue(mContextHubClient != null);
- }
-
- @Override
- public void onMessageFromNanoApp(ContextHubClient client, NanoAppMessage message) {
- if (message.getNanoAppId() == mNanoAppId) {
- Log.e(TAG, "Got message from nanoapp: type " + message.getMessageType());
- mMessageQueue.add(message);
- }
- }
-
- @Override
- public void onClientAuthorizationChanged(
- ContextHubClient client, long nanoAppId, int authorization) {
- if (nanoAppId == mNanoAppId) {
- Log.d(TAG, "onClientAuthorizationChanged: nanoapp ID " + nanoAppId + " auth state "
- + authorization);
- mAuthorizationUpdateQueue.add(authorization);
- }
- }
-
- @Override
- public void onHubReset(ContextHubClient client) {
- mHubResetDuringTest.set(true);
- }
-
- /**
- * Should be invoked before run() is invoked to set up the test, e.g. in a @Before method.
- */
- public void init() {
- ChreTestUtil.loadNanoAppAssertSuccess(mContextHubManager, mContextHubInfo, mNanoAppBinary);
- }
-
- /**
- * Runs the test where an app is forced to the denied authentication state.
- */
- public void permissionsDisabledTest() throws Exception {
- PingTest.PingCommand command =
- PingTest.PingCommand.newBuilder().build();
- NanoAppMessage message = NanoAppMessage.createMessageToNanoApp(
- mNanoAppId, PingTest.MessageType.PING_COMMAND_VALUE,
- command.toByteArray());
- int result = mContextHubClient.sendMessageToNanoApp(message);
- if (result != ContextHubTransaction.RESULT_SUCCESS) {
- Assert.fail("Failed to send message: result = " + result);
- }
-
- try {
- NanoAppMessage msg = mMessageQueue.poll(2, TimeUnit.SECONDS);
- Assert.assertNotNull("Timed out waiting for a message", msg);
- Log.d(TAG, "Got message from nanoapp: " + msg);
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
-
- // No need to grant our package again since the denial will be tied to
- // the current contexthubclient which is only used by this test.
- ChreTestUtil.executeShellCommandWithAppPerms(
- "cmd contexthub deny " + mContextHubInfo.getId()
- + " " + mContext.getPackageName() + " " + mNanoAppId);
-
- int authorization = mAuthorizationUpdateQueue.poll(2, TimeUnit.SECONDS);
- Assert.assertEquals(authorization, ContextHubManager.AUTHORIZATION_DENIED);
-
- try {
- mContextHubClient.sendMessageToNanoApp(message);
- Assert.fail("Sent message to nanoapp even though permissions were denied");
- } catch (SecurityException e) {
- // Expected
- }
- Assert.assertTrue(mAuthorizationUpdateQueue.isEmpty());
- Assert.assertFalse(mHubResetDuringTest.get());
- }
-
- /**
- * Runs the test where an app attempts to send a message with data covered
- * by permissions.
- */
- public void messagePermissionsTest() throws Exception {
- // Defined in chre/util/system/napp_permissions.h
- final int audioPermission = 1;
- PingTest.PingCommand command =
- PingTest.PingCommand.newBuilder().setPermissions(audioPermission).build();
- NanoAppMessage message = NanoAppMessage.createMessageToNanoApp(
- mNanoAppId, PingTest.MessageType.PING_COMMAND_VALUE,
- command.toByteArray());
- int result = mContextHubClient.sendMessageToNanoApp(message);
- if (result != ContextHubTransaction.RESULT_SUCCESS) {
- Assert.fail("Failed to send message: result = " + result);
- }
-
- try {
- NanoAppMessage msg = mMessageQueue.poll(2, TimeUnit.SECONDS);
- Assert.assertNotNull("Timed out waiting for a message", msg);
- Log.d(TAG, "Got message from nanoapp: " + msg);
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
- }
-
- /**
- * Cleans up the test, should be invoked in e.g. @After method.
- */
- public void deinit() {
- ChreTestUtil.unloadNanoApp(mContextHubManager, mContextHubInfo, mNanoAppId);
- mContextHubClient.close();
- }
-}
diff --git a/java/test/settings/Android.bp b/java/test/settings/Android.bp
index f26ff7f2..b10c8849 100644
--- a/java/test/settings/Android.bp
+++ b/java/test/settings/Android.bp
@@ -1,4 +1,4 @@
-// Copyright (C) 2020 The Android Open Source Project
+// Copyright (C) 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -12,15 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
java_library {
name: "context-hub-settings-test",
diff --git a/java/test/settings/src/com/google/android/chre/test/setting/ContextHubMicDisableSettingsTestExecutor.java b/java/test/settings/src/com/google/android/chre/test/setting/ContextHubMicDisableSettingsTestExecutor.java
deleted file mode 100644
index 90959258..00000000
--- a/java/test/settings/src/com/google/android/chre/test/setting/ContextHubMicDisableSettingsTestExecutor.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.setting;
-
-import android.app.Instrumentation;
-import android.hardware.location.NanoAppBinary;
-
-import androidx.test.InstrumentationRegistry;
-
-import com.google.android.chre.nanoapp.proto.ChreSettingsTest;
-import com.google.android.utils.chre.ChreTestUtil;
-
-import org.junit.Assert;
-
-/**
- * A test to check for behavior when MIC_DISABLE settings are changed.
- */
-public class ContextHubMicDisableSettingsTestExecutor {
- private static final String TAG = "ContextHubMicDisableSettingsTest";
- private final ContextHubSettingsTestExecutor mExecutor;
-
- private final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
-
- /* TODO: Until we implement an API to query the setting state from within CHRE, assume that
- * microphone access is always enabled.
- */
- private final boolean mInitialMicDisabledState = false;
-
- public ContextHubMicDisableSettingsTestExecutor(NanoAppBinary binary) {
- mExecutor = new ContextHubSettingsTestExecutor(binary);
- }
-
- /**
- * Should be called in a @Before method.
- */
- public void setUp() {
- mExecutor.init();
- }
-
- public void runMicDisableSettingsTest() {
- setMicrophoneDisableSetting(false /* disableAccess */);
- runTest(ChreSettingsTest.TestCommand.Feature.AUDIO, false /* enableFeature */);
-
- setMicrophoneDisableSetting(true /* disableAccess */);
- runTest(ChreSettingsTest.TestCommand.Feature.AUDIO, true /* enableFeature */);
- }
-
- /**
- * Should be called in an @After method.
- */
- public void tearDown() {
- mExecutor.deinit();
- setMicrophoneDisableSetting(mInitialMicDisabledState);
- }
-
- /**
- * Helper function to set the Microphone Disable user setting
- * @param enable True to disable microphone access, false to allow it.
- */
- private void setMicrophoneDisableSetting(boolean disableAccess) {
- String settingEnableStr = disableAccess ? "enable" : "disable";
- ChreTestUtil.executeShellCommand(mInstrumentation,
- "cmd sensor_privacy " + settingEnableStr + " 0 microphone");
-
- try {
- Thread.sleep(1000); // wait for setting to propagate
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
- }
-
- /**
- * Helper function to run the test.
- * @param feature The feature to test.
- * @param enableFeature True for enable.
- */
- private void runTest(ChreSettingsTest.TestCommand.Feature feature, boolean enableFeature) {
- ChreSettingsTest.TestCommand.State state = enableFeature
- ? ChreSettingsTest.TestCommand.State.ENABLED
- : ChreSettingsTest.TestCommand.State.DISABLED;
- mExecutor.startTestAssertSuccess(feature, state);
- }
-}
diff --git a/java/test/settings/src/com/google/android/chre/test/setting/ContextHubWifiSettingsTestExecutor.java b/java/test/settings/src/com/google/android/chre/test/setting/ContextHubWifiSettingsTestExecutor.java
index 50d740dd..ae3a09b7 100644
--- a/java/test/settings/src/com/google/android/chre/test/setting/ContextHubWifiSettingsTestExecutor.java
+++ b/java/test/settings/src/com/google/android/chre/test/setting/ContextHubWifiSettingsTestExecutor.java
@@ -22,7 +22,6 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.location.NanoAppBinary;
import android.net.wifi.WifiManager;
-import android.util.Log;
import androidx.test.InstrumentationRegistry;
@@ -38,7 +37,6 @@ import java.util.concurrent.TimeUnit;
* A test to check for behavior when WiFi settings are changed.
*/
public class ContextHubWifiSettingsTestExecutor {
- private static final String TAG = "ContextHubWifiSettingsTestExecutor";
private final ContextHubSettingsTestExecutor mExecutor;
private final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
@@ -89,9 +87,6 @@ public class ContextHubWifiSettingsTestExecutor {
mInitialLocationEnabled = mSettingsUtil.isLocationEnabled();
mInitialWifiEnabled = mSettingsUtil.isWifiEnabled();
mInitialWifiScanningAlwaysEnabled = mSettingsUtil.isWifiScanningAlwaysEnabled();
- Log.d(TAG, "isLocationEnalbed=" + mInitialLocationEnabled
- + ", isWifiEnabled=" + mInitialWifiEnabled
- + ", isWifiScanningAlwaysEnabled=" + mInitialWifiScanningAlwaysEnabled);
mExecutor.init();
}
@@ -132,7 +127,7 @@ public class ContextHubWifiSettingsTestExecutor {
wifiUpdateListener.mWifiLatch.await(30, TimeUnit.SECONDS);
// Wait a few seconds to ensure setting is propagated to CHRE path
- Thread.sleep(10000);
+ Thread.sleep(5000);
} catch (InterruptedException e) {
Assert.fail(e.getMessage());
}
diff --git a/java/test/settings/src/com/google/android/chre/test/setting/ContextHubWwanSettingsTestExecutor.java b/java/test/settings/src/com/google/android/chre/test/setting/ContextHubWwanSettingsTestExecutor.java
index 02a33989..cf044915 100644
--- a/java/test/settings/src/com/google/android/chre/test/setting/ContextHubWwanSettingsTestExecutor.java
+++ b/java/test/settings/src/com/google/android/chre/test/setting/ContextHubWwanSettingsTestExecutor.java
@@ -16,10 +16,6 @@
package com.google.android.chre.test.setting;
import android.app.Instrumentation;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
import android.hardware.location.NanoAppBinary;
import androidx.test.InstrumentationRegistry;
@@ -29,9 +25,6 @@ import com.google.android.utils.chre.ChreTestUtil;
import org.junit.Assert;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
/**
* A test to check for behavior when WWAN settings are changed.
*/
@@ -42,19 +35,6 @@ public class ContextHubWwanSettingsTestExecutor {
private final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
- private class AirplaneModeListener {
- protected CountDownLatch mAirplaneModeLatch = new CountDownLatch(1);
-
- protected BroadcastReceiver mAirplaneModeReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) {
- mAirplaneModeLatch.countDown();
- }
- }
- };
- }
-
public ContextHubWwanSettingsTestExecutor(NanoAppBinary binary) {
mExecutor = new ContextHubSettingsTestExecutor(binary);
}
@@ -92,6 +72,7 @@ public class ContextHubWwanSettingsTestExecutor {
ChreTestUtil.executeShellCommand(
mInstrumentation, "cmd connectivity airplane-mode disable");
}
+ Assert.assertTrue(isAirplaneModeOn() == enable);
}
/**
@@ -99,27 +80,11 @@ public class ContextHubWwanSettingsTestExecutor {
* @param enableFeature True for enable.
*/
private void runTest(boolean enableFeature) {
- Context context = InstrumentationRegistry.getTargetContext();
- AirplaneModeListener listener = new AirplaneModeListener();
- context.registerReceiver(
- listener.mAirplaneModeReceiver,
- new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
-
- boolean airplaneModeExpected = !enableFeature;
- setAirplaneMode(airplaneModeExpected);
-
- if (isAirplaneModeOn() != airplaneModeExpected) {
- try {
- listener.mAirplaneModeLatch.await(5, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
- }
- context.unregisterReceiver(listener.mAirplaneModeReceiver);
- Assert.assertTrue(isAirplaneModeOn() == airplaneModeExpected);
+ setAirplaneMode(!enableFeature);
+ // Wait for the setting to propagate
try {
- Thread.sleep(5000); // wait for setting to propagate
+ Thread.sleep(10000);
} catch (InterruptedException e) {
Assert.fail(e.getMessage());
}
diff --git a/java/test/stress/Android.bp b/java/test/stress/Android.bp
deleted file mode 100644
index c0c2cc84..00000000
--- a/java/test/stress/Android.bp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (C) 2021 The Android Open Source Project
-//
-// 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.
-
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
-java_library {
- name: "context-hub-stress-test",
-
- srcs: ["src/**/*.java"],
-
- static_libs: [
- "androidx.test.rules",
- "chre_stress_test_java_proto",
- "chre_test_common_java_proto",
- "chre-test-utils",
- ],
-
- sdk_version: "system_current",
-}
diff --git a/java/test/stress/src/com/google/android/chre/test/stress/ContextHubStressTestExecutor.java b/java/test/stress/src/com/google/android/chre/test/stress/ContextHubStressTestExecutor.java
deleted file mode 100644
index c822b7f7..00000000
--- a/java/test/stress/src/com/google/android/chre/test/stress/ContextHubStressTestExecutor.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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.
- */
-package com.google.android.chre.test.stress;
-
-import android.app.Instrumentation;
-import android.content.Context;
-import android.hardware.location.ContextHubClient;
-import android.hardware.location.ContextHubClientCallback;
-import android.hardware.location.ContextHubInfo;
-import android.hardware.location.ContextHubManager;
-import android.hardware.location.ContextHubTransaction;
-import android.hardware.location.NanoAppBinary;
-import android.hardware.location.NanoAppMessage;
-import android.net.wifi.WifiManager;
-import android.util.Log;
-
-import androidx.test.InstrumentationRegistry;
-
-import com.google.android.chre.nanoapp.proto.ChreStressTest;
-import com.google.android.chre.nanoapp.proto.ChreTestCommon;
-import com.google.android.utils.chre.ChreTestUtil;
-import com.google.protobuf.InvalidProtocolBufferException;
-
-import org.junit.Assert;
-
-import java.nio.charset.StandardCharsets;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * A class that can execute the CHRE Stress test.
- */
-public class ContextHubStressTestExecutor extends ContextHubClientCallback {
- private static final String TAG = "ContextHubStressTestExecutor";
-
- private final NanoAppBinary mNanoAppBinary;
-
- private final long mNanoAppId;
-
- private ContextHubClient mContextHubClient;
-
- private final AtomicReference<ChreTestCommon.TestResult> mTestResult =
- new AtomicReference<>();
-
- private final AtomicBoolean mChreReset = new AtomicBoolean(false);
-
- private final ContextHubManager mContextHubManager;
-
- private final ContextHubInfo mContextHubInfo;
-
- private CountDownLatch mCountDownLatch;
-
- // Set to true to have the test suite only load the nanoapp and start the test.
- // This can be useful for long-running stress tests, where we do not want to wait a fixed
- // time to wait for successful completion.
- private boolean mLoadAndStartOnly = false;
-
- private final AtomicBoolean mWifiScanMonitorTriggered = new AtomicBoolean(false);
-
- private final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
-
- public ContextHubStressTestExecutor(ContextHubManager manager, ContextHubInfo info,
- NanoAppBinary binary) {
- mNanoAppBinary = binary;
- mNanoAppId = mNanoAppBinary.getNanoAppId();
- mContextHubManager = manager;
- mContextHubInfo = info;
- }
-
- @Override
- public void onMessageFromNanoApp(ContextHubClient client, NanoAppMessage message) {
- if (message.getNanoAppId() == mNanoAppId) {
- Log.d(TAG, "Got message from nanoapp: " + message);
- boolean valid = false;
- switch (message.getMessageType()) {
- case ChreStressTest.MessageType.TEST_RESULT_VALUE: {
- try {
- mTestResult.set(
- ChreTestCommon.TestResult.parseFrom(message.getMessageBody()));
- valid = true;
- } catch (InvalidProtocolBufferException e) {
- Log.e(TAG, "Failed to parse message: " + e.getMessage());
- }
- break;
- }
- case ChreStressTest.MessageType.TEST_WIFI_SCAN_MONITOR_TRIGGERED_VALUE: {
- mWifiScanMonitorTriggered.set(true);
- valid = true;
- break;
- }
- default: {
- Log.e(TAG, "Unknown message type " + message.getMessageType());
- }
- }
-
- if (valid && mCountDownLatch != null) {
- mCountDownLatch.countDown();
- }
- }
- }
-
- @Override
- public void onHubReset(ContextHubClient client) {
- mChreReset.set(true);
- if (mCountDownLatch != null) {
- mCountDownLatch.countDown();
- }
- }
-
- /**
- * Should be invoked before run() is invoked to set up the test, e.g. in a @Before method.
- */
- public void init() {
- init(false /* loadAndStartOnly */, false /* unloadOnly */);
- }
-
- /**
- * Same version of init, but specifies mLoadAndStartOnly.
- *
- * @param loadAndStartOnly Sets mLoadAndStartOnly.
- */
- public void init(boolean loadAndStartOnly) {
- init(loadAndStartOnly, false /* unloadOnly */);
- }
-
- /**
- * Same version of init, but specifies mLoadAndStartOnly and unloadOnly.
- *
- * @param loadAndStartOnly Sets mLoadAndStartOnly.
- * @param unloadOnly Set to true if the nanoapp is already loaded.
- */
- public void init(boolean loadAndStartOnly, boolean unloadOnly) {
- mLoadAndStartOnly = loadAndStartOnly;
- if (!unloadOnly) {
- ChreTestUtil.loadNanoAppAssertSuccess(mContextHubManager, mContextHubInfo,
- mNanoAppBinary);
- }
- mContextHubClient = mContextHubManager.createClient(mContextHubInfo, this);
- Assert.assertTrue(mContextHubClient != null);
- }
-
- /**
- * @param timeout The amount of time to run the stress test.
- * @param unit The unit for timeout.
- */
- public void runStressTest(long timeout, TimeUnit unit) {
- ChreStressTest.TestCommand.Feature[] features = {
- ChreStressTest.TestCommand.Feature.WIFI_ON_DEMAND_SCAN,
- ChreStressTest.TestCommand.Feature.GNSS_LOCATION,
- ChreStressTest.TestCommand.Feature.GNSS_MEASUREMENT,
- ChreStressTest.TestCommand.Feature.WWAN,
- };
-
- mTestResult.set(null);
- mCountDownLatch = new CountDownLatch(1);
-
- for (ChreStressTest.TestCommand.Feature feature : features) {
- sendTestMessage(feature, true /* start */);
- }
-
- if (!mLoadAndStartOnly) {
- try {
- mCountDownLatch.await(timeout, unit);
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
-
- checkTestFailure();
-
- for (ChreStressTest.TestCommand.Feature feature : features) {
- sendTestMessage(feature, false /* start */);
- }
-
- try {
- // Add a short delay to make sure the stop command did not cause issues.
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
- }
- }
-
- /**
- * Sends a command to enable scan monitoring.
- */
- public void sendScanMonitorCommand() {
- sendTestMessage(ChreStressTest.TestCommand.Feature.WIFI_SCAN_MONITOR, true /* start */);
- }
-
- /**
- * A test to verify whether a scan monitor request persists through WLAN restarts.
- *
- * The test framework is expected to perform the following operations prior to running this
- * method.
- * 1. Load the nanoapp through init() (with loadAndStartOnly enabled)
- * 2. Invoke sendScanMonitorCommand
- * 3. Restart the WLAN.
- * 4. Keep the nanoapp loaded, and then run this test.
- * 5. Unload the nanoapp after this test ends.
- */
- public void runWifiScanMonitorRestartTest() {
- // Since the host connection may have reset, inform the nanoapp about this event.
- NanoAppMessage message = NanoAppMessage.createMessageToNanoApp(
- mNanoAppId, ChreStressTest.MessageType.TEST_HOST_RESTARTED_VALUE,
- new byte[0]);
- sendMessageToNanoApp(message);
-
- WifiManager manager = (WifiManager) mInstrumentation.getContext().getSystemService(
- Context.WIFI_SERVICE);
- Assert.assertNotNull(manager);
-
- mWifiScanMonitorTriggered.set(false);
- mCountDownLatch = new CountDownLatch(1);
- manager.startScan();
-
- try {
- mCountDownLatch.await(30, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- Assert.fail(e.getMessage());
- }
- Assert.assertTrue(mWifiScanMonitorTriggered.get());
- checkTestFailure();
-
- sendTestMessage(ChreStressTest.TestCommand.Feature.WIFI_SCAN_MONITOR, false /* start */);
- }
-
- /**
- * Cleans up the test, should be invoked in e.g. @After method.
- */
- public void deinit() {
- if (!mLoadAndStartOnly) {
- ChreTestUtil.unloadNanoApp(mContextHubManager, mContextHubInfo, mNanoAppId);
- }
- if (mContextHubClient != null) {
- mContextHubClient.close();
- }
-
- if (mChreReset.get()) {
- Assert.fail("CHRE reset during the test");
- }
- }
-
- /**
- * @param feature The feature to start testing for.
- * @param start true to start the test, false to stop.
- */
- private void sendTestMessage(ChreStressTest.TestCommand.Feature feature, boolean start) {
- ChreStressTest.TestCommand testCommand = ChreStressTest.TestCommand.newBuilder()
- .setFeature(feature).setStart(start).build();
-
- NanoAppMessage message = NanoAppMessage.createMessageToNanoApp(
- mNanoAppId, ChreStressTest.MessageType.TEST_COMMAND_VALUE,
- testCommand.toByteArray());
- sendMessageToNanoApp(message);
- }
-
- private void sendMessageToNanoApp(NanoAppMessage message) {
- int result = mContextHubClient.sendMessageToNanoApp(message);
- if (result != ContextHubTransaction.RESULT_SUCCESS) {
- Assert.fail("Failed to send message: result = " + result);
- }
- }
-
- private void checkTestFailure() {
- if (mTestResult.get() != null
- && mTestResult.get().getCode() == ChreTestCommon.TestResult.Code.FAILED) {
- if (mTestResult.get().hasErrorMessage()) {
- Assert.fail(new String(mTestResult.get().getErrorMessage().toByteArray(),
- StandardCharsets.UTF_8));
- } else {
- Assert.fail("Stress test failed");
- }
- }
- }
-}
diff --git a/java/test/utils/Android.bp b/java/test/utils/Android.bp
index 16490cc4..b5061e81 100644
--- a/java/test/utils/Android.bp
+++ b/java/test/utils/Android.bp
@@ -1,4 +1,4 @@
-// Copyright (C) 2019 The Android Open Source Project
+// Copyright (C) 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -12,15 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_chre_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_chre_license"],
-}
-
java_library {
name: "chre-test-utils",
diff --git a/java/test/utils/src/com/google/android/utils/chre/ChreTestUtil.java b/java/test/utils/src/com/google/android/utils/chre/ChreTestUtil.java
index d69a1824..761ca81b 100644
--- a/java/test/utils/src/com/google/android/utils/chre/ChreTestUtil.java
+++ b/java/test/utils/src/com/google/android/utils/chre/ChreTestUtil.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright (C) 2020 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,12 +49,12 @@ public class ChreTestUtil {
private static final long QUERY_NANOAPPS_TIMEOUT_SECONDS = 5;
/**
- * Read the nanoapp to an InputStream object.
- *
- * @param context the Context to find the asset resources
- * @param fileName the fileName of the nanoapp
- * @return the InputStream of the nanoapp
- */
+ * Read the nanoapp to an InputStream object.
+ *
+ * @param context the Context to find the asset resources
+ * @param fileName the fileName of the nanoapp
+ * @return the InputStream of the nanoapp
+ */
public static InputStream getNanoAppInputStream(Context context, String fileName) {
InputStream inputStream = null;
try {
@@ -66,11 +66,11 @@ public class ChreTestUtil {
}
/**
- * Creates a NanoAppBinary object from the nanoapp fileName.
- *
- * @param fileName the fileName of the nanoapp
- * @return the NanoAppBinary object
- */
+ * Creates a NanoAppBinary object from the nanoapp fileName.
+ *
+ * @param fileName the fileName of the nanoapp
+ * @return the NanoAppBinary object
+ */
public static NanoAppBinary createNanoAppBinary(String fileName) {
Context context = InstrumentationRegistry.getTargetContext();
@@ -87,14 +87,13 @@ public class ChreTestUtil {
}
/**
- * Loads a nanoapp.
- *
- * @param manager The ContextHubManager to use to load the nanoapp.
- * @param info The ContextHubInfo describing the Context Hub to load the nanoapp to.
- * @param nanoAppBinary The nanoapp binary to load.
- * @return true if the load succeeded.
- */
- public static boolean loadNanoApp(
+ * Loads a nanoapp and asserts success.
+ *
+ * @param manager The ContextHubManager to use to load the nanoapp.
+ * @param info The ContextHubInfo describing the Context Hub to load the nanoapp to.
+ * @param nanoAppBinary The nanoapp binary to load.
+ */
+ public static void loadNanoAppAssertSuccess(
ContextHubManager manager, ContextHubInfo info, NanoAppBinary nanoAppBinary) {
ContextHubTransaction<Void> txn = manager.loadNanoApp(info, nanoAppBinary);
ContextHubTransaction.Response<Void> resp = null;
@@ -104,28 +103,19 @@ public class ChreTestUtil {
Assert.fail(e.getMessage());
}
- return resp != null && resp.getResult() == ContextHubTransaction.RESULT_SUCCESS;
- }
-
- /**
- * Same as loadNanoApp(), but asserts that it succeeds.
- */
- public static void loadNanoAppAssertSuccess(
- ContextHubManager manager, ContextHubInfo info, NanoAppBinary nanoAppBinary) {
- if (!loadNanoApp(manager, info, nanoAppBinary)) {
- Assert.fail("Failed to load nanoapp");
+ if (resp != null && resp.getResult() != ContextHubTransaction.RESULT_SUCCESS) {
+ Assert.fail("Failed to load nanoapp: result = " + resp.getResult());
}
}
/**
- * Unloads a nanoapp.
- *
- * @param manager The ContextHubManager to use to unload the nanoapp.
- * @param info The ContextHubInfo describing the Context Hub to unload the nanoapp from.
- * @param nanoAppId The 64-bit ID of the nanoapp to unload.
- * @return true if the unload succeeded.
- */
- public static boolean unloadNanoApp(
+ * Unloads a nanoapp and asserts success.
+ *
+ * @param manager The ContextHubManager to use to unload the nanoapp.
+ * @param info The ContextHubInfo describing the Context Hub to unload the nanoapp from.
+ * @param nanoAppBinary The nanoapp to unload.
+ */
+ public static void unloadNanoAppAssertSuccess(
ContextHubManager manager, ContextHubInfo info, long nanoAppId) {
ContextHubTransaction<Void> txn = manager.unloadNanoApp(info, nanoAppId);
ContextHubTransaction.Response<Void> resp = null;
@@ -135,55 +125,43 @@ public class ChreTestUtil {
Assert.fail(e.getMessage());
}
- return resp != null && resp.getResult() == ContextHubTransaction.RESULT_SUCCESS;
- }
- /**
- * Same as unloadNanoApp(), but asserts that it succeeds.
- */
- public static void unloadNanoAppAssertSuccess(
- ContextHubManager manager, ContextHubInfo info, long nanoAppId) {
- if (!unloadNanoApp(manager, info, nanoAppId)) {
- Assert.fail("Failed to unload nanoapp");
+ if (resp != null && resp.getResult() != ContextHubTransaction.RESULT_SUCCESS) {
+ Assert.fail("Failed to unload nanoapp: result = " + resp.getResult());
}
}
/**
- * Executes a given shell command.
- *
- * @param instrumentation The instrumentation to use.
- * @param command The shell command to execute.
- * @return The string output.
- */
+ * Executes a given shell command.
+ *
+ * @param instrumentation The instrumentation to use.
+ * @param command The shell command to execute.
+ * @return The string output.
+ */
public static String executeShellCommand(Instrumentation instrumentation, String command) {
final ParcelFileDescriptor pfd = instrumentation.getUiAutomation()
.executeShellCommand(command);
+ StringBuilder out = new StringBuilder();
try (InputStream in = new FileInputStream(pfd.getFileDescriptor())) {
- return readFromInputStream(in);
- } catch (Exception e) {
+ BufferedReader br = new BufferedReader(new InputStreamReader(in,
+ StandardCharsets.UTF_8));
+ String str = null;
+ while ((str = br.readLine()) != null) {
+ out.append(str);
+ }
+
+ closeOrAssert(br);
+ } catch (IOException e) {
Assert.fail(e.getMessage());
- } finally {
- closeOrAssert(pfd);
}
- return null;
- }
- /**
- * Executes a given shell command using the app context rather than the shells so that the app's
- * permissions are used.
- *
- * @param command The shell command to execute.
- * @return The string output.
- */
- public static String executeShellCommandWithAppPerms(String command) throws Exception {
- final Process process = Runtime.getRuntime().exec(command);
- process.waitFor();
- return readFromInputStream(process.getInputStream());
+ closeOrAssert(pfd);
+ return out.toString();
}
/**
- * @param input The string input of an integer.
- * @return The converted integer.
- */
+ * @param input The string input of an integer.
+ * @return The converted integer.
+ */
public static int convertToIntegerOrFail(String input) {
try {
return Integer.parseInt(input);
@@ -195,10 +173,10 @@ public class ChreTestUtil {
}
/**
- * Get all the nanoapps currently loaded on device.
- *
- * @return The nanoapps loaded currently.
- */
+ * Get all the nanoapps currently loaded on device.
+ *
+ * @return The nanoapps loaded currently.
+ */
public static List<NanoAppState> queryNanoAppsAssertSuccess(
ContextHubManager contextHubManager, ContextHubInfo contextHubInfo) {
ContextHubTransaction<List<NanoAppState>> transaction =
@@ -217,30 +195,8 @@ public class ChreTestUtil {
}
/**
- * Queries for the nanoapp version.
- *
- * @param contextHubManager The ContextHubManager to use.
- * @param contextHubInfo The ContextHubInfo describing the Context Hub to query.
- * @param nanoAppId The ID of the nanoapp to get the version for.
- * @return The nanoapp version.
- */
- public static int getNanoAppVersion(ContextHubManager contextHubManager,
- ContextHubInfo contextHubInfo, long nanoAppId) {
- List<NanoAppState> stateList = queryNanoAppsAssertSuccess(contextHubManager,
- contextHubInfo);
- for (NanoAppState state : stateList) {
- if (state.getNanoAppId() == nanoAppId) {
- return (int) state.getNanoAppVersion();
- }
- }
-
- Assert.fail("Could not query for nanoapp with ID 0x" + Long.toHexString(nanoAppId));
- return -1;
- }
-
- /**
- * @param closeable The object to close.
- */
+ * @param closeable The object to close.
+ */
private static void closeOrAssert(AutoCloseable closeable) {
try {
closeable.close();
@@ -249,25 +205,12 @@ public class ChreTestUtil {
}
}
- private static String readFromInputStream(InputStream in) throws Exception {
- StringBuilder out = new StringBuilder();
- BufferedReader br = new BufferedReader(new InputStreamReader(in,
- StandardCharsets.UTF_8));
- String str = null;
- while ((str = br.readLine()) != null) {
- out.append(str);
- }
-
- closeOrAssert(br);
- return out.toString();
- }
-
/**
- * Assert that the context hub transaction gets a successful response.
- *
- * @param transaction The context hub transaction
- * @param timeoutInSeconds The timeout while waiting for the transaction response in seconds
- */
+ * Assert that the context hub transaction gets a successful response.
+ *
+ * @param transaction The context hub transaction
+ * @param timeoutInSeconds The timeout while waiting for the transaction response in seconds
+ */
private static void assertTransactionSuccessSync(
ContextHubTransaction<?> transaction, long timeoutInSeconds) throws AssertionError {
if (transaction == null) {
diff --git a/pal/doc/Doxyfile b/pal/doc/Doxyfile
index 70f98d0d..d66abc84 100644
--- a/pal/doc/Doxyfile
+++ b/pal/doc/Doxyfile
@@ -1261,7 +1261,7 @@ CHM_FILE =
HHC_LOCATION =
# The GENERATE_CHI flag controls if a separate .chi index file is generated
-# (YES) or that it should be included in the main .chm file (NO).
+# (YES) or that it should be included in the master .chm file (NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
diff --git a/pal/include/chre/pal/sensor.h b/pal/include/chre/pal/sensor.h
index 5f13eb15..7f68ed21 100644
--- a/pal/include/chre/pal/sensor.h
+++ b/pal/include/chre/pal/sensor.h
@@ -252,8 +252,8 @@ struct chrePalSensorApi {
/**
* Issues a request to flush all samples stored for batching. The PAL
- * implementation is expected to unconditionally issue this request for the
- * given sensor. The CHRE framework will ensure that it must have an active,
+ * implementation is expected to blindly issue this request for the given
+ * sensor. The CHRE framework will ensure that it must have an active,
* powered, batching request issued through configureSensor before invoking
* this method.
*
diff --git a/pal/include/chre/pal/wifi.h b/pal/include/chre/pal/wifi.h
index f40a3ea4..21238ba4 100644
--- a/pal/include/chre/pal/wifi.h
+++ b/pal/include/chre/pal/wifi.h
@@ -44,20 +44,14 @@ extern "C" {
/**
* Introduced alongside CHRE API v1.2, adding support for RTT ranging and radio
- * chain preference.
+ * chain preference
*/
#define CHRE_PAL_WIFI_API_V1_2 CHRE_PAL_CREATE_API_VERSION(1, 2)
/**
- * Introduced alongside CHRE API v1.5, adding support for additional WiFi
- * security modes.
+ * The version of the WiFi GNSS PAL defined in this header file.
*/
-#define CHRE_PAL_WIFI_API_V1_5 CHRE_PAL_CREATE_API_VERSION(1, 5)
-
-/**
- * The version of the WiFi PAL defined in this header file.
- */
-#define CHRE_PAL_WIFI_API_CURRENT_VERSION CHRE_PAL_WIFI_API_V1_5
+#define CHRE_PAL_WIFI_API_CURRENT_VERSION CHRE_PAL_WIFI_API_V1_2
struct chrePalWifiCallbacks {
/**
diff --git a/pal/pal.mk b/pal/pal.mk
index bf4dd462..0c92ecf8 100644
--- a/pal/pal.mk
+++ b/pal/pal.mk
@@ -9,8 +9,5 @@ COMMON_CFLAGS += -Ipal/include
# GoogleTest Source Files ######################################################
-GOOGLETEST_CFLAGS += -Ipal/tests/include
-GOOGLETEST_SRCS += pal/tests/src/version_test.cc
-GOOGLETEST_SRCS += pal/tests/src/wwan_test.cc
-GOOGLETEST_PAL_IMPL_SRCS += pal/tests/src/gnss_pal_impl_test.cc
-GOOGLETEST_PAL_IMPL_SRCS += pal/tests/src/wifi_pal_impl_test.cc
+GOOGLETEST_SRCS += pal/tests/version_test.cc
+GOOGLETEST_SRCS += pal/tests/wwan_test.cc
diff --git a/pal/tests/include/gnss_pal_impl_test.h b/pal/tests/include/gnss_pal_impl_test.h
deleted file mode 100644
index d290b44b..00000000
--- a/pal/tests/include/gnss_pal_impl_test.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 GNSSPAL_IMPL_TEST_H_
-#define GNSSPAL_IMPL_TEST_H_
-
-#include "chre/pal/gnss.h"
-#include "chre/platform/condition_variable.h"
-#include "chre/platform/mutex.h"
-#include "chre/util/fixed_size_vector.h"
-#include "chre/util/time.h"
-#include "gtest/gtest.h"
-
-namespace gnss_pal_impl_test {
-
-class PalGnssTest : public ::testing::TestWithParam<uint64_t> {
- public:
- /**
- * Implements CHRE PAL API callbacks
- */
- void requestStateResync();
- void locationStatusChangeCallback(bool enabled, uint8_t errorCode);
- void locationEventCallback(struct chreGnssLocationEvent *event);
- void measurementStatusChangeCallback(bool enabled, uint8_t errorCode);
- void measurementEventCallback(struct chreGnssDataEvent *event);
-
- protected:
- void SetUp() override;
-
- void TearDown() override;
-
- /**
- * Prepares for a subsequent PAL API call that expects an async response.
- */
- void prepareForAsyncResponse() {
- errorCode_ = CHRE_ERROR_LAST;
- }
-
- /**
- * Waits for an async response by the PAL implementation (e.g. via location
- * or measurement status change callback), and asserts that a success
- * error code was received.
- */
- void waitForAsyncResponseAssertSuccess(chre::Nanoseconds timeoutNs);
-
- //! The pointer to the CHRE PAL implementation API
- const struct chrePalGnssApi *api_;
-
- //! The error code of the most recent callback
- uint8_t errorCode_ = CHRE_ERROR_LAST;
-
- //! True if location session is currently enabled
- bool locationSessionEnabled_ = false;
-
- //! True if location session is currently enabled
- bool measurementSessionEnabled_ = false;
-
- //! A list to store the location events
- static constexpr size_t kEventArraySize = 5;
- chre::FixedSizeVector<chreGnssLocationEvent *, kEventArraySize>
- locationEventVector_;
- chre::FixedSizeVector<chreGnssDataEvent *, kEventArraySize>
- measurementEventVector_;
-
- //! Mutex to protect class variables
- chre::Mutex mutex_;
- chre::ConditionVariable condVar_;
-};
-
-} // namespace gnss_pal_impl_test
-
-#endif // GNSSPAL_IMPL_TEST_H_
diff --git a/pal/tests/include/wifi_pal_impl_test.h b/pal/tests/include/wifi_pal_impl_test.h
deleted file mode 100644
index 2188ea60..00000000
--- a/pal/tests/include/wifi_pal_impl_test.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 WIFI_PAL_IMPL_TEST_H_
-#define WIFI_PAL_IMPL_TEST_H_
-
-#include "chre/pal/wifi.h"
-#include "chre/platform/condition_variable.h"
-#include "chre/platform/mutex.h"
-#include "chre/util/dynamic_vector.h"
-#include "chre/util/optional.h"
-#include "chre/util/time.h"
-#include "gtest/gtest.h"
-
-namespace wifi_pal_impl_test {
-
-class PalWifiTest : public ::testing::Test {
- public:
- /**
- * Implements CHRE PAL API callbacks
- */
- void scanMonitorStatusChangeCallback(bool enabled, uint8_t errorCode);
- void scanResponseCallback(bool pending, uint8_t errorCode);
- void scanEventCallback(struct chreWifiScanEvent *event);
- void rangingEventCallback(uint8_t errorCode,
- struct chreWifiRangingEvent *event);
-
- protected:
- void SetUp() override;
-
- void TearDown() override;
-
- /**
- * Validates an incoming WiFi scan event.
- *
- * @param event The WiFi scan event.
- */
- void validateWifiScanEvent(const chreWifiScanEvent &event);
-
- /**
- * Prepares for a subsequent PAL API call that expects an async response.
- */
- void prepareForAsyncResponse() {
- errorCode_ = CHRE_ERROR_LAST;
- }
-
- /**
- * Waits for an async response by the PAL implementation (e.g. via scan
- * response/monitor status change callback), and asserts that a success
- * error code was received.
- */
- void waitForAsyncResponseAssertSuccess(chre::Nanoseconds timeoutNs);
-
- //! The pointer to the CHRE PAL implementation API
- const struct chrePalWifiApi *api_;
-
- //! The error code of the most recent callback
- uint8_t errorCode_ = CHRE_ERROR_LAST;
-
- //! The number of scan events currently stored
- uint32_t numScanResultCount_ = 0;
-
- //! True if the last scan event has been received
- bool lastScanEventReceived_ = false;
-
- //! A list to store the scan results
- chre::DynamicVector<chreWifiScanEvent *> scanEventList_;
-
- //! Stores active scan params
- chre::Optional<chreWifiScanParams> scanParams_;
-
- //! The last scan event index received, UINT8_MAX if invalid
- uint8_t lastEventIndex_;
-
- //! True if scan monitoring is currently enabled
- bool scanMonitorEnabled_ = false;
-
- //! Mutex to protect class variables
- chre::Mutex mutex_;
- chre::ConditionVariable condVar_;
-};
-
-} // namespace wifi_pal_impl_test
-
-#endif // WIFI_PAL_IMPL_TEST_H_
diff --git a/pal/tests/src/gnss_pal_impl_test.cc b/pal/tests/src/gnss_pal_impl_test.cc
deleted file mode 100644
index 45eb444c..00000000
--- a/pal/tests/src/gnss_pal_impl_test.cc
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "gnss_pal_impl_test.h"
-
-#include "chre/platform/log.h"
-#include "chre/platform/shared/pal_system_api.h"
-#include "chre/platform/system_time.h"
-#include "chre/util/lock_guard.h"
-
-#include <cinttypes>
-
-//! Flag to require GNSS location sessions capability to be enabled for the test
-//! to pass. Set to false to allow tests to pass on disabled platforms.
-//! Note that it is required to run this test where location can be acquired.
-//! The constants kGnssEventTimeoutNs and kEventArraySize may be tuned if
-//! applicable.
-#ifndef PAL_IMPL_TEST_GNSS_LOCATION_REQUIRED
-#define PAL_IMPL_TEST_GNSS_LOCATION_REQUIRED true
-#endif
-
-//! Same as above for GNSS measurement sessions.
-#ifndef PAL_IMPL_TEST_GNSS_MEASUREMENTS_REQUIRED
-#define PAL_IMPL_TEST_GNSS_MEASUREMENTS_REQUIRED true
-#endif
-
-namespace gnss_pal_impl_test {
-
-namespace {
-
-using ::chre::Nanoseconds;
-using ::chre::Seconds;
-using ::chre::SystemTime;
-
-//! A pointer to the current test running
-gnss_pal_impl_test::PalGnssTest *gTest = nullptr;
-
-//! Timeout as specified by the CHRE API
-const Nanoseconds kGnssAsyncResultTimeoutNs =
- Nanoseconds(CHRE_GNSS_ASYNC_RESULT_TIMEOUT_NS);
-
-//! Timeout to wait for kEventArraySize events.
-const Nanoseconds kGnssEventTimeoutNs = Seconds(60);
-
-void chrePalRequestStateResync() {
- if (gTest != nullptr) {
- gTest->requestStateResync();
- }
-}
-
-void chrePalLocationStatusChangeCallback(bool enabled, uint8_t errorCode) {
- if (gTest != nullptr) {
- gTest->locationStatusChangeCallback(enabled, errorCode);
- }
-}
-
-void chrePalLocationEventCallback(struct chreGnssLocationEvent *event) {
- if (gTest != nullptr) {
- gTest->locationEventCallback(event);
- }
-}
-
-void chrePalMeasurementStatusChangeCallback(bool enabled, uint8_t errorCode) {
- if (gTest != nullptr) {
- gTest->measurementStatusChangeCallback(enabled, errorCode);
- }
-}
-
-void chrePalMeasurementEventCallback(struct chreGnssDataEvent *event) {
- if (gTest != nullptr) {
- gTest->measurementEventCallback(event);
- }
-}
-
-void logLocationEvent(const struct chreGnssLocationEvent &event) {
- LOGI("Received location: %" PRId32 ", %" PRId32, event.latitude_deg_e7,
- event.longitude_deg_e7);
- LOGI(" timestamp (ms): %" PRIu64, event.timestamp);
- LOGI(" altitude (m): %f", event.altitude);
- LOGI(" speed (m/s): %f", event.speed);
- LOGI(" bearing (deg): %f", event.bearing);
- LOGI(" accuracy: %f", event.accuracy);
- LOGI(" flags: 0x%" PRIx16, event.flags);
- LOGI(" altitude_accuracy: %f", event.altitude_accuracy);
- LOGI(" speed_accuracy: %f", event.speed_accuracy);
- LOGI(" bearing_accuracy: %f", event.bearing_accuracy);
-}
-
-void validateLocationEvent(const struct chreGnssLocationEvent &event) {
- static uint64_t sLastTimestampNs = 0;
- EXPECT_GE(event.timestamp, sLastTimestampNs);
- sLastTimestampNs = event.timestamp;
- if (event.flags & CHRE_GPS_LOCATION_HAS_LAT_LONG) {
- EXPECT_GE(event.latitude_deg_e7, -90 * 1e7);
- EXPECT_LE(event.latitude_deg_e7, 90 * 1e7);
- EXPECT_GE(event.longitude_deg_e7, -180 * 1e7);
- EXPECT_LE(event.longitude_deg_e7, 180 * 1e7);
- }
- if (event.flags & CHRE_GPS_LOCATION_HAS_BEARING) {
- EXPECT_GE(event.bearing, 0);
- EXPECT_LT(event.bearing, 360); // [0, 360) per API
- }
-}
-
-void logMeasurementEvent(const struct chreGnssDataEvent &event) {
- LOGI("Received data: %" PRIu8 " measurements", event.measurement_count);
-
- for (uint8_t i = 0; i < event.measurement_count; i++) {
- LOGI("%" PRIu8 ": const %" PRIu8 ", cn0 %.2f, freq %.3f MHz", i,
- event.measurements[i].constellation, event.measurements[i].c_n0_dbhz,
- event.measurements[i].carrier_frequency_hz / 1e6);
- }
-}
-
-void validateMeasurementEvent(const struct chreGnssDataEvent &event) {
- EXPECT_GE(event.measurement_count, 0);
- EXPECT_LE(event.measurement_count, CHRE_GNSS_MAX_MEASUREMENT);
- if (event.measurement_count > 0) {
- EXPECT_NE(event.measurements, nullptr);
- }
-
- static int64_t sLastClockTimeNs = INT64_MIN;
- EXPECT_GE(event.clock.time_ns, sLastClockTimeNs);
- sLastClockTimeNs = event.clock.time_ns;
-
- for (uint8_t i = 0; i < event.measurement_count; i++) {
- EXPECT_GE(event.measurements[i].c_n0_dbhz, 0);
- EXPECT_LE(event.measurements[i].c_n0_dbhz, 63);
- }
-}
-
-} // anonymous namespace
-
-void PalGnssTest::SetUp() {
- api_ = chrePalGnssGetApi(CHRE_PAL_GNSS_API_CURRENT_VERSION);
- ASSERT_NE(api_, nullptr);
- EXPECT_EQ(api_->moduleVersion, CHRE_PAL_GNSS_API_CURRENT_VERSION);
-
- // Open the PAL API
- static const struct chrePalGnssCallbacks kCallbacks = {
- .requestStateResync = chrePalRequestStateResync,
- .locationStatusChangeCallback = chrePalLocationStatusChangeCallback,
- .locationEventCallback = chrePalLocationEventCallback,
- .measurementStatusChangeCallback = chrePalMeasurementStatusChangeCallback,
- .measurementEventCallback = chrePalMeasurementEventCallback,
- };
- ASSERT_TRUE(api_->open(&chre::gChrePalSystemApi, &kCallbacks));
- gTest = this;
-
- errorCode_ = CHRE_ERROR_LAST;
- locationSessionEnabled_ = false;
- locationEventVector_.resize(0);
- measurementSessionEnabled_ = false;
- measurementEventVector_.resize(0);
-}
-
-void PalGnssTest::TearDown() {
- gTest = nullptr;
- if (api_ != nullptr) {
- api_->close();
- }
-}
-
-void PalGnssTest::requestStateResync() {
- // TODO:
-}
-
-void PalGnssTest::locationStatusChangeCallback(bool enabled,
- uint8_t errorCode) {
- LOGI("Received location status change with enabled %d error %" PRIu8, enabled,
- errorCode);
- if (errorCode == CHRE_ERROR_LAST) {
- LOGE("Received CHRE_ERROR_LAST");
- errorCode = CHRE_ERROR;
- }
- chre::LockGuard<chre::Mutex> lock(mutex_);
- errorCode_ = errorCode;
- locationSessionEnabled_ = enabled;
- condVar_.notify_one();
-}
-
-void PalGnssTest::locationEventCallback(struct chreGnssLocationEvent *event) {
- LOGI("Received location event");
- chre::LockGuard<chre::Mutex> lock(mutex_);
- if (!locationEventVector_.full()) {
- locationEventVector_.push_back(event);
- if (locationEventVector_.full()) {
- condVar_.notify_one();
- }
- }
-}
-
-void PalGnssTest::measurementStatusChangeCallback(bool enabled,
- uint8_t errorCode) {
- LOGI("Received measurement status change with enabled %d error %" PRIu8,
- enabled, errorCode);
- if (errorCode == CHRE_ERROR_LAST) {
- LOGE("Received CHRE_ERROR_LAST");
- errorCode = CHRE_ERROR;
- }
- chre::LockGuard<chre::Mutex> lock(mutex_);
- errorCode_ = errorCode;
- measurementSessionEnabled_ = enabled;
- condVar_.notify_one();
-}
-
-void PalGnssTest::measurementEventCallback(struct chreGnssDataEvent *event) {
- LOGI("Received measurement event");
- chre::LockGuard<chre::Mutex> lock(mutex_);
- if (!measurementEventVector_.full()) {
- measurementEventVector_.push_back(event);
- if (measurementEventVector_.full()) {
- condVar_.notify_one();
- }
- }
-}
-
-void PalGnssTest::waitForAsyncResponseAssertSuccess(
- chre::Nanoseconds timeoutNs) {
- bool waitSuccess = true;
- while (errorCode_ == CHRE_ERROR_LAST && waitSuccess) {
- waitSuccess = condVar_.wait_for(mutex_, timeoutNs);
- }
- ASSERT_TRUE(waitSuccess);
- ASSERT_EQ(errorCode_, CHRE_ERROR_NONE);
-}
-
-TEST_P(PalGnssTest, LocationSessionTest) {
- bool hasLocationCapability =
- ((api_->getCapabilities() & CHRE_GNSS_CAPABILITIES_LOCATION) ==
- CHRE_GNSS_CAPABILITIES_LOCATION);
-#if PAL_IMPL_TEST_GNSS_LOCATION_REQUIRED
- ASSERT_TRUE(hasLocationCapability);
-#else
- if (!hasLocationCapability) {
- GTEST_SKIP();
- }
-#endif
-
- chre::LockGuard<chre::Mutex> lock(mutex_);
-
- prepareForAsyncResponse();
- ASSERT_TRUE(api_->controlLocationSession(true /* enable */,
- GetParam() /* minIntervalMs */,
- 0 /* minTimeToNextFixMs */));
- waitForAsyncResponseAssertSuccess(kGnssAsyncResultTimeoutNs);
- ASSERT_TRUE(locationSessionEnabled_);
-
- bool waitSuccess = true;
- while (!locationEventVector_.full() && waitSuccess) {
- waitSuccess = condVar_.wait_for(mutex_, kGnssEventTimeoutNs);
- }
-
- for (size_t i = 0; i < locationEventVector_.size(); i++) {
- logLocationEvent(*locationEventVector_[i]);
- validateLocationEvent(*locationEventVector_[i]);
- api_->releaseLocationEvent(locationEventVector_[i]);
- }
- EXPECT_TRUE(locationEventVector_.full());
-
- prepareForAsyncResponse();
- ASSERT_TRUE(api_->controlLocationSession(
- false /* enable */, 0 /* minIntervalMs */, 0 /* minTimeToNextFixMs */));
- waitForAsyncResponseAssertSuccess(kGnssAsyncResultTimeoutNs);
- ASSERT_FALSE(locationSessionEnabled_);
-}
-
-TEST_P(PalGnssTest, MeasurementSessionTest) {
- bool hasMeasurementCapability =
- ((api_->getCapabilities() & CHRE_GNSS_CAPABILITIES_MEASUREMENTS) ==
- CHRE_GNSS_CAPABILITIES_MEASUREMENTS);
-#if PAL_IMPL_TEST_GNSS_MEAUSUREMENT_REQUIRED
- ASSERT_TRUE(hasMeasurementCapability);
-#else
- if (!hasMeasurementCapability) {
- GTEST_SKIP();
- }
-#endif
-
- chre::LockGuard<chre::Mutex> lock(mutex_);
-
- prepareForAsyncResponse();
- ASSERT_TRUE(api_->controlMeasurementSession(true /* enable */,
- GetParam() /* minIntervalMs */));
- waitForAsyncResponseAssertSuccess(kGnssAsyncResultTimeoutNs);
- ASSERT_TRUE(measurementSessionEnabled_);
-
- bool waitSuccess = true;
- while (!measurementEventVector_.full() && waitSuccess) {
- waitSuccess = condVar_.wait_for(mutex_, kGnssEventTimeoutNs);
- }
- EXPECT_TRUE(measurementEventVector_.full());
-
- for (size_t i = 0; i < measurementEventVector_.size(); i++) {
- logMeasurementEvent(*measurementEventVector_[i]);
- validateMeasurementEvent(*measurementEventVector_[i]);
- api_->releaseMeasurementDataEvent(measurementEventVector_[i]);
- }
-
- prepareForAsyncResponse();
- ASSERT_TRUE(api_->controlMeasurementSession(false /* enable */,
- 0 /* minIntervalMs */));
- waitForAsyncResponseAssertSuccess(kGnssAsyncResultTimeoutNs);
- ASSERT_FALSE(measurementSessionEnabled_);
-}
-
-INSTANTIATE_TEST_SUITE_P(PalGnssTestRange, PalGnssTest,
- // Parameter: minIntervalMs argument
- testing::Values(1000, 8000));
-
-} // namespace gnss_pal_impl_test
diff --git a/pal/tests/src/wifi_pal_impl_test.cc b/pal/tests/src/wifi_pal_impl_test.cc
deleted file mode 100644
index 7e43ff4c..00000000
--- a/pal/tests/src/wifi_pal_impl_test.cc
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "wifi_pal_impl_test.h"
-
-#include "chre/platform/log.h"
-#include "chre/platform/shared/pal_system_api.h"
-#include "chre/platform/system_time.h"
-#include "chre/util/lock_guard.h"
-#include "chre/util/nanoapp/wifi.h"
-
-#include <cinttypes>
-
-// Flag to require on-demand WiFi scanning capability to be enabled for the test
-// to pass. Set to false to allow tests to pass on disabled platforms.
-#ifndef PAL_IMPL_TEST_WIFI_ON_DEMAND_SCAN_REQUIRED
-#define PAL_IMPL_TEST_WIFI_ON_DEMAND_SCAN_REQUIRED true
-#endif
-
-// Same as above for scan monitoring.
-#ifndef PAL_IMPL_TEST_WIFI_SCAN_MONITORING_REQUIRED
-#define PAL_IMPL_TEST_WIFI_SCAN_MONITORING_REQUIRED true
-#endif
-
-namespace wifi_pal_impl_test {
-
-namespace {
-
-using ::chre::Nanoseconds;
-using ::chre::Seconds;
-using ::chre::SystemTime;
-
-//! A pointer to the current test running
-wifi_pal_impl_test::PalWifiTest *gTest = nullptr;
-
-//! Timeout as specified by the CHRE API
-const Nanoseconds kAsyncResultTimeoutNs =
- Nanoseconds(CHRE_ASYNC_RESULT_TIMEOUT_NS);
-const Nanoseconds kScanResultTimeoutNs =
- Nanoseconds(CHRE_WIFI_SCAN_RESULT_TIMEOUT_NS);
-
-void chrePalScanMonitorStatusChangeCallback(bool enabled, uint8_t errorCode) {
- if (gTest != nullptr) {
- gTest->scanMonitorStatusChangeCallback(enabled, errorCode);
- }
-}
-
-void chrePalScanResponseCallback(bool pending, uint8_t errorCode) {
- if (gTest != nullptr) {
- gTest->scanResponseCallback(pending, errorCode);
- }
-}
-
-void chrePalScanEventCallback(struct chreWifiScanEvent *event) {
- if (gTest != nullptr) {
- gTest->scanEventCallback(event);
- }
-}
-
-void chrePalRangingEventCallback(uint8_t errorCode,
- struct chreWifiRangingEvent *event) {
- if (gTest != nullptr) {
- gTest->rangingEventCallback(errorCode, event);
- }
-}
-
-} // anonymous namespace
-
-void PalWifiTest::SetUp() {
- api_ = chrePalWifiGetApi(CHRE_PAL_WIFI_API_CURRENT_VERSION);
- ASSERT_NE(api_, nullptr);
- EXPECT_EQ(api_->moduleVersion, CHRE_PAL_WIFI_API_CURRENT_VERSION);
-
- // Open the PAL API
- static const struct chrePalWifiCallbacks kCallbacks = {
- .scanMonitorStatusChangeCallback = chrePalScanMonitorStatusChangeCallback,
- .scanResponseCallback = chrePalScanResponseCallback,
- .scanEventCallback = chrePalScanEventCallback,
- .rangingEventCallback = chrePalRangingEventCallback,
- };
- ASSERT_TRUE(api_->open(&chre::gChrePalSystemApi, &kCallbacks));
- gTest = this;
-
- errorCode_ = CHRE_ERROR_LAST;
- numScanResultCount_ = 0;
- lastScanEventReceived_ = false;
- scanEventList_.clear();
- scanParams_.reset();
- lastEventIndex_ = UINT8_MAX;
- scanMonitorEnabled_ = false;
-}
-
-void PalWifiTest::TearDown() {
- gTest = nullptr;
- if (api_ != nullptr) {
- api_->close();
- }
-}
-
-void PalWifiTest::scanMonitorStatusChangeCallback(bool enabled,
- uint8_t errorCode) {
- LOGI("Received scan monitor response with enabled %d error %" PRIu8, enabled,
- errorCode);
- if (errorCode == CHRE_ERROR_LAST) {
- LOGE("Received CHRE_ERROR_LAST");
- errorCode = CHRE_ERROR;
- }
- chre::LockGuard<chre::Mutex> lock(mutex_);
- scanMonitorEnabled_ = enabled;
- errorCode_ = errorCode;
- condVar_.notify_one();
-}
-
-void PalWifiTest::scanResponseCallback(bool pending, uint8_t errorCode) {
- LOGI("Received scan response with pending %d error %" PRIu8, pending,
- errorCode);
- if (errorCode == CHRE_ERROR_LAST) {
- LOGE("Received CHRE_ERROR_LAST");
- errorCode = CHRE_ERROR;
- }
- chre::LockGuard<chre::Mutex> lock(mutex_);
- errorCode_ = errorCode;
- condVar_.notify_one();
-}
-
-void PalWifiTest::scanEventCallback(struct chreWifiScanEvent *event) {
- if (event == nullptr) {
- LOGE("Got null scan event");
- } else {
- {
- chre::LockGuard<chre::Mutex> lock(mutex_);
- scanEventList_.push_back(event);
- numScanResultCount_ += event->resultCount;
- lastScanEventReceived_ = (numScanResultCount_ == event->resultTotal);
- }
-
- condVar_.notify_one();
- }
-}
-
-void PalWifiTest::rangingEventCallback(uint8_t errorCode,
- struct chreWifiRangingEvent *event) {
- // TODO:
-}
-
-void PalWifiTest::validateWifiScanEvent(const chreWifiScanEvent &event) {
- if (scanParams_.has_value()) {
- EXPECT_EQ(event.scanType, scanParams_->scanType);
- EXPECT_GE(event.referenceTime,
- chreGetTime() - (scanParams_->maxScanAgeMs *
- chre::kOneMillisecondInNanoseconds));
- EXPECT_EQ(event.radioChainPref, scanParams_->radioChainPref);
- EXPECT_EQ(event.eventIndex, static_cast<uint8_t>(lastEventIndex_ + 1));
- }
-}
-
-void PalWifiTest::waitForAsyncResponseAssertSuccess(
- chre::Nanoseconds timeoutNs) {
- bool waitSuccess = true;
- while (errorCode_ == CHRE_ERROR_LAST && waitSuccess) {
- waitSuccess = condVar_.wait_for(mutex_, timeoutNs);
- }
- ASSERT_TRUE(waitSuccess);
- ASSERT_EQ(errorCode_, CHRE_ERROR_NONE);
-}
-
-TEST_F(PalWifiTest, ScanAsyncTest) {
- bool hasOnDemandScanCapability =
- (api_->getCapabilities() & CHRE_WIFI_CAPABILITIES_ON_DEMAND_SCAN) ==
- CHRE_WIFI_CAPABILITIES_ON_DEMAND_SCAN;
-#if PAL_IMPL_TEST_WIFI_ON_DEMAND_SCAN_REQUIRED
- ASSERT_TRUE(hasOnDemandScanCapability);
-#else
- if (!hasOnDemandScanCapability) {
- GTEST_SKIP();
- }
-#endif
-
- // Request a WiFi scan
- chre::LockGuard<chre::Mutex> lock(mutex_);
-
- struct chreWifiScanParams params = {};
- params.scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE;
- params.maxScanAgeMs = 5000; // 5 seconds
- params.frequencyListLen = 0;
- params.ssidListLen = 0;
- params.radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT;
- scanParams_ = params;
-
- prepareForAsyncResponse();
- ASSERT_TRUE(api_->requestScan(&scanParams_.value()));
- waitForAsyncResponseAssertSuccess(kScanResultTimeoutNs);
-
- // The CHRE API only poses timeout requirements on the async response. Use
- // the same timeout to receive the scan results to avoid blocking forever.
- bool waitSuccess = true;
- while (!lastScanEventReceived_ && waitSuccess) {
- waitSuccess = condVar_.wait_for(mutex_, kScanResultTimeoutNs);
- }
-
- for (auto *event : scanEventList_) {
- for (uint8_t i = 0; i < event->resultCount; i++) {
- const chreWifiScanResult &result = event->results[i];
- chre::logChreWifiResult(result);
- }
- validateWifiScanEvent(*event);
-
- lastEventIndex_ = event->eventIndex;
- api_->releaseScanEvent(event);
- }
-
- EXPECT_TRUE(lastScanEventReceived_);
- EXPECT_GT(numScanResultCount_, 0u);
-}
-
-// Note: This test only verifies that the scan monitor succeeds according
-// to the async response.
-TEST_F(PalWifiTest, ScanMonitorTest) {
- bool hasScanMonitoringCapability =
- (api_->getCapabilities() & CHRE_WIFI_CAPABILITIES_SCAN_MONITORING) ==
- CHRE_WIFI_CAPABILITIES_SCAN_MONITORING;
-#if PAL_IMPL_TEST_WIFI_SCAN_MONITORING_REQUIRED
- ASSERT_TRUE(hasScanMonitoringCapability);
-#else
- if (!hasScanMonitoringCapability) {
- GTEST_SKIP();
- }
-#endif
-
- chre::LockGuard<chre::Mutex> lock(mutex_);
-
- prepareForAsyncResponse();
- ASSERT_TRUE(api_->configureScanMonitor(true /* enable */));
- waitForAsyncResponseAssertSuccess(kAsyncResultTimeoutNs);
- ASSERT_TRUE(scanMonitorEnabled_);
-
- prepareForAsyncResponse();
- ASSERT_TRUE(api_->configureScanMonitor(false /* enable */));
- waitForAsyncResponseAssertSuccess(kAsyncResultTimeoutNs);
- ASSERT_FALSE(scanMonitorEnabled_);
-}
-
-} // namespace wifi_pal_impl_test
diff --git a/pal/tests/src/version_test.cc b/pal/tests/version_test.cc
index 431cb5bb..38a39874 100644
--- a/pal/tests/src/version_test.cc
+++ b/pal/tests/version_test.cc
@@ -19,8 +19,8 @@
TEST(PalVersionTest, CreateApiVersion) {
constexpr uint32_t version = CHRE_PAL_CREATE_API_VERSION(3, 6);
- EXPECT_EQ(version, 0x03060000u);
- EXPECT_EQ(CHRE_PAL_GET_API_MAJOR_VERSION(version), 3u);
+ EXPECT_EQ(version, 0x03060000);
+ EXPECT_EQ(CHRE_PAL_GET_API_MAJOR_VERSION(version), 3);
}
TEST(PalVersionTest, CompatibilityCheck) {
diff --git a/pal/tests/src/wwan_test.cc b/pal/tests/wwan_test.cc
index 9c91026e..9c91026e 100644
--- a/pal/tests/src/wwan_test.cc
+++ b/pal/tests/wwan_test.cc
diff --git a/pal/util/include/chre/pal/util/wifi_scan_cache.h b/pal/util/include/chre/pal/util/wifi_scan_cache.h
deleted file mode 100644
index 96af281c..00000000
--- a/pal/util/include/chre/pal/util/wifi_scan_cache.h
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PAL_WIFI_SCAN_CACHE_H_
-#define CHRE_PAL_WIFI_SCAN_CACHE_H_
-
-/**
- * @file
- * Defines a WiFi scan caching library that may be used beneath the CHRE WiFi
- * PAL layer.
- *
- * This library should be used by the CHRE WiFi PAL implementation as a
- * convenience module to store completed WiFi scan results, and provide them to
- * CHRE as defined by the CHRE WiFi PAL API. If this library is used, there is
- * no need to invoke the chrePalWifiCallback functions related to WiFi scans
- * (e.g. scanResponseCallback()/scanEventCallback()) directly, as it will be
- * performed by the caching library.
- *
- * The memory footprint of this library can be controlled at compile-time using
- * macros. For instance, CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY can be adjusted to
- * reduce the size of the cache storage.
- *
- * @see chreWifiScanCacheScanEventBegin() for how to cache scan results.
- */
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include "chre/pal/wifi.h"
-#include "chre_api/chre/wifi.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-//! The number of chreWifiScanResult items that will be stored in the scan
-//! cache library.
-#ifndef CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY
-#define CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY 255
-#endif
-
-//! The maximum value of chreWifiScanEvent.resultCount that will be used
-//! in the scan cache library to send results to CHRE.
-#ifndef CHRE_PAL_WIFI_SCAN_CACHE_MAX_RESULT_COUNT
-#define CHRE_PAL_WIFI_SCAN_CACHE_MAX_RESULT_COUNT 20
-#endif
-
-/**
- * Initializes the WiFi scan cache.
- *
- * Only one scan cache library can be instantiated per compilation unit, and is
- * not thread safe.
- *
- * This method must be invoked as a result of a chrePalWiFiApi->open() call.
- *
- * @param systemApi A non-null pointer to the system API functions.
- * @param callbacks A non-null pointer to the callback functions.
- *
- * @return true if successfully initialized.
- */
-bool chreWifiScanCacheInit(const struct chrePalSystemApi *systemApi,
- const struct chrePalWifiCallbacks *callbacks);
-
-/**
- * This method must be invoked as a result of a chrePalWifiApi->close() call.
- */
-void chreWifiScanCacheDeinit(void);
-
-/**
- * Begins the caching of results from a single WiFi scan.
- *
- * This method must be invoked as a result of a WLAN performing a WiFi scan
- * (either due to a request from CHRE or otherwise if scan monitoring is
- * enabled).
- *
- * When a WiFi scan is performed, the following is the expected flow:
- * 1. Invoke chreWifiScanCacheScanEventBegin() to start the cache.
- * 2. For each successful WiFi scan result, invoke
- * chreWifiScanCacheScanEventAdd(). If the scan is unsuccessful or no WiFi APs
- * are scanned, this step is optional.
- * 3. When the WiFi scan is completed (or failed), invoke
- * chreWifiScanCacheScanEventEnd().
- *
- * This function must not be invoked while a scan caching is currently taking
- * place (i.e. until chreWifiScanCacheScanEventEnd() is invoked).
- *
- * @param activeScanResult true if this WiFi scan was a result of an active WiFi
- * scan from CHRE (i.e. not a result of passive scan monitoring only). If true,
- * a scanResponseCallback will be invoked in chreWifiScanCacheScanEventEnd().
- *
- * @return true if the scan cache was successfully started.
- *
- * @see The fields of chreWifiScanEvent for the other parameters.
- */
-bool chreWifiScanCacheScanEventBegin(enum chreWifiScanType scanType,
- uint8_t ssidSetSize,
- const uint32_t *scannedFreqList,
- uint16_t scannedFreqListLength,
- uint8_t radioChainPref,
- bool activeScanResult);
-
-/**
- * Adds a WiFi scan result to the current WiFi scan event cache.
- *
- * This method must only be invoked after chreWifiScanCacheScanEventBegin()
- * and before chreWifiScanCacheScanEventEnd(), otherwise has no effect.
- * When this method is invoked, the provided result is stored in the current
- * WiFi scan cache. The cache library may drop scan results if it is out of
- * memory (decided by the CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY value).
- *
- * The function does not obtain ownership of the provided pointer.
- *
- * This function must be invoked as soon as the scan result is available (i.e
- * the access point is detected). The chreWifiScanResult.ageMs field is
- * ignored by the scan cache library, and will be populated internally when
- * chreWifiScanCacheScanEventEnd() is invoked.
- *
- * @param result A non-null pointer to a WiFi scan result.
- *
- * @see chreWifiScanCacheScanEventBegin for the expected flow.
- */
-void chreWifiScanCacheScanEventAdd(const struct chreWifiScanResult *result);
-
-/**
- * Ends the caching of a single scan event.
- *
- * This method must be invoked when a WiFi scan event is fully completed. This
- * method will take the cached scan results and provide them (if any) to CHRE
- * through the chrePalWifiCallbacks provided in chreWifiScanCacheInit().
- *
- * Note that this function may be directly invoked after
- * chreWifiScanCacheScanEventBegin() without chreWifiScanCacheScanEventAdd() if
- * the scanning failed.
- *
- * @param errorCode The error code of the scan operation.
- *
- * @see chreWifiScanCacheScanEventBegin for the expected flow.
- */
-void chreWifiScanCacheScanEventEnd(enum chreError errorCode);
-
-/**
- * Checks if a new scan request from CHRE must be dispatched from the cache,
- * and dispatches them through the chrePalWifiCallbacks if appropriate.
- *
- * This method will look at the currently completed WiFi scans and checks if the
- * cache is within the maxScanAgeMs field of the scan parameter. If this method
- * returns false, the current cache does not meet the maxScanAgeMs requirement,
- * and the WLAN must perform a fresh scan.
- *
- * This method must be invoked when by the chrePalWifiApi->requestScan()
- * implementation to see if a cached WiFi scan event can be used. An example
- * usage is the following:
- *
- * if (chreWifiScanCacheDispatchFromCache(params)) {
- * // Cached WiFi scan event was dispatched - no need to perform fresh scan
- * // and can return a synchronous success.
- * return true;
- * } else {
- * // Perform WiFi scan
- * }
- *
- * @param params The chreWifiScanParams parameter of a scan request from CHRE.
- *
- * @return true if a scan was dispatched from the cache, false otherwise.
- */
-bool chreWifiScanCacheDispatchFromCache(
- const struct chreWifiScanParams *params);
-
-/**
- * Invoked to free a WiFi scan event produced by this caching library.
- *
- * This method must invoked by the chrePalWifiApi->releaseScanEvent()
- * implementation if the caching library was used to send WiFi scan events.
- */
-void chreWifiScanCacheReleaseScanEvent(struct chreWifiScanEvent *event);
-
-/**
- * Configures scan monitoring for the cache scan library.
- *
- * This method must be invoked by the chrePalWifiApi->configureScanMonitor()
- * implementation.
- *
- * If scan monitoring is enabled, the cache scan library will send WiFi scan
- * events provided through chreWifiScanCacheScanEventAdd() even if no
- * outstanding request from CHRE is present.
- *
- * @param enable true to enable WiFi scan monitoring, false otherwise.
- */
-void chreWifiScanCacheConfigureScanMonitor(bool enable);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHRE_PAL_WIFI_SCAN_CACHE_H_
diff --git a/pal/util/tests/wifi_scan_cache_test.cc b/pal/util/tests/wifi_scan_cache_test.cc
deleted file mode 100644
index dad64ff7..00000000
--- a/pal/util/tests/wifi_scan_cache_test.cc
+++ /dev/null
@@ -1,365 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/pal/util/wifi_scan_cache.h"
-
-#include <algorithm>
-#include <cinttypes>
-#include <cstring>
-
-#include "chre/platform/log.h"
-#include "chre/platform/shared/pal_system_api.h"
-#include "chre/util/fixed_size_vector.h"
-#include "chre/util/macros.h"
-#include "chre/util/nanoapp/wifi.h"
-#include "chre/util/optional.h"
-#include "chre_api/chre/common.h"
-#include "gtest/gtest.h"
-
-namespace {
-
-/************************************************
- * Prototypes
- ***********************************************/
-void chreWifiScanResponseCallback(bool pending, uint8_t errorCode);
-void chreWifiScanEventCallback(struct chreWifiScanEvent *event);
-
-struct WifiScanResponse {
- bool pending;
- uint8_t errorCode;
-};
-
-/************************************************
- * Global variables
- ***********************************************/
-const chrePalWifiCallbacks gChreWifiPalCallbacks = {
- .scanResponseCallback = chreWifiScanResponseCallback,
- .scanEventCallback = chreWifiScanEventCallback,
-};
-
-chre::Optional<WifiScanResponse> gWifiScanResponse;
-chre::FixedSizeVector<chreWifiScanResult, CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY>
- gWifiScanResultList;
-chre::Optional<chreWifiScanEvent> gExpectedWifiScanEvent;
-bool gWifiScanEventCompleted;
-
-/************************************************
- * Test class
- ***********************************************/
-class WifiScanCacheTests : public ::testing::Test {
- protected:
- void SetUp() override {
- clearTestState();
- EXPECT_TRUE(chreWifiScanCacheInit(&chre::gChrePalSystemApi,
- &gChreWifiPalCallbacks));
- }
-
- void TearDown() override {
- chreWifiScanCacheDeinit();
- }
-
- void clearTestState() {
- gExpectedWifiScanEvent.reset();
- gWifiScanResponse.reset();
- while (!gWifiScanResultList.empty()) {
- gWifiScanResultList.pop_back();
- }
- }
-};
-
-/************************************************
- * Private functions
- ***********************************************/
-void chreWifiScanResponseCallback(bool pending, uint8_t errorCode) {
- WifiScanResponse response = {
- .pending = pending,
- .errorCode = errorCode,
- };
- gWifiScanResponse = response;
-}
-
-void chreWifiScanEventCallback(struct chreWifiScanEvent *event) {
- ASSERT_TRUE(gExpectedWifiScanEvent.has_value());
- EXPECT_EQ(event->version, gExpectedWifiScanEvent->version);
- EXPECT_EQ(event->scanType, gExpectedWifiScanEvent->scanType);
- EXPECT_EQ(event->ssidSetSize, gExpectedWifiScanEvent->ssidSetSize);
- ASSERT_EQ(event->scannedFreqListLen,
- gExpectedWifiScanEvent->scannedFreqListLen);
- if (event->scannedFreqListLen > 0) {
- ASSERT_NE(event->scannedFreqList, nullptr);
- EXPECT_EQ(
- memcmp(gExpectedWifiScanEvent->scannedFreqList, event->scannedFreqList,
- event->scannedFreqListLen * sizeof(uint32_t)),
- 0);
- }
-
- EXPECT_EQ(event->radioChainPref, gExpectedWifiScanEvent->radioChainPref);
- EXPECT_EQ(event->eventIndex, gExpectedWifiScanEvent->eventIndex);
- gExpectedWifiScanEvent->eventIndex++;
-
- for (uint8_t i = 0; i < event->resultCount; i++) {
- const chreWifiScanResult &result = event->results[i];
- gWifiScanResultList.push_back(result);
- }
-
- if (gWifiScanResultList.size() == event->resultTotal) {
- gWifiScanEventCompleted = true;
- }
-
- chreWifiScanCacheReleaseScanEvent(event);
-}
-
-void beginDefaultWifiCache(const uint32_t *scannedFreqList,
- uint16_t scannedFreqListLen,
- bool activeScanResult = true) {
- chreWifiScanEvent event;
- memset(&event, 0, sizeof(chreWifiScanEvent));
- event.version = CHRE_WIFI_SCAN_EVENT_VERSION;
- event.scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE;
- event.scannedFreqList = scannedFreqList;
- event.scannedFreqListLen = scannedFreqListLen;
- event.radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT;
- gExpectedWifiScanEvent = event;
-
- chreWifiScanCacheScanEventBegin(
- static_cast<enum chreWifiScanType>(gExpectedWifiScanEvent->scanType),
- gExpectedWifiScanEvent->ssidSetSize,
- gExpectedWifiScanEvent->scannedFreqList,
- gExpectedWifiScanEvent->scannedFreqListLen,
- gExpectedWifiScanEvent->radioChainPref, activeScanResult);
-}
-
-void cacheDefaultWifiCacheTest(size_t numEvents,
- const uint32_t *scannedFreqList,
- uint16_t scannedFreqListLen,
- bool activeScanResult = true,
- bool scanMonitoringEnabled = false) {
- gWifiScanEventCompleted = false;
- beginDefaultWifiCache(scannedFreqList, scannedFreqListLen, activeScanResult);
-
- chreWifiScanResult result = {};
- for (size_t i = 0; i < numEvents; i++) {
- result.rssi = static_cast<int8_t>(i);
- memcpy(result.bssid, &i, sizeof(i));
- chreWifiScanCacheScanEventAdd(&result);
- }
-
- chreWifiScanCacheScanEventEnd(CHRE_ERROR_NONE);
-
- if (activeScanResult) {
- EXPECT_TRUE(gWifiScanResponse.has_value());
- EXPECT_EQ(gWifiScanResponse->pending, true);
- ASSERT_EQ(gWifiScanResponse->errorCode, CHRE_ERROR_NONE);
- } else {
- EXPECT_FALSE(gWifiScanResponse.has_value());
- }
-
- size_t numEventsExpected = 0;
- if (activeScanResult || scanMonitoringEnabled) {
- numEventsExpected = std::min(
- numEvents, static_cast<size_t>(CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY));
- ASSERT_TRUE(gWifiScanEventCompleted);
- }
-
- ASSERT_EQ(gWifiScanResultList.size(), numEventsExpected);
- for (size_t i = 0; i < gWifiScanResultList.size(); i++) {
- // ageMs is not known apriori
- result.ageMs = gWifiScanResultList[i].ageMs;
- result.rssi = static_cast<int8_t>(i);
- memcpy(result.bssid, &i, sizeof(i));
- EXPECT_EQ(
- memcmp(&gWifiScanResultList[i], &result, sizeof(chreWifiScanResult)),
- 0);
- }
-}
-
-void testCacheDispatch(size_t numEvents, uint32_t maxScanAgeMs,
- bool expectSuccess) {
- cacheDefaultWifiCacheTest(numEvents, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */);
-
- gExpectedWifiScanEvent->eventIndex = 0;
- gWifiScanResponse.reset();
- while (!gWifiScanResultList.empty()) {
- gWifiScanResultList.pop_back();
- }
-
- struct chreWifiScanParams params = {
- .scanType = CHRE_WIFI_SCAN_TYPE_NO_PREFERENCE,
- .maxScanAgeMs = maxScanAgeMs,
- .frequencyListLen = 0,
- .frequencyList = nullptr,
- .ssidListLen = 0,
- .ssidList = nullptr,
- .radioChainPref = CHRE_WIFI_RADIO_CHAIN_PREF_DEFAULT,
- .channelSet = CHRE_WIFI_CHANNEL_SET_NON_DFS,
- };
- EXPECT_EQ(chreWifiScanCacheDispatchFromCache(&params), expectSuccess);
-
- EXPECT_EQ(gWifiScanResponse.has_value(), expectSuccess);
- if (expectSuccess) {
- EXPECT_TRUE(gWifiScanResponse->pending);
- EXPECT_EQ(gWifiScanResponse->errorCode, CHRE_ERROR_NONE);
- }
-
- EXPECT_EQ(gWifiScanResultList.size(), expectSuccess ? numEvents : 0);
-}
-
-} // anonymous namespace
-
-/************************************************
- * Tests
- ***********************************************/
-TEST_F(WifiScanCacheTests, SingleWifiResultTest) {
- cacheDefaultWifiCacheTest(1 /* numEvents */, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */);
-}
-
-TEST_F(WifiScanCacheTests, MultiWifiResultTest) {
- cacheDefaultWifiCacheTest(
- CHRE_PAL_WIFI_SCAN_CACHE_MAX_RESULT_COUNT + 1 /* numEvents */,
- nullptr /* scannedFreqList */, 0 /* scannedFreqListLen */);
-}
-
-TEST_F(WifiScanCacheTests, WifiResultOverflowTest) {
- cacheDefaultWifiCacheTest(
- CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY + 1 /* numEvents */,
- nullptr /* scannedFreqList */, 0 /* scannedFreqListLen */);
-}
-
-TEST_F(WifiScanCacheTests, EmptyWifiResultTest) {
- cacheDefaultWifiCacheTest(0 /* numEvents */, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */);
-}
-
-TEST_F(WifiScanCacheTests, FailedWifiCacheTest) {
- beginDefaultWifiCache(nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */);
-
- chreWifiScanCacheScanEventEnd(CHRE_ERROR);
-
- EXPECT_TRUE(gWifiScanResponse.has_value());
- EXPECT_FALSE(gWifiScanResponse->pending);
- EXPECT_EQ(gWifiScanResponse->errorCode, CHRE_ERROR);
-
- EXPECT_EQ(gWifiScanResultList.size(), 0);
-}
-
-TEST_F(WifiScanCacheTests, FrequencyListTest) {
- const uint32_t freqList[2] = {5210, 5240};
- cacheDefaultWifiCacheTest(1 /* numEvents */, freqList, ARRAY_SIZE(freqList));
-}
-
-TEST_F(WifiScanCacheTests, InvalidFrequencyListTest) {
- beginDefaultWifiCache(nullptr /* scannedFreqList */,
- 1 /* scannedFreqListLen */);
-
- EXPECT_TRUE(gWifiScanResponse.has_value());
- EXPECT_FALSE(gWifiScanResponse->pending);
- EXPECT_EQ(gWifiScanResponse->errorCode, CHRE_ERROR_INVALID_ARGUMENT);
-
- EXPECT_EQ(gWifiScanResultList.size(), 0);
-}
-
-TEST_F(WifiScanCacheTests, SequentialWifiResultTest) {
- cacheDefaultWifiCacheTest(1 /* numEvents */, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */);
-
- clearTestState();
- cacheDefaultWifiCacheTest(1 /* numEvents */, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */);
-}
-
-TEST_F(WifiScanCacheTests, ScanMonitorDisabledTest) {
- cacheDefaultWifiCacheTest(1 /* numEvents */, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */,
- false /* activeScanResult */,
- false /* scanMonitoringEnabled */);
-}
-
-TEST_F(WifiScanCacheTests, ScanMonitorEnabledTest) {
- chreWifiScanCacheConfigureScanMonitor(true /* enable */);
- cacheDefaultWifiCacheTest(1 /* numEvents */, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */,
- false /* activeScanResult */,
- true /* scanMonitoringEnabled */);
-}
-
-TEST_F(WifiScanCacheTests, ScanMonitorEnableDisableTest) {
- chreWifiScanCacheConfigureScanMonitor(true /* enable */);
- cacheDefaultWifiCacheTest(1 /* numEvents */, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */,
- false /* activeScanResult */,
- true /* scanMonitoringEnabled */);
-
- clearTestState();
- chreWifiScanCacheConfigureScanMonitor(false /* enable */);
- cacheDefaultWifiCacheTest(1 /* numEvents */, nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */,
- false /* activeScanResult */,
- false /* scanMonitoringEnabled */);
-}
-
-TEST_F(WifiScanCacheTests, CacheDispatchTest) {
- testCacheDispatch(1 /* numEvents */, 5000 /* maxScanAgeMs */,
- true /* expectSuccess */);
-}
-
-TEST_F(WifiScanCacheTests, ZeroMaxScanAgeCacheDispatchTest) {
- testCacheDispatch(1 /* numEvents */, 0 /* maxScanAgeMs */,
- false /* expectSuccess */);
-}
-
-TEST_F(WifiScanCacheTests, DuplicateScanResultTest) {
- beginDefaultWifiCache(nullptr /* scannedFreqList */,
- 0 /* scannedFreqListLen */,
- true /* activeScanResult */);
-
- chreWifiScanResult result = {};
- result.rssi = -98;
- result.primaryChannel = 5270;
- const char *dummySsid = "Test ssid";
- memcpy(result.ssid, dummySsid, strlen(dummySsid));
- result.ssidLen = strlen(dummySsid);
- const char *dummyBssid = "12:34:56:78:9a:bc";
- memcpy(result.bssid, dummyBssid, strlen(dummyBssid));
- chreWifiScanResult result2 = {};
- result.rssi = -98;
- result.primaryChannel = 5270;
- const char *dummySsid2 = "Test ssid 2";
- memcpy(result.ssid, dummySsid, strlen(dummySsid2));
- result.ssidLen = strlen(dummySsid);
- const char *dummyBssid2 = "34:56:78:9a:bc:de";
- memcpy(result.bssid, dummyBssid, strlen(dummyBssid2));
-
- chreWifiScanCacheScanEventAdd(&result);
- chreWifiScanCacheScanEventAdd(&result2);
- chreWifiScanCacheScanEventAdd(&result);
-
- chreWifiScanCacheScanEventEnd(CHRE_ERROR_NONE);
-
- EXPECT_TRUE(gWifiScanResponse.has_value());
- EXPECT_EQ(gWifiScanResponse->pending, true);
- ASSERT_EQ(gWifiScanResponse->errorCode, CHRE_ERROR_NONE);
-
- ASSERT_EQ(gWifiScanResultList.size(), 2);
- result.ageMs = gWifiScanResultList[0].ageMs;
- EXPECT_EQ(
- memcmp(&gWifiScanResultList[0], &result, sizeof(chreWifiScanResult)), 0);
- result2.ageMs = gWifiScanResultList[1].ageMs;
- EXPECT_EQ(
- memcmp(&gWifiScanResultList[1], &result2, sizeof(chreWifiScanResult)), 0);
-}
diff --git a/pal/util/wifi_scan_cache.c b/pal/util/wifi_scan_cache.c
deleted file mode 100644
index 57b67f46..00000000
--- a/pal/util/wifi_scan_cache.c
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/pal/util/wifi_scan_cache.h"
-
-#include <inttypes.h>
-
-#include "chre/util/macros.h"
-
-/************************************************
- * Prototypes
- ***********************************************/
-
-struct chreWifiScanCacheState {
- //! true if the scan cache has started, i.e. chreWifiScanCacheScanEventBegin
- //! was invoked and has not yet ended.
- bool started;
-
- //! true if the current scan cache is a result of a CHRE active scan request.
- bool activeScanResult;
-
- //! The number of chreWifiScanResults dropped due to OOM.
- uint16_t numWifiScanResultsDropped;
-
- //! Stores the WiFi cache elements
- struct chreWifiScanEvent event;
- struct chreWifiScanResult resultList[CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY];
-
- //! The number of chreWifiScanEvent data pending release via
- //! chreWifiScanCacheReleaseScanEvent().
- uint8_t numWifiEventsPendingRelease;
-
- bool scanMonitoringEnabled;
-
- uint32_t scannedFreqList[CHRE_WIFI_FREQUENCY_LIST_MAX_LEN];
-};
-
-/************************************************
- * Global variables
- ***********************************************/
-static const struct chrePalSystemApi *gSystemApi = NULL;
-static const struct chrePalWifiCallbacks *gCallbacks = NULL;
-
-static struct chreWifiScanCacheState gWifiCacheState;
-
-//! true if scan monitoring is enabled via
-//! chreWifiScanCacheConfigureScanMonitor().
-static bool gScanMonitoringEnabled;
-
-static const uint64_t kOneMillisecondInNanoseconds = UINT64_C(1000000);
-
-/************************************************
- * Private functions
- ***********************************************/
-static bool chreWifiScanCacheIsInitialized(void) {
- return (gSystemApi != NULL && gCallbacks != NULL);
-}
-
-static bool areAllScanEventsReleased(void) {
- return gWifiCacheState.numWifiEventsPendingRelease == 0;
-}
-
-static bool isFrequencyListValid(const uint32_t *frequencyList,
- uint16_t frequencyListLen) {
- return (frequencyListLen == 0) || (frequencyList != NULL);
-}
-
-static bool paramsMatchScanCache(const struct chreWifiScanParams *params) {
- uint64_t timeNs = gWifiCacheState.event.referenceTime;
- bool scan_within_age =
- (timeNs >= gSystemApi->getCurrentTime() -
- (params->maxScanAgeMs * kOneMillisecondInNanoseconds));
-
- // Perform a conservative check for the params and scan cache.
- // TODO(b/174510035): Consider optimizing for the case for channelSet ==
- // CHRE_WIFI_CHANNEL_SET_ALL.
- bool params_non_dfs =
- (params->scanType == CHRE_WIFI_SCAN_TYPE_ACTIVE) ||
- ((params->scanType == CHRE_WIFI_SCAN_TYPE_NO_PREFERENCE) &&
- (params->channelSet == CHRE_WIFI_CHANNEL_SET_NON_DFS));
- bool cache_non_dfs =
- (gWifiCacheState.event.scanType == CHRE_WIFI_SCAN_TYPE_ACTIVE) ||
- (gWifiCacheState.event.scanType == CHRE_WIFI_SCAN_TYPE_PASSIVE);
-
- bool cache_all_freq = (gWifiCacheState.event.scannedFreqListLen == 0);
- bool cache_all_ssid = (gWifiCacheState.event.ssidSetSize == 0);
-
- return scan_within_age && (params_non_dfs || !cache_non_dfs) &&
- cache_all_freq && cache_all_ssid;
-}
-
-static bool isWifiScanCacheBusy(bool logOnBusy) {
- bool busy = true;
- if (gWifiCacheState.started) {
- if (logOnBusy) {
- gSystemApi->log(CHRE_LOG_ERROR, "Scan cache already started");
- }
- } else if (!areAllScanEventsReleased()) {
- if (logOnBusy) {
- gSystemApi->log(CHRE_LOG_ERROR, "Scan cache events pending release");
- }
- } else {
- busy = false;
- }
-
- return busy;
-}
-
-static void chreWifiScanCacheDispatchAll(void) {
- gSystemApi->log(CHRE_LOG_DEBUG, "Dispatching %" PRIu8 " events",
- gWifiCacheState.event.resultTotal);
- if (gWifiCacheState.event.resultTotal == 0) {
- gWifiCacheState.event.eventIndex = 0;
- gWifiCacheState.event.resultCount = 0;
- gWifiCacheState.event.results = NULL;
- gCallbacks->scanEventCallback(&gWifiCacheState.event);
- } else {
- uint8_t eventIndex = 0;
- for (uint16_t i = 0; i < gWifiCacheState.event.resultTotal;
- i += CHRE_PAL_WIFI_SCAN_CACHE_MAX_RESULT_COUNT) {
- gWifiCacheState.event.resultCount =
- MIN(CHRE_PAL_WIFI_SCAN_CACHE_MAX_RESULT_COUNT,
- (uint8_t)(gWifiCacheState.event.resultTotal - i));
- gWifiCacheState.event.eventIndex = eventIndex++;
- gWifiCacheState.event.results = &gWifiCacheState.resultList[i];
-
- // TODO(b/174511061): The current approach only works for situations where
- // the event is released immediately. Add a way to handle this scenario
- // (e.g. an array of chreWifiScanEvent's).
- gWifiCacheState.numWifiEventsPendingRelease++;
- gCallbacks->scanEventCallback(&gWifiCacheState.event);
- }
- }
-}
-
-static bool isWifiScanResultInCache(const struct chreWifiScanResult *result,
- size_t *index) {
- for (uint8_t i = 0; i < gWifiCacheState.event.resultTotal; i++) {
- const struct chreWifiScanResult *cacheResult =
- &gWifiCacheState.resultList[i];
- // Filtering based on BSSID + SSID + frequency based on Linux cfg80211.
- // https://github.com/torvalds/linux/blob/master/net/wireless/scan.c
- if ((result->primaryChannel == cacheResult->primaryChannel) &&
- (memcmp(result->bssid, cacheResult->bssid, CHRE_WIFI_BSSID_LEN) == 0) &&
- (result->ssidLen == cacheResult->ssidLen) &&
- (memcmp(result->ssid, cacheResult->ssid, result->ssidLen) == 0)) {
- *index = i;
- return true;
- }
- }
-
- return false;
-}
-
-/************************************************
- * Public functions
- ***********************************************/
-bool chreWifiScanCacheInit(const struct chrePalSystemApi *systemApi,
- const struct chrePalWifiCallbacks *callbacks) {
- if (systemApi == NULL || callbacks == NULL) {
- return false;
- }
-
- gSystemApi = systemApi;
- gCallbacks = callbacks;
- memset(&gWifiCacheState, 0, sizeof(gWifiCacheState));
- gScanMonitoringEnabled = false;
-
- return true;
-}
-
-void chreWifiScanCacheDeinit(void) {
- gSystemApi = NULL;
- gCallbacks = NULL;
-}
-
-bool chreWifiScanCacheScanEventBegin(enum chreWifiScanType scanType,
- uint8_t ssidSetSize,
- const uint32_t *scannedFreqList,
- uint16_t scannedFreqListLength,
- uint8_t radioChainPref,
- bool activeScanResult) {
- bool success = false;
- if (chreWifiScanCacheIsInitialized()) {
- enum chreError error = CHRE_ERROR_NONE;
- if (!isFrequencyListValid(scannedFreqList, scannedFreqListLength)) {
- gSystemApi->log(CHRE_LOG_ERROR, "Invalid frequency argument");
- error = CHRE_ERROR_INVALID_ARGUMENT;
- } else if (isWifiScanCacheBusy(true /* logOnBusy */)) {
- error = CHRE_ERROR_BUSY;
- } else {
- success = true;
- memset(&gWifiCacheState, 0, sizeof(gWifiCacheState));
-
- gWifiCacheState.event.version = CHRE_WIFI_SCAN_EVENT_VERSION;
- gWifiCacheState.event.scanType = scanType;
- gWifiCacheState.event.ssidSetSize = ssidSetSize;
-
- scannedFreqListLength =
- MIN(scannedFreqListLength, CHRE_WIFI_FREQUENCY_LIST_MAX_LEN);
- if (scannedFreqList != NULL) {
- memcpy(gWifiCacheState.scannedFreqList, scannedFreqList,
- scannedFreqListLength * sizeof(uint32_t));
- }
- gWifiCacheState.event.scannedFreqListLen = scannedFreqListLength;
- gWifiCacheState.event.radioChainPref = radioChainPref;
-
- gWifiCacheState.activeScanResult = activeScanResult;
- gWifiCacheState.started = true;
- }
-
- if (activeScanResult && !success) {
- gCallbacks->scanResponseCallback(false /* pending */, error);
- }
- }
-
- return success;
-}
-
-void chreWifiScanCacheScanEventAdd(const struct chreWifiScanResult *result) {
- if (!gWifiCacheState.started) {
- gSystemApi->log(CHRE_LOG_ERROR, "Cannot add to cache before starting it");
- } else {
- size_t index;
- bool exists = isWifiScanResultInCache(result, &index);
- if (!exists && gWifiCacheState.event.resultTotal >=
- CHRE_PAL_WIFI_SCAN_CACHE_CAPACITY) {
- // TODO(b/174510884): Filter based on e.g. RSSI if full
- gWifiCacheState.numWifiScanResultsDropped++;
- } else {
- if (!exists) {
- // Only add a new entry if the result was not already cached.
- index = gWifiCacheState.event.resultTotal;
- gWifiCacheState.event.resultTotal++;
- }
-
- memcpy(&gWifiCacheState.resultList[index], result,
- sizeof(const struct chreWifiScanResult));
-
- // ageMs will be properly populated in chreWifiScanCacheScanEventEnd
- gWifiCacheState.resultList[index].ageMs = (uint32_t)(
- gSystemApi->getCurrentTime() / kOneMillisecondInNanoseconds);
- }
- }
-}
-
-void chreWifiScanCacheScanEventEnd(enum chreError errorCode) {
- if (gWifiCacheState.started) {
- if (gWifiCacheState.numWifiScanResultsDropped > 0) {
- gSystemApi->log(CHRE_LOG_WARN,
- "Dropped total of %" PRIu32 " access points",
- gWifiCacheState.numWifiScanResultsDropped);
- }
- if (gWifiCacheState.activeScanResult) {
- gCallbacks->scanResponseCallback(
- errorCode == CHRE_ERROR_NONE /* pending */, errorCode);
- }
-
- if (errorCode == CHRE_ERROR_NONE &&
- (gWifiCacheState.activeScanResult || gScanMonitoringEnabled)) {
- gWifiCacheState.event.referenceTime = gSystemApi->getCurrentTime();
- gWifiCacheState.event.scannedFreqList = gWifiCacheState.scannedFreqList;
-
- uint32_t referenceTimeMs = (uint32_t)(
- gWifiCacheState.event.referenceTime / kOneMillisecondInNanoseconds);
- for (uint16_t i = 0; i < gWifiCacheState.event.resultTotal; i++) {
- gWifiCacheState.resultList[i].ageMs =
- referenceTimeMs - gWifiCacheState.resultList[i].ageMs;
- }
-
- chreWifiScanCacheDispatchAll();
- }
-
- gWifiCacheState.started = false;
- gWifiCacheState.activeScanResult = false;
- }
-}
-
-bool chreWifiScanCacheDispatchFromCache(
- const struct chreWifiScanParams *params) {
- if (!chreWifiScanCacheIsInitialized()) {
- return false;
- }
-
- if (paramsMatchScanCache(params) &&
- !isWifiScanCacheBusy(false /* logOnBusy */)) {
- // TODO(b/174511061): Handle scenario where cache is working on delivering
- // a scan event. Ideally the library will wait until it is complete to
- // dispatch from the cache if it meets the criteria, rather than scheduling
- // a fresh scan.
- gCallbacks->scanResponseCallback(true /* pending */, CHRE_ERROR_NONE);
- chreWifiScanCacheDispatchAll();
- return true;
- } else {
- return false;
- }
-}
-
-void chreWifiScanCacheReleaseScanEvent(struct chreWifiScanEvent *event) {
- if (!chreWifiScanCacheIsInitialized()) {
- return;
- }
-
- if (event != &gWifiCacheState.event) {
- gSystemApi->log(CHRE_LOG_ERROR, "Invalid event pointer %p", event);
- } else if (gWifiCacheState.numWifiEventsPendingRelease > 0) {
- gWifiCacheState.numWifiEventsPendingRelease--;
- }
-}
-
-void chreWifiScanCacheConfigureScanMonitor(bool enable) {
- if (!chreWifiScanCacheIsInitialized()) {
- return;
- }
-
- gScanMonitoringEnabled = enable;
-}
diff --git a/platform/android/host_link.cc b/platform/android/host_link.cc
index 79628471..ae1b61f2 100644
--- a/platform/android/host_link.cc
+++ b/platform/android/host_link.cc
@@ -18,14 +18,18 @@
#include "chre/core/event_loop_manager.h"
#include "chre/platform/shared/host_protocol_common.h"
-#include "chre/util/flatbuffers/helpers.h"
#include "chre/util/macros.h"
-#include "chre/util/nested_data_ptr.h"
#include "chre_api/chre/version.h"
#include "chre_host/generated/host_messages_generated.h"
namespace chre {
+//! Used to pass the client ID through the user data pointer in deferCallback
+union HostClientIdCallbackData {
+ uint16_t hostClientId;
+ void *ptr;
+};
+
static_assert(sizeof(uint16_t) <= sizeof(void *),
"Pointer must at least fit a u16 for passing the host client ID");
@@ -56,7 +60,7 @@ void sendFlatbufferToHost(T &message, uint16_t hostClientId) {
container.message.Set(std::move(message));
container.host_addr.reset(new fbs::HostAddress(hostClientId));
- ChreFlatBufferBuilder builder;
+ flatbuffers::FlatBufferBuilder builder;
auto containerOffset = CreateMessageContainer(builder, &container, nullptr);
builder.Finish(containerOffset);
@@ -107,38 +111,40 @@ void handleHubInfoRequest(uint16_t hostClientId) {
sendFlatbufferToHost(response, hostClientId);
}
+void constructNanoappListCallback(uint16_t /*eventType*/, void *cookie) {
+ HostClientIdCallbackData clientIdCbData;
+ clientIdCbData.ptr = cookie;
+
+ auto nanoappAddCallback = [](const Nanoapp *nanoapp, void *data) {
+ auto response = static_cast<fbs::NanoappListResponseT *>(data);
+ auto nanoappListEntry =
+ std::unique_ptr<fbs::NanoappListEntryT>(new fbs::NanoappListEntryT());
+ nanoappListEntry->app_id = nanoapp->getAppId();
+ nanoappListEntry->version = nanoapp->getAppVersion();
+ nanoappListEntry->enabled = true;
+ nanoappListEntry->is_system = nanoapp->isSystemNanoapp();
+ response->nanoapps.push_back(std::move(nanoappListEntry));
+ };
+
+ fbs::NanoappListResponseT response;
+ EventLoop &eventLoop = EventLoopManagerSingleton::get()->getEventLoop();
+ eventLoop.forEachNanoapp(nanoappAddCallback, &response);
+
+ sendFlatbufferToHost(response, clientIdCbData.hostClientId);
+}
+
/**
* Handles a request from the host for a list of nanoapps.
*
* @param hostClientId The client ID on the host making the request.
*/
void handleNanoappListRequest(uint16_t hostClientId) {
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- uint16_t cbHostClientId = NestedDataPtr<uint16_t>(data);
-
- auto nanoappAddCallback = [](const Nanoapp *nanoapp, void *data) {
- auto response = static_cast<fbs::NanoappListResponseT *>(data);
- auto nanoappListEntry =
- std::unique_ptr<fbs::NanoappListEntryT>(new fbs::NanoappListEntryT());
- nanoappListEntry->app_id = nanoapp->getAppId();
- nanoappListEntry->version = nanoapp->getAppVersion();
- nanoappListEntry->enabled = true;
- nanoappListEntry->is_system = nanoapp->isSystemNanoapp();
- nanoappListEntry->permissions = nanoapp->getAppPermissions();
- response->nanoapps.push_back(std::move(nanoappListEntry));
- };
-
- fbs::NanoappListResponseT response;
- EventLoop &eventLoop = EventLoopManagerSingleton::get()->getEventLoop();
- eventLoop.forEachNanoapp(nanoappAddCallback, &response);
-
- sendFlatbufferToHost(response, cbHostClientId);
- };
-
LOGD("handleNanoappListRequest");
+ HostClientIdCallbackData cbData = {};
+ cbData.hostClientId = hostClientId;
EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::NanoappListResponse,
- NestedDataPtr<uint16_t>(hostClientId), callback);
+ SystemCallbackType::NanoappListResponse, cbData.ptr,
+ constructNanoappListCallback);
}
/**
diff --git a/platform/android/platform_audio.cc b/platform/android/platform_audio.cc
index 39812b76..f501da01 100644
--- a/platform/android/platform_audio.cc
+++ b/platform/android/platform_audio.cc
@@ -19,7 +19,6 @@
#include <cinttypes>
#include "chre/core/audio_request_manager.h"
-#include "chre/core/audio_util.h"
#include "chre/core/event_loop_manager.h"
#include "chre/platform/fatal_error.h"
#include "chre/platform/log.h"
@@ -44,14 +43,16 @@ void PlatformAudioBase::audioReadCallback(void *cookie) {
auto *platformAudio = static_cast<PlatformAudio *>(cookie);
auto &dataEvent = platformAudio->mDataEvent;
- Nanoseconds samplingTime = AudioUtil::getDurationFromSampleCountAndRate(
- platformAudio->mNumSamples, kAndroidAudioSampleRate);
+ Nanoseconds samplingTime =
+ AudioRequestManager::getDurationFromSampleCountAndRate(
+ platformAudio->mNumSamples, kAndroidAudioSampleRate);
dataEvent.timestamp =
(SystemTime::getMonotonicTime() - samplingTime).toRawNanoseconds();
if (dataEvent.format == CHRE_AUDIO_DATA_FORMAT_16_BIT_SIGNED_PCM) {
- uint32_t intervalNumSamples = AudioUtil::getSampleCountFromRateAndDuration(
- kAndroidAudioSampleRate, platformAudio->mEventDelay);
+ uint32_t intervalNumSamples =
+ AudioRequestManager::getSampleCountFromRateAndDuration(
+ kAndroidAudioSampleRate, platformAudio->mEventDelay);
// Determine how much new audio data is required to be read from the device.
// Samples that are already buffered by this implementation may be reused.
@@ -109,10 +110,10 @@ PlatformAudio::PlatformAudio() {
int32_t bufferSize = AAudioStream_getBufferCapacityInFrames(mStream);
LOGD("Created audio stream with %" PRId32 " frames buffer size", bufferSize);
- mMinBufferDuration = AudioUtil::getDurationFromSampleCountAndRate(
+ mMinBufferDuration = AudioRequestManager::getDurationFromSampleCountAndRate(
kAndroidAudioMinBufferSize, kAndroidAudioSampleRate)
.toRawNanoseconds();
- mMaxBufferDuration = AudioUtil::getDurationFromSampleCountAndRate(
+ mMaxBufferDuration = AudioRequestManager::getDurationFromSampleCountAndRate(
bufferSize, kAndroidAudioSampleRate)
.toRawNanoseconds();
diff --git a/platform/freertos/context.cc b/platform/freertos/context.cc
deleted file mode 100644
index 8ee7448b..00000000
--- a/platform/freertos/context.cc
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 "chre/platform/context.h"
-#include "chre/target_platform/init.h"
-
-#include "FreeRTOS.h"
-#include "task.h"
-
-namespace chre {
-
-bool inEventLoopThread() {
- TaskHandle_t evtLoopTaskHandle = xTaskGetHandle(freertos::getChreTaskName());
- TaskHandle_t currentTaskHandle = xTaskGetCurrentTaskHandle();
-
- return (evtLoopTaskHandle == currentTaskHandle);
-}
-
-} // namespace chre
diff --git a/platform/freertos/include/chre/target_platform/atomic_base.h b/platform/freertos/include/chre/target_platform/atomic_base.h
deleted file mode 100644
index 582d0ae4..00000000
--- a/platform/freertos/include/chre/target_platform/atomic_base.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_FREERTOS_ATOMIC_BASE_H_
-#define CHRE_PLATFORM_FREERTOS_ATOMIC_BASE_H_
-
-#include <atomic>
-
-namespace chre {
-
-template <typename AtomicType>
-class AtomicBase {
- protected:
- std::atomic<AtomicType> mAtomic;
-};
-
-typedef AtomicBase<bool> AtomicBoolBase;
-typedef AtomicBase<uint32_t> AtomicUint32Base;
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_FREERTOS_ATOMIC_BASE_H_
diff --git a/platform/freertos/include/chre/target_platform/atomic_base_impl.h b/platform/freertos/include/chre/target_platform/atomic_base_impl.h
deleted file mode 100644
index d44a1978..00000000
--- a/platform/freertos/include/chre/target_platform/atomic_base_impl.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_FREERTOS_ATOMIC_BASE_IMPL_H_
-#define CHRE_PLATFORM_FREERTOS_ATOMIC_BASE_IMPL_H_
-
-#include "chre/platform/atomic.h"
-
-namespace chre {
-
-inline AtomicBool::AtomicBool(bool startingValue) {
- std::atomic_init(&mAtomic, startingValue);
-}
-
-inline bool AtomicBool::operator=(bool desired) {
- mAtomic = desired;
- return desired;
-}
-
-inline bool AtomicBool::load() const {
- return mAtomic.load();
-}
-
-inline void AtomicBool::store(bool desired) {
- mAtomic.store(desired);
-}
-
-inline bool AtomicBool::exchange(bool desired) {
- return mAtomic.exchange(desired);
-}
-
-inline AtomicUint32::AtomicUint32(uint32_t startingValue) {
- std::atomic_init(&mAtomic, startingValue);
-}
-
-inline uint32_t AtomicUint32::operator=(uint32_t desired) {
- mAtomic = desired;
- return desired;
-}
-
-inline uint32_t AtomicUint32::load() const {
- return mAtomic.load();
-}
-
-inline void AtomicUint32::store(uint32_t desired) {
- mAtomic.store(desired);
-}
-
-inline uint32_t AtomicUint32::exchange(uint32_t desired) {
- return mAtomic.exchange(desired);
-}
-
-inline uint32_t AtomicUint32::fetch_add(uint32_t arg) {
- return mAtomic.fetch_add(arg);
-}
-
-inline uint32_t AtomicUint32::fetch_increment() {
- return mAtomic.fetch_add(1);
-}
-
-inline uint32_t AtomicUint32::fetch_sub(uint32_t arg) {
- return mAtomic.fetch_sub(arg);
-}
-
-inline uint32_t AtomicUint32::fetch_decrement() {
- return mAtomic.fetch_sub(1);
-}
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_FREERTOS_ATOMIC_BASE_IMPL_H_
diff --git a/platform/freertos/include/chre/target_platform/init.h b/platform/freertos/include/chre/target_platform/init.h
deleted file mode 100644
index 4c8927dc..00000000
--- a/platform/freertos/include/chre/target_platform/init.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_FREERTOS_INIT_H_
-#define CHRE_PLATFORM_FREERTOS_INIT_H_
-
-#include "FreeRTOS.h"
-
-namespace chre {
-
-/** @return the CHRE task priority being used. */
-BaseType_t getChreTaskPriority();
-
-namespace freertos {
-
-/**
- * This init function spawns a (non-privileged) FreeRTOS task that
- * initializes the CHRE core, loads any static nanoapps, and starts
- * the CHRE event loop.
- * The task attribute constants are located in the corresponding init.cc
- * source file, in case they need to be altered. The defaults chosen are:
- * - Task Stack Depth: 8K Words
- * - Task Priority: 1 (idle_task + 1)
- *
- * @return pdPASS on success, a FreeRTOS error code otherwise.
- */
-BaseType_t init();
-
-/**
- * Delete the task spawned in the init function
- */
-void deinit();
-
-const char *getChreTaskName();
-
-} // namespace freertos
-} // namespace chre
-
-#endif // CHRE_PLATFORM_FREERTOS_INIT_H_
diff --git a/platform/freertos/include/chre/target_platform/mutex_base.h b/platform/freertos/include/chre/target_platform/mutex_base.h
deleted file mode 100644
index bf05b6f8..00000000
--- a/platform/freertos/include/chre/target_platform/mutex_base.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_FREERTOS_MUTEX_BASE_H_
-#define CHRE_PLATFORM_FREERTOS_MUTEX_BASE_H_
-
-#include "chre/platform/fatal_error.h"
-#include "chre/platform/log.h"
-
-#include "FreeRTOS.h"
-#include "semphr.h"
-
-namespace chre {
-
-/**
- * The FreeRTOS implementation of MutexBase
- */
-class MutexBase {
- protected:
- SemaphoreHandle_t mSemaphoreHandle;
-
- /**
- * Initialize the mutex handle using a static semaphore
- * to avoid heap allocations
- */
- void initStaticMutex() {
- mSemaphoreHandle = xSemaphoreCreateMutexStatic(&mStaticSemaphore);
- if (mSemaphoreHandle == NULL) {
- FATAL_ERROR("Failed to initialize mutex");
- }
- }
-
- private:
- StaticSemaphore_t mStaticSemaphore;
-};
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_FREERTOS_MUTEX_BASE_H_
diff --git a/platform/freertos/include/chre/target_platform/mutex_base_impl.h b/platform/freertos/include/chre/target_platform/mutex_base_impl.h
deleted file mode 100644
index 23e957d7..00000000
--- a/platform/freertos/include/chre/target_platform/mutex_base_impl.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_FREERTOS_MUTEX_BASE_IMPL_H_
-#define CHRE_PLATFORM_FREERTOS_MUTEX_BASE_IMPL_H_
-
-#include "chre/platform/mutex.h"
-
-namespace chre {
-
-inline Mutex::Mutex() {
- initStaticMutex();
-}
-
-inline Mutex::~Mutex() {
- if (mSemaphoreHandle) {
- vSemaphoreDelete(mSemaphoreHandle);
- }
-}
-
-inline void Mutex::lock() {
- TickType_t blockForever = portMAX_DELAY;
- if (pdTRUE != xSemaphoreTake(mSemaphoreHandle, blockForever)) {
- LOGE("Failed to lock mutex");
- }
-}
-
-inline bool Mutex::try_lock() {
- TickType_t doNotBlock = static_cast<TickType_t>(0);
- BaseType_t rv = xSemaphoreTake(mSemaphoreHandle, doNotBlock);
-
- return (rv == pdTRUE) ? true : false;
-}
-
-inline void Mutex::unlock() {
- if (pdTRUE != xSemaphoreGive(mSemaphoreHandle)) {
- LOGE("Failed to properly unlock mutex!");
- }
-}
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_FREERTOS_MUTEX_BASE_IMPL_H_
diff --git a/platform/freertos/include/chre/target_platform/platform_debug_dump_manager_base.h b/platform/freertos/include/chre/target_platform/platform_debug_dump_manager_base.h
deleted file mode 100644
index 99725c98..00000000
--- a/platform/freertos/include/chre/target_platform/platform_debug_dump_manager_base.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_FREERTOS_PLATFORM_DEBUG_DUMP_MANAGER_BASE_H_
-#define CHRE_PLATFORM_FREERTOS_PLATFORM_DEBUG_DUMP_MANAGER_BASE_H_
-
-#include <cstdbool>
-#include <cstddef>
-#include <cstdint>
-
-namespace chre {
-
-/**
- * FreeRTOS-specific debug dump functionality.
- */
-class PlatformDebugDumpManagerBase {
- public:
- /**
- * To be called when receiving a debug dump request from host.
- *
- * @param hostClientId The host client ID that requested the debug dump.
- */
- void onDebugDumpRequested(uint16_t hostClientId);
-
- /**
- * @see PlatformDebugDumpManager::sendDebugDump
- */
- void sendDebugDumpResult(const char *debugStr, size_t debugStrSize,
- bool complete);
-
- protected:
- //! Host client ID that triggered the debug dump process.
- uint16_t mHostClientId = 0;
-
- //! Number of times sendDebugDumpToHost called with debugStrSize > 0.
- uint32_t mDataCount = 0;
-
- //! Whenther the last debug dump session has been marked complete.
- bool mComplete = true;
-
- static constexpr size_t kDebugDumpStrMaxSize = CHRE_MESSAGE_TO_HOST_MAX_SIZE;
-};
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_FREERTOS_PLATFORM_DEBUG_DUMP_MANAGER_BASE_H_
diff --git a/platform/freertos/include/chre/target_platform/platform_nanoapp_base.h b/platform/freertos/include/chre/target_platform/platform_nanoapp_base.h
deleted file mode 100644
index ae17d3e4..00000000
--- a/platform/freertos/include/chre/target_platform/platform_nanoapp_base.h
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_FREERTOS_PLATFORM_NANOAPP_BASE_H_
-#define CHRE_PLATFORM_FREERTOS_PLATFORM_NANOAPP_BASE_H_
-
-#include "chre/platform/shared/memory.h"
-#include "chre/platform/shared/nanoapp_support_lib_dso.h"
-
-namespace chre {
-
-/**
- * FREERTOS-specific nanoapp functionality.
- */
-class PlatformNanoappBase {
- public:
- /**
- * Associate this Nanoapp instance with a nanoapp that is statically built
- * into the CHRE binary with the given app info structure.
- */
- void loadStatic(const struct chreNslNanoappInfo *appInfo);
-
- /**
- * @return true if the app's binary data is resident in memory or if the app's
- * filename is saved, i.e. all binary fragments are loaded through
- * copyNanoappFragment, loadFromFile/loadStatic() was successful
- */
- bool isLoaded() const;
-
- /**
- * @return true if this app is loaded into TCM.
- */
- bool isTcmApp() const;
-
- /**
- * Sets app info that will be used later when the app is loaded into the
- * system.
- *
- * @param appId The unique app identifier associated with this binary
- * @param appVersion An application-defined version number
- * @param appFilename The filename of the app that should be loaded from disk
- * @param targetApiVersion The target API version the nanoapp was compiled for
- *
- * @return true if the info was successfully stored
- */
- bool setAppInfo(uint64_t appId, uint32_t appVersion, const char *appFilename,
- uint32_t targetApiVersion);
-
- /**
- * Reserves buffer space for a nanoapp's binary. This method should be called
- * before copyNanoappFragment is called.
- *
- * @param appId The unique app identifier associated with this binary
- * @param appVersion An application-defined version number
- * @param appFlags The flags provided by the app being loaded
- * @param appBinaryLen Size of appBinary, in bytes
- * @param targetApiVersion The target API version of the nanoapp
- *
- * @return true if the allocation was successful, false otherwise
- */
- bool reserveBuffer(uint64_t appId, uint32_t appVersion, uint32_t appFlags,
- size_t appBinaryLen, uint32_t targetApiVersion);
-
- /**
- * Copies the (possibly fragmented) application binary data into the allocated
- * buffer, and updates the pointer to the next address to write into. The
- * application may be invalid - full checking and initialization happens just
- * before invoking start() nanoapp entry point.
- *
- * @param buffer The pointer to the buffer
- * @param bufferSize The size of the buffer in bytes
- *
- * @return true if the reserved buffer did not overflow, false otherwise
- */
- bool copyNanoappFragment(const void *buffer, size_t bufferSize);
-
- protected:
- //! The app ID we received in the metadata alongside the nanoapp binary. This
- //! is also included in (and checked against) mAppInfo.
- uint64_t mExpectedAppId;
-
- //! The application-defined version number we received in the metadata
- //! alongside the nanoapp binary. This is also included in (and checked
- //! against) mAppInfo.
- uint32_t mExpectedAppVersion = 0;
-
- //! Whether the nanoapp is expected to be loaded into TCM.
- bool mExpectedTcmCapable = false;
-
- //! The app target API version in the metadata alongside the nanoapp binary.
- uint32_t mExpectedTargetApiVersion = 0;
-
- //! Whether this nanoapp is loaded into TCM.
- bool mIsTcmNanoapp = false;
-
- //! Buffer containing the complete DSO binary - only populated if
- //! copyNanoappFragment() was used to load this nanoapp
- void *mAppBinary = nullptr;
- size_t mAppBinaryLen = 0;
-
- //! Null-terminated ASCII string containing the file name that contains the
- //! app binary to be loaded. This is used over mAppBinary to load the nanoapp
- //! if set.
- char *mAppFilename = nullptr;
-
- //! The dynamic shared object (DSO) handle returned by dlopenbuf()
- void *mDsoHandle = nullptr;
-
- //! Pointer to the app info structure within this nanoapp
- const struct chreNslNanoappInfo *mAppInfo = nullptr;
-
- //! Pointer containing the unstable ID section for this nanoapp
- const char *mAppUnstableId = nullptr;
-
- //! Set to true if this app is built into the CHRE binary, and was loaded via
- //! loadStatic(). In this case, the member variables above are not valid or
- //! applicable.
- bool mIsStatic = false;
-
- //! The number of bytes of the binary that has been loaded so far.
- size_t mBytesLoaded = 0;
-
- /**
- * Loads the nanoapp symbols from the currently loaded binary and verifies
- * they match the expected information the nanoapp should have.
- *
- * @return true if the app info structure passed validation.
- */
- bool verifyNanoappInfo();
-
- /**
- * Calls through to openNanoappFromBuffer or openNanoappFromFile, depending on
- * how this nanoapp was loaded.
- */
- bool openNanoapp();
-
- /**
- * Releases the DSO handle if it was active, by calling dlclose(). This will
- * result in execution of any unload handlers in the nanoapp.
- */
- void closeNanoapp();
-
- /**
- * Retrieves the nanoapp's version string. This is intended to be a human
- * readable version string to aid in debugging. This must always return a
- * valid string so if none is available it is recommended to return
- * "<undefined>" or similar.
- *
- * @param length The length of the returned version string
- * @return A char array containing the version string for this nanoapp.
- */
- const char *getAppVersionString(size_t *length) const;
-
- /** If this app needs to access DRAM to function, enables DRAM access. */
- inline void enableDramAccessIfRequired() const {
- if (!isTcmApp()) {
- forceDramAccess();
- }
- }
-};
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_FREERTOS_PLATFORM_NANOAPP_BASE_H_
diff --git a/platform/freertos/include/chre/target_platform/static_nanoapp_init.h b/platform/freertos/include/chre/target_platform/static_nanoapp_init.h
deleted file mode 100644
index aa9932dd..00000000
--- a/platform/freertos/include/chre/target_platform/static_nanoapp_init.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_FREERTOS_STATIC_NANOAPP_INIT_H_
-#define CHRE_PLATFORM_FREERTOS_STATIC_NANOAPP_INIT_H_
-
-#include "chre/core/nanoapp.h"
-#include "chre/platform/fatal_error.h"
-#include "chre/util/unique_ptr.h"
-
-/**
- * Initializes a static nanoapp that is based on the FreeRTOS implementation of
- * PlatformNanoappBase.
- *
- * @param appName the name of the nanoapp. This will be prefixed by gNanoapp
- * when creating the global instance of the nanoapp.
- * @param appId the app's unique 64-bit ID
- * @param appVersion the application-defined 32-bit version number
- * @param appPerms the declared CHRE_PERMS_ permissions for the nanoapp.
- */
-#define CHRE_STATIC_NANOAPP_INIT(appName, appId_, appVersion_, appPerms) \
- namespace chre { \
- \
- UniquePtr<Nanoapp> initializeStaticNanoapp##appName() { \
- UniquePtr<Nanoapp> nanoapp = MakeUnique<Nanoapp>(); \
- static struct chreNslNanoappInfo appInfo; \
- appInfo.magic = CHRE_NSL_NANOAPP_INFO_MAGIC; \
- appInfo.structMinorVersion = CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION; \
- appInfo.targetApiVersion = CHRE_API_VERSION; \
- appInfo.vendor = "Google"; /* TODO: make this configurable */ \
- appInfo.name = #appName; \
- appInfo.isSystemNanoapp = true; \
- appInfo.isTcmNanoapp = false; \
- appInfo.appId = appId_; \
- appInfo.appVersion = appVersion_; \
- appInfo.entryPoints.start = nanoappStart; \
- appInfo.entryPoints.handleEvent = nanoappHandleEvent; \
- appInfo.entryPoints.end = nanoappEnd; \
- appInfo.appVersionString = "<undefined>"; \
- appInfo.appPermissions = appPerms; \
- if (nanoapp.isNull()) { \
- FATAL_ERROR("Failed to allocate nanoapp " #appName); \
- } else { \
- nanoapp->loadStatic(&appInfo); \
- } \
- \
- return nanoapp; \
- } \
- } /* namespace chre */
-
-#endif // CHRE_PLATFORM_FREERTOS_NANOAPP_INIT_H_
diff --git a/platform/freertos/init.cc b/platform/freertos/init.cc
deleted file mode 100644
index 1cab708e..00000000
--- a/platform/freertos/init.cc
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/core/init.h"
-
-#include "chpp/platform/chpp_init.h"
-#include "chre/core/event_loop_manager.h"
-#include "chre/core/static_nanoapps.h"
-#include "chre/platform/shared/dram_vote_client.h"
-#include "chre/target_platform/init.h"
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
-#include "chre/platform/shared/log_buffer_manager.h"
-#include "chre/target_platform/macros.h"
-#endif
-
-#include "task.h"
-
-namespace chre {
-namespace freertos {
-namespace {
-
-constexpr configSTACK_DEPTH_TYPE kChreTaskStackDepthWords = 0x800;
-
-constexpr UBaseType_t kChreTaskPriority = tskIDLE_PRIORITY + 1;
-
-TaskHandle_t gChreTaskHandle;
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
-
-TaskHandle_t gChreFlushTaskHandle;
-
-#ifdef CHRE_HIGH_POWER_TEXT_ATTRIBUTE
-CHRE_HIGH_POWER_TEXT_ATTRIBUTE
-#endif
-uint8_t gSecondaryLogBufferData[CHRE_LOG_BUFFER_DATA_SIZE];
-
-uint8_t gPrimaryLogBufferData[CHRE_LOG_BUFFER_DATA_SIZE];
-
-#endif
-
-// This function is intended to be the task action function for FreeRTOS.
-// It Initializes CHRE, runs the event loop, and only exits if it receives
-// a message to shutdown. Note that depending on the hardware platform this
-// runs on, CHRE might create additional threads, which are cleaned up when
-// CHRE exits.
-void chreThreadEntry(void *context) {
- DramVoteClientSingleton::init();
-
- chre::init();
- chre::EventLoopManagerSingleton::get()->lateInit();
- chre::loadStaticNanoapps();
-
- chre::EventLoopManagerSingleton::get()->getEventLoop().run();
-
- // we only get here if the CHRE EventLoop exited
- chre::deinit();
-
- DramVoteClientSingleton::deinit();
-
- vTaskDelete(nullptr);
- gChreTaskHandle = nullptr;
-}
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
-void chreFlushLogsToHostThreadEntry(void *context) {
- // Never exits
- chre::LogBufferManagerSingleton::get()->startSendLogsToHostLoop();
-}
-#endif
-
-} // namespace
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
-const char *getChreFlushTaskName();
-#endif
-
-BaseType_t init() {
- BaseType_t rc = pdPASS;
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
- chre::LogBufferManagerSingleton::init(gPrimaryLogBufferData,
- gSecondaryLogBufferData,
- sizeof(gPrimaryLogBufferData));
-
- rc = xTaskCreate(chreFlushLogsToHostThreadEntry, getChreFlushTaskName(),
- kChreTaskStackDepthWords, nullptr /* args */,
- kChreTaskPriority, &gChreFlushTaskHandle);
-#endif
-
- if (rc == pdPASS) {
- rc = xTaskCreate(chreThreadEntry, getChreTaskName(),
- kChreTaskStackDepthWords, nullptr /* args */,
- kChreTaskPriority, &gChreTaskHandle);
- }
-
- CHRE_ASSERT(rc == pdPASS);
-
- chpp::init();
-
- return rc;
-}
-
-void deinit() {
- // On a deinit call, we just stop the CHRE event loop. This causes the 'run'
- // method in the task function exit, and move on to handle task cleanup
- if (gChreTaskHandle != nullptr) {
- chre::EventLoopManagerSingleton::get()->getEventLoop().stop();
- }
-
- chpp::deinit();
-}
-
-const char *getChreTaskName() {
- static constexpr char kChreTaskName[] = "CHRE";
- return kChreTaskName;
-}
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
-const char *getChreFlushTaskName() {
- static constexpr char kChreFlushTaskName[] = "CHRELogs";
- return kChreFlushTaskName;
-}
-#endif
-
-} // namespace freertos
-
-BaseType_t getChreTaskPriority() {
- return freertos::kChreTaskPriority;
-}
-
-} // namespace chre
diff --git a/platform/freertos/memory_manager.cc b/platform/freertos/memory_manager.cc
deleted file mode 100644
index d3e5b101..00000000
--- a/platform/freertos/memory_manager.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 "chre/platform/memory_manager.h"
-#include "chre/platform/shared/memory.h"
-#include "chre/util/memory.h"
-
-namespace chre {
-
-void *MemoryManager::doAlloc(Nanoapp *app, uint32_t bytes) {
- if (app->isTcmApp()) {
- return chre::memoryAlloc(bytes);
- } else {
- return chre::memoryAllocDram(bytes);
- }
-}
-
-void MemoryManager::doFree(Nanoapp *app, void *ptr) {
- if (app->isTcmApp()) {
- chre::memoryFree(ptr);
- } else {
- chre::memoryFreeDram(ptr);
- }
-}
-
-} // namespace chre
diff --git a/platform/freertos/platform_debug_dump_manager.cc b/platform/freertos/platform_debug_dump_manager.cc
deleted file mode 100644
index c353e973..00000000
--- a/platform/freertos/platform_debug_dump_manager.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/platform/platform_debug_dump_manager.h"
-
-#include "chpp/platform/chpp_init.h"
-#include "chre/core/event_loop_manager.h"
-#include "chre/platform/log.h"
-#include "chre/target_platform/host_link_base.h"
-#include "chre/target_platform/platform_debug_dump_manager_base.h"
-
-#include <cstring>
-
-namespace chre {
-
-void PlatformDebugDumpManager::sendDebugDump(const char *debugStr,
- bool complete) {
- // DDM is guaranteed to call complete=true at the end of a debug dump session.
- // However, sendDebugDumpResult may not get called with complete=true.
- // Therefore, mDataCount has to be reset here instead of in
- // sendDebugDumpResult(), to properly start the next debug dump session.
- if (mComplete) {
- mDataCount = 0;
- }
- mComplete = complete;
-
- sendDebugDumpResult(debugStr, strlen(debugStr), complete);
-}
-
-void PlatformDebugDumpManager::logStateToBuffer(DebugDumpWrapper &debugDump) {
- chpp::logStateToBuffer(debugDump);
-}
-
-void PlatformDebugDumpManagerBase::onDebugDumpRequested(uint16_t hostClientId) {
- mHostClientId = hostClientId;
-
- EventLoopManagerSingleton::get()->getDebugDumpManager().trigger();
-}
-
-void PlatformDebugDumpManagerBase::sendDebugDumpResult(const char *debugStr,
- size_t debugStrSize,
- bool complete) {
- if (debugStrSize > 0) {
- mDataCount++;
- }
- sendDebugDumpResultToHost(mHostClientId, debugStr, debugStrSize, complete,
- mDataCount);
-}
-
-} // namespace chre
diff --git a/platform/freertos/platform_nanoapp.cc b/platform/freertos/platform_nanoapp.cc
deleted file mode 100644
index 9f5115ae..00000000
--- a/platform/freertos/platform_nanoapp.cc
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * 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 "chre/platform/platform_nanoapp.h"
-
-#include <dlfcn.h>
-#include <cinttypes>
-
-#include "chre/platform/assert.h"
-#include "chre/platform/log.h"
-#include "chre/platform/shared/authentication.h"
-#include "chre/platform/shared/nanoapp_dso_util.h"
-#include "chre/platform/shared/nanoapp_loader.h"
-#include "chre/util/macros.h"
-#include "chre/util/system/napp_header_utils.h"
-#include "chre/util/system/napp_permissions.h"
-#include "chre_api/chre/version.h"
-
-namespace chre {
-namespace {
-
-const char kDefaultAppVersionString[] = "<undefined>";
-size_t kDefaultAppVersionStringSize = ARRAY_SIZE(kDefaultAppVersionString);
-
-} // namespace
-
-PlatformNanoapp::~PlatformNanoapp() {
- closeNanoapp();
-
- if (mAppBinary != nullptr) {
- forceDramAccess();
- nanoappBinaryDramFree(mAppBinary);
- }
-}
-
-bool PlatformNanoapp::start() {
- //! Always force DRAM access when starting since nanoapps are loaded via DRAM.
- forceDramAccess();
-
- bool success = false;
- if (!openNanoapp()) {
- LOGE("Failed to open nanoapp");
- } else if (mAppInfo == nullptr) {
- LOGE("Null app info!");
- } else {
- success = mAppInfo->entryPoints.start();
- }
-
- return success;
-}
-
-void PlatformNanoapp::handleEvent(uint32_t senderInstanceId, uint16_t eventType,
- const void *eventData) {
- enableDramAccessIfRequired();
- mAppInfo->entryPoints.handleEvent(senderInstanceId, eventType, eventData);
-}
-
-void PlatformNanoapp::end() {
- enableDramAccessIfRequired();
- mAppInfo->entryPoints.end();
- closeNanoapp();
-}
-
-uint64_t PlatformNanoapp::getAppId() const {
- // TODO (karthikmb/stange): Ideally, we should store the metadata as
- // variables in TCM, to avoid bumping into DRAM for basic queries.
- enableDramAccessIfRequired();
- return (mAppInfo != nullptr) ? mAppInfo->appId : mExpectedAppId;
-}
-
-uint32_t PlatformNanoapp::getAppVersion() const {
- enableDramAccessIfRequired();
- return (mAppInfo != nullptr) ? mAppInfo->appVersion : mExpectedAppVersion;
-}
-
-bool PlatformNanoapp::supportsAppPermissions() const {
- return (mAppInfo != nullptr) ? (mAppInfo->structMinorVersion >=
- CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION)
- : false;
-}
-
-uint32_t PlatformNanoapp::getAppPermissions() const {
- return (supportsAppPermissions())
- ? mAppInfo->appPermissions
- : static_cast<uint32_t>(chre::NanoappPermissions::CHRE_PERMS_NONE);
-}
-
-const char *PlatformNanoapp::getAppName() const {
- enableDramAccessIfRequired();
- return (mAppInfo != nullptr) ? mAppInfo->name : "Unknown";
-}
-
-uint32_t PlatformNanoapp::getTargetApiVersion() const {
- enableDramAccessIfRequired();
- return (mAppInfo != nullptr) ? mAppInfo->targetApiVersion
- : mExpectedTargetApiVersion;
-}
-
-bool PlatformNanoapp::isSystemNanoapp() const {
- enableDramAccessIfRequired();
- return (mAppInfo != nullptr && mAppInfo->isSystemNanoapp);
-}
-
-void PlatformNanoapp::logStateToBuffer(DebugDumpWrapper &debugDump) const {
- if (mAppInfo != nullptr) {
- enableDramAccessIfRequired();
- size_t versionLen = 0;
- const char *version = getAppVersionString(&versionLen);
- debugDump.print("%s (%s) @ build: %.*s", mAppInfo->name, mAppInfo->vendor,
- versionLen, version);
- }
-}
-
-const char *PlatformNanoappBase::getAppVersionString(size_t *length) const {
- const char *versionString = kDefaultAppVersionString;
- *length = kDefaultAppVersionStringSize;
- enableDramAccessIfRequired();
-
- if (mAppUnstableId != nullptr) {
- size_t appVersionStringLength = strlen(mAppUnstableId);
-
- //! The unstable ID is expected to be in the format of
- //! <descriptor>=<nanoapp_name>@<build_id>. Use this expected layout
- //! knowledge to parse the string and only return the build ID portion that
- //! should be printed.
- size_t startOffset = appVersionStringLength;
- for (size_t i = 0; i < appVersionStringLength; i++) {
- size_t offset = i + 1;
- if (startOffset == appVersionStringLength && mAppUnstableId[i] == '@') {
- startOffset = offset;
- }
- }
-
- if (startOffset < appVersionStringLength) {
- versionString = &mAppUnstableId[startOffset];
- *length = appVersionStringLength - startOffset;
- }
- }
-
- return versionString;
-}
-
-bool PlatformNanoappBase::isLoaded() const {
- return (mIsStatic ||
- (mAppBinary != nullptr && mBytesLoaded == mAppBinaryLen) ||
- mDsoHandle != nullptr || mAppFilename != nullptr);
-}
-
-bool PlatformNanoappBase::isTcmApp() const {
- return mIsTcmNanoapp;
-}
-
-void PlatformNanoappBase::loadStatic(const struct chreNslNanoappInfo *appInfo) {
- CHRE_ASSERT(!isLoaded());
- mIsStatic = true;
- mAppInfo = appInfo;
-}
-
-bool PlatformNanoappBase::reserveBuffer(uint64_t appId, uint32_t appVersion,
- uint32_t appFlags, size_t appBinaryLen,
- uint32_t targetApiVersion) {
- CHRE_ASSERT(!isLoaded());
-
- forceDramAccess();
-
- bool success = false;
- mAppBinary = nanoappBinaryDramAlloc(appBinaryLen);
-
- bool isSigned = IS_BIT_SET(appFlags, CHRE_NAPP_HEADER_SIGNED);
- if (!isSigned) {
- LOGE("Unable to load unsigned nanoapps");
- } else if (mAppBinary == nullptr) {
- LOG_OOM();
- } else {
- bool tcmCapable = IS_BIT_SET(appFlags, CHRE_NAPP_HEADER_TCM_CAPABLE);
- mExpectedAppId = appId;
- mExpectedAppVersion = appVersion;
- mExpectedTargetApiVersion = targetApiVersion;
- mExpectedTcmCapable = tcmCapable;
- mAppBinaryLen = appBinaryLen;
- success = true;
- }
-
- return success;
-}
-
-bool PlatformNanoappBase::copyNanoappFragment(const void *buffer,
- size_t bufferLen) {
- CHRE_ASSERT(!isLoaded());
-
- forceDramAccess();
-
- bool success = true;
-
- if ((mBytesLoaded + bufferLen) > mAppBinaryLen) {
- LOGE("Overflow: cannot load %zu bytes to %zu/%zu nanoapp binary buffer",
- bufferLen, mBytesLoaded, mAppBinaryLen);
- success = false;
- } else {
- uint8_t *binaryBuffer = static_cast<uint8_t *>(mAppBinary) + mBytesLoaded;
- memcpy(binaryBuffer, buffer, bufferLen);
- mBytesLoaded += bufferLen;
- }
-
- return success;
-}
-
-bool PlatformNanoappBase::verifyNanoappInfo() {
- bool success = false;
-
- if (mDsoHandle == nullptr) {
- LOGE("No nanoapp info to verify");
- } else {
- mAppInfo = static_cast<const struct chreNslNanoappInfo *>(
- dlsym(mDsoHandle, CHRE_NSL_DSO_NANOAPP_INFO_SYMBOL_NAME));
- if (mAppInfo == nullptr) {
- LOGE("Failed to find app info symbol");
- } else {
- mAppUnstableId = mAppInfo->appVersionString;
- if (mAppUnstableId == nullptr) {
- LOGE("Failed to find unstable ID symbol");
- } else {
- success = validateAppInfo(mExpectedAppId, mExpectedAppVersion,
- mExpectedTargetApiVersion, mAppInfo);
- if (success && mAppInfo->isTcmNanoapp != mExpectedTcmCapable) {
- success = false;
- LOGE("Expected TCM nanoapp %d found %d", mExpectedTcmCapable,
- mAppInfo->isTcmNanoapp);
- }
-
- if (!success) {
- mAppInfo = nullptr;
- } else {
- LOGI("Nanoapp loaded: %s (0x%016" PRIx64 ") version 0x%" PRIx32
- " (%s) uimg %d system %d",
- mAppInfo->name, mAppInfo->appId, mAppInfo->appVersion,
- mAppInfo->appVersionString, mAppInfo->isTcmNanoapp,
- mAppInfo->isSystemNanoapp);
- if (mAppInfo->structMinorVersion >=
- CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION) {
- LOGI("Nanoapp permissions: 0x%" PRIx32, mAppInfo->appPermissions);
- }
- }
- }
- }
- }
- return success;
-}
-
-bool PlatformNanoappBase::openNanoapp() {
- bool success = false;
- if (mIsStatic) {
- success = true;
- } else if (mAppBinary != nullptr) {
- //! The true start of the binary will be after the authentication header.
- //! Use the returned value from authenticateBinary to ensure dlopenbuf has
- //! the starting address to a valid ELF.
- void *binaryStart = mAppBinary;
- if (!authenticateBinary(mAppBinary, &binaryStart)) {
- LOGE("Unable to authenticate 0x%" PRIx64 " not loading", mExpectedAppId);
- } else if (mDsoHandle != nullptr) {
- LOGE("Trying to reopen an existing buffer");
- } else {
- mDsoHandle = dlopenbuf(binaryStart, mExpectedTcmCapable);
- success = verifyNanoappInfo();
- }
- }
-
- if (!success) {
- closeNanoapp();
- }
-
- if (mAppBinary != nullptr) {
- nanoappBinaryDramFree(mAppBinary);
- mAppBinary = nullptr;
- }
-
- // Save this flag locally since it may be referenced while the system is in
- // TCM-only mode.
- if (mAppInfo != nullptr) {
- mIsTcmNanoapp = mAppInfo->isTcmNanoapp;
- }
-
- return success;
-}
-
-void PlatformNanoappBase::closeNanoapp() {
- if (mDsoHandle != nullptr) {
- // Force DRAM access since dl* functions are only safe to call with DRAM
- // available.
- forceDramAccess();
- mAppInfo = nullptr;
- if (dlclose(mDsoHandle) != 0) {
- LOGE("dlclose failed");
- }
- mDsoHandle = nullptr;
- }
-}
-
-} // namespace chre
diff --git a/platform/include/chre/platform/assert.h b/platform/include/chre/platform/assert.h
index c5b404a4..7cdc3064 100644
--- a/platform/include/chre/platform/assert.h
+++ b/platform/include/chre/platform/assert.h
@@ -21,19 +21,23 @@
/**
* @file
- * Defines the CHRE_ASSERT and CHRE_ASSERT_LOG macros for CHRE platforms.
- * Platforms must supply an implementation for assertCondition or use the shared
- * implementation.
+ * Includes the platform-specific header file that supplies an assertion macro.
+ * The platform header must supply the following symbol as a macro or free
+ * function:
+ *
+ * CHRE_ASSERT(scalar expression)
+ *
+ * Where expression will be checked to be false (ie: compares equal to zero) and
+ * terminate the program if found to be the case.
*/
#if defined(CHRE_ASSERTIONS_ENABLED)
-#define CHRE_ASSERT(condition) \
- do { \
- if (!(condition)) { \
- chre::doAssert(CHRE_FILENAME, __LINE__); \
- } \
- } while (0)
+#include "chre/target_platform/assert.h"
+
+#ifndef CHRE_ASSERT
+#error "CHRE_ASSERT must be defined by the target platform's assert.h"
+#endif // CHRE_ASSERT
#elif defined(CHRE_ASSERTIONS_DISABLED)
@@ -43,12 +47,6 @@
#error "CHRE_ASSERTIONS_ENABLED or CHRE_ASSERTIONS_DISABLED must be defined"
#endif // CHRE_ASSERTIONS_ENABLED
-#ifdef __cplusplus
-#define CHRE_ASSERT_NOT_NULL(ptr) CHRE_ASSERT((ptr) != nullptr)
-#else
-#define CHRE_ASSERT_NOT_NULL(ptr) CHRE_ASSERT((ptr) != NULL)
-#endif
-
/**
* Combination macro that always logs an error message if the condition
* evaluates to false.
@@ -68,29 +66,4 @@
} \
} while (0)
-/**
- * Defines "if not test" macros that allow code to not assert when running
- * on-device unit tests if the assertion isn't useful during testing.
- */
-#ifdef CHRE_ON_DEVICE_TESTS_ENABLED
-#define CHRE_ASSERT_LOG_IF_NOT_TEST(condition, fmt, ...)
-#define CHRE_ASSERT_IF_NOT_TEST(condition) ((void)(condition))
-#else
-#define CHRE_ASSERT_LOG_IF_NOT_TEST(condition, fmt, ...) \
- CHRE_ASSERT_LOG(condition, fmt, ##__VA_ARGS__)
-#define CHRE_ASSERT_IF_NOT_TEST(condition) CHRE_ASSERT(condition)
-#endif
-
-namespace chre {
-
-/**
- * Performs assertion while logging the filename and line provided.
- *
- * @param filename The filename containing the assertion being fired.
- * @param line The line that contains the assertion being fired.
- */
-void doAssert(const char *filename, size_t line);
-
-} // namespace chre
-
#endif // CHRE_PLATFORM_ASSERT_H_
diff --git a/platform/include/chre/platform/host_link.h b/platform/include/chre/platform/host_link.h
index 6576c1a2..ad705198 100644
--- a/platform/include/chre/platform/host_link.h
+++ b/platform/include/chre/platform/host_link.h
@@ -30,12 +30,7 @@ typedef HostMessage MessageToHost;
/**
* Abstracts the platform-specific communications link between CHRE and the host
- * processor.
- *
- * The common-code HostCommsManager inherits from this class, so based on
- * later-established convention, a more fitting name for it would be
- * PlatformHostCommsManager. But the HostLink name is kept for compatibility
- * with legacy code.
+ * processor
*/
class HostLink : public HostLinkBase, public NonCopyable {
public:
@@ -54,14 +49,22 @@ class HostLink : public HostLinkBase, public NonCopyable {
* Enqueues a message for sending to the host. Once sending the message is
* complete (success or failure), the platform implementation must invoke
* HostCommsManager::onMessageToHostComplete (can be called from any thread).
- * To meet the requirements of chreSendMessageToHostEndpoint(), this function
- * must wake up the host if it is suspended.
*
* @param message A non-null pointer to the message
*
* @return true if the message was successfully queued
*/
bool sendMessage(const MessageToHost *message);
+
+ /**
+ * Enqueues a log message to be sent to the host.
+ *
+ * @param logMessage Pointer to a buffer that has the log message. Note that
+ * the message might be encoded
+ *
+ * @param logMessageSize length of the log message buffer
+ */
+ void sendLogMessage(const char *logMessage, size_t logMessageSize);
};
} // namespace chre
diff --git a/platform/include/chre/platform/log.h b/platform/include/chre/platform/log.h
index f236e586..1f8b7a0e 100644
--- a/platform/include/chre/platform/log.h
+++ b/platform/include/chre/platform/log.h
@@ -28,9 +28,6 @@
* LOGI(format, ...)
* LOGD(format, ...)
*
- * The platform header is recommend to also supply LOGV for verbose logs,
- * however it is not required.
- *
* Where "format" is a printf-style format string, and E, W, I, D correspond to
* the log levels Error, Warning, Informational, and Debug, respectively.
*/
@@ -38,29 +35,26 @@
#include "chre/target_platform/log.h"
#include "chre/util/log_common.h"
+/*
+ * Log errors if the platform does not supply logging macros.
+ */
+
#ifndef LOGE
-#error "LOGE must be defined by chre/target_platform/log.h"
+#error "LOGE must be defined"
#endif // LOGE
#ifndef LOGW
-#error "LOGW must be defined by chre/target_platform/log.h"
+#error "LOGW must be defined"
#endif // LOGW
#ifndef LOGI
-#error "LOGI must be defined by chre/target_platform/log.h"
+#error "LOGI must be defined"
#endif // LOGI
#ifndef LOGD
-#error "LOGD must be defined by chre/target_platform/log.h"
+#error "LOGD must be defined"
#endif // LOGD
-#ifndef LOGV
-// Map LOGV to LOGD if the platform doesn't supply it - in that case LOGV won't
-// be distinguished at runtime from LOGD, but we'll still retain the ability to
-// compile out LOGV based on CHRE_MINIMUM_LOG_LEVEL
-#define LOGV LOGD
-#endif
-
/*
* Supply a stub implementation of the LOGx macros when the build is
* configured with a minimum logging level that is above the requested level.
@@ -72,27 +66,27 @@
#if CHRE_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_ERROR
#undef LOGE
-#define LOGE(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
+#define LOGE(format, ...) chreLogNull(format, ##__VA_ARGS__)
#endif
#if CHRE_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_WARN
#undef LOGW
-#define LOGW(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
+#define LOGW(format, ...) chreLogNull(format, ##__VA_ARGS__)
#endif
#if CHRE_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_INFO
#undef LOGI
-#define LOGI(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
+#define LOGI(format, ...) chreLogNull(format, ##__VA_ARGS__)
#endif
#if CHRE_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_DEBUG
#undef LOGD
-#define LOGD(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
+#define LOGD(format, ...) chreLogNull(format, ##__VA_ARGS__)
#endif
-#if CHRE_MINIMUM_LOG_LEVEL < CHRE_LOG_LEVEL_VERBOSE
-#undef LOGV
-#define LOGV(format, ...) CHRE_LOG_NULL(format, ##__VA_ARGS__)
-#endif
+/**
+ * Logs an out of memory error with file and line number.
+ */
+#define LOG_OOM() LOGE("OOM at %s:%d", CHRE_FILENAME, __LINE__)
#endif // CHRE_PLATFORM_LOG_H_
diff --git a/platform/include/chre/platform/platform_debug_dump_manager.h b/platform/include/chre/platform/platform_debug_dump_manager.h
index 89b2dcee..683c22eb 100644
--- a/platform/include/chre/platform/platform_debug_dump_manager.h
+++ b/platform/include/chre/platform/platform_debug_dump_manager.h
@@ -22,7 +22,6 @@
#include "chre/target_platform/platform_debug_dump_manager_base.h"
#include "chre/util/non_copyable.h"
-#include "chre/util/system/debug_dump.h"
#include "chre_api/chre/re.h"
namespace chre {
@@ -45,14 +44,6 @@ class PlatformDebugDumpManager : public PlatformDebugDumpManagerBase,
*/
void sendDebugDump(const char *debugStr, bool complete);
- /**
- * A function to log platform-specific debug dumps. Must only be called from
- * the context of the main CHRE thread.
- *
- * @param debugDump Reference to the debug dump wrapper to print logs.
- */
- void logStateToBuffer(DebugDumpWrapper &debugDump);
-
private:
//! kDebugDumpStrMaxSize must be provided by PlatformDebugDumpManagerBase.
//!
diff --git a/platform/include/chre/platform/platform_gnss.h b/platform/include/chre/platform/platform_gnss.h
index c922f5e8..6f3c0638 100644
--- a/platform/include/chre/platform/platform_gnss.h
+++ b/platform/include/chre/platform/platform_gnss.h
@@ -84,13 +84,6 @@ class PlatformGnss : public PlatformGnssBase {
* @param event the event to release.
*/
void releaseMeasurementDataEvent(chreGnssDataEvent *event);
-
- /**
- * @param enable true to enable the configuration.
- *
- * @return true if the request was received.
- */
- bool configurePassiveLocationListener(bool enable);
};
} // namespace chre
diff --git a/platform/include/chre/platform/platform_nanoapp.h b/platform/include/chre/platform/platform_nanoapp.h
index 817226ca..4a7994d7 100644
--- a/platform/include/chre/platform/platform_nanoapp.h
+++ b/platform/include/chre/platform/platform_nanoapp.h
@@ -83,23 +83,13 @@ class PlatformNanoapp : public PlatformNanoappBase, public NonCopyable {
uint32_t getAppVersion() const;
/**
- * Retrieves the API version that this nanoapp was compiled against.
+ * Retrieves the API version that this nanoapp was compiled against. This
+ * function must only be called while the nanoapp is running (i.e. between
+ * calls to start() and end()).
*/
uint32_t getTargetApiVersion() const;
/**
- * Returns true if the nanoapp supports permissions (i.e. minor version >=
- * CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION).
- */
- bool supportsAppPermissions() const;
-
- /**
- * Retrieves the nanoapp's permissions. If unsupported, returns with no
- * permissions.
- */
- uint32_t getAppPermissions() const;
-
- /**
* Retrieves the human-friendly name for the nanoapp (null-terminated string).
*/
const char *getAppName() const;
diff --git a/platform/include/chre/platform/platform_sensor.h b/platform/include/chre/platform/platform_sensor.h
index 277afb5d..93d2fe9d 100644
--- a/platform/include/chre/platform/platform_sensor.h
+++ b/platform/include/chre/platform/platform_sensor.h
@@ -65,16 +65,6 @@ class PlatformSensor : public PlatformSensorBase, public NonCopyable {
*/
const char *getSensorName() const;
- /**
- * @return The index of the sensor.
- */
- uint8_t getSensorIndex() const;
-
- /**
- * @return The mask of groups that events this sensor produces should target.
- */
- uint16_t getTargetGroupMask() const;
-
protected:
/**
* Default constructor that puts this instance in an unspecified state.
diff --git a/platform/include/chre/platform/platform_sensor_manager.h b/platform/include/chre/platform/platform_sensor_manager.h
index ded98595..6d4276fe 100644
--- a/platform/include/chre/platform/platform_sensor_manager.h
+++ b/platform/include/chre/platform/platform_sensor_manager.h
@@ -47,15 +47,6 @@ class PlatformSensorManager : public PlatformSensorManagerBase {
*
* @return A DynamicVector to populate with the list of sensors the framework
* can send requests to.
- *
- * @note For the returned list of sensors, the following requirements MUST be
- * respected:
- * - A given sensor's target group mask MUST NOT overlap with another
- * sensor's target group mask if both have the same index and type.
- * - One-shot sensors MUST only appear once in this list. i.e. they
- * cannot support multiple indices / target group ID masks.
- * - There cannot be multiple sensors with the same index of the same
- * type.
*/
DynamicVector<Sensor> getSensors();
@@ -73,9 +64,6 @@ class PlatformSensorManager : public PlatformSensorManagerBase {
* TODO(b/142958445): Make the above modification to the request before it
* reaches the platform code.
*
- * If the sensor was previously configured, but the new request fails to be
- * processed, the previous configuration must remain in place.
- *
* @param sensor One of the sensors provided by getSensors().
* @param request The new request that contains the details about how the
* sensor should be configured.
@@ -139,13 +127,6 @@ class PlatformSensorManager : public PlatformSensorManagerBase {
*/
bool flush(const Sensor &sensor, uint32_t *flushRequestId);
- /**
- * @return the target group ID for a given nanoapp. This mapping is not
- * allowed to change based on state that can change after a nanoapp is
- * loaded and must remain constant for the lifetime of the nanoapp.
- */
- uint16_t getTargetGroupId(const Nanoapp &nanoapp) const;
-
//! Methods that allow the platform to free the data given via the below
//! event handlers
void releaseSamplingStatusUpdate(struct chreSensorSamplingStatus *status);
diff --git a/platform/include/chre/platform/static_nanoapp_init.h b/platform/include/chre/platform/static_nanoapp_init.h
index c90259b9..aa1d7e8a 100644
--- a/platform/include/chre/platform/static_nanoapp_init.h
+++ b/platform/include/chre/platform/static_nanoapp_init.h
@@ -30,6 +30,17 @@
* application-defined 32-bit version number.
*/
+// Since this file is included in nanoapp code, it's likely that the nanoapp log
+// macro will have been included, resulting in conflicting definitions of the
+// log macros with the ones pulled in via nanoapp.h. Undefine these macros to
+// allow their redefinition for CHRE system code.
+#ifdef CHRE_UTIL_NANOAPP_LOG_H_
+#undef LOGE
+#undef LOGW
+#undef LOGI
+#undef LOGD
+#endif // CHRE_UTIL_NANOAPP_LOG_H_
+
#include "chre/target_platform/static_nanoapp_init.h"
#ifndef CHRE_STATIC_NANOAPP_INIT
diff --git a/platform/include/chre/platform/system_timer.h b/platform/include/chre/platform/system_timer.h
index 0ffcdbc6..e569d163 100644
--- a/platform/include/chre/platform/system_timer.h
+++ b/platform/include/chre/platform/system_timer.h
@@ -68,8 +68,7 @@ class SystemTimer : public SystemTimerBase, public NonCopyable {
* Note that it is possible for the timer to fire before this function
* returns.
*
- * @param callback Non-null pointer to a callback to invoke when the timer has
- * elapsed.
+ * @param callback The callback to invoke when the timer has elapsed.
* @param data The data to pass to the callback when it is invoked.
* @param delay The minimum delay until the first firing of the timer.
* @return true on success, false on failure
@@ -81,8 +80,7 @@ class SystemTimer : public SystemTimerBase, public NonCopyable {
* firing, this prevents the callback from being invoked until the timer is
* restarted by a subsequent call to set().
*
- * @return true if the timer was cancelled successfully and false if the timer
- * was already canceled or something failed.
+ * @return Whether or not the timer was cancelled successfully.
*/
bool cancel();
diff --git a/platform/include/chre/platform/version.h b/platform/include/chre/platform/version.h
deleted file mode 100644
index 4ac4b67a..00000000
--- a/platform/include/chre/platform/version.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_VERSION_H_
-#define CHRE_PLATFORM_VERSION_H_
-
-namespace chre {
-
-/**
- * @return A string that is unique to this particular build of CHRE (for
- * production-bound builds) so that it's easy to determine what version of
- * code is present in the binary.
- */
-const char *getChreVersionString();
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_VERSION_H_
diff --git a/platform/linux/assert.cc b/platform/linux/assert.cc
index e93c4bb1..79ce12f0 100644
--- a/platform/linux/assert.cc
+++ b/platform/linux/assert.cc
@@ -14,34 +14,10 @@
* limitations under the License.
*/
-#include "chre/platform/assert.h"
-
-#include <cassert>
-
-#include "chre/platform/linux/expect_assert.h"
+#include "chre/target_platform/assert.h"
#ifdef GTEST
-MockAssert *gMockAssert;
-#endif // GTEST
-namespace chre {
+MockAssert *gMockAssert;
-void doAssert(const char *filename, size_t line) {
- LOGE("Assertion failure at %s:%zu", filename, line);
-#ifdef GTEST
- if (gMockAssert != nullptr) {
- gMockAssert->doAssert();
- } else
#endif // GTEST
- {
-#ifdef NDEBUG
- // Directly abort the program if assert is a no-op so that gtests can
- // work properly.
- abort();
-#else
- assert(false);
-#endif // NDEBUG
- }
-}
-
-} // namespace chre
diff --git a/platform/linux/fatal_error.cc b/platform/linux/fatal_error.cc
index c908a503..37d4f33b 100644
--- a/platform/linux/fatal_error.cc
+++ b/platform/linux/fatal_error.cc
@@ -16,7 +16,7 @@
#include "chre/target_platform/fatal_error.h"
-#include "chre/platform/linux/platform_log.h"
+#include "chre/platform/shared/platform_log.h"
namespace chre {
diff --git a/platform/linux/host_link.cc b/platform/linux/host_link.cc
index 6490cc2a..8d7d20fe 100644
--- a/platform/linux/host_link.cc
+++ b/platform/linux/host_link.cc
@@ -18,13 +18,17 @@
namespace chre {
-void HostLink::flushMessagesSentByNanoapp(uint64_t /* appId */) {
+void HostLink::flushMessagesSentByNanoapp(uint64_t appId) {
// TODO: implement
}
-bool HostLink::sendMessage(const MessageToHost * /* message */) {
+bool HostLink::sendMessage(const MessageToHost *message) {
// TODO: implement
return false;
}
+void HostLink::sendLogMessage(const char *logMessage, size_t logMessageSize) {
+ // TODO: implement
+}
+
} // namespace chre
diff --git a/platform/linux/include/chre/platform/linux/expect_assert.h b/platform/linux/include/chre/target_platform/assert.h
index e71ce715..38e1d213 100644
--- a/platform/linux/include/chre/platform/linux/expect_assert.h
+++ b/platform/linux/include/chre/target_platform/assert.h
@@ -14,11 +14,13 @@
* limitations under the License.
*/
-#ifndef CHRE_PLATFORM_LINUX_EXPECT_ASSERT_H_
-#define CHRE_PLATFORM_LINUX_EXPECT_ASSERT_H_
+#ifndef CHRE_PLATFORM_LINUX_ASSERT_H_
+#define CHRE_PLATFORM_LINUX_ASSERT_H_
#include <cassert>
+#define CHRE_ASSERT_USES_STDLIB_ASSERT
+
#ifdef GTEST
#include "chre/platform/log.h"
@@ -68,6 +70,20 @@ class MockAssert : public AssertInterface {
statement; \
} while (0)
+#define CHRE_ASSERT(condition) \
+ do { \
+ if (gMockAssert != nullptr && !(condition)) { \
+ LOGI("Mocked assertion " #condition " triggered"); \
+ gMockAssert->doAssert(); \
+ } else { \
+ assert(condition); \
+ } \
+ } while (0)
+
+#else // if !defined(GTEST)
+
+#define CHRE_ASSERT(condition) assert(condition)
+
#endif // GTEST
-#endif // CHRE_PLATFORM_LINUX_EXPECT_ASSERT_H_ \ No newline at end of file
+#endif // CHRE_PLATFORM_LINUX_ASSERT_H_
diff --git a/platform/linux/include/chre/target_platform/log.h b/platform/linux/include/chre/target_platform/log.h
index fa1a9440..899c1481 100644
--- a/platform/linux/include/chre/target_platform/log.h
+++ b/platform/linux/include/chre/target_platform/log.h
@@ -17,8 +17,6 @@
#ifndef CHRE_PLATFORM_LINUX_LOG_H_
#define CHRE_PLATFORM_LINUX_LOG_H_
-#include "chre_api/chre/re.h"
-
#ifndef __FILENAME__
#define __FILENAME__ __FILE__
#endif
@@ -29,27 +27,21 @@
// used.
#include <stdio.h>
-#define CHRE_LINUX_LOG(logLevel, levelStr, color, fmt, ...) \
- printf("\e[" color "m%s %s:%d\t" fmt "\e[0m\n", levelStr, __FILENAME__, \
+#define CHRE_LINUX_LOG(level, color, fmt, ...) \
+ printf("\e[" color "m%s %s:%d\t" fmt "\e[0m\n", level, __FILENAME__, \
__LINE__, ##__VA_ARGS__)
#else
-#include "chre/platform/linux/platform_log.h"
+#include "chre/platform/shared/platform_log.h"
-#define CHRE_LINUX_LOG(logLevel, levelStr, color, fmt, ...) \
- if (::chre::PlatformLogSingleton::isInitialized()) { \
- ::chre::PlatformLogSingleton::get()->log( \
- logLevel, "\e[" color "m%s %s:%d\t" fmt "\e[0m", levelStr, \
- __FILENAME__, __LINE__, ##__VA_ARGS__); \
- }
+#define CHRE_LINUX_LOG(level, color, fmt, ...) \
+ ::chre::PlatformLogSingleton::get()->log( \
+ "\e[" color "m%s %s:%d\t" fmt "\e[0m", level, __FILENAME__, __LINE__, \
+ ##__VA_ARGS__)
#endif
-#define LOGE(fmt, ...) \
- CHRE_LINUX_LOG(CHRE_LOG_ERROR, "E", "91", fmt, ##__VA_ARGS__)
-#define LOGW(fmt, ...) \
- CHRE_LINUX_LOG(CHRE_LOG_WARN, "W", "93", fmt, ##__VA_ARGS__)
-#define LOGI(fmt, ...) \
- CHRE_LINUX_LOG(CHRE_LOG_INFO, "I", "96", fmt, ##__VA_ARGS__)
-#define LOGD(fmt, ...) \
- CHRE_LINUX_LOG(CHRE_LOG_DEBUG, "D", "97", fmt, ##__VA_ARGS__)
+#define LOGE(fmt, ...) CHRE_LINUX_LOG("E", "91", fmt, ##__VA_ARGS__)
+#define LOGW(fmt, ...) CHRE_LINUX_LOG("W", "93", fmt, ##__VA_ARGS__)
+#define LOGI(fmt, ...) CHRE_LINUX_LOG("I", "96", fmt, ##__VA_ARGS__)
+#define LOGD(fmt, ...) CHRE_LINUX_LOG("D", "97", fmt, ##__VA_ARGS__)
#endif // CHRE_PLATFORM_LINUX_LOG_H_
diff --git a/platform/linux/include/chre/platform/linux/platform_log.h b/platform/linux/include/chre/target_platform/platform_log_base.h
index 64264950..480c92f6 100644
--- a/platform/linux/include/chre/platform/linux/platform_log.h
+++ b/platform/linux/include/chre/target_platform/platform_log_base.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,46 +14,21 @@
* limitations under the License.
*/
-#ifndef CHRE_PLATFORM_LINUX_PLATFORM_LOG_H_
-#define CHRE_PLATFORM_LINUX_PLATFORM_LOG_H_
+#ifndef CHRE_PLATFORM_LINUX_PLATFORM_LOG_BASE_H_
+#define CHRE_PLATFORM_LINUX_PLATFORM_LOG_BASE_H_
#include <condition_variable>
#include <mutex>
#include <queue>
#include <thread>
-#include "chre/util/singleton.h"
-#include "chre_api/chre/re.h"
-
namespace chre {
/**
* Storage for the Linux implementation of the PlatformLog class.
*/
-class PlatformLog {
- public:
- PlatformLog();
-
- ~PlatformLog();
-
- /**
- * Logs message with printf-style arguments. No trailing newline is required
- * for this method.
- */
- void log(chreLogLevel logLevel, const char *formatStr, ...) {
- va_list args;
- va_start(args, formatStr);
- logVa(logLevel, formatStr, args);
- va_end(args);
- }
-
- /**
- * Logs message with printf-style arguments. No trailing newline is required
- * for this method. Uses va_list parameter instead of ...
- */
- void logVa(chreLogLevel logLevel, const char *formatStr, va_list args);
-
- private:
+class PlatformLogBase {
+ protected:
/**
* A looper method that idles on a condition variable on logs becoming
* available. When logs are available, they are output via std::cout.
@@ -78,8 +53,6 @@ class PlatformLog {
bool mStopLogger = false;
};
-typedef Singleton<PlatformLog> PlatformLogSingleton;
-
} // namespace chre
-#endif // CHRE_PLATFORM_LINUX_PLATFORM_LOG_H_
+#endif // CHRE_PLATFORM_LINUX_PLATFORM_LOG_BASE_H_
diff --git a/platform/linux/include/chre/target_platform/static_nanoapp_init.h b/platform/linux/include/chre/target_platform/static_nanoapp_init.h
index 8e0d3400..6b540655 100644
--- a/platform/linux/include/chre/target_platform/static_nanoapp_init.h
+++ b/platform/linux/include/chre/target_platform/static_nanoapp_init.h
@@ -17,9 +17,9 @@
#ifndef CHRE_PLATFORM_LINUX_STATIC_NANOAPP_INIT_H_
#define CHRE_PLATFORM_LINUX_STATIC_NANOAPP_INIT_H_
-#include "chre/core/static_nanoapps.h"
+#include "chre/core/nanoapp.h"
#include "chre/platform/fatal_error.h"
-#include "chre/platform/shared/nanoapp_support_lib_dso.h"
+#include "chre/util/unique_ptr.h"
/**
* Initializes a static nanoapp that is based on the Linux implementation of
@@ -28,10 +28,8 @@
* @param appName the name of the nanoapp. This will be prefixed by gNanoapp
* when creating the global instance of the nanoapp.
* @param appId the app's unique 64-bit ID
- * @param appVersion the application-defined 32-bit version number
- * @param appPerms the declared CHRE_PERMS_ permissions for the nanoapp.
*/
-#define CHRE_STATIC_NANOAPP_INIT(appName, appId_, appVersion_, appPerms) \
+#define CHRE_STATIC_NANOAPP_INIT(appName, appId_, appVersion_) \
namespace chre { \
\
UniquePtr<Nanoapp> initializeStaticNanoapp##appName() { \
@@ -50,7 +48,6 @@
appInfo.entryPoints.handleEvent = nanoappHandleEvent; \
appInfo.entryPoints.end = nanoappEnd; \
appInfo.appVersionString = "<undefined>"; \
- appInfo.appPermissions = appPerms; \
if (nanoapp.isNull()) { \
FATAL_ERROR("Failed to allocate nanoapp " #appName); \
} else { \
@@ -59,7 +56,6 @@
\
return nanoapp; \
} \
- \
- } // namespace chre
+ } /* namespace chre */
#endif // CHRE_PLATFORM_LINUX_STATIC_NANOAPP_INIT_H_
diff --git a/platform/linux/init.cc b/platform/linux/init.cc
index 1e3572de..630d1693 100644
--- a/platform/linux/init.cc
+++ b/platform/linux/init.cc
@@ -25,8 +25,8 @@
#endif // CHRE_AUDIO_SUPPORT_ENABLED
#include "chre/platform/context.h"
#include "chre/platform/fatal_error.h"
-#include "chre/platform/linux/platform_log.h"
#include "chre/platform/log.h"
+#include "chre/platform/shared/platform_log.h"
#include "chre/platform/system_timer.h"
#include "chre/util/time.h"
diff --git a/platform/linux/memory_manager.cc b/platform/linux/memory_manager.cc
index fd730f9d..6d55a644 100644
--- a/platform/linux/memory_manager.cc
+++ b/platform/linux/memory_manager.cc
@@ -20,11 +20,11 @@
namespace chre {
-void *MemoryManager::doAlloc(Nanoapp * /* app */, uint32_t bytes) {
+void *MemoryManager::doAlloc(Nanoapp *app, uint32_t bytes) {
return chre::memoryAlloc(bytes);
}
-void MemoryManager::doFree(Nanoapp * /* app */, void *ptr) {
+void MemoryManager::doFree(Nanoapp *app, void *ptr) {
chre::memoryFree(ptr);
}
diff --git a/platform/linux/pal_gnss.cc b/platform/linux/pal_gnss.cc
deleted file mode 100644
index 16f6ffcb..00000000
--- a/platform/linux/pal_gnss.cc
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/pal/gnss.h"
-
-#include "chre/util/memory.h"
-#include "chre/util/unique_ptr.h"
-
-#include <chrono>
-#include <cinttypes>
-#include <future>
-#include <thread>
-
-/**
- * A simulated implementation of the GNSS PAL for the linux platform.
- */
-namespace {
-const struct chrePalSystemApi *gSystemApi = nullptr;
-const struct chrePalGnssCallbacks *gCallbacks = nullptr;
-
-//! Thread to deliver asynchronous location data after a CHRE request.
-std::thread gLocationEventsThread;
-std::promise<void> gStopLocationEventsThread;
-
-//! Thead to use when delivering a location status update.
-std::thread gLocationStatusThread;
-
-//! Thread to deliver asynchronous measurement data after a CHRE request.
-std::thread gMeasurementEventsThread;
-std::promise<void> gStopMeasurementEventsThread;
-
-//! Thead to use when delivering a measurement status update.
-std::thread gMeasurementStatusThread;
-
-void sendLocationEvents(uint32_t minIntervalMs) {
- gCallbacks->locationStatusChangeCallback(true, CHRE_ERROR_NONE);
-
- std::future<void> signal = gStopLocationEventsThread.get_future();
- while (signal.wait_for(std::chrono::milliseconds(minIntervalMs)) ==
- std::future_status::timeout) {
- auto event = chre::MakeUniqueZeroFill<struct chreGnssLocationEvent>();
- event->timestamp = gSystemApi->getCurrentTime();
- gCallbacks->locationEventCallback(event.release());
- }
-}
-
-void sendMeasurementEvents(uint32_t minIntervalMs) {
- gCallbacks->measurementStatusChangeCallback(true, CHRE_ERROR_NONE);
-
- std::future<void> signal = gStopMeasurementEventsThread.get_future();
- while (signal.wait_for(std::chrono::milliseconds(minIntervalMs)) ==
- std::future_status::timeout) {
- auto event = chre::MakeUniqueZeroFill<struct chreGnssDataEvent>();
- auto measurement = chre::MakeUniqueZeroFill<struct chreGnssMeasurement>();
- measurement->c_n0_dbhz = 63.0f;
-
- event->measurements = measurement.release();
- event->measurement_count = 1;
- event->clock.time_ns = static_cast<int64_t>(gSystemApi->getCurrentTime());
- gCallbacks->measurementEventCallback(event.release());
- }
-}
-
-void stopLocation() {
- gCallbacks->locationStatusChangeCallback(false, CHRE_ERROR_NONE);
-}
-
-void stopMeasurement() {
- gCallbacks->measurementStatusChangeCallback(false, CHRE_ERROR_NONE);
-}
-
-void stopLocationThreads() {
- if (gLocationEventsThread.joinable()) {
- gStopLocationEventsThread.set_value();
- gLocationEventsThread.join();
- }
- if (gLocationStatusThread.joinable()) {
- gLocationStatusThread.join();
- }
-}
-
-void stopMeasurementThreads() {
- if (gMeasurementEventsThread.joinable()) {
- gStopMeasurementEventsThread.set_value();
- gMeasurementEventsThread.join();
- }
- if (gMeasurementStatusThread.joinable()) {
- gMeasurementStatusThread.join();
- }
-}
-
-uint32_t chrePalGnssGetCapabilities() {
- return CHRE_GNSS_CAPABILITIES_LOCATION | CHRE_GNSS_CAPABILITIES_MEASUREMENTS;
-}
-
-bool chrePalControlLocationSession(bool enable, uint32_t minIntervalMs,
- uint32_t /* minTimeToNextFixMs */) {
- stopLocationThreads();
-
- if (enable) {
- gStopLocationEventsThread = std::promise<void>();
- gLocationEventsThread = std::thread(sendLocationEvents, minIntervalMs);
- } else {
- gLocationStatusThread = std::thread(stopLocation);
- }
-
- return true;
-}
-
-void chrePalGnssReleaseLocationEvent(struct chreGnssLocationEvent *event) {
- chre::memoryFree(event);
-}
-
-bool chrePalControlMeasurementSession(bool enable, uint32_t minIntervalMs) {
- stopMeasurementThreads();
-
- if (enable) {
- gStopMeasurementEventsThread = std::promise<void>();
- gMeasurementEventsThread =
- std::thread(sendMeasurementEvents, minIntervalMs);
- } else {
- gMeasurementStatusThread = std::thread(stopMeasurement);
- }
-
- return true;
-}
-
-void chrePalGnssReleaseMeasurementDataEvent(struct chreGnssDataEvent *event) {
- chre::memoryFree(
- const_cast<struct chreGnssMeasurement *>(event->measurements));
- chre::memoryFree(event);
-}
-
-void chrePalGnssApiClose() {
- stopLocationThreads();
- stopMeasurementThreads();
-}
-
-bool chrePalGnssApiOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalGnssCallbacks *callbacks) {
- chrePalGnssApiClose();
-
- bool success = false;
- if (systemApi != nullptr && callbacks != nullptr) {
- gSystemApi = systemApi;
- gCallbacks = callbacks;
- success = true;
- }
-
- return success;
-}
-
-} // anonymous namespace
-
-const struct chrePalGnssApi *chrePalGnssGetApi(uint32_t requestedApiVersion) {
- static const struct chrePalGnssApi kApi = {
- .moduleVersion = CHRE_PAL_GNSS_API_CURRENT_VERSION,
- .open = chrePalGnssApiOpen,
- .close = chrePalGnssApiClose,
- .getCapabilities = chrePalGnssGetCapabilities,
- .controlLocationSession = chrePalControlLocationSession,
- .releaseLocationEvent = chrePalGnssReleaseLocationEvent,
- .controlMeasurementSession = chrePalControlMeasurementSession,
- .releaseMeasurementDataEvent = chrePalGnssReleaseMeasurementDataEvent,
- };
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(kApi.moduleVersion,
- requestedApiVersion)) {
- return nullptr;
- } else {
- return &kApi;
- }
-}
diff --git a/platform/linux/pal_wifi.cc b/platform/linux/pal_wifi.cc
deleted file mode 100644
index f6eb1c96..00000000
--- a/platform/linux/pal_wifi.cc
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/pal/wifi.h"
-
-#include "chre/util/memory.h"
-#include "chre/util/unique_ptr.h"
-
-#include <chrono>
-#include <cinttypes>
-#include <thread>
-
-/**
- * A simulated implementation of the WiFi PAL for the linux platform.
- */
-namespace {
-const struct chrePalSystemApi *gSystemApi = nullptr;
-const struct chrePalWifiCallbacks *gCallbacks = nullptr;
-
-//! Thread to deliver asynchronous WiFi scan results after a CHRE request.
-std::thread gScanEventsThread;
-
-//! Thread to use when delivering a scan monitor status update.
-std::thread gScanMonitorStatusThread;
-
-void sendScanResponse() {
- gCallbacks->scanResponseCallback(true, CHRE_ERROR_NONE);
-
- auto event = chre::MakeUniqueZeroFill<struct chreWifiScanEvent>();
- auto result = chre::MakeUniqueZeroFill<struct chreWifiScanResult>();
- event->resultCount = 1;
- event->resultTotal = 1;
- event->referenceTime = gSystemApi->getCurrentTime();
- event->results = result.release();
-
- gCallbacks->scanEventCallback(event.release());
-}
-
-void sendScanMonitorResponse(bool enable) {
- gCallbacks->scanMonitorStatusChangeCallback(enable, CHRE_ERROR_NONE);
-}
-
-void stopScanEventThreads() {
- if (gScanEventsThread.joinable()) {
- gScanEventsThread.join();
- }
-}
-
-void stopScanMonitorThreads() {
- if (gScanMonitorStatusThread.joinable()) {
- gScanMonitorStatusThread.join();
- }
-}
-
-uint32_t chrePalWifiGetCapabilities() {
- return CHRE_WIFI_CAPABILITIES_SCAN_MONITORING |
- CHRE_WIFI_CAPABILITIES_ON_DEMAND_SCAN;
-}
-
-bool chrePalWifiConfigureScanMonitor(bool enable) {
- stopScanMonitorThreads();
-
- gScanMonitorStatusThread = std::thread(sendScanMonitorResponse, enable);
-
- return true;
-}
-
-bool chrePalWifiApiRequestScan(const struct chreWifiScanParams * /* params */) {
- stopScanEventThreads();
-
- gScanEventsThread = std::thread(sendScanResponse);
-
- return true;
-}
-
-void chrePalWifiApiReleaseScanEvent(struct chreWifiScanEvent *event) {
- chre::memoryFree(const_cast<uint32_t *>(event->scannedFreqList));
- chre::memoryFree(const_cast<struct chreWifiScanResult *>(event->results));
- chre::memoryFree(event);
-}
-
-void chrePalWifiApiClose() {
- stopScanEventThreads();
- stopScanMonitorThreads();
-}
-
-bool chrePalWifiApiOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalWifiCallbacks *callbacks) {
- chrePalWifiApiClose();
-
- bool success = false;
- if (systemApi != nullptr && callbacks != nullptr) {
- gSystemApi = systemApi;
- gCallbacks = callbacks;
- success = true;
- }
-
- return success;
-}
-
-} // anonymous namespace
-
-const struct chrePalWifiApi *chrePalWifiGetApi(uint32_t requestedApiVersion) {
- static const struct chrePalWifiApi kApi = {
- .moduleVersion = CHRE_PAL_WIFI_API_CURRENT_VERSION,
- .open = chrePalWifiApiOpen,
- .close = chrePalWifiApiClose,
- .getCapabilities = chrePalWifiGetCapabilities,
- .configureScanMonitor = chrePalWifiConfigureScanMonitor,
- .requestScan = chrePalWifiApiRequestScan,
- .releaseScanEvent = chrePalWifiApiReleaseScanEvent,
- };
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(kApi.moduleVersion,
- requestedApiVersion)) {
- return nullptr;
- } else {
- return &kApi;
- }
-}
diff --git a/platform/linux/pal_wwan.cc b/platform/linux/pal_wwan.cc
deleted file mode 100644
index e60abb1e..00000000
--- a/platform/linux/pal_wwan.cc
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/pal/wwan.h"
-
-#include "chre/util/memory.h"
-#include "chre/util/unique_ptr.h"
-
-#include <chrono>
-#include <cinttypes>
-#include <thread>
-
-/**
- * A simulated implementation of the WWAN PAL for the linux platform.
- */
-namespace {
-const struct chrePalSystemApi *gSystemApi = nullptr;
-const struct chrePalWwanCallbacks *gCallbacks = nullptr;
-
-//! Thread to deliver asynchronous WWAN cell info results after a CHRE request.
-std::thread gCellInfosThread;
-
-void sendCellInfoResult() {
- auto result = chre::MakeUniqueZeroFill<struct chreWwanCellInfoResult>();
- auto cell = chre::MakeUniqueZeroFill<struct chreWwanCellInfo>();
- cell->timeStamp = gSystemApi->getCurrentTime();
- cell->cellInfoType = CHRE_WWAN_CELL_INFO_TYPE_GSM;
- // INT*_MAX == unknown
- cell->CellInfo.gsm.cellIdentityGsm.mcc = INT32_MAX;
- cell->CellInfo.gsm.cellIdentityGsm.mnc = INT32_MAX;
- cell->CellInfo.gsm.cellIdentityGsm.lac = INT32_MAX;
- cell->CellInfo.gsm.cellIdentityGsm.cid = INT32_MAX;
- cell->CellInfo.gsm.cellIdentityGsm.arfcn = INT32_MAX;
- cell->CellInfo.gsm.cellIdentityGsm.bsic = INT8_MAX;
- cell->CellInfo.gsm.signalStrengthGsm.signalStrength = INT32_MAX;
- cell->CellInfo.gsm.signalStrengthGsm.signalStrength = INT32_MAX;
- cell->CellInfo.gsm.signalStrengthGsm.signalStrength = INT32_MAX;
-
- result->cellInfoCount = 1;
- result->errorCode = CHRE_ERROR_NONE;
- result->cells = cell.release();
-
- gCallbacks->cellInfoResultCallback(result.release());
-}
-
-void stopCellInfoThread() {
- if (gCellInfosThread.joinable()) {
- gCellInfosThread.join();
- }
-}
-
-uint32_t chrePalWwanGetCapabilities() {
- return CHRE_WWAN_GET_CELL_INFO;
-}
-
-bool chrePalWwanRequestCellInfo() {
- stopCellInfoThread();
-
- gCellInfosThread = std::thread(sendCellInfoResult);
-
- return true;
-}
-
-void chrePalWwanReleaseCellInfoResult(struct chreWwanCellInfoResult *result) {
- for (uint8_t i = 0; i < result->cellInfoCount; i++) {
- chre::memoryFree(const_cast<struct chreWwanCellInfo *>(&result->cells[i]));
- }
- chre::memoryFree(result);
-}
-
-void chrePalWwanApiClose() {
- stopCellInfoThread();
-}
-
-bool chrePalWwanApiOpen(const struct chrePalSystemApi *systemApi,
- const struct chrePalWwanCallbacks *callbacks) {
- chrePalWwanApiClose();
-
- bool success = false;
- if (systemApi != nullptr && callbacks != nullptr) {
- gSystemApi = systemApi;
- gCallbacks = callbacks;
- success = true;
- }
-
- return success;
-}
-
-} // anonymous namespace
-
-const struct chrePalWwanApi *chrePalWwanGetApi(uint32_t requestedApiVersion) {
- static const struct chrePalWwanApi kApi = {
- .moduleVersion = CHRE_PAL_WWAN_API_CURRENT_VERSION,
- .open = chrePalWwanApiOpen,
- .close = chrePalWwanApiClose,
- .getCapabilities = chrePalWwanGetCapabilities,
- .requestCellInfo = chrePalWwanRequestCellInfo,
- .releaseCellInfoResult = chrePalWwanReleaseCellInfoResult,
- };
-
- if (!CHRE_PAL_VERSIONS_ARE_COMPATIBLE(kApi.moduleVersion,
- requestedApiVersion)) {
- return nullptr;
- } else {
- return &kApi;
- }
-}
diff --git a/platform/linux/platform_audio.cc b/platform/linux/platform_audio.cc
index bf133ff9..8f6759e9 100644
--- a/platform/linux/platform_audio.cc
+++ b/platform/linux/platform_audio.cc
@@ -18,7 +18,6 @@
#include <cinttypes>
-#include "chre/core/audio_util.h"
#include "chre/core/event_loop_manager.h"
#include "chre/platform/fatal_error.h"
#include "chre/platform/log.h"
@@ -45,17 +44,19 @@ void audioSourceCallback(void *cookie) {
auto *audioSource = static_cast<AudioSource *>(cookie);
auto &dataEvent = audioSource->dataEvent;
- Nanoseconds samplingTime = AudioUtil::getDurationFromSampleCountAndRate(
- audioSource->numSamples,
- static_cast<uint32_t>(audioSource->audioInfo.samplerate));
+ Nanoseconds samplingTime =
+ AudioRequestManager::getDurationFromSampleCountAndRate(
+ audioSource->numSamples,
+ static_cast<uint32_t>(audioSource->audioInfo.samplerate));
dataEvent.timestamp =
(SystemTime::getMonotonicTime() - samplingTime).toRawNanoseconds();
dataEvent.sampleCount = audioSource->numSamples;
if (dataEvent.format == CHRE_AUDIO_DATA_FORMAT_16_BIT_SIGNED_PCM) {
- uint32_t intervalNumSamples = AudioUtil::getSampleCountFromRateAndDuration(
- static_cast<uint32_t>(audioSource->audioInfo.samplerate),
- audioSource->eventDelay);
+ uint32_t intervalNumSamples =
+ AudioRequestManager::getSampleCountFromRateAndDuration(
+ static_cast<uint32_t>(audioSource->audioInfo.samplerate),
+ audioSource->eventDelay);
if (intervalNumSamples > audioSource->numSamples) {
sf_count_t seekAmount = intervalNumSamples - audioSource->numSamples;
sf_seek(audioSource->audioFile, -seekAmount, SEEK_CUR);
@@ -133,7 +134,7 @@ void PlatformAudioBase::addAudioSource(UniquePtr<AudioSource> &source) {
auto &audioInfo = source->audioInfo;
source->audioFile =
sf_open(source->audioFilename.c_str(), SFM_READ, &audioInfo);
- auto sampleCount = AudioUtil::getSampleCountFromRateAndDuration(
+ auto sampleCount = AudioRequestManager::getSampleCountFromRateAndDuration(
static_cast<uint32_t>(source->audioInfo.samplerate),
source->maxBufferDuration);
if (source->audioFile == nullptr) {
diff --git a/platform/linux/platform_debug_dump_manager.cc b/platform/linux/platform_debug_dump_manager.cc
index 96c87c37..6d5b7c69 100644
--- a/platform/linux/platform_debug_dump_manager.cc
+++ b/platform/linux/platform_debug_dump_manager.cc
@@ -21,7 +21,4 @@ namespace chre {
void PlatformDebugDumpManager::sendDebugDump(const char * /*debugStr*/,
bool /*complete*/) {}
-void PlatformDebugDumpManager::logStateToBuffer(
- DebugDumpWrapper & /* debugDump */) {}
-
} // namespace chre
diff --git a/platform/linux/platform_log.cc b/platform/linux/platform_log.cc
index b4679b1e..67949d44 100644
--- a/platform/linux/platform_log.cc
+++ b/platform/linux/platform_log.cc
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include "chre/platform/linux/platform_log.h"
+#include "chre/platform/shared/platform_log.h"
#include <cstdarg>
#include <cstdio>
@@ -24,7 +24,7 @@
namespace chre {
-void PlatformLog::logLooper() {
+void PlatformLogBase::logLooper() {
while (1) {
char *logMessage = nullptr;
@@ -67,10 +67,12 @@ PlatformLog::~PlatformLog() {
mLoggerThread.join();
}
-void PlatformLog::logVa(chreLogLevel /*logLevel*/, const char *formatStr,
- va_list args) {
+void PlatformLog::log(const char *formatStr, ...) {
char *formattedStr;
- int result = vasprintf(&formattedStr, formatStr, args);
+ va_list argList;
+ va_start(argList, formatStr);
+ int result = vasprintf(&formattedStr, formatStr, argList);
+ va_end(argList);
if (result >= 0) {
std::unique_lock<std::mutex> lock(mMutex);
diff --git a/platform/linux/platform_nanoapp.cc b/platform/linux/platform_nanoapp.cc
index d3e02b93..d5fadf46 100644
--- a/platform/linux/platform_nanoapp.cc
+++ b/platform/linux/platform_nanoapp.cc
@@ -22,7 +22,6 @@
#include "chre/platform/assert.h"
#include "chre/platform/log.h"
#include "chre/platform/shared/nanoapp_dso_util.h"
-#include "chre/util/system/napp_permissions.h"
#include "chre_api/chre/version.h"
namespace chre {
@@ -61,24 +60,11 @@ const char *PlatformNanoapp::getAppName() const {
return (mAppInfo != nullptr) ? mAppInfo->name : "Unknown";
}
-bool PlatformNanoapp::supportsAppPermissions() const {
- return (mAppInfo != nullptr) ? (mAppInfo->structMinorVersion >=
- CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION)
- : false;
-}
-
-uint32_t PlatformNanoapp::getAppPermissions() const {
- return (supportsAppPermissions())
- ? mAppInfo->appPermissions
- : static_cast<uint32_t>(chre::NanoappPermissions::CHRE_PERMS_NONE);
-}
-
bool PlatformNanoapp::isSystemNanoapp() const {
return (mAppInfo != nullptr && mAppInfo->isSystemNanoapp);
}
-void PlatformNanoapp::logStateToBuffer(
- DebugDumpWrapper & /* debugDump */) const {}
+void PlatformNanoapp::logStateToBuffer(DebugDumpWrapper &debugDump) const {}
void PlatformNanoappBase::loadFromFile(const std::string &filename) {
CHRE_ASSERT(!isLoaded());
@@ -132,15 +118,11 @@ bool PlatformNanoappBase::openNanoappFromFile() {
if (!success) {
mAppInfo = nullptr;
} else {
- LOGI("Nanoapp loaded: %s (0x%016" PRIx64 ") version 0x%" PRIx32
- " uimg %d system %d from file %s",
+ LOGI("Successfully loaded nanoapp %s (0x%016" PRIx64
+ ") version 0x%" PRIx32 " uimg %d system %d from file %s",
mAppInfo->name, mAppInfo->appId, mAppInfo->appVersion,
mAppInfo->isTcmNanoapp, mAppInfo->isSystemNanoapp,
mFilename.c_str());
- if (mAppInfo->structMinorVersion >=
- CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION) {
- LOGI("Nanoapp permissions: 0x%" PRIx32, mAppInfo->appPermissions);
- }
}
}
}
diff --git a/platform/linux/platform_sensor.cc b/platform/linux/platform_sensor.cc
index c39e0c3c..ebf48444 100644
--- a/platform/linux/platform_sensor.cc
+++ b/platform/linux/platform_sensor.cc
@@ -38,14 +38,6 @@ const char *PlatformSensor::getSensorName() const {
return mSensorInfo->sensorName;
}
-uint8_t PlatformSensor::getSensorIndex() const {
- return CHRE_SENSOR_INDEX_DEFAULT;
-}
-
-uint16_t PlatformSensor::getTargetGroupMask() const {
- return kDefaultTargetGroupMask;
-}
-
PlatformSensor::PlatformSensor(PlatformSensor &&other) {
*this = std::move(other);
}
diff --git a/platform/linux/power_control_manager.cc b/platform/linux/power_control_manager.cc
index c007da99..c1ebb4a1 100644
--- a/platform/linux/power_control_manager.cc
+++ b/platform/linux/power_control_manager.cc
@@ -18,7 +18,7 @@
namespace chre {
-void PowerControlManager::postEventLoopProcess(size_t /* numPendingEvents */) {}
+void PowerControlManager::postEventLoopProcess(size_t numPendingEvents) {}
bool PowerControlManager::hostIsAwake() {
return true;
diff --git a/platform/platform.mk b/platform/platform.mk
index 29e52253..10d317c6 100644
--- a/platform/platform.mk
+++ b/platform/platform.mk
@@ -33,6 +33,14 @@ SLPI_CFLAGS += -Iplatform/slpi/include
# We use FlatBuffers in the SLPI platform layer
SLPI_CFLAGS += $(FLATBUFFERS_CFLAGS)
+ifneq ($(CHRE_ENABLE_ACCEL_CAL), false)
+SLPI_CFLAGS += -DCHRE_ENABLE_ACCEL_CAL
+endif
+
+ifneq ($(CHRE_ENABLE_ASH_DEBUG_DUMP), false)
+SLPI_CFLAGS += -DCHRE_ENABLE_ASH_DEBUG_DUMP
+endif
+
# SLPI/SEE-specific Compiler Flags #############################################
# Include paths.
@@ -61,57 +69,29 @@ ifeq ($(IMPORT_CHRE_UTILS), true)
SLPI_SEE_CFLAGS += -DIMPORT_CHRE_UTILS
endif
-# Enable accel calibration and ASH debug dump by default unless overridden
-# explicitly by the environment.
-ifneq ($(CHRE_ENABLE_ACCEL_CAL), false)
-SLPI_SEE_CFLAGS += -DCHRE_ENABLE_ACCEL_CAL
-endif
-
-ifneq ($(CHRE_ENABLE_ASH_DEBUG_DUMP), false)
-SLPI_SEE_CFLAGS += -DCHRE_ENABLE_ASH_DEBUG_DUMP
-endif
-
-# SLPI/QSH-specific Compiler Flags #############################################
-
-# Include paths.
-SLPI_QSH_CFLAGS += -I$(SLPI_PREFIX)/config/cust
-SLPI_QSH_CFLAGS += -I$(SLPI_PREFIX)/qsh/qsh_nanoapp/inc
-SLPI_QSH_CFLAGS += -Iplatform/slpi/see/include
-
-ifeq ($(CHRE_USE_BUFFERED_LOGGING), true)
-SLPI_QSH_CFLAGS += -DCHRE_USE_BUFFERED_LOGGING
-endif
-
-# Define CHRE_SLPI_SEE for the few components that are still shared between QSH
-# and SEE.
-SLPI_QSH_CFLAGS += -DCHRE_SLPI_SEE
-
# SLPI-specific Source Files ###################################################
-SLPI_SRCS += platform/shared/assert.cc
SLPI_SRCS += platform/shared/chre_api_audio.cc
SLPI_SRCS += platform/shared/chre_api_core.cc
SLPI_SRCS += platform/shared/chre_api_gnss.cc
SLPI_SRCS += platform/shared/chre_api_re.cc
-SLPI_SRCS += platform/shared/chre_api_user_settings.cc
+SLPI_SRCS += platform/shared/chre_api_sensor.cc
SLPI_SRCS += platform/shared/chre_api_version.cc
SLPI_SRCS += platform/shared/chre_api_wifi.cc
SLPI_SRCS += platform/shared/chre_api_wwan.cc
SLPI_SRCS += platform/shared/host_protocol_chre.cc
SLPI_SRCS += platform/shared/host_protocol_common.cc
SLPI_SRCS += platform/shared/memory_manager.cc
-SLPI_SRCS += platform/shared/nanoapp_load_manager.cc
SLPI_SRCS += platform/shared/nanoapp/nanoapp_dso_util.cc
SLPI_SRCS += platform/shared/pal_system_api.cc
-SLPI_SRCS += platform/shared/pw_tokenized_log.cc
SLPI_SRCS += platform/shared/system_time.cc
-SLPI_SRCS += platform/shared/version.cc
SLPI_SRCS += platform/slpi/chre_api_re.cc
SLPI_SRCS += platform/slpi/fatal_error.cc
SLPI_SRCS += platform/slpi/host_link.cc
SLPI_SRCS += platform/slpi/init.cc
SLPI_SRCS += platform/slpi/memory.cc
SLPI_SRCS += platform/slpi/memory_manager.cc
+SLPI_SRCS += platform/slpi/nanoapp_load_manager.cc
SLPI_SRCS += platform/slpi/platform_debug_dump_manager.cc
SLPI_SRCS += platform/slpi/platform_nanoapp.cc
SLPI_SRCS += platform/slpi/platform_pal.cc
@@ -142,16 +122,16 @@ endif
# SLPI/SEE-specific Source Files ###############################################
-# Optional sensors support.
-ifeq ($(CHRE_SENSORS_SUPPORT_ENABLED), true)
SLPI_SEE_SRCS += platform/slpi/see/platform_sensor.cc
SLPI_SEE_SRCS += platform/slpi/see/platform_sensor_manager.cc
+SLPI_SEE_SRCS += platform/slpi/see/power_control_manager.cc
+
ifneq ($(IMPORT_CHRE_UTILS), true)
+SLPI_SEE_SRCS += platform/slpi/see/island_vote_client.cc
SLPI_SEE_SRCS += platform/slpi/see/see_cal_helper.cc
SLPI_SEE_SRCS += platform/slpi/see/see_helper.cc
endif
-SLPI_SEE_SRCS += platform/shared/chre_api_sensor.cc
SLPI_SEE_SRCS += $(SLPI_PREFIX)/ssc_api/pb/sns_client.pb.c
SLPI_SEE_SRCS += $(SLPI_PREFIX)/ssc_api/pb/sns_suid.pb.c
SLPI_SEE_SRCS += $(SLPI_PREFIX)/ssc_api/pb/sns_cal.pb.c
@@ -165,26 +145,6 @@ SLPI_SEE_SRCS += $(SLPI_PREFIX)/ssc_api/pb/sns_std_type.pb.c
SLPI_SEE_QSK_SRCS += $(SLPI_PREFIX)/chre/chre/src/system/chre/platform/slpi/sns_qmi_client_alt.c
SLPI_SEE_QMI_SRCS += $(SLPI_PREFIX)/chre/chre/src/system/chre/platform/slpi/sns_qmi_client.c
-endif
-
-SLPI_SEE_SRCS += platform/slpi/see/power_control_manager.cc
-
-ifneq ($(IMPORT_CHRE_UTILS), true)
-SLPI_SEE_SRCS += platform/slpi/see/island_vote_client.cc
-endif
-
-# SLPI/QSH-specific Source Files ###############################################
-
-SLPI_QSH_SRCS += platform/slpi/see/island_vote_client.cc
-SLPI_QSH_SRCS += platform/slpi/see/power_control_manager.cc
-SLPI_QSH_SRCS += platform/slpi/qsh/qsh_shim.cc
-
-ifeq ($(CHRE_USE_BUFFERED_LOGGING), true)
-SLPI_QSH_SRCS += platform/shared/log_buffer.cc
-SLPI_QSH_SRCS += platform/shared/log_buffer_manager.cc
-SLPI_QSH_SRCS += platform/slpi/log_buffer_manager.cc
-endif
-
# Simulator-specific Compiler Flags ############################################
@@ -213,7 +173,6 @@ SIM_SRCS += platform/shared/chre_api_core.cc
SIM_SRCS += platform/shared/chre_api_gnss.cc
SIM_SRCS += platform/shared/chre_api_re.cc
SIM_SRCS += platform/shared/chre_api_sensor.cc
-SIM_SRCS += platform/shared/chre_api_user_settings.cc
SIM_SRCS += platform/shared/chre_api_version.cc
SIM_SRCS += platform/shared/chre_api_wifi.cc
SIM_SRCS += platform/shared/chre_api_wwan.cc
@@ -223,23 +182,22 @@ SIM_SRCS += platform/shared/pal_sensor_stub.cc
SIM_SRCS += platform/shared/pal_system_api.cc
SIM_SRCS += platform/shared/platform_sensor_manager.cc
SIM_SRCS += platform/shared/system_time.cc
-SIM_SRCS += platform/shared/version.cc
# Optional GNSS support.
ifeq ($(CHRE_GNSS_SUPPORT_ENABLED), true)
-SIM_SRCS += platform/linux/pal_gnss.cc
+SIM_SRCS += platform/shared/pal_gnss_stub.cc
SIM_SRCS += platform/shared/platform_gnss.cc
endif
# Optional Wi-Fi support.
ifeq ($(CHRE_WIFI_SUPPORT_ENABLED), true)
-SIM_SRCS += platform/linux/pal_wifi.cc
+SIM_SRCS += platform/shared/pal_wifi_stub.cc
SIM_SRCS += platform/shared/platform_wifi.cc
endif
# Optional WWAN support.
ifeq ($(CHRE_WWAN_SUPPORT_ENABLED), true)
-SIM_SRCS += platform/linux/pal_wwan.cc
+SIM_SRCS += platform/shared/pal_wwan_stub.cc
SIM_SRCS += platform/shared/platform_wwan.cc
endif
@@ -250,7 +208,6 @@ GOOGLE_X86_LINUX_CFLAGS += -Iplatform/linux/include
# Linux-specific Source Files ##################################################
GOOGLE_X86_LINUX_SRCS += platform/linux/init.cc
-GOOGLE_X86_LINUX_SRCS += platform/linux/assert.cc
# Optional audio support.
ifeq ($(CHRE_AUDIO_SUPPORT_ENABLED), true)
@@ -265,10 +222,10 @@ GOOGLE_ARM64_ANDROID_CFLAGS += -Iplatform/android/include
# Add in host sources to allow the executable to both be a socket server and
# CHRE implementation.
-GOOGLE_ARM64_ANDROID_CFLAGS += -I$(ANDROID_BUILD_TOP)/system/libbase/include
+GOOGLE_ARM64_ANDROID_CFLAGS += -I$(ANDROID_BUILD_TOP)/system/core/base/include
GOOGLE_ARM64_ANDROID_CFLAGS += -I$(ANDROID_BUILD_TOP)/system/core/libcutils/include
GOOGLE_ARM64_ANDROID_CFLAGS += -I$(ANDROID_BUILD_TOP)/system/core/libutils/include
-GOOGLE_ARM64_ANDROID_CFLAGS += -I$(ANDROID_BUILD_TOP)/system/logging/liblog/include
+GOOGLE_ARM64_ANDROID_CFLAGS += -I$(ANDROID_BUILD_TOP)/system/core/liblog/include
GOOGLE_ARM64_ANDROID_CFLAGS += -Ihost/common/include
# Also add the linux sources to fall back to the default Linux implementation.
@@ -280,7 +237,7 @@ GOOGLE_ARM64_ANDROID_CFLAGS += -I$(FLATBUFFERS_PATH)/include
# Android-specific Source Files ################################################
ANDROID_CUTILS_TOP = $(ANDROID_BUILD_TOP)/system/core/libcutils
-ANDROID_LOG_TOP = $(ANDROID_BUILD_TOP)/system/logging/liblog
+ANDROID_LOG_TOP = $(ANDROID_BUILD_TOP)/system/core/liblog
GOOGLE_ARM64_ANDROID_SRCS += $(ANDROID_CUTILS_TOP)/sockets_unix.cpp
GOOGLE_ARM64_ANDROID_SRCS += $(ANDROID_CUTILS_TOP)/android_get_control_file.cpp
@@ -309,8 +266,6 @@ GOOGLETEST_CFLAGS += -Iplatform/slpi/include
# GoogleTest Source Files ######################################################
-GOOGLETEST_COMMON_SRCS += platform/linux/assert.cc
-GOOGLETEST_COMMON_SRCS += platform/linux/audio_source.cc
-GOOGLETEST_COMMON_SRCS += platform/linux/platform_audio.cc
-GOOGLETEST_COMMON_SRCS += platform/tests/log_buffer_test.cc
-GOOGLETEST_COMMON_SRCS += platform/shared/log_buffer.cc
+GOOGLETEST_SRCS += platform/linux/assert.cc
+GOOGLETEST_SRCS += platform/linux/audio_source.cc
+GOOGLETEST_SRCS += platform/linux/platform_audio.cc
diff --git a/platform/shared/assert.cc b/platform/shared/assert.cc
deleted file mode 100644
index 43b11c8e..00000000
--- a/platform/shared/assert.cc
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/platform/assert.h"
-
-#include "chre/platform/fatal_error.h"
-
-namespace chre {
-
-void doAssert(const char *filename, size_t line) {
- FATAL_ERROR("Assertion failure at %s:%zu", filename, line);
-}
-
-} // namespace chre
diff --git a/platform/shared/chre_api_audio.cc b/platform/shared/chre_api_audio.cc
index 9f512cbe..b688c5b0 100644
--- a/platform/shared/chre_api_audio.cc
+++ b/platform/shared/chre_api_audio.cc
@@ -18,7 +18,6 @@
#include "chre/core/event_loop_manager.h"
#include "chre/util/macros.h"
-#include "chre/util/system/napp_permissions.h"
#ifdef CHRE_AUDIO_SUPPORT_ENABLED
#include "chre/platform/platform_audio.h"
@@ -27,7 +26,6 @@
using chre::EventLoopManager;
using chre::EventLoopManagerSingleton;
using chre::Nanoapp;
-using chre::NanoappPermissions;
DLL_EXPORT bool chreAudioGetSource(uint32_t handle,
struct chreAudioSource *audioSource) {
@@ -50,11 +48,10 @@ DLL_EXPORT bool chreAudioConfigureSource(uint32_t handle, bool enable,
uint64_t deliveryInterval) {
#ifdef CHRE_AUDIO_SUPPORT_ENABLED
Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_AUDIO) &&
- EventLoopManagerSingleton::get()
- ->getAudioRequestManager()
- .configureSource(nanoapp, handle, enable, bufferDuration,
- deliveryInterval);
+ return EventLoopManagerSingleton::get()
+ ->getAudioRequestManager()
+ .configureSource(nanoapp, handle, enable, bufferDuration,
+ deliveryInterval);
#else
return false;
#endif // CHRE_AUDIO_SUPPORT_ENABLED
diff --git a/platform/shared/chre_api_core.cc b/platform/shared/chre_api_core.cc
index e46a22eb..a3d9a128 100644
--- a/platform/shared/chre_api_core.cc
+++ b/platform/shared/chre_api_core.cc
@@ -23,7 +23,6 @@
#include "chre/platform/fatal_error.h"
#include "chre/platform/log.h"
#include "chre/util/macros.h"
-#include "chre/util/system/napp_permissions.h"
#include "chre_api/chre/event.h"
#include "chre_api/chre/re.h"
@@ -73,10 +72,9 @@ DLL_EXPORT bool chreSendMessageToHost(void *message, uint32_t messageSize,
CHRE_HOST_ENDPOINT_BROADCAST, freeCallback);
}
-DLL_EXPORT bool chreSendMessageWithPermissions(
+DLL_EXPORT bool chreSendMessageToHostEndpoint(
void *message, size_t messageSize, uint32_t messageType,
- uint16_t hostEndpoint, uint32_t messagePermissions,
- chreMessageFreeFunction *freeCallback) {
+ uint16_t hostEndpoint, chreMessageFreeFunction *freeCallback) {
Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
bool success = false;
@@ -89,8 +87,7 @@ DLL_EXPORT bool chreSendMessageWithPermissions(
auto &hostCommsManager =
EventLoopManagerSingleton::get()->getHostCommsManager();
success = hostCommsManager.sendMessageToHostFromNanoapp(
- nanoapp, message, messageSize, messageType, hostEndpoint,
- messagePermissions, freeCallback);
+ nanoapp, message, messageSize, messageType, hostEndpoint, freeCallback);
}
if (!success && freeCallback != nullptr) {
@@ -100,15 +97,6 @@ DLL_EXPORT bool chreSendMessageWithPermissions(
return success;
}
-DLL_EXPORT bool chreSendMessageToHostEndpoint(
- void *message, size_t messageSize, uint32_t messageType,
- uint16_t hostEndpoint, chreMessageFreeFunction *freeCallback) {
- return chreSendMessageWithPermissions(
- message, messageSize, messageType, hostEndpoint,
- static_cast<uint32_t>(chre::NanoappPermissions::CHRE_PERMS_NONE),
- freeCallback);
-}
-
DLL_EXPORT bool chreGetNanoappInfoByAppId(uint64_t appId,
struct chreNanoappInfo *info) {
return EventLoopManagerSingleton::get()
diff --git a/platform/shared/chre_api_gnss.cc b/platform/shared/chre_api_gnss.cc
index ef789699..c4617f86 100644
--- a/platform/shared/chre_api_gnss.cc
+++ b/platform/shared/chre_api_gnss.cc
@@ -18,13 +18,11 @@
#include "chre/core/event_loop_manager.h"
#include "chre/util/macros.h"
-#include "chre/util/system/napp_permissions.h"
#include "chre/util/time.h"
using chre::EventLoopManager;
using chre::EventLoopManagerSingleton;
using chre::Milliseconds;
-using chre::NanoappPermissions;
DLL_EXPORT uint32_t chreGnssGetCapabilities() {
#ifdef CHRE_GNSS_SUPPORT_ENABLED
@@ -41,12 +39,11 @@ DLL_EXPORT bool chreGnssLocationSessionStartAsync(uint32_t minIntervalMs,
const void *cookie) {
#ifdef CHRE_GNSS_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_GNSS) &&
- chre::EventLoopManagerSingleton::get()
- ->getGnssManager()
- .getLocationSession()
- .addRequest(nanoapp, Milliseconds(minIntervalMs),
- Milliseconds(minTimeToNextFixMs), cookie);
+ return chre::EventLoopManagerSingleton::get()
+ ->getGnssManager()
+ .getLocationSession()
+ .addRequest(nanoapp, Milliseconds(minIntervalMs),
+ Milliseconds(minTimeToNextFixMs), cookie);
#else
return false;
#endif // CHRE_GNSS_SUPPORT_ENABLED
@@ -55,11 +52,10 @@ DLL_EXPORT bool chreGnssLocationSessionStartAsync(uint32_t minIntervalMs,
DLL_EXPORT bool chreGnssLocationSessionStopAsync(const void *cookie) {
#ifdef CHRE_GNSS_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_GNSS) &&
- chre::EventLoopManagerSingleton::get()
- ->getGnssManager()
- .getLocationSession()
- .removeRequest(nanoapp, cookie);
+ return chre::EventLoopManagerSingleton::get()
+ ->getGnssManager()
+ .getLocationSession()
+ .removeRequest(nanoapp, cookie);
#else
return false;
#endif // CHRE_GNSS_SUPPORT_ENABLED
@@ -69,12 +65,11 @@ DLL_EXPORT bool chreGnssMeasurementSessionStartAsync(uint32_t minIntervalMs,
const void *cookie) {
#ifdef CHRE_GNSS_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_GNSS) &&
- chre::EventLoopManagerSingleton::get()
- ->getGnssManager()
- .getMeasurementSession()
- .addRequest(nanoapp, Milliseconds(minIntervalMs),
- Milliseconds(0) /* minTimeToNext */, cookie);
+ return chre::EventLoopManagerSingleton::get()
+ ->getGnssManager()
+ .getMeasurementSession()
+ .addRequest(nanoapp, Milliseconds(minIntervalMs),
+ Milliseconds(0) /* minTimeToNext */, cookie);
#else
return false;
#endif // CHRE_GNSS_SUPPORT_ENABLED
@@ -83,23 +78,10 @@ DLL_EXPORT bool chreGnssMeasurementSessionStartAsync(uint32_t minIntervalMs,
DLL_EXPORT bool chreGnssMeasurementSessionStopAsync(const void *cookie) {
#ifdef CHRE_GNSS_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_GNSS) &&
- chre::EventLoopManagerSingleton::get()
- ->getGnssManager()
- .getMeasurementSession()
- .removeRequest(nanoapp, cookie);
-#else
- return false;
-#endif // CHRE_GNSS_SUPPORT_ENABLED
-}
-
-DLL_EXPORT bool chreGnssConfigurePassiveLocationListener(bool enable) {
-#ifdef CHRE_GNSS_SUPPORT_ENABLED
- chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_GNSS) &&
- chre::EventLoopManagerSingleton::get()
- ->getGnssManager()
- .configurePassiveLocationListener(nanoapp, enable);
+ return chre::EventLoopManagerSingleton::get()
+ ->getGnssManager()
+ .getMeasurementSession()
+ .removeRequest(nanoapp, cookie);
#else
return false;
#endif // CHRE_GNSS_SUPPORT_ENABLED
diff --git a/platform/shared/chre_api_sensor.cc b/platform/shared/chre_api_sensor.cc
index 9b7b434d..ad264101 100644
--- a/platform/shared/chre_api_sensor.cc
+++ b/platform/shared/chre_api_sensor.cc
@@ -16,7 +16,6 @@
#include "chre/core/event_loop_manager.h"
#include "chre/core/sensor_request.h"
-#include "chre/core/sensor_type_helpers.h"
#include "chre/util/macros.h"
#include "chre/util/time.h"
#include "chre_api/chre/sensor.h"
@@ -29,28 +28,95 @@ using chre::SensorRequest;
using chre::getSensorModeFromEnum;
-DLL_EXPORT bool chreSensorFindDefault(uint8_t sensorType, uint32_t *handle) {
- return chreSensorFind(sensorType, CHRE_SENSOR_INDEX_DEFAULT, handle);
+#if defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
+namespace {
+constexpr uint8_t kBigImageAccelSensorType =
+ (CHRE_SENSOR_TYPE_VENDOR_START + 3);
+constexpr uint8_t kBigImageUncalAccelSensorType =
+ (CHRE_SENSOR_TYPE_VENDOR_START + 6);
+constexpr uint8_t kBigImageUncalGyroSensorType =
+ (CHRE_SENSOR_TYPE_VENDOR_START + 7);
+constexpr uint8_t kBigImageUncalMagSensorType =
+ (CHRE_SENSOR_TYPE_VENDOR_START + 8);
+constexpr uint8_t kBigImageLightSensorType =
+ (CHRE_SENSOR_TYPE_VENDOR_START + 9);
+
+bool isBigImageSensorType(uint8_t sensorType) {
+ return (sensorType == kBigImageAccelSensorType ||
+ sensorType == kBigImageUncalAccelSensorType ||
+ sensorType == kBigImageUncalGyroSensorType ||
+ sensorType == kBigImageUncalMagSensorType ||
+ sensorType == kBigImageLightSensorType);
+}
+
+/**
+ * Rewrites the provided sensorType to its big-image counterpart if it exists.
+ */
+void rewriteToBigImageSensorType(uint8_t *sensorType) {
+ CHRE_ASSERT(sensorType);
+
+ if (*sensorType == CHRE_SENSOR_TYPE_ACCELEROMETER) {
+ *sensorType = kBigImageAccelSensorType;
+ } else if (*sensorType == CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER) {
+ *sensorType = kBigImageUncalAccelSensorType;
+ } else if (*sensorType == CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE) {
+ *sensorType = kBigImageUncalGyroSensorType;
+ } else if (*sensorType == CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD) {
+ *sensorType = kBigImageUncalMagSensorType;
+ } else if (*sensorType == CHRE_SENSOR_TYPE_LIGHT) {
+ *sensorType = kBigImageLightSensorType;
+ }
+}
+
+/**
+ * Rewrites a big-image sensorType to its regular CHRE counterpart.
+ */
+void rewriteToChreSensorType(uint8_t *sensorType) {
+ CHRE_ASSERT(sensorType);
+
+ if (*sensorType == kBigImageAccelSensorType) {
+ *sensorType = CHRE_SENSOR_TYPE_ACCELEROMETER;
+ } else if (*sensorType == kBigImageUncalAccelSensorType) {
+ *sensorType = CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER;
+ } else if (*sensorType == kBigImageUncalGyroSensorType) {
+ *sensorType = CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE;
+ } else if (*sensorType == kBigImageUncalMagSensorType) {
+ *sensorType = CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD;
+ } else if (*sensorType == kBigImageLightSensorType) {
+ *sensorType = CHRE_SENSOR_TYPE_LIGHT;
+ }
}
+} // anonymous namespace
+#endif // defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
-DLL_EXPORT bool chreSensorFind(uint8_t sensorType, uint8_t sensorIndex,
- uint32_t *handle) {
-#if CHRE_SENSORS_SUPPORT_ENABLED
+DLL_EXPORT bool chreSensorFindDefault(uint8_t sensorType, uint32_t *handle) {
+#if defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
+ // HACK: as SEE does not support software batching in uimg via QCM/uQSockets,
+ // reroute requests for accel and uncal accel/gyro/mag from a big image
+ // nanoapp to a separate sensor type internally. These are the only always-on
+ // sensors used today by big image nanoapps, and this change allows these
+ // requests to transparently go to a separate sensor implementation that
+ // supports uimg batching via CM/QMI.
+ // TODO(P2-5673a9): work with QC to determine a better long-term solution
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
+ if (!nanoapp->isUimgApp()) {
+ // Since we have an accompanying hack in PlatformNanoapp::handleEvent(),
+ // hide the vendor sensor type from big image nanoapps as we're unable to
+ // deliver events for it
+ if (isBigImageSensorType(sensorType)) {
+ return false;
+ }
+ rewriteToBigImageSensorType(&sensorType);
+ }
+#endif // defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
+
return EventLoopManagerSingleton::get()
->getSensorRequestManager()
- .getSensorHandleForNanoapp(sensorType, sensorIndex, *nanoapp, handle);
-#else // CHRE_SENSORS_SUPPORT_ENABLED
- UNUSED_VAR(sensorType);
- UNUSED_VAR(sensorIndex);
- UNUSED_VAR(handle);
- return false;
-#endif
+ .getSensorHandle(sensorType, handle);
}
DLL_EXPORT bool chreGetSensorInfo(uint32_t sensorHandle,
struct chreSensorInfo *info) {
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
CHRE_ASSERT(info);
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
@@ -60,18 +126,21 @@ DLL_EXPORT bool chreGetSensorInfo(uint32_t sensorHandle,
success = EventLoopManagerSingleton::get()
->getSensorRequestManager()
.getSensorInfo(sensorHandle, *nanoapp, info);
+
+ // The distinction between big/uimg accel and uncal accel/gyro/mag should
+ // be abstracted away from big image nanoapps, so overwrite any platform
+ // implementation here.
+#if defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
+ if (!nanoapp->isUimgApp()) {
+ rewriteToChreSensorType(&info->sensorType);
+ }
+#endif // defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
}
return success;
-#else // CHRE_SENSORS_SUPPORT_ENABLED
- UNUSED_VAR(sensorHandle);
- UNUSED_VAR(info);
- return false;
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
}
DLL_EXPORT bool chreGetSensorSamplingStatus(
uint32_t sensorHandle, struct chreSensorSamplingStatus *status) {
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
CHRE_ASSERT(status);
bool success = false;
@@ -81,17 +150,11 @@ DLL_EXPORT bool chreGetSensorSamplingStatus(
.getSensorSamplingStatus(sensorHandle, status);
}
return success;
-#else // CHRE_SENSORS_SUPPORT_ENABLED
- UNUSED_VAR(sensorHandle);
- UNUSED_VAR(status);
- return false;
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
}
DLL_EXPORT bool chreSensorConfigure(uint32_t sensorHandle,
enum chreSensorConfigureMode mode,
uint64_t interval, uint64_t latency) {
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
SensorMode sensorMode = getSensorModeFromEnum(mode);
SensorRequest sensorRequest(nanoapp->getInstanceId(), sensorMode,
@@ -99,51 +162,26 @@ DLL_EXPORT bool chreSensorConfigure(uint32_t sensorHandle,
return EventLoopManagerSingleton::get()
->getSensorRequestManager()
.setSensorRequest(nanoapp, sensorHandle, sensorRequest);
-#else // CHRE_SENSORS_SUPPORT_ENABLED
- UNUSED_VAR(sensorHandle);
- UNUSED_VAR(mode);
- UNUSED_VAR(interval);
- UNUSED_VAR(latency);
- return false;
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
}
DLL_EXPORT bool chreSensorConfigureBiasEvents(uint32_t sensorHandle,
bool enable) {
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
return EventLoopManagerSingleton::get()
->getSensorRequestManager()
.configureBiasEvents(nanoapp, sensorHandle, enable);
-#else // CHRE_SENSORS_SUPPORT_ENABLED
- UNUSED_VAR(sensorHandle);
- UNUSED_VAR(enable);
- return false;
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
}
DLL_EXPORT bool chreSensorGetThreeAxisBias(
uint32_t sensorHandle, struct chreSensorThreeAxisData *bias) {
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
return EventLoopManagerSingleton::get()
->getSensorRequestManager()
.getThreeAxisBias(sensorHandle, bias);
-#else // CHRE_SENSORS_SUPPORT_ENABLED
- UNUSED_VAR(sensorHandle);
- UNUSED_VAR(bias);
- return false;
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
}
DLL_EXPORT bool chreSensorFlushAsync(uint32_t sensorHandle,
const void *cookie) {
-#ifdef CHRE_SENSORS_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
return EventLoopManagerSingleton::get()->getSensorRequestManager().flushAsync(
nanoapp, sensorHandle, cookie);
-#else // CHRE_SENSORS_SUPPORT_ENABLED
- UNUSED_VAR(sensorHandle);
- UNUSED_VAR(cookie);
- return false;
-#endif // CHRE_SENSORS_SUPPORT_ENABLED
}
diff --git a/platform/shared/chre_api_user_settings.cc b/platform/shared/chre_api_user_settings.cc
deleted file mode 100644
index d1496888..00000000
--- a/platform/shared/chre_api_user_settings.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 "chre_api/chre/user_settings.h"
-
-#include "chre/core/event_loop_manager.h"
-#include "chre/core/settings.h"
-#include "chre/util/macros.h"
-
-using chre::EventLoopManager;
-using chre::Nanoapp;
-using chre::Setting;
-using chre::SettingState;
-
-DLL_EXPORT int8_t chreUserSettingGetState(uint8_t setting) {
- return chre::getSettingStateAsInt8(setting);
-}
-
-DLL_EXPORT void chreUserSettingConfigureEvents(uint8_t setting, bool enable) {
- if (setting < static_cast<uint8_t>(Setting::SETTING_MAX)) {
- Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- nanoapp->configureUserSettingEvent(setting, enable);
- }
-}
diff --git a/platform/shared/chre_api_wifi.cc b/platform/shared/chre_api_wifi.cc
index 25fb2ea2..93e852aa 100644
--- a/platform/shared/chre_api_wifi.cc
+++ b/platform/shared/chre_api_wifi.cc
@@ -18,11 +18,9 @@
#include "chre/core/event_loop_manager.h"
#include "chre/util/macros.h"
-#include "chre/util/system/napp_permissions.h"
using chre::EventLoopManager;
using chre::EventLoopManagerSingleton;
-using chre::NanoappPermissions;
DLL_EXPORT uint32_t chreWifiGetCapabilities() {
#ifdef CHRE_WIFI_SUPPORT_ENABLED
@@ -38,10 +36,9 @@ DLL_EXPORT bool chreWifiConfigureScanMonitorAsync(bool enable,
const void *cookie) {
#ifdef CHRE_WIFI_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_WIFI) &&
- EventLoopManagerSingleton::get()
- ->getWifiRequestManager()
- .configureScanMonitor(nanoapp, enable, cookie);
+ return EventLoopManagerSingleton::get()
+ ->getWifiRequestManager()
+ .configureScanMonitor(nanoapp, enable, cookie);
#else
return false;
#endif // CHRE_WIFI_SUPPORT_ENABLED
@@ -51,9 +48,10 @@ DLL_EXPORT bool chreWifiRequestScanAsync(
const struct chreWifiScanParams *params, const void *cookie) {
#ifdef CHRE_WIFI_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_WIFI) &&
- EventLoopManagerSingleton::get()->getWifiRequestManager().requestScan(
- nanoapp, params, cookie);
+ return (params == nullptr) ? false
+ : EventLoopManagerSingleton::get()
+ ->getWifiRequestManager()
+ .requestScan(nanoapp, params, cookie);
#else
return false;
#endif // CHRE_WIFI_SUPPORT_ENABLED
@@ -63,10 +61,10 @@ DLL_EXPORT bool chreWifiRequestRangingAsync(
const struct chreWifiRangingParams *params, const void *cookie) {
#ifdef CHRE_WIFI_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_WIFI) &&
- EventLoopManagerSingleton::get()
- ->getWifiRequestManager()
- .requestRanging(nanoapp, params, cookie);
+ return (params == nullptr) ? false
+ : EventLoopManagerSingleton::get()
+ ->getWifiRequestManager()
+ .requestRanging(nanoapp, params, cookie);
#else
return false;
#endif // CHRE_WIFI_SUPPORT_ENABLED
diff --git a/platform/shared/chre_api_wwan.cc b/platform/shared/chre_api_wwan.cc
index 7196d9e8..bb2fcd2d 100644
--- a/platform/shared/chre_api_wwan.cc
+++ b/platform/shared/chre_api_wwan.cc
@@ -18,11 +18,9 @@
#include "chre/core/event_loop_manager.h"
#include "chre/util/macros.h"
-#include "chre/util/system/napp_permissions.h"
using chre::EventLoopManager;
using chre::EventLoopManagerSingleton;
-using chre::NanoappPermissions;
DLL_EXPORT uint32_t chreWwanGetCapabilities() {
#ifdef CHRE_WWAN_SUPPORT_ENABLED
@@ -37,10 +35,9 @@ DLL_EXPORT uint32_t chreWwanGetCapabilities() {
DLL_EXPORT bool chreWwanGetCellInfoAsync(const void *cookie) {
#ifdef CHRE_WWAN_SUPPORT_ENABLED
chre::Nanoapp *nanoapp = EventLoopManager::validateChreApiCall(__func__);
- return nanoapp->permitPermissionUse(NanoappPermissions::CHRE_PERMS_WWAN) &&
- chre::EventLoopManagerSingleton::get()
- ->getWwanRequestManager()
- .requestCellInfo(nanoapp, cookie);
+ return chre::EventLoopManagerSingleton::get()
+ ->getWwanRequestManager()
+ .requestCellInfo(nanoapp, cookie);
#else
return false;
#endif // CHRE_WWAN_SUPPORT_ENABLED
diff --git a/platform/shared/dlfcn.cc b/platform/shared/dlfcn.cc
deleted file mode 100644
index 630b73c8..00000000
--- a/platform/shared/dlfcn.cc
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <dlfcn.h>
-
-#include "chre/platform/assert.h"
-#include "chre/platform/shared/nanoapp_loader.h"
-#include "chre/util/unique_ptr.h"
-
-void *dlopenbuf(void *elfBinary, bool mapIntoTcm) {
- return chre::NanoappLoader::create(elfBinary, mapIntoTcm);
-}
-
-void *dlsym(void *handle, const char *symbol) {
- LOGV("Attempting to find %s", symbol);
-
- void *resolvedSymbol = nullptr;
- if (handle == RTLD_NEXT) {
- resolvedSymbol = chre::NanoappLoader::findExportedSymbol(symbol);
- } else if (handle != nullptr) {
- auto *loader = reinterpret_cast<chre::NanoappLoader *>(handle);
- resolvedSymbol = loader->findSymbolByName(symbol);
- }
-
- if (resolvedSymbol == nullptr) {
- LOGE("dlsym unable to resolve %s", symbol);
- } else {
- LOGV("Found symbol at %p", resolvedSymbol);
- }
-
- return resolvedSymbol;
-}
-
-int dlclose(void *handle) {
- int rv = -1;
-
- if (handle != nullptr) {
- chre::NanoappLoader::destroy(static_cast<chre::NanoappLoader *>(handle));
- rv = 0;
- }
-
- return rv;
-}
-
-const char *dlerror() {
- return "Shared library load failed";
-}
diff --git a/platform/shared/dram_vote_client.cc b/platform/shared/dram_vote_client.cc
deleted file mode 100644
index 13030c65..00000000
--- a/platform/shared/dram_vote_client.cc
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/platform/shared/dram_vote_client.h"
-
-#include <cinttypes>
-
-#include "chre/platform/assert.h"
-#include "chre/platform/fatal_error.h"
-#include "chre/platform/log.h"
-#include "chre/platform/system_time.h"
-
-namespace chre {
-
-void DramVoteClient::voteDramAccess(bool enabled) {
- LockGuard<Mutex> lock(mMutex);
- mLastDramRequest = enabled;
-
- bool needDram = (enabled || mDramVoteCount > 0);
- if (needDram != mLastDramVote) {
- issueDramVote(needDram);
- mLastDramVote = needDram;
- }
-}
-
-void DramVoteClient::incrementDramVoteCount() {
- LockGuard<Mutex> lock(mMutex);
-
- if (mDramVoteCount++ == 0) {
- mVoteCountStart = Milliseconds(SystemTime::getMonotonicTime());
- // TODO(b/181172259): Change back to LOGW once buffered logging path is
- // refactored.
- // LOGW("DRAM vote count begins");
- printf("CHRE: DRAM vote count begins");
-
- if (!mLastDramVote) {
- // Do not call voteDramAccess() directly as it will override
- // mLastDramRequest.
- issueDramVote(true /* enabled */);
- mLastDramVote = true;
- }
- } else {
- checkDramDuration();
- }
-}
-
-void DramVoteClient::decrementDramVoteCount() {
- LockGuard<Mutex> lock(mMutex);
- CHRE_ASSERT_LOG(mDramVoteCount > 0,
- "Tried to decrement DRAM vote count when it's 0");
-
- if (--mDramVoteCount == 0) {
- // TODO(b/181172259): Change back to LOGW once buffered logging path is
- // refactored.
- // LOGW("DRAM vote count ends: %" PRIu64 " ms", checkDramDuration());
- printf("CHRE: DRAM vote count ends: %" PRIu64 " ms", checkDramDuration());
-
- // There's no DRAM activity now, remove CHRE's DRAM access vote.
- if (!mLastDramRequest) {
- issueDramVote(false /* enabled */);
- mLastDramVote = false;
- }
- }
-}
-
-Milliseconds DramVoteClient::checkDramDuration() const {
- Milliseconds duration(0);
- if (mDramVoteCount > 0) {
- duration = Milliseconds(SystemTime::getMonotonicTime()) - mVoteCountStart;
- }
-
- // DRAM memory fallback only intends to handle a surge of DRAM memory
- // requests. If there's a prolonged period of memory fallback, this might
- // indicate a memory leak or inadequate SRAM heap size.
- if (duration > kMaxDramDuration) {
- FATAL_ERROR("Forced into DRAM for %" PRIu64 " msec",
- duration.getMilliseconds());
- }
- return duration;
-}
-
-//! Explicitly instantiate the DramVoteClient singleton to reduce code size.
-template class Singleton<DramVoteClient>;
-
-} // namespace chre
diff --git a/platform/shared/host_protocol_chre.cc b/platform/shared/host_protocol_chre.cc
index adb701a7..c6725dda 100644
--- a/platform/shared/host_protocol_chre.cc
+++ b/platform/shared/host_protocol_chre.cc
@@ -22,6 +22,7 @@
#include "chre/platform/log.h"
#include "chre/platform/shared/generated/host_messages_generated.h"
+using flatbuffers::FlatBufferBuilder;
using flatbuffers::Offset;
using flatbuffers::Vector;
@@ -81,10 +82,9 @@ bool HostProtocolChre::decodeMessageFromHost(const void *message,
getStringFromByteVector(request->app_binary_file_name());
HostMessageHandlers::handleLoadNanoappRequest(
hostClientId, request->transaction_id(), request->app_id(),
- request->app_version(), request->app_flags(),
- request->target_api_version(), appBinary->data(), appBinary->size(),
- appBinaryFilename, request->fragment_id(),
- request->total_app_size(), request->respond_before_start());
+ request->app_version(), request->target_api_version(),
+ appBinary->data(), appBinary->size(), appBinaryFilename,
+ request->fragment_id(), request->total_app_size());
break;
}
@@ -117,11 +117,6 @@ bool HostProtocolChre::decodeMessageFromHost(const void *message,
break;
}
- case fbs::ChreMessage::SelfTestRequest: {
- HostMessageHandlers::handleSelfTestRequest(hostClientId);
- break;
- }
-
default:
LOGW("Got invalid/unexpected message type %" PRIu8,
static_cast<uint8_t>(container->message_type()));
@@ -133,7 +128,7 @@ bool HostProtocolChre::decodeMessageFromHost(const void *message,
}
void HostProtocolChre::encodeHubInfoResponse(
- ChreFlatBufferBuilder &builder, const char *name, const char *vendor,
+ FlatBufferBuilder &builder, const char *name, const char *vendor,
const char *toolchain, uint32_t legacyPlatformVersion,
uint32_t legacyToolchainVersion, float peakMips, float stoppedPower,
float sleepPower, float peakPower, uint32_t maxMessageLen,
@@ -151,19 +146,18 @@ void HostProtocolChre::encodeHubInfoResponse(
}
void HostProtocolChre::addNanoappListEntry(
- ChreFlatBufferBuilder &builder,
+ FlatBufferBuilder &builder,
DynamicVector<Offset<fbs::NanoappListEntry>> &offsetVector, uint64_t appId,
- uint32_t appVersion, bool enabled, bool isSystemNanoapp,
- uint32_t appPermissions) {
+ uint32_t appVersion, bool enabled, bool isSystemNanoapp) {
auto offset = fbs::CreateNanoappListEntry(builder, appId, appVersion, enabled,
- isSystemNanoapp, appPermissions);
+ isSystemNanoapp);
if (!offsetVector.push_back(offset)) {
LOGE("Couldn't push nanoapp list entry offset!");
}
}
void HostProtocolChre::finishNanoappListResponse(
- ChreFlatBufferBuilder &builder,
+ FlatBufferBuilder &builder,
DynamicVector<Offset<fbs::NanoappListEntry>> &offsetVector,
uint16_t hostClientId) {
auto vectorOffset =
@@ -173,11 +167,9 @@ void HostProtocolChre::finishNanoappListResponse(
hostClientId);
}
-void HostProtocolChre::encodeLoadNanoappResponse(ChreFlatBufferBuilder &builder,
- uint16_t hostClientId,
- uint32_t transactionId,
- bool success,
- uint32_t fragmentId) {
+void HostProtocolChre::encodeLoadNanoappResponse(
+ flatbuffers::FlatBufferBuilder &builder, uint16_t hostClientId,
+ uint32_t transactionId, bool success, uint32_t fragmentId) {
auto response = fbs::CreateLoadNanoappResponse(builder, transactionId,
success, fragmentId);
finalize(builder, fbs::ChreMessage::LoadNanoappResponse, response.Union(),
@@ -185,7 +177,7 @@ void HostProtocolChre::encodeLoadNanoappResponse(ChreFlatBufferBuilder &builder,
}
void HostProtocolChre::encodeUnloadNanoappResponse(
- ChreFlatBufferBuilder &builder, uint16_t hostClientId,
+ flatbuffers::FlatBufferBuilder &builder, uint16_t hostClientId,
uint32_t transactionId, bool success) {
auto response =
fbs::CreateUnloadNanoappResponse(builder, transactionId, success);
@@ -193,30 +185,18 @@ void HostProtocolChre::encodeUnloadNanoappResponse(
hostClientId);
}
-void HostProtocolChre::encodeLogMessages(ChreFlatBufferBuilder &builder,
- const uint8_t *logBuffer,
- size_t bufferSize) {
+void HostProtocolChre::encodeLogMessages(
+ flatbuffers::FlatBufferBuilder &builder, const char *logBuffer,
+ size_t bufferSize) {
auto logBufferOffset = builder.CreateVector(
reinterpret_cast<const int8_t *>(logBuffer), bufferSize);
auto message = fbs::CreateLogMessage(builder, logBufferOffset);
finalize(builder, fbs::ChreMessage::LogMessage, message.Union());
}
-void HostProtocolChre::encodeLogMessagesV2(ChreFlatBufferBuilder &builder,
- const uint8_t *logBuffer,
- size_t bufferSize,
- uint32_t numLogsDropped) {
- auto logBufferOffset = builder.CreateVector(
- reinterpret_cast<const int8_t *>(logBuffer), bufferSize);
- auto message =
- fbs::CreateLogMessageV2(builder, logBufferOffset, numLogsDropped);
- finalize(builder, fbs::ChreMessage::LogMessageV2, message.Union());
-}
-
-void HostProtocolChre::encodeDebugDumpData(ChreFlatBufferBuilder &builder,
- uint16_t hostClientId,
- const char *debugStr,
- size_t debugStrSize) {
+void HostProtocolChre::encodeDebugDumpData(
+ flatbuffers::FlatBufferBuilder &builder, uint16_t hostClientId,
+ const char *debugStr, size_t debugStrSize) {
auto debugStrOffset = builder.CreateVector(
reinterpret_cast<const int8_t *>(debugStr), debugStrSize);
auto message = fbs::CreateDebugDumpData(builder, debugStrOffset);
@@ -224,82 +204,32 @@ void HostProtocolChre::encodeDebugDumpData(ChreFlatBufferBuilder &builder,
hostClientId);
}
-void HostProtocolChre::encodeDebugDumpResponse(ChreFlatBufferBuilder &builder,
- uint16_t hostClientId,
- bool success,
- uint32_t dataCount) {
+void HostProtocolChre::encodeDebugDumpResponse(
+ flatbuffers::FlatBufferBuilder &builder, uint16_t hostClientId,
+ bool success, uint32_t dataCount) {
auto response = fbs::CreateDebugDumpResponse(builder, success, dataCount);
finalize(builder, fbs::ChreMessage::DebugDumpResponse, response.Union(),
hostClientId);
}
-void HostProtocolChre::encodeTimeSyncRequest(ChreFlatBufferBuilder &builder) {
+void HostProtocolChre::encodeTimeSyncRequest(
+ flatbuffers::FlatBufferBuilder &builder) {
auto request = fbs::CreateTimeSyncRequest(builder);
finalize(builder, fbs::ChreMessage::TimeSyncRequest, request.Union());
}
void HostProtocolChre::encodeLowPowerMicAccessRequest(
- ChreFlatBufferBuilder &builder) {
+ flatbuffers::FlatBufferBuilder &builder) {
auto request = fbs::CreateLowPowerMicAccessRequest(builder);
finalize(builder, fbs::ChreMessage::LowPowerMicAccessRequest,
request.Union());
}
void HostProtocolChre::encodeLowPowerMicAccessRelease(
- ChreFlatBufferBuilder &builder) {
+ flatbuffers::FlatBufferBuilder &builder) {
auto request = fbs::CreateLowPowerMicAccessRelease(builder);
finalize(builder, fbs::ChreMessage::LowPowerMicAccessRelease,
request.Union());
}
-void HostProtocolChre::encodeSelfTestResponse(ChreFlatBufferBuilder &builder,
- uint16_t hostClientId,
- bool success) {
- auto response = fbs::CreateSelfTestResponse(builder, success);
- finalize(builder, fbs::ChreMessage::SelfTestResponse, response.Union(),
- hostClientId);
-}
-
-bool HostProtocolChre::getSettingFromFbs(fbs::Setting setting,
- Setting *chreSetting) {
- bool success = true;
- switch (setting) {
- case fbs::Setting::LOCATION:
- *chreSetting = Setting::LOCATION;
- break;
- case fbs::Setting::WIFI_AVAILABLE:
- *chreSetting = Setting::WIFI_AVAILABLE;
- break;
- case fbs::Setting::AIRPLANE_MODE:
- *chreSetting = Setting::AIRPLANE_MODE;
- break;
- case fbs::Setting::MICROPHONE:
- *chreSetting = Setting::MICROPHONE;
- break;
- default:
- LOGE("Unknown setting %" PRIu8, static_cast<uint8_t>(setting));
- success = false;
- }
-
- return success;
-}
-
-bool HostProtocolChre::getSettingStateFromFbs(fbs::SettingState state,
- SettingState *chreSettingState) {
- bool success = true;
- switch (state) {
- case fbs::SettingState::DISABLED:
- *chreSettingState = SettingState::DISABLED;
- break;
- case fbs::SettingState::ENABLED:
- *chreSettingState = SettingState::ENABLED;
- break;
- default:
- LOGE("Unknown state %" PRIu8, static_cast<uint8_t>(state));
- success = false;
- }
-
- return success;
-}
-
} // namespace chre
diff --git a/platform/shared/host_protocol_common.cc b/platform/shared/host_protocol_common.cc
index c0ce52b6..6cf8b134 100644
--- a/platform/shared/host_protocol_common.cc
+++ b/platform/shared/host_protocol_common.cc
@@ -28,14 +28,12 @@ namespace chre {
void HostProtocolCommon::encodeNanoappMessage(
FlatBufferBuilder &builder, uint64_t appId, uint32_t messageType,
- uint16_t hostEndpoint, const void *messageData, size_t messageDataLen,
- uint32_t permissions, uint32_t messagePermissions) {
+ uint16_t hostEndpoint, const void *messageData, size_t messageDataLen) {
auto messageDataOffset = builder.CreateVector(
static_cast<const uint8_t *>(messageData), messageDataLen);
auto nanoappMessage = fbs::CreateNanoappMessage(
- builder, appId, messageType, hostEndpoint, messageDataOffset,
- messagePermissions, permissions);
+ builder, appId, messageType, hostEndpoint, messageDataOffset);
finalize(builder, fbs::ChreMessage::NanoappMessage, nanoappMessage.Union());
}
diff --git a/platform/shared/idl/host_messages.fbs b/platform/shared/idl/host_messages.fbs
index dd6ebaa7..a34836c8 100644
--- a/platform/shared/idl/host_messages.fbs
+++ b/platform/shared/idl/host_messages.fbs
@@ -26,17 +26,6 @@ table NanoappMessage {
/// Vector containing arbitrary application-specific message data
message:[ubyte] (required);
-
- /// List of Android permissions that cover the contents of a message from a
- /// nanoapp to the host.
- /// These permissions are used to record and attribute access to
- /// permissions-controlled resources.
- message_permissions:uint;
-
- /// List of Android permissions declared by the nanoapp / granted to the host.
- /// For messages from a nanoaapp to the host, this must be a superset of
- /// message_permissions.
- permissions:uint;
}
table HubInfoRequest {}
@@ -86,10 +75,6 @@ table NanoappListEntry {
/// and do not interact via the context hub HAL.
is_system:bool = false;
- /// Nanoapp permissions, if supported. Nanoapp permissions are required on
- /// CHRE API v1.5+, and are defined in chre/util/system/napp_permissions.h
- permissions:uint;
-
// TODO: memory usage
}
@@ -154,16 +139,6 @@ table LoadNanoappRequest {
/// Null-terminated ASCII string containing the file name that contains the
/// app binary to be loaded.
app_binary_file_name:[byte];
-
- /// The nanoapp flag values from the nanoapp header defined in
- /// build/build_template.mk. Refer to that file for more details.
- app_flags:uint;
-
- /// If true and fragmented loading is requested, the LoadNanoappResponse
- /// for the last fragment will be sent after the fragment was confirmed
- /// to be placed in memory and no additional response will be sent after
- /// the nanoapp is linked and started in the framework.
- respond_before_start:bool;
}
table LoadNanoappResponse {
@@ -256,9 +231,6 @@ table LowPowerMicAccessRelease {}
/// An enum describing the setting type.
enum Setting : byte {
LOCATION = 0,
- WIFI_AVAILABLE,
- AIRPLANE_MODE,
- MICROPHONE,
}
/// An enum describing the state of a setting.
@@ -276,37 +248,6 @@ table SettingChangeMessage {
state:SettingState = DISABLED;
}
-/// Represents V2 log messages from CHRE.
-table LogMessageV2 {
- /// A buffer containing formatted log data. A flat array is used here to avoid
- /// overhead in serializing and deserializing. The format is as follows:
- ///
- /// uint8_t - LogBuffer log level (1 = error, 2 = warn,
- /// 3 = info, 4 = debug,
- /// 5 = verbose)
- /// uint32_t, little-endian - timestamp in milliseconds
- /// char[] - message to log
- /// char, \0 - null-terminator
- ///
- /// This pattern repeats until the end of the buffer for multiple log
- /// messages. The last byte will always be a null-terminator. There are no
- /// padding bytes between these fields. Treat this like a packed struct and be
- /// cautious with unaligned access when reading/writing this buffer.
- buffer:[byte];
-
- /// The number of logs dropped since CHRE started
- num_logs_dropped:uint;
-}
-
-// A request to perform basic internal self-test in CHRE. The test to be performed
-// is platform-dependent, and can be used to check if the system is functioning
-// properly. This message should be used for debugging/testing.
-table SelfTestRequest {}
-table SelfTestResponse {
- // True if the self-test succeeded.
- success:bool;
-}
-
/// A union that joins together all possible messages. Note that in FlatBuffers,
/// unions have an implicit type
union ChreMessage {
@@ -338,11 +279,6 @@ union ChreMessage {
LowPowerMicAccessRelease,
SettingChangeMessage,
-
- LogMessageV2,
-
- SelfTestRequest,
- SelfTestResponse,
}
struct HostAddress {
diff --git a/platform/shared/include/chre/platform/shared/authentication.h b/platform/shared/include/chre/platform/shared/authentication.h
deleted file mode 100644
index 6409b474..00000000
--- a/platform/shared/include/chre/platform/shared/authentication.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SHARED_AUTHENTICATION_H_
-#define CHRE_PLATFORM_SHARED_AUTHENTICATION_H_
-
-namespace chre {
-
-/**
- * Authenticates the signature of the provided binary. If not provided
- * elsewhere by the platform, this method must ensure that nanoapps are signed
- * appropriately and no corruption has occurred to the binary prior to being
- * loaded. If this method succeeds, CHRE will assume the binary has the same
- * execution privileges as the core framework itself.
- *
- * @param binary Pointer to the binary that should be authenticated.
- * @param realBinaryStart A non-null pointer that, if this method succeeds, must
- * be filled with the starting address of the raw binary after any headers
- * used by the authentication code. This will be passed to the dynamic
- * loader which will assume the starting address is a valid ELF binary.
- * @return True if the binary passed authentication.
- */
-bool authenticateBinary(void *binary, void **realBinaryStart);
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_SHARED_AUTHENTICATION_H_
diff --git a/platform/shared/include/chre/platform/shared/dram_vote_client.h b/platform/shared/include/chre/platform/shared/dram_vote_client.h
deleted file mode 100644
index 00476a49..00000000
--- a/platform/shared/include/chre/platform/shared/dram_vote_client.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SHARED_VOTE_CLIENT_H_
-#define CHRE_PLATFORM_SHARED_VOTE_CLIENT_H_
-
-#include "chre/platform/mutex.h"
-#include "chre/util/lock_guard.h"
-#include "chre/util/singleton.h"
-#include "chre/util/time.h"
-
-namespace chre {
-
-/**
- * Class used to manage voting for access to DRAM for platforms that require
- * voting for DRAM memory to be accessible.
- */
-class DramVoteClient : public NonCopyable {
- public:
- /**
- * @return true if CHRE currently has a DRAM vote in place.
- */
- bool isDramVoteActive() {
- LockGuard<Mutex> lock(mMutex);
- return mLastDramVote;
- }
-
- /**
- * Makes a DRAM access request. An actual vote to the memory manager may not
- * be cast depending on the current mode and mDramVoteCount.
- *
- * @param enabled Whether to request DRAM access.
- */
- void voteDramAccess(bool enabled);
-
- /**
- * Increment the DRAM vote count when a client needs to perform some DRAM
- * activity. A DRAM vote is issued when the count increments from 0.
- */
- void incrementDramVoteCount();
-
- /**
- * Decrement the DRAM vote count when a client finishes some activity that has
- * to be performed in DRAM. A DRAM vote may be removed when the count
- * decrements to 0, depending on if explicit DRAM votes have been issued from
- * voteDramAccess.
- */
- void decrementDramVoteCount();
-
- private:
- //! The maximum allowed duration to be voted into DRAM by
- //! incrementDramVoteCount before a FATAL_ERROR is triggered.
- static constexpr Seconds kMaxDramDuration = Seconds(300);
-
- //! Last DRAM request made through voteDramAccess().
- bool mLastDramRequest = false;
-
- //! Last DRAM vote cast to the system.
- bool mLastDramVote = false;
-
- //! The system time mDramVoteCount increments from 0.
- Milliseconds mVoteCountStart = Milliseconds(0);
-
- //! The count of DRAM activities.
- uint32_t mDramVoteCount = 0;
-
- //! Used to protect access to member variables from other threads.
- Mutex mMutex;
-
- /**
- * Issue a vote to the underlying system. This must be implemented by each
- * platform to communicate with the right system.
- *
- * @param enabled Whether DRAM should be accessible.
- */
- void issueDramVote(bool enabled);
-
- /**
- * Check how long the system has been voted into DRAM due to
- * incrementDramVoteCount. If longer than kMaxDramDuration, trigger a crash.
- *
- * @return the duration in milliseconds since the system has been voted into
- * big image due to incrementDramVoteCount.
- */
- Milliseconds checkDramDuration() const;
-};
-
-//! Provides an alias to the DramVoteClient singleton
-typedef Singleton<DramVoteClient> DramVoteClientSingleton;
-
-extern template class Singleton<DramVoteClient>;
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_SHARED_VOTE_CLIENT_H_
diff --git a/platform/shared/include/chre/platform/shared/generated/host_messages_generated.h b/platform/shared/include/chre/platform/shared/generated/host_messages_generated.h
index 8fc7f0cb..15a92844 100644
--- a/platform/shared/include/chre/platform/shared/generated/host_messages_generated.h
+++ b/platform/shared/include/chre/platform/shared/generated/host_messages_generated.h
@@ -66,15 +66,6 @@ struct LowPowerMicAccessReleaseBuilder;
struct SettingChangeMessage;
struct SettingChangeMessageBuilder;
-struct LogMessageV2;
-struct LogMessageV2Builder;
-
-struct SelfTestRequest;
-struct SelfTestRequestBuilder;
-
-struct SelfTestResponse;
-struct SelfTestResponseBuilder;
-
struct HostAddress;
struct MessageContainer;
@@ -83,36 +74,27 @@ struct MessageContainerBuilder;
/// An enum describing the setting type.
enum class Setting : int8_t {
LOCATION = 0,
- WIFI_AVAILABLE = 1,
- AIRPLANE_MODE = 2,
- MICROPHONE = 3,
MIN = LOCATION,
- MAX = MICROPHONE
+ MAX = LOCATION
};
-inline const Setting (&EnumValuesSetting())[4] {
+inline const Setting (&EnumValuesSetting())[1] {
static const Setting values[] = {
- Setting::LOCATION,
- Setting::WIFI_AVAILABLE,
- Setting::AIRPLANE_MODE,
- Setting::MICROPHONE
+ Setting::LOCATION
};
return values;
}
inline const char * const *EnumNamesSetting() {
- static const char * const names[5] = {
+ static const char * const names[2] = {
"LOCATION",
- "WIFI_AVAILABLE",
- "AIRPLANE_MODE",
- "MICROPHONE",
nullptr
};
return names;
}
inline const char *EnumNameSetting(Setting e) {
- if (flatbuffers::IsOutRange(e, Setting::LOCATION, Setting::MICROPHONE)) return "";
+ if (flatbuffers::IsOutRange(e, Setting::LOCATION, Setting::LOCATION)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesSetting()[index];
}
@@ -170,14 +152,11 @@ enum class ChreMessage : uint8_t {
LowPowerMicAccessRequest = 16,
LowPowerMicAccessRelease = 17,
SettingChangeMessage = 18,
- LogMessageV2 = 19,
- SelfTestRequest = 20,
- SelfTestResponse = 21,
MIN = NONE,
- MAX = SelfTestResponse
+ MAX = SettingChangeMessage
};
-inline const ChreMessage (&EnumValuesChreMessage())[22] {
+inline const ChreMessage (&EnumValuesChreMessage())[19] {
static const ChreMessage values[] = {
ChreMessage::NONE,
ChreMessage::NanoappMessage,
@@ -197,16 +176,13 @@ inline const ChreMessage (&EnumValuesChreMessage())[22] {
ChreMessage::TimeSyncRequest,
ChreMessage::LowPowerMicAccessRequest,
ChreMessage::LowPowerMicAccessRelease,
- ChreMessage::SettingChangeMessage,
- ChreMessage::LogMessageV2,
- ChreMessage::SelfTestRequest,
- ChreMessage::SelfTestResponse
+ ChreMessage::SettingChangeMessage
};
return values;
}
inline const char * const *EnumNamesChreMessage() {
- static const char * const names[23] = {
+ static const char * const names[20] = {
"NONE",
"NanoappMessage",
"HubInfoRequest",
@@ -226,16 +202,13 @@ inline const char * const *EnumNamesChreMessage() {
"LowPowerMicAccessRequest",
"LowPowerMicAccessRelease",
"SettingChangeMessage",
- "LogMessageV2",
- "SelfTestRequest",
- "SelfTestResponse",
nullptr
};
return names;
}
inline const char *EnumNameChreMessage(ChreMessage e) {
- if (flatbuffers::IsOutRange(e, ChreMessage::NONE, ChreMessage::SelfTestResponse)) return "";
+ if (flatbuffers::IsOutRange(e, ChreMessage::NONE, ChreMessage::SettingChangeMessage)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesChreMessage()[index];
}
@@ -316,18 +289,6 @@ template<> struct ChreMessageTraits<chre::fbs::SettingChangeMessage> {
static const ChreMessage enum_value = ChreMessage::SettingChangeMessage;
};
-template<> struct ChreMessageTraits<chre::fbs::LogMessageV2> {
- static const ChreMessage enum_value = ChreMessage::LogMessageV2;
-};
-
-template<> struct ChreMessageTraits<chre::fbs::SelfTestRequest> {
- static const ChreMessage enum_value = ChreMessage::SelfTestRequest;
-};
-
-template<> struct ChreMessageTraits<chre::fbs::SelfTestResponse> {
- static const ChreMessage enum_value = ChreMessage::SelfTestResponse;
-};
-
bool VerifyChreMessage(flatbuffers::Verifier &verifier, const void *obj, ChreMessage type);
bool VerifyChreMessageVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
@@ -355,9 +316,7 @@ struct NanoappMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_APP_ID = 4,
VT_MESSAGE_TYPE = 6,
VT_HOST_ENDPOINT = 8,
- VT_MESSAGE = 10,
- VT_MESSAGE_PERMISSIONS = 12,
- VT_PERMISSIONS = 14
+ VT_MESSAGE = 10
};
uint64_t app_id() const {
return GetField<uint64_t>(VT_APP_ID, 0);
@@ -375,19 +334,6 @@ struct NanoappMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::Vector<uint8_t> *message() const {
return GetPointer<const flatbuffers::Vector<uint8_t> *>(VT_MESSAGE);
}
- /// List of Android permissions that cover the contents of a message from a
- /// nanoapp to the host.
- /// These permissions are used to record and attribute access to
- /// permissions-controlled resources.
- uint32_t message_permissions() const {
- return GetField<uint32_t>(VT_MESSAGE_PERMISSIONS, 0);
- }
- /// List of Android permissions declared by the nanoapp / granted to the host.
- /// For messages from a nanoaapp to the host, this must be a superset of
- /// message_permissions.
- uint32_t permissions() const {
- return GetField<uint32_t>(VT_PERMISSIONS, 0);
- }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint64_t>(verifier, VT_APP_ID) &&
@@ -395,8 +341,6 @@ struct NanoappMessage FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VerifyField<uint16_t>(verifier, VT_HOST_ENDPOINT) &&
VerifyOffsetRequired(verifier, VT_MESSAGE) &&
verifier.VerifyVector(message()) &&
- VerifyField<uint32_t>(verifier, VT_MESSAGE_PERMISSIONS) &&
- VerifyField<uint32_t>(verifier, VT_PERMISSIONS) &&
verifier.EndTable();
}
};
@@ -417,12 +361,6 @@ struct NanoappMessageBuilder {
void add_message(flatbuffers::Offset<flatbuffers::Vector<uint8_t>> message) {
fbb_.AddOffset(NanoappMessage::VT_MESSAGE, message);
}
- void add_message_permissions(uint32_t message_permissions) {
- fbb_.AddElement<uint32_t>(NanoappMessage::VT_MESSAGE_PERMISSIONS, message_permissions, 0);
- }
- void add_permissions(uint32_t permissions) {
- fbb_.AddElement<uint32_t>(NanoappMessage::VT_PERMISSIONS, permissions, 0);
- }
explicit NanoappMessageBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -441,13 +379,9 @@ inline flatbuffers::Offset<NanoappMessage> CreateNanoappMessage(
uint64_t app_id = 0,
uint32_t message_type = 0,
uint16_t host_endpoint = 65534,
- flatbuffers::Offset<flatbuffers::Vector<uint8_t>> message = 0,
- uint32_t message_permissions = 0,
- uint32_t permissions = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<uint8_t>> message = 0) {
NanoappMessageBuilder builder_(_fbb);
builder_.add_app_id(app_id);
- builder_.add_permissions(permissions);
- builder_.add_message_permissions(message_permissions);
builder_.add_message(message);
builder_.add_message_type(message_type);
builder_.add_host_endpoint(host_endpoint);
@@ -459,18 +393,14 @@ inline flatbuffers::Offset<NanoappMessage> CreateNanoappMessageDirect(
uint64_t app_id = 0,
uint32_t message_type = 0,
uint16_t host_endpoint = 65534,
- const std::vector<uint8_t> *message = nullptr,
- uint32_t message_permissions = 0,
- uint32_t permissions = 0) {
+ const std::vector<uint8_t> *message = nullptr) {
auto message__ = message ? _fbb.CreateVector<uint8_t>(*message) : 0;
return chre::fbs::CreateNanoappMessage(
_fbb,
app_id,
message_type,
host_endpoint,
- message__,
- message_permissions,
- permissions);
+ message__);
}
struct HubInfoRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -737,8 +667,7 @@ struct NanoappListEntry FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_APP_ID = 4,
VT_VERSION = 6,
VT_ENABLED = 8,
- VT_IS_SYSTEM = 10,
- VT_PERMISSIONS = 12
+ VT_IS_SYSTEM = 10
};
uint64_t app_id() const {
return GetField<uint64_t>(VT_APP_ID, 0);
@@ -756,18 +685,12 @@ struct NanoappListEntry FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
bool is_system() const {
return GetField<uint8_t>(VT_IS_SYSTEM, 0) != 0;
}
- /// Nanoapp permissions, if supported. Nanoapp permissions are required on
- /// CHRE API v1.5+, and are defined in chre/util/system/napp_permissions.h
- uint32_t permissions() const {
- return GetField<uint32_t>(VT_PERMISSIONS, 0);
- }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint64_t>(verifier, VT_APP_ID) &&
VerifyField<uint32_t>(verifier, VT_VERSION) &&
VerifyField<uint8_t>(verifier, VT_ENABLED) &&
VerifyField<uint8_t>(verifier, VT_IS_SYSTEM) &&
- VerifyField<uint32_t>(verifier, VT_PERMISSIONS) &&
verifier.EndTable();
}
};
@@ -788,9 +711,6 @@ struct NanoappListEntryBuilder {
void add_is_system(bool is_system) {
fbb_.AddElement<uint8_t>(NanoappListEntry::VT_IS_SYSTEM, static_cast<uint8_t>(is_system), 0);
}
- void add_permissions(uint32_t permissions) {
- fbb_.AddElement<uint32_t>(NanoappListEntry::VT_PERMISSIONS, permissions, 0);
- }
explicit NanoappListEntryBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -808,11 +728,9 @@ inline flatbuffers::Offset<NanoappListEntry> CreateNanoappListEntry(
uint64_t app_id = 0,
uint32_t version = 0,
bool enabled = true,
- bool is_system = false,
- uint32_t permissions = 0) {
+ bool is_system = false) {
NanoappListEntryBuilder builder_(_fbb);
builder_.add_app_id(app_id);
- builder_.add_permissions(permissions);
builder_.add_version(version);
builder_.add_is_system(is_system);
builder_.add_enabled(enabled);
@@ -921,9 +839,7 @@ struct LoadNanoappRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_APP_BINARY = 12,
VT_FRAGMENT_ID = 14,
VT_TOTAL_APP_SIZE = 16,
- VT_APP_BINARY_FILE_NAME = 18,
- VT_APP_FLAGS = 20,
- VT_RESPOND_BEFORE_START = 22
+ VT_APP_BINARY_FILE_NAME = 18
};
uint32_t transaction_id() const {
return GetField<uint32_t>(VT_TRANSACTION_ID, 0);
@@ -955,18 +871,6 @@ struct LoadNanoappRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::Vector<int8_t> *app_binary_file_name() const {
return GetPointer<const flatbuffers::Vector<int8_t> *>(VT_APP_BINARY_FILE_NAME);
}
- /// The nanoapp flag values from the nanoapp header defined in
- /// build/build_template.mk. Refer to that file for more details.
- uint32_t app_flags() const {
- return GetField<uint32_t>(VT_APP_FLAGS, 0);
- }
- /// If true and fragmented loading is requested, the LoadNanoappResponse
- /// for the last fragment will be sent after the fragment was confirmed
- /// to be placed in memory and no additional response will be sent after
- /// the nanoapp is linked and started in the framework.
- bool respond_before_start() const {
- return GetField<uint8_t>(VT_RESPOND_BEFORE_START, 0) != 0;
- }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint32_t>(verifier, VT_TRANSACTION_ID) &&
@@ -979,8 +883,6 @@ struct LoadNanoappRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VerifyField<uint32_t>(verifier, VT_TOTAL_APP_SIZE) &&
VerifyOffset(verifier, VT_APP_BINARY_FILE_NAME) &&
verifier.VerifyVector(app_binary_file_name()) &&
- VerifyField<uint32_t>(verifier, VT_APP_FLAGS) &&
- VerifyField<uint8_t>(verifier, VT_RESPOND_BEFORE_START) &&
verifier.EndTable();
}
};
@@ -1013,12 +915,6 @@ struct LoadNanoappRequestBuilder {
void add_app_binary_file_name(flatbuffers::Offset<flatbuffers::Vector<int8_t>> app_binary_file_name) {
fbb_.AddOffset(LoadNanoappRequest::VT_APP_BINARY_FILE_NAME, app_binary_file_name);
}
- void add_app_flags(uint32_t app_flags) {
- fbb_.AddElement<uint32_t>(LoadNanoappRequest::VT_APP_FLAGS, app_flags, 0);
- }
- void add_respond_before_start(bool respond_before_start) {
- fbb_.AddElement<uint8_t>(LoadNanoappRequest::VT_RESPOND_BEFORE_START, static_cast<uint8_t>(respond_before_start), 0);
- }
explicit LoadNanoappRequestBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -1041,12 +937,9 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequest(
flatbuffers::Offset<flatbuffers::Vector<uint8_t>> app_binary = 0,
uint32_t fragment_id = 0,
uint32_t total_app_size = 0,
- flatbuffers::Offset<flatbuffers::Vector<int8_t>> app_binary_file_name = 0,
- uint32_t app_flags = 0,
- bool respond_before_start = false) {
+ flatbuffers::Offset<flatbuffers::Vector<int8_t>> app_binary_file_name = 0) {
LoadNanoappRequestBuilder builder_(_fbb);
builder_.add_app_id(app_id);
- builder_.add_app_flags(app_flags);
builder_.add_app_binary_file_name(app_binary_file_name);
builder_.add_total_app_size(total_app_size);
builder_.add_fragment_id(fragment_id);
@@ -1054,7 +947,6 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequest(
builder_.add_target_api_version(target_api_version);
builder_.add_app_version(app_version);
builder_.add_transaction_id(transaction_id);
- builder_.add_respond_before_start(respond_before_start);
return builder_.Finish();
}
@@ -1067,9 +959,7 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequestDirect(
const std::vector<uint8_t> *app_binary = nullptr,
uint32_t fragment_id = 0,
uint32_t total_app_size = 0,
- const std::vector<int8_t> *app_binary_file_name = nullptr,
- uint32_t app_flags = 0,
- bool respond_before_start = false) {
+ const std::vector<int8_t> *app_binary_file_name = nullptr) {
auto app_binary__ = app_binary ? _fbb.CreateVector<uint8_t>(*app_binary) : 0;
auto app_binary_file_name__ = app_binary_file_name ? _fbb.CreateVector<int8_t>(*app_binary_file_name) : 0;
return chre::fbs::CreateLoadNanoappRequest(
@@ -1081,9 +971,7 @@ inline flatbuffers::Offset<LoadNanoappRequest> CreateLoadNanoappRequestDirect(
app_binary__,
fragment_id,
total_app_size,
- app_binary_file_name__,
- app_flags,
- respond_before_start);
+ app_binary_file_name__);
}
struct LoadNanoappResponse FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -1673,158 +1561,6 @@ inline flatbuffers::Offset<SettingChangeMessage> CreateSettingChangeMessage(
return builder_.Finish();
}
-/// Represents V2 log messages from CHRE.
-struct LogMessageV2 FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
- typedef LogMessageV2Builder Builder;
- enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
- VT_BUFFER = 4,
- VT_NUM_LOGS_DROPPED = 6
- };
- /// A buffer containing formatted log data. A flat array is used here to avoid
- /// overhead in serializing and deserializing. The format is as follows:
- ///
- /// uint8_t - LogBuffer log level (1 = error, 2 = warn,
- /// 3 = info, 4 = debug,
- /// 5 = verbose)
- /// uint32_t, little-endian - timestamp in milliseconds
- /// char[] - message to log
- /// char, \0 - null-terminator
- ///
- /// This pattern repeats until the end of the buffer for multiple log
- /// messages. The last byte will always be a null-terminator. There are no
- /// padding bytes between these fields. Treat this like a packed struct and be
- /// cautious with unaligned access when reading/writing this buffer.
- const flatbuffers::Vector<int8_t> *buffer() const {
- return GetPointer<const flatbuffers::Vector<int8_t> *>(VT_BUFFER);
- }
- /// The number of logs dropped since CHRE started
- uint32_t num_logs_dropped() const {
- return GetField<uint32_t>(VT_NUM_LOGS_DROPPED, 0);
- }
- bool Verify(flatbuffers::Verifier &verifier) const {
- return VerifyTableStart(verifier) &&
- VerifyOffset(verifier, VT_BUFFER) &&
- verifier.VerifyVector(buffer()) &&
- VerifyField<uint32_t>(verifier, VT_NUM_LOGS_DROPPED) &&
- verifier.EndTable();
- }
-};
-
-struct LogMessageV2Builder {
- typedef LogMessageV2 Table;
- flatbuffers::FlatBufferBuilder &fbb_;
- flatbuffers::uoffset_t start_;
- void add_buffer(flatbuffers::Offset<flatbuffers::Vector<int8_t>> buffer) {
- fbb_.AddOffset(LogMessageV2::VT_BUFFER, buffer);
- }
- void add_num_logs_dropped(uint32_t num_logs_dropped) {
- fbb_.AddElement<uint32_t>(LogMessageV2::VT_NUM_LOGS_DROPPED, num_logs_dropped, 0);
- }
- explicit LogMessageV2Builder(flatbuffers::FlatBufferBuilder &_fbb)
- : fbb_(_fbb) {
- start_ = fbb_.StartTable();
- }
- LogMessageV2Builder &operator=(const LogMessageV2Builder &);
- flatbuffers::Offset<LogMessageV2> Finish() {
- const auto end = fbb_.EndTable(start_);
- auto o = flatbuffers::Offset<LogMessageV2>(end);
- return o;
- }
-};
-
-inline flatbuffers::Offset<LogMessageV2> CreateLogMessageV2(
- flatbuffers::FlatBufferBuilder &_fbb,
- flatbuffers::Offset<flatbuffers::Vector<int8_t>> buffer = 0,
- uint32_t num_logs_dropped = 0) {
- LogMessageV2Builder builder_(_fbb);
- builder_.add_num_logs_dropped(num_logs_dropped);
- builder_.add_buffer(buffer);
- return builder_.Finish();
-}
-
-inline flatbuffers::Offset<LogMessageV2> CreateLogMessageV2Direct(
- flatbuffers::FlatBufferBuilder &_fbb,
- const std::vector<int8_t> *buffer = nullptr,
- uint32_t num_logs_dropped = 0) {
- auto buffer__ = buffer ? _fbb.CreateVector<int8_t>(*buffer) : 0;
- return chre::fbs::CreateLogMessageV2(
- _fbb,
- buffer__,
- num_logs_dropped);
-}
-
-struct SelfTestRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
- typedef SelfTestRequestBuilder Builder;
- bool Verify(flatbuffers::Verifier &verifier) const {
- return VerifyTableStart(verifier) &&
- verifier.EndTable();
- }
-};
-
-struct SelfTestRequestBuilder {
- typedef SelfTestRequest Table;
- flatbuffers::FlatBufferBuilder &fbb_;
- flatbuffers::uoffset_t start_;
- explicit SelfTestRequestBuilder(flatbuffers::FlatBufferBuilder &_fbb)
- : fbb_(_fbb) {
- start_ = fbb_.StartTable();
- }
- SelfTestRequestBuilder &operator=(const SelfTestRequestBuilder &);
- flatbuffers::Offset<SelfTestRequest> Finish() {
- const auto end = fbb_.EndTable(start_);
- auto o = flatbuffers::Offset<SelfTestRequest>(end);
- return o;
- }
-};
-
-inline flatbuffers::Offset<SelfTestRequest> CreateSelfTestRequest(
- flatbuffers::FlatBufferBuilder &_fbb) {
- SelfTestRequestBuilder builder_(_fbb);
- return builder_.Finish();
-}
-
-struct SelfTestResponse FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
- typedef SelfTestResponseBuilder Builder;
- enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
- VT_SUCCESS = 4
- };
- bool success() const {
- return GetField<uint8_t>(VT_SUCCESS, 0) != 0;
- }
- bool Verify(flatbuffers::Verifier &verifier) const {
- return VerifyTableStart(verifier) &&
- VerifyField<uint8_t>(verifier, VT_SUCCESS) &&
- verifier.EndTable();
- }
-};
-
-struct SelfTestResponseBuilder {
- typedef SelfTestResponse Table;
- flatbuffers::FlatBufferBuilder &fbb_;
- flatbuffers::uoffset_t start_;
- void add_success(bool success) {
- fbb_.AddElement<uint8_t>(SelfTestResponse::VT_SUCCESS, static_cast<uint8_t>(success), 0);
- }
- explicit SelfTestResponseBuilder(flatbuffers::FlatBufferBuilder &_fbb)
- : fbb_(_fbb) {
- start_ = fbb_.StartTable();
- }
- SelfTestResponseBuilder &operator=(const SelfTestResponseBuilder &);
- flatbuffers::Offset<SelfTestResponse> Finish() {
- const auto end = fbb_.EndTable(start_);
- auto o = flatbuffers::Offset<SelfTestResponse>(end);
- return o;
- }
-};
-
-inline flatbuffers::Offset<SelfTestResponse> CreateSelfTestResponse(
- flatbuffers::FlatBufferBuilder &_fbb,
- bool success = false) {
- SelfTestResponseBuilder builder_(_fbb);
- builder_.add_success(success);
- return builder_.Finish();
-}
-
/// The top-level container that encapsulates all possible messages. Note that
/// per FlatBuffers requirements, we can't use a union as the top-level
/// structure (root type), so we must wrap it in a table.
@@ -1896,15 +1632,6 @@ struct MessageContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const chre::fbs::SettingChangeMessage *message_as_SettingChangeMessage() const {
return message_type() == chre::fbs::ChreMessage::SettingChangeMessage ? static_cast<const chre::fbs::SettingChangeMessage *>(message()) : nullptr;
}
- const chre::fbs::LogMessageV2 *message_as_LogMessageV2() const {
- return message_type() == chre::fbs::ChreMessage::LogMessageV2 ? static_cast<const chre::fbs::LogMessageV2 *>(message()) : nullptr;
- }
- const chre::fbs::SelfTestRequest *message_as_SelfTestRequest() const {
- return message_type() == chre::fbs::ChreMessage::SelfTestRequest ? static_cast<const chre::fbs::SelfTestRequest *>(message()) : nullptr;
- }
- const chre::fbs::SelfTestResponse *message_as_SelfTestResponse() const {
- return message_type() == chre::fbs::ChreMessage::SelfTestResponse ? static_cast<const chre::fbs::SelfTestResponse *>(message()) : nullptr;
- }
/// The originating or destination client ID on the host side, used to direct
/// responses only to the client that sent the request. Although initially
/// populated by the requesting client, this is enforced to be the correct
@@ -1996,18 +1723,6 @@ template<> inline const chre::fbs::SettingChangeMessage *MessageContainer::messa
return message_as_SettingChangeMessage();
}
-template<> inline const chre::fbs::LogMessageV2 *MessageContainer::message_as<chre::fbs::LogMessageV2>() const {
- return message_as_LogMessageV2();
-}
-
-template<> inline const chre::fbs::SelfTestRequest *MessageContainer::message_as<chre::fbs::SelfTestRequest>() const {
- return message_as_SelfTestRequest();
-}
-
-template<> inline const chre::fbs::SelfTestResponse *MessageContainer::message_as<chre::fbs::SelfTestResponse>() const {
- return message_as_SelfTestResponse();
-}
-
struct MessageContainerBuilder {
typedef MessageContainer Table;
flatbuffers::FlatBufferBuilder &fbb_;
@@ -2124,18 +1839,6 @@ inline bool VerifyChreMessage(flatbuffers::Verifier &verifier, const void *obj,
auto ptr = reinterpret_cast<const chre::fbs::SettingChangeMessage *>(obj);
return verifier.VerifyTable(ptr);
}
- case ChreMessage::LogMessageV2: {
- auto ptr = reinterpret_cast<const chre::fbs::LogMessageV2 *>(obj);
- return verifier.VerifyTable(ptr);
- }
- case ChreMessage::SelfTestRequest: {
- auto ptr = reinterpret_cast<const chre::fbs::SelfTestRequest *>(obj);
- return verifier.VerifyTable(ptr);
- }
- case ChreMessage::SelfTestResponse: {
- auto ptr = reinterpret_cast<const chre::fbs::SelfTestResponse *>(obj);
- return verifier.VerifyTable(ptr);
- }
default: return true;
}
}
diff --git a/platform/shared/include/chre/platform/shared/host_protocol_chre.h b/platform/shared/include/chre/platform/shared/host_protocol_chre.h
index eb6a0a0d..ae6c6345 100644
--- a/platform/shared/include/chre/platform/shared/host_protocol_chre.h
+++ b/platform/shared/include/chre/platform/shared/host_protocol_chre.h
@@ -19,11 +19,8 @@
#include <stdint.h>
-#include "chre/core/settings.h"
#include "chre/platform/shared/generated/host_messages_generated.h"
#include "chre/platform/shared/host_protocol_common.h"
-#include "chre/util/dynamic_vector.h"
-#include "chre/util/flatbuffers/helpers.h"
#include "flatbuffers/flatbuffers.h"
namespace chre {
@@ -60,9 +57,9 @@ class HostMessageHandlers {
static void handleLoadNanoappRequest(
uint16_t hostClientId, uint32_t transactionId, uint64_t appId,
- uint32_t appVersion, uint32_t appFlags, uint32_t targetApiVersion,
- const void *buffer, size_t bufferLen, const char *appFileName,
- uint32_t fragmentId, size_t appBinaryLen, bool respondBeforeStart);
+ uint32_t appVersion, uint32_t targetApiVersion, const void *buffer,
+ size_t bufferLen, const char *appFileName, uint32_t fragmentId,
+ size_t appBinaryLen);
static void handleUnloadNanoappRequest(uint16_t hostClientId,
uint32_t transactionId, uint64_t appId,
@@ -74,8 +71,6 @@ class HostMessageHandlers {
static void handleSettingChangeMessage(fbs::Setting setting,
fbs::SettingState state);
-
- static void handleSelfTestRequest(uint16_t hostClientId);
};
/**
@@ -99,12 +94,12 @@ class HostProtocolChre : public HostProtocolCommon {
/**
* Refer to the context hub HAL definition for a details of these parameters.
*
- * @param builder A newly constructed ChreFlatBufferBuilder that will be used
- * to encode the message
+ * @param builder A newly constructed FlatBufferBuilder that will be used to
+ * encode the message
*/
static void encodeHubInfoResponse(
- ChreFlatBufferBuilder &builder, const char *name, const char *vendor,
- const char *toolchain, uint32_t legacyPlatformVersion,
+ flatbuffers::FlatBufferBuilder &builder, const char *name,
+ const char *vendor, const char *toolchain, uint32_t legacyPlatformVersion,
uint32_t legacyToolchainVersion, float peakMips, float stoppedPower,
float sleepPower, float peakPower, uint32_t maxMessageLen,
uint64_t platformId, uint32_t version, uint16_t hostClientId);
@@ -115,36 +110,35 @@ class HostProtocolChre : public HostProtocolCommon {
* maintained in the given vector until finishNanoappListResponse() is called.
* Example usage:
*
- * ChreFlatBufferBuilder builder;
+ * FlatBufferBuilder builder;
* DynamicVector<NanoappListEntryOffset> vector;
* for (auto app : appList) {
* HostProtocolChre::addNanoppListEntry(builder, vector, ...);
* }
* HostProtocolChre::finishNanoappListResponse(builder, vector);
*
- * @param builder A ChreFlatBufferBuilder to use for encoding the message
+ * @param builder A FlatBufferBuilder to use for encoding the message
* @param offsetVector A vector to track the offset to the newly added
* NanoappListEntry, which be passed to finishNanoappListResponse()
* once all entries are added
*/
static void addNanoappListEntry(
- ChreFlatBufferBuilder &builder,
+ flatbuffers::FlatBufferBuilder &builder,
DynamicVector<NanoappListEntryOffset> &offsetVector, uint64_t appId,
- uint32_t appVersion, bool enabled, bool isSystemNanoapp,
- uint32_t appPermissions);
+ uint32_t appVersion, bool enabled, bool isSystemNanoapp);
/**
* Finishes encoding a NanoappListResponse message after all NanoappListEntry
* elements have already been added to the builder.
*
- * @param builder The ChreFlatBufferBuilder used with addNanoappListEntry()
+ * @param builder The FlatBufferBuilder used with addNanoappListEntry()
* @param offsetVector The vector used with addNanoappListEntry()
* @param hostClientId
*
* @see addNanoappListEntry()
*/
static void finishNanoappListResponse(
- ChreFlatBufferBuilder &builder,
+ flatbuffers::FlatBufferBuilder &builder,
DynamicVector<NanoappListEntryOffset> &offsetVector,
uint16_t hostClientId);
@@ -152,7 +146,7 @@ class HostProtocolChre : public HostProtocolCommon {
* Encodes a response to the host communicating the result of dynamically
* loading a nanoapp.
*/
- static void encodeLoadNanoappResponse(ChreFlatBufferBuilder &builder,
+ static void encodeLoadNanoappResponse(flatbuffers::FlatBufferBuilder &builder,
uint16_t hostClientId,
uint32_t transactionId, bool success,
uint32_t fragmentId);
@@ -161,22 +155,15 @@ class HostProtocolChre : public HostProtocolCommon {
* Encodes a response to the host communicating the result of dynamically
* unloading a nanoapp.
*/
- static void encodeUnloadNanoappResponse(ChreFlatBufferBuilder &builder,
- uint16_t hostClientId,
- uint32_t transactionId, bool success);
+ static void encodeUnloadNanoappResponse(
+ flatbuffers::FlatBufferBuilder &builder, uint16_t hostClientId,
+ uint32_t transactionId, bool success);
/**
* Encodes a buffer of log messages to the host.
*/
- static void encodeLogMessages(ChreFlatBufferBuilder &builder,
- const uint8_t *logBuffer, size_t bufferSize);
-
- /**
- * Encodes a buffer of V2 log messages to the host.
- */
- static void encodeLogMessagesV2(ChreFlatBufferBuilder &builder,
- const uint8_t *logBuffer, size_t bufferSize,
- uint32_t numLogsDropped);
+ static void encodeLogMessages(flatbuffers::FlatBufferBuilder &builder,
+ const char *logBuffer, size_t bufferSize);
/**
* Encodes a string into a DebugDumpData message.
@@ -184,58 +171,35 @@ class HostProtocolChre : public HostProtocolCommon {
* @param debugStr Null-terminated ASCII string containing debug information
* @param debugStrSize Size of the debugStr buffer, including null termination
*/
- static void encodeDebugDumpData(ChreFlatBufferBuilder &builder,
+ static void encodeDebugDumpData(flatbuffers::FlatBufferBuilder &builder,
uint16_t hostClientId, const char *debugStr,
size_t debugStrSize);
/**
* Encodes the final response to a debug dump request.
*/
- static void encodeDebugDumpResponse(ChreFlatBufferBuilder &builder,
+ static void encodeDebugDumpResponse(flatbuffers::FlatBufferBuilder &builder,
uint16_t hostClientId, bool success,
uint32_t dataCount);
/**
* Encodes a message requesting time sync from host.
*/
- static void encodeTimeSyncRequest(ChreFlatBufferBuilder &builder);
+ static void encodeTimeSyncRequest(flatbuffers::FlatBufferBuilder &builder);
/**
* Encodes a message notifying the host that audio has been requested by a
* nanoapp, so the low-power microphone needs to be powered on.
*/
- static void encodeLowPowerMicAccessRequest(ChreFlatBufferBuilder &builder);
+ static void encodeLowPowerMicAccessRequest(
+ flatbuffers::FlatBufferBuilder &builder);
/**
* Encodes a message notifying the host that no nanoapps are requesting audio
* anymore, so the low-power microphone may be powered off.
*/
- static void encodeLowPowerMicAccessRelease(ChreFlatBufferBuilder &builder);
-
- /**
- * @param state The fbs::Setting value.
- * @param chreSetting If success, stores the corresponding
- * chre::Setting value.
- *
- * @return true if state was a valid fbs::Setting value.
- */
- static bool getSettingFromFbs(fbs::Setting setting, Setting *chreSetting);
-
- /**
- * @param state The fbs::SettingState value.
- * @param chreSettingState If success, stores the corresponding
- * chre::SettingState value.
- *
- * @return true if state was a valid fbs::SettingState value.
- */
- static bool getSettingStateFromFbs(fbs::SettingState state,
- SettingState *chreSettingState);
-
- /**
- * Encodes a message notifying the result of a self test.
- */
- static void encodeSelfTestResponse(ChreFlatBufferBuilder &builder,
- uint16_t hostClientId, bool success);
+ static void encodeLowPowerMicAccessRelease(
+ flatbuffers::FlatBufferBuilder &builder);
};
} // namespace chre
diff --git a/platform/shared/include/chre/platform/shared/host_protocol_common.h b/platform/shared/include/chre/platform/shared/host_protocol_common.h
index abb9baa6..6ee9bcf8 100644
--- a/platform/shared/include/chre/platform/shared/host_protocol_common.h
+++ b/platform/shared/include/chre/platform/shared/host_protocol_common.h
@@ -19,7 +19,6 @@
#include <stdint.h>
-#include "chre/util/system/napp_permissions.h"
#include "flatbuffers/flatbuffers.h"
namespace chre {
@@ -47,37 +46,18 @@ constexpr uint16_t kHostClientIdUnspecified = 0;
class HostProtocolCommon {
public:
/**
- * Encodes a message between a nanoapp and a host (in both directions) using
- * the given FlatBufferBuilder and supplied parameters.
- * Note that messagePermissions is only applicable to messages from a nanoapp
- * to the host.
+ * Encodes a message to/from a nanoapp using the given FlatBufferBuilder and
+ * supplied parameters.
*
* @param builder A newly constructed FlatBufferBuilder that will be used to
* encode the message. It will be finalized before returning from this
* function.
- * @param appId Nanoapp ID.
- * @param messageType Type of message that was constructed.
- * @param hostEndpoint The host endpoint the data was sent from or that should
- * receive this message.
- * @param messageData Pointer to message payload. Can be null if
- * messageDataLen is zero.
- * @param messageDataLen Size of messageData, in bytes.
- * @param permissions List of Android permissions declared by the nanoapp or
- * granted to the host. For from the nanoapp to the host messages, this
- * must be a superset of messagePermissions.
- * @param messagePermissions Used only for messages from the nanoapp to the
- * host. Lists the Android permissions covering the contents of the
- * message. These permissions are used to record and attribute access
- * to permissions-controlled resources.
*/
- static void encodeNanoappMessage(
- flatbuffers::FlatBufferBuilder &builder, uint64_t appId,
- uint32_t messageType, uint16_t hostEndpoint, const void *messageData,
- size_t messageDataLen,
- uint32_t permissions =
- static_cast<uint32_t>(chre::NanoappPermissions::CHRE_PERMS_ALL),
- uint32_t messagePermissions =
- static_cast<uint32_t>(chre::NanoappPermissions::CHRE_PERMS_ALL));
+ static void encodeNanoappMessage(flatbuffers::FlatBufferBuilder &builder,
+ uint64_t appId, uint32_t messageType,
+ uint16_t hostEndpoint,
+ const void *messageData,
+ size_t messageDataLen);
/**
* Adds a string to the provided builder as a byte vector.
diff --git a/platform/shared/include/chre/platform/shared/libc/dlfcn.h b/platform/shared/include/chre/platform/shared/libc/dlfcn.h
deleted file mode 100644
index 97583783..00000000
--- a/platform/shared/include/chre/platform/shared/libc/dlfcn.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SHARED_DLFCN_H_
-#define CHRE_PLATFORM_SHARED_DLFCN_H_
-
-//! This file is intended to be used when a platform doesn't provide a dlfcn.h
-//! implementation so that dynamic loading support can be provided to nanoapps.
-
-#include <cstdlib>
-
-//! Indicates that the dlsym call is attempting to lookup the provided symbol
-//! in another library (CHRE).
-#ifndef RTLD_NEXT
-#define RTLD_NEXT ((void *)-1L)
-#endif // RTLD_NEXT
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * This function parses, verifies, and loads a buffer containing an ELF
- * file, and returns an opaque handle for symbol lookup via dlsym.
- * Note that there is no requirement to pass in a 'buffer size' argument,
- * since all the necessary information is gathered from the headers
- * embedded in the elf file itself. The buffer is expected to contain the
- * entire elf file in memory (cannot be a FILE pointer, for example).
- *
- * @param elfBinary is a buffer containing the elf file
- * @param mapIntoTcm Indicates whether the elfBinary should be mapped into
- * tightly coupled memory.
- */
-void *dlopenbuf(void *elfBinary, bool mapIntoTcm);
-
-/**
- * Returns a (function) pointer to the symbol named by the input argument.
- *
- * @return pointer to the symbol if it was found, nullptr if not found or
- * the handle was invalid
- */
-void *dlsym(void *handle, const char *symbol);
-
-/**
- * Invalidate the handle used for symbol lookup, and free up any
- * allocated memory.
- *
- * @return 0 on success
- */
-int dlclose(void *handle);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CHRE_PLATFORM_SHARED_DLFCN_H_
diff --git a/platform/shared/include/chre/platform/shared/loader_util.h b/platform/shared/include/chre/platform/shared/loader_util.h
deleted file mode 100644
index 8e334287..00000000
--- a/platform/shared/include/chre/platform/shared/loader_util.h
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SHARED_LOADER_UTIL_H_
-#define CHRE_PLATFORM_SHARED_LOADER_UTIL_H_
-
-// The below macros allow switching the ELF symbol type between 32/64-bit
-// depending on what the chipset supports.
-#ifndef ELFW
-#ifndef __WORDSIZE
-// Until we can get a hold of wordsize.h, we need to define it here.
-// Only 32-bit architectures currently supported.
-#ifndef __aarch64__
-#define __WORDSIZE 32
-#else
-#error "Only 32-bit architectures currently supported"
-#endif
-#endif
-// https://refspecs.linuxbase.org/elf/gabi4+/ch4.reloc.html
-#define ELF32_R_SYM(info) ((info) >> 8)
-#define ELF32_R_TYPE(info) ((unsigned char)(info))
-#define ELF32_R_INFO(sym, type) (((sym) << 8) + (unsigned char)(type))
-#define __ELF_NATIVE_CLASS __WORDSIZE
-#define ELFW(type) _ELFW(__ELF_NATIVE_CLASS, type)
-#define _ELFW(bits, type) __ELFW(bits, type)
-#define __ELFW(bits, type) ELF##bits##_##type
-#endif
-#define ELFW_R_TYPE(x) ELFW(R_TYPE)(x)
-#define ELFW_R_SYM(x) ELFW(R_SYM)(x)
-
-struct ExportedData {
- void *data;
- const char *dataName;
-};
-
-// The below is copied from bionic/libc/kernel/uapi/linux/elf.h
-// to avoid pulling those deps into the build.
-#if defined(__LP64__)
-#define ElfW(type) Elf64_##type
-#else
-#define ElfW(type) Elf32_##type
-#endif
-
-#define EM_ARM 40
-#define EI_MAG0 0
-#define EI_MAG1 1
-#define EI_MAG2 2
-#define EI_MAG3 3
-#define EI_CLASS 4
-#define EI_DATA 5
-#define EI_VERSION 6
-#define EI_OSABI 7
-#define EI_PAD 8
-#define ELFMAG0 0x7f
-#define ELFMAG1 'E'
-#define ELFMAG2 'L'
-#define ELFMAG3 'F'
-#define ELFMAG "\177ELF"
-#define SELFMAG 4
-#define ELFCLASSNONE 0
-#define ELFCLASS32 1
-#define ELFCLASS64 2
-#define ELFCLASSNUM 3
-#define ELFDATANONE 0
-#define ELFDATA2LSB 1
-#define ELFDATA2MSB 2
-#define EV_NONE 0
-#define EV_CURRENT 1
-#define EV_NUM 2
-#define ELFOSABI_NONE 0
-#define ELFOSABI_LINUX 3
-#define PT_NULL 0
-#define PT_LOAD 1
-#define PT_DYNAMIC 2
-#define PT_INTERP 3
-#define PT_NOTE 4
-#define PT_SHLIB 5
-#define PT_PHDR 6
-#define PT_TLS 7
-#define PT_LOOS 0x60000000
-#define PT_HIOS 0x6fffffff
-#define PT_LOPROC 0x70000000
-#define PT_HIPROC 0x7fffffff
-#define PT_GNU_EH_FRAME 0x6474e550
-#define PT_GNU_STACK (PT_LOOS + 0x474e551)
-#define PN_XNUM 0xffff
-#define ET_NONE 0
-#define ET_REL 1
-#define ET_EXEC 2
-#define ET_DYN 3
-#define ET_CORE 4
-#define ET_LOPROC 0xff00
-#define ET_HIPROC 0xffff
-#define DT_NULL 0
-#define DT_NEEDED 1
-#define DT_PLTRELSZ 2
-#define DT_PLTGOT 3
-#define DT_HASH 4
-#define DT_STRTAB 5
-#define DT_SYMTAB 6
-#define DT_RELA 7
-#define DT_RELASZ 8
-#define DT_RELAENT 9
-#define DT_STRSZ 10
-#define DT_SYMENT 11
-#define DT_INIT 12
-#define DT_FINI 13
-#define DT_SONAME 14
-#define DT_RPATH 15
-#define DT_SYMBOLIC 16
-#define DT_REL 17
-#define DT_RELSZ 18
-#define DT_RELENT 19
-#define DT_PLTREL 20
-#define DT_DEBUG 21
-#define DT_TEXTREL 22
-#define DT_JMPREL 23
-#define DT_ENCODING 32
-
-typedef __signed__ char __s8;
-typedef unsigned char __u8;
-typedef __signed__ short __s16;
-typedef unsigned short __u16;
-typedef __signed__ int __s32;
-typedef unsigned int __u32;
-typedef __signed__ long __s64;
-typedef unsigned long __u64;
-
-typedef __u32 Elf32_Addr;
-typedef __u16 Elf32_Half;
-typedef __u32 Elf32_Off;
-typedef __s32 Elf32_Sword;
-typedef __u32 Elf32_Word;
-
-#define EI_NIDENT 16
-typedef struct elf32_hdr {
- unsigned char e_ident[EI_NIDENT];
- Elf32_Half e_type;
- Elf32_Half e_machine;
- Elf32_Word e_version;
- Elf32_Addr e_entry;
- Elf32_Off e_phoff;
- Elf32_Off e_shoff;
- Elf32_Word e_flags;
- Elf32_Half e_ehsize;
- Elf32_Half e_phentsize;
- Elf32_Half e_phnum;
- Elf32_Half e_shentsize;
- Elf32_Half e_shnum;
- Elf32_Half e_shstrndx;
-} Elf32_Ehdr;
-
-typedef struct dynamic {
- Elf32_Sword d_tag;
- union {
- Elf32_Sword d_val;
- Elf32_Addr d_ptr;
- } d_un;
-} Elf32_Dyn;
-
-typedef struct elf32_phdr {
- Elf32_Word p_type;
- Elf32_Off p_offset;
- Elf32_Addr p_vaddr;
- Elf32_Addr p_paddr;
- Elf32_Word p_filesz;
- Elf32_Word p_memsz;
- Elf32_Word p_flags;
- Elf32_Word p_align;
-} Elf32_Phdr;
-
-typedef struct elf32_shdr {
- Elf32_Word sh_name;
- Elf32_Word sh_type;
- Elf32_Word sh_flags;
- Elf32_Addr sh_addr;
- Elf32_Off sh_offset;
- Elf32_Word sh_size;
- Elf32_Word sh_link;
- Elf32_Word sh_info;
- Elf32_Word sh_addralign;
- Elf32_Word sh_entsize;
-} Elf32_Shdr;
-
-typedef struct elf32_rela {
- Elf32_Addr r_offset;
- Elf32_Word r_info;
- Elf32_Sword r_addend;
-} Elf32_Rela;
-
-typedef struct elf32_rel {
- Elf32_Addr r_offset;
- Elf32_Word r_info;
-} Elf32_Rel;
-
-typedef struct elf32_sym {
- Elf32_Word st_name;
- Elf32_Addr st_value;
- Elf32_Word st_size;
- unsigned char st_info;
- unsigned char st_other;
- Elf32_Half st_shndx;
-} Elf32_Sym;
-
-// The following defines are copied from bionic's elf_arm.h header
-// at bionic/libc/kernel/uapi/linux/elf.h
-// Only the relocation types currently supported are copied.
-#define R_ARM_NONE 0
-#define R_ARM_ABS32 2
-#define R_ARM_COPY 20
-#define R_ARM_GLOB_DAT 21
-#define R_ARM_JUMP_SLOT 22
-#define R_ARM_RELATIVE 23
-
-// The following (legal values for segment flags) are copied from
-// bionic's elf.h
-/* http://www.sco.com/developers/gabi/latest/ch5.pheader.html */
-#define PF_X 0x1
-#define PF_W 0x2
-#define PF_R 0x4
-#define PF_MASKOS 0x0ff00000
-#define PF_MASKPROC 0xf0000000
-
-#endif // CHRE_PLATFORM_SHARED_LOADER_UTIL_H_
diff --git a/platform/shared/include/chre/platform/shared/log_buffer.h b/platform/shared/include/chre/platform/shared/log_buffer.h
deleted file mode 100644
index 55e166ec..00000000
--- a/platform/shared/include/chre/platform/shared/log_buffer.h
+++ /dev/null
@@ -1,305 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SHARED_LOG_BUFFER_H_
-#define CHRE_PLATFORM_SHARED_LOG_BUFFER_H_
-
-#include <cinttypes>
-#include <cstdarg>
-#include <cstring>
-
-#include "chre/platform/mutex.h"
-
-namespace chre {
-
-/**
- * Values that represent a preferred setting for when the LogBuffer should
- * notify the platform that logs are ready to be copied.
- *
- * ALWAYS - The LogBuffer should immediately notify the platform when a new log
- * is received.
- * NEVER - The LogBuffer should never alert the platform that logs have been
- * received. It is up to the platform to decide when to copy logs out.
- * THRESHOLD - The LogBuffer should notify the platform when a certain thresold
- * of memory has been allocated for logs in the buffer.
- */
-enum class LogBufferNotificationSetting : uint8_t { ALWAYS, NEVER, THRESHOLD };
-
-/**
- * The log level options for logs stored in a log buffer.
- */
-enum class LogBufferLogLevel : uint8_t { ERROR, WARN, INFO, DEBUG, VERBOSE };
-
-// Forward declaration for LogBufferCallbackInterface.
-class LogBuffer;
-
-/**
- * Callback objects that are implemented by the platform code and passed to the
- * log buffer instances are notified of changes in the state of the buffer
- * through this callback interface.
- */
-class LogBufferCallbackInterface {
- public:
- virtual ~LogBufferCallbackInterface() {}
-
- /**
- * Notify the platform code that is using the buffer manager that it should
- * call copyLogs because the buffer internal state has changed to suit the
- * requirements for alerting the platform that logs are ready to be copied
- * out of buffer.
- */
- virtual void onLogsReady() = 0;
-};
-
-/**
- * The class responsible for batching logs in memory until the notification
- * callback is triggered and the platform copies log data out of the buffer.
- */
-class LogBuffer {
- public:
- //! The max size of a single log entry which must fit in a single byte.
- static constexpr size_t kLogMaxSize = UINT8_MAX;
-
- /**
- * @param callback The callback object that will receive notifications about
- * the state of the log buffer or nullptr if it is not needed.
- * @param buffer The buffer location that will store log data.
- * message.
- * @param bufferSize The number of bytes in the buffer. This value must be >
- * kBufferMinSize
- */
- LogBuffer(LogBufferCallbackInterface *callback, void *buffer,
- size_t bufferSize);
-
- /**
- * Buffer this log and possibly call on logs ready callback depending on the
- * notification setting in place. The method is thread-safe and will ensure
- * that logs are buffered in a FIFO ordering. If the buffer is full then drop
- * the oldest log.
- *
- * @param logLevel The log level.
- * @param timestampMs The timestamp that the log was collected as in
- * milliseconds. Monotonically increasing and in
- * milliseconds since boot.
- * @param logFormat The ASCII log format that is buffered.
- * @param ... The variable length set of parameters to print into the
- * logFormat string.
- */
- void handleLog(LogBufferLogLevel logLevel, uint32_t timestampMs,
- const char *logFormat, ...);
-
- /**
- * Same as handleLog but with a va_list argument instead of a ... parameter.
- *
- * @param args The arguments in a va_list type.
- */
- void handleLogVa(LogBufferLogLevel logLevel, uint32_t timestampMs,
- const char *logFormat, va_list args);
-
- // TODO(b/179786399): Remove the copyLogs method when the LogBufferManager is
- // refactored to no longer use it.
- /**
- * Copy out as many logs as will fit into destination buffer as they are
- * formatted internally. The memory where the logs were stored will be freed.
- * This method is thread-safe and will ensure that copyLogs will only copy
- * out the logs in a FIFO ordering.
- *
- * @param destination Pointer to the destination memory address.
- * @param size The max number of bytes to copy.
- * @param numLogsDropped Non-null pointer which will be set to the number of
- * logs dropped since CHRE started.
- *
- * @return The number of bytes copied from buffer to destination which may be
- * less than size because partial logs are not copied into
- * destination or the number of bytes left in the buffer is less than
- * size.
- */
- size_t copyLogs(void *destination, size_t size, size_t *numLogsDropped);
-
- /**
- *
- * @param logSize The size of the log text in bytes.
- * @return true if log would cause an overflow of the buffer and would
- * overwrite a log if it was pushed onto the buffer.
- */
- bool logWouldCauseOverflow(size_t logSize);
-
- /**
- * Transfer all data from one log buffer to another. The destination log
- * buffer must have equal or greater capacity than this buffer. The
- * otherBuffer will be reset prior to this buffer's data being transferred to
- * it and after the transfer this buffer will be reset. This method is
- * thread-safe and will ensure that logs are kept in FIFO ordering during a
- * transfer operation.
- *
- * @param otherBuffer The log buffer that is transferred to.
- */
- void transferTo(LogBuffer &otherBuffer);
-
- /**
- * Update the current log buffer notification setting which will determine
- * when the platform is notified to copy logs out of the buffer. Thread-safe.
- *
- * @param setting The new notification setting value.
- * @param thresholdBytes If the nofification setting is THRESHOLD, then if
- * the buffer allocates this many bytes the notification
- * callback will be triggerd, otherwise this parameter
- * is ignored.
- */
- void updateNotificationSetting(LogBufferNotificationSetting setting,
- size_t thresholdBytes = 0);
-
- /**
- * Thread safe.
- *
- * Empty out the log entries currently in the buffer and reset the number of
- * logs dropped.
- */
- void reset();
-
- /**
- * The data inside the buffer that is returned may be altered by
- * another thread so it is up to the calling code to ensure that race
- * conditions do not occur on writes to the data.
- *
- * @return The pointer to the underlying data buffer.
- */
- const uint8_t *getBufferData();
-
- /**
- * Thread safe.
- *
- * @return The current buffer size.
- */
- size_t getBufferSize();
-
- /**
- *
- * Thread safe.
- *
- * @return The number of logs dropped since the object was last reset or
- * instantiated.
- */
- size_t getNumLogsDropped();
-
- private:
- /**
- * Increment the value and take the modulus of the max size of the buffer.
- *
- * @param originalVal The original value to increment and mod.
- * @param incrementBy The amount to increment by.
- * @return The final value after incrementing and modulus.
- */
- size_t incrementAndModByBufferMaxSize(size_t originalVal,
- size_t incrementBy) const;
-
- /**
- * Copy from the source memory location to the buffer data ensuring that
- * the copy wraps around the buffer data if needed.
- *
- * @param size The number of bytes to copy into the buffer.
- * @param source The memory location to copy from.
- */
- void copyToBuffer(size_t size, const void *source);
-
- /**
- * Copy from the buffer data to a destination memory location ensuring that
- * the copy wraps around the buffer data if needed.
- *
- * @param size The number of bytes to copy into the buffer.
- * @param destination The memory location to copy to.
- */
- void copyFromBuffer(size_t size, void *destination);
-
- /**
- * Same as copyLogs method but requires that a lock already be held.
- */
- size_t copyLogsLocked(void *destination, size_t size, size_t *numLogsDropped);
-
- /**
- * Same as reset method but requires that a lock already be held.
- */
- void resetLocked();
-
- /**
- * Get next index indicating the start of a log entry from the starting
- * index of a previous log entry.
- *
- * @param startingIndex The starting index given.
- * @param logSize Non-null pointer that will be set to the size of the current
- * log message.
- * @return The next starting log index.
- */
- size_t getNextLogIndex(size_t startingIndex, size_t *logSize);
-
- /**
- * @param startingIndex The index to start from.
- * @return The length of the data portion of a log along with the null
- * terminator. If a null terminator was not found at most
- * kLogMaxSize - kLogDataOffset bytes away from the startingIndex
- * then kLogMaxSize - kLogDataOffset + 1 is returned.
- */
- size_t getLogDataLength(size_t startingIndex);
-
- //! The number of bytes in a log entry of the buffer before the log data is
- //! encountered.
- static constexpr size_t kLogDataOffset = 5;
-
- /**
- * The buffer data is stored in the format
- *
- * [ logLevel (1B) , timestamp (4B), data (dataLenB) , \0 (1B) ]
- *
- * This pattern is repeated as many times as there is log entries in the
- * buffer.
- *
- * Since dataLength cannot be greater than uint8_t the max size of the data
- * portion can be max 255.
- */
- uint8_t *const mBufferData;
-
- // TODO(b/170870354): Create a cirular buffer class to reuse this concept in
- // other parts of CHRE
- //! The buffer data head index
- size_t mBufferDataHeadIndex = 0;
- //! The buffer data tail index
- size_t mBufferDataTailIndex = 0;
- //! The current size of the data buffer
- size_t mBufferDataSize = 0;
- //! The buffer max size
- size_t mBufferMaxSize;
- //! The number of logs that have been dropped
- size_t mNumLogsDropped = 0;
- //! The buffer min size
- // TODO(b/170870354): Setup a more appropriate min size
- static constexpr size_t kBufferMinSize = 1024; // 1KB
-
- //! The callback object
- LogBufferCallbackInterface *mCallback;
- //! The notification setting object
- LogBufferNotificationSetting mNotificationSetting =
- LogBufferNotificationSetting::ALWAYS;
- //! The number of bytes that will trigger the threshold notification
- size_t mNotificationThresholdBytes = 0;
-
- // TODO(srok): Optimize the locking scheme
- //! The mutex guarding all thread safe operations.
- Mutex mLock;
-};
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_SHARED_LOG_BUFFER_H_
diff --git a/platform/shared/include/chre/platform/shared/log_buffer_manager.h b/platform/shared/include/chre/platform/shared/log_buffer_manager.h
deleted file mode 100644
index 817b8ddf..00000000
--- a/platform/shared/include/chre/platform/shared/log_buffer_manager.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_LOG_BUFFER_MANAGER_BUFFER_H_
-#define CHRE_PLATFORM_LOG_BUFFER_MANAGER_BUFFER_H_
-
-#include "chre/platform/assert.h"
-#include "chre/platform/condition_variable.h"
-#include "chre/platform/mutex.h"
-#include "chre/platform/shared/log_buffer.h"
-#include "chre/util/singleton.h"
-#include "chre_api/chre/re.h"
-
-#ifndef CHRE_LOG_BUFFER_DATA_SIZE
-#define CHRE_LOG_BUFFER_DATA_SIZE CHRE_MESSAGE_TO_HOST_MAX_SIZE
-#endif
-
-namespace chre {
-
-/**
- * A log buffer manager that platform code can use to buffer logs when the host
- * is not available and then send them off when the host becomes available. Uses
- * the LogBuffer API to buffer the logs in memory.
- *
- * The manager uses two LogBuffer objects to handle flushing logs to the host at
- * the same time as handling more incoming logs. Incoming logs are always put
- * into the primary buffer first. The secondary buffer takes all the logs
- * currently in the primary buffer before the logs are sent off to the host
- * because the secondary buffer is the memory location passed to the
- * HostLink::sendLogs API. Logs are also flushed to the secondary buffer from
- * the primary buffer when the primary buffer fills up.
- *
- * When implementing this class in platform code. Use the singleton defined
- * after this class and pass logs to the log or logVa methods. Initialize the
- * singleton before using it. Call the onLogsSentToHost callback immediately
- * after sending logs to the host.
- */
-class LogBufferManager : public LogBufferCallbackInterface {
- public:
- LogBufferManager(uint8_t *primaryBufferData, uint8_t *secondaryBufferData,
- size_t bufferSize)
- : mPrimaryLogBuffer(this, primaryBufferData, bufferSize),
- mSecondaryLogBuffer(nullptr /* callback */, secondaryBufferData,
- bufferSize) {}
-
- ~LogBufferManager() = default;
-
- /**
- * Logs message with printf-style arguments. No trailing newline is required
- * for this method.
- */
- void log(chreLogLevel logLevel, const char *formatStr, ...);
-
- /**
- * Logs message with printf-style arguments. No trailing newline is required
- * for this method. Uses va_list parameter instead of ...
- */
- void logVa(chreLogLevel logLevel, const char *formatStr, va_list args);
-
- /**
- * Overrides required method from LogBufferCallbackInterface.
- */
- void onLogsReady() final;
-
- /**
- * Flush any logs that might be in the default log buffer.
- */
- void flushLogs();
-
- /**
- * The platform code should call this method after the logs have been sent to
- * the host to signal that more logs can be sent to the host when ready. The
- * caller must indicate whether the platform could successfully deliver the
- * logs as well.
- *
- * @param success true if the logs were sent through to host successfully.
- */
- void onLogsSentToHost(bool success);
-
- /**
- * Loop that waits on the conditions for sending logs to host to be met and
- * sends the logs to the host if so. This method never exits. Should be called
- * by a platform thread.
- */
- void startSendLogsToHostLoop();
-
- private:
- /*
- * @return The LogBuffer log level for the given CHRE log level.
- */
- LogBufferLogLevel chreToLogBufferLogLevel(chreLogLevel chreLogLevel);
-
- /**
- * Perform any setup needed by the plaform before the secondary buffer is
- * used.
- *
- * Implemented by the platform.
- */
- void preSecondaryBufferUse() const;
-
- /**
- * Same as onLogsSentToHost, but without locking. The calling code should have
- * the flush logs mutex locked before calling this method.
- *
- * @param success true if the logs were successfully delivered to the host.
- */
- void onLogsSentToHostLocked(bool success);
-
- LogBuffer mPrimaryLogBuffer;
- LogBuffer mSecondaryLogBuffer;
-
- size_t mNumLogsDroppedTotal = 0;
-
- ConditionVariable mSendLogsToHostCondition;
- bool mLogFlushToHostPending = false;
- bool mLogsBecameReadyWhileFlushPending = false;
- Mutex mFlushLogsMutex;
-};
-
-//! Provides an alias to the LogBufferManager singleton.
-typedef Singleton<LogBufferManager> LogBufferManagerSingleton;
-
-//! Extern the explicit LogBufferManagerSingleton to force non-inline calls.
-//! This reduces codesize considerably.
-extern template class Singleton<LogBufferManager>;
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_LOG_BUFFER_MANAGER_H_
diff --git a/platform/shared/include/chre/platform/shared/memory.h b/platform/shared/include/chre/platform/shared/memory.h
deleted file mode 100644
index 3bec3189..00000000
--- a/platform/shared/include/chre/platform/shared/memory.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SHARED_MEMORY_H_
-#define CHRE_PLATFORM_SHARED_MEMORY_H_
-
-#include <cstddef>
-#include <type_traits>
-
-namespace chre {
-
-/**
- * Allocates space for a nanoapp binary to be mapped into. Memory allocation
- * should come from the lowest power memory region available. If alignment is
- * left as 0, the default alignment for the platform should be used.
- *
- * @param size The size of the binary that will be placed in the memory region
- * @param alignment The alignment boundary the nanoapp binary requires
- */
-void *nanoappBinaryAlloc(size_t size, size_t alignment = 0);
-
-/**
- * Allocates space for a nanoapp binary to be mapped into. Memory allocation
- * should come from a high capacity memory region. If DRAM or another large
- * capacity region is not available, this will allocate from the same memory
- * region as nanoappBinaryAlloc. If alignment is left as 0, the default
- * alignment for the platform should be used.
- *
- * @param size The size of the binary that will be placed in the memory region
- * @param alignment The alignment boundary the nanoapp binary requires
- */
-void *nanoappBinaryDramAlloc(size_t size, size_t alignment = 0);
-
-/**
- * Memory free from memory allocated using nanoappBinaryAlloc. The semantics
- * are the same as free.
- *
- * @param pointer Pointer to data returned from nanoappBinaryAlloc
- */
-void nanoappBinaryFree(void *pointer);
-
-/**
- * Memory free from memory allocated using nanoappBinaryDramAlloc. The semantics
- * are the same as free.
- *
- * @param pointer Pointer to data returned from nanoappBinaryDramAlloc
- */
-void nanoappBinaryDramFree(void *pointer);
-
-/**
- * Memory allocation specifically using the DRAM heap. The semantics are the
- * same as malloc.
- *
- * If DRAM or another large memory capacity region is not available, this will
- * allocate from the same memory region as memoryAlloc.
- */
-void *memoryAllocDram(size_t size);
-
-/**
- * Memory free from memory allocated using the DRAM heap. The semantics are the
- * same as free.
- *
- * If DRAM or another large memory capacity region is not available, this will
- * free from the same memory region as memoryFree.
- */
-void memoryFreeDram(void *pointer);
-
-/**
- * Ensures memory allocated through memoryAllocDram can be utilized. If memory
- * allocated through memoryAllocDram is always available, this method can be a
- * no-op.
- *
- * This must be support being invoked from multiple threads.
- */
-void forceDramAccess();
-
-/**
- * Removes CHRE's vote to keep DRAM accessible. This must only be called when
- * CHRE is idle.
- */
-void removeDramAccessVote();
-
-/**
- * Allocates memory in DRAM for an object of size T and constructs the object in
- * the newly allocated object by forwarding the provided parameters.
- */
-template <typename T, typename... Args>
-inline T *memoryAllocDram(Args &&... args) {
- auto *storage = static_cast<T *>(memoryAllocDram(sizeof(T)));
- if (storage != nullptr) {
- new (storage) T(std::forward<Args>(args)...);
- }
-
- return storage;
-}
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_SHARED_MEMORY_H_
diff --git a/platform/shared/include/chre/platform/shared/memory_debug.h b/platform/shared/include/chre/platform/shared/memory_debug.h
index 898ddeda..9976f359 100644
--- a/platform/shared/include/chre/platform/shared/memory_debug.h
+++ b/platform/shared/include/chre/platform/shared/memory_debug.h
@@ -88,7 +88,7 @@ inline void *debugAlloc(MemoryAllocFunction *allocFunc, size_t size) {
/**
* Free memory previously allocated from debugAlloc, but first perform some
- * consistency checks, triggering ERR_FATAL if they fail.
+ * sanity checks, triggering ERR_FATAL if they fail.
*
* @param freeFunc Function to call to actually free memory (e.g. free)
* @param pointer Pointer previously returned by debugAlloc
diff --git a/platform/shared/include/chre/platform/shared/nanoapp_dso_util.h b/platform/shared/include/chre/platform/shared/nanoapp_dso_util.h
index dd366750..b6ea036a 100644
--- a/platform/shared/include/chre/platform/shared/nanoapp_dso_util.h
+++ b/platform/shared/include/chre/platform/shared/nanoapp_dso_util.h
@@ -22,19 +22,16 @@
namespace chre {
/**
- * Performs consistency checks on the app info structure included in a
- * dynamically loaded nanoapp.
+ * Performs sanity checks on the app info structure included in a dynamically
+ * loaded nanoapp.
*
* @param expectedAppId The app ID passed alongside the binary
* @param expectedAppVersion The app version number passed alongside the binary
- * @param expectedTargetApiVersion The app target API version number passed
- * alongside the binary
* @param appInfo App info structure included in the nanoapp binary
*
* @return true if validation was successful
*/
bool validateAppInfo(uint64_t expectedAppId, uint32_t expectedAppVersion,
- uint32_t expectedTargetApiVersion,
const struct chreNslNanoappInfo *appInfo);
} // namespace chre
diff --git a/platform/shared/include/chre/platform/shared/nanoapp_loader.h b/platform/shared/include/chre/platform/shared/nanoapp_loader.h
deleted file mode 100644
index 72a46408..00000000
--- a/platform/shared/include/chre/platform/shared/nanoapp_loader.h
+++ /dev/null
@@ -1,345 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SHARED_NANOAPP_LOADER_H_
-#define CHRE_PLATFORM_SHARED_NANOAPP_LOADER_H_
-
-#include <cinttypes>
-#include <cstdlib>
-
-#include "chre/platform/shared/loader_util.h"
-
-#include "chre/util/dynamic_vector.h"
-
-namespace chre {
-
-/**
- * Provides dynamic loading support for nanoapps on FreeRTOS-based platforms.
- * At a high level, this class is responsible for mapping the provided binary
- * into CHRE's address space, relocating and resolving symbols, and initializing
- * and freeing static data.
- */
-class NanoappLoader {
- public:
- NanoappLoader() = delete;
-
- explicit NanoappLoader(void *elfInput, bool mapIntoTcm) {
- mBinary = static_cast<uint8_t *>(elfInput);
- mIsTcmBinary = mapIntoTcm;
- }
-
- /**
- * Factory method to create a NanoappLoader Instance after loading
- * the buffer containing the ELF binary.
- *
- * @param elfInput Buffer containing the elf file
- * @param mapIntoTcm Indicates whether the elfBinary should be mapped into
- * tightly coupled memory.
- * @return Class instance on successful load and verification,
- * nullptr otherwise.
- */
- static void *create(void *elfInput, bool mapIntoTcm);
-
- /**
- * Closes and destroys the NanoappLoader instance.
- *
- * @param loader A non-null pointer to the loader that must be destroyed.
- */
- static void destroy(NanoappLoader *loader);
-
- /**
- * Attempts to locate the exported symbol specified by the given function
- * name.
- *
- * @param name A null-terminated char array that is the name of the function
- * to be found.
- * @return The address of the function. nullptr if not found.
- */
- static void *findExportedSymbol(const char *name);
-
- /**
- * Method for pointer lookup by symbol name. Only function pointers
- * are currently supported.
- *
- * @return function pointer on successful lookup, nullptr otherwise
- */
- void *findSymbolByName(const char *name);
-
- /**
- * Registers a function provided through atexit during static initialization
- * that should be called prior to unloading a nanoapp.
- *
- * @param function Function that should be invoked prior to unloading a
- * nanoapp.
- */
- void registerAtexitFunction(void (*function)(void));
-
- private:
- /**
- * Opens the ELF binary. This maps the binary into memory, resolves symbols,
- * and invokes any static initializers.
- *
- * @return true if all required opening steps were completed.
- */
- bool open();
-
- /**
- * Closes the loader, freeing any state associated with the loaded ELF binary
- * and unmapping it from memory. Prior to unmapping from memory, any static
- * termination functions will be invoked.
- */
- void close();
-
- using DynamicHeader = ElfW(Dyn);
- using ElfAddr = ElfW(Addr);
- using ElfHeader = ElfW(Ehdr);
- using ElfRel = ElfW(Rel); // Relocation table entry,
- // in section of type SHT_REL
- using ElfRela = ElfW(Rela);
- using ElfSym = ElfW(Sym);
- using ElfWord = ElfW(Word);
- using ProgramHeader = ElfW(Phdr);
- using SectionHeader = ElfW(Shdr);
-
- //! Name of various segments in the ELF that need to be looked up
- static constexpr const char *kSymTableName = ".symtab";
- static constexpr const char *kStrTableName = ".strtab";
- static constexpr const char *kInitArrayName = ".init_array";
- static constexpr const char *kFiniArrayName = ".fini_array";
- // For now, assume all segments are 4K aligned.
- static constexpr size_t kBinaryAlignment = 4096;
-
- //! Pointer to the table of all the section names.
- char *mSectionNamesPtr = nullptr;
- //! Pointer to the table of symbol names of defined symbols.
- char *mStringTablePtr = nullptr;
- //! Pointer to the table of symbol information for defined symbols.
- uint8_t *mSymbolTablePtr = nullptr;
- //! Pointer to the array of section header entries.
- SectionHeader *mSectionHeadersPtr = nullptr;
- //! Number of SectionHeaders pointed to by mSectionHeadersPtr.
- size_t mNumSectionHeaders = 0;
- //! Size of the data pointed to by mSymbolTablePtr.
- size_t mSymbolTableSize = 0;
-
- //! The ELF that is being mapped into the system. This pointer will be invalid
- //! after open returns.
- uint8_t *mBinary = nullptr;
- //! The starting location of the memory that has been mapped into the system.
- uint8_t *mMapping = nullptr;
- //! The difference between where the first load segment was mapped into
- //! virtual memory and what the virtual load offset was of that segment.
- ElfAddr mLoadBias = 0;
- //! Dynamic vector containing functions that should be invoked prior to
- //! unloading this nanoapp. Note that functions are stored in the order they
- //! were added and should be called in reverse.
- DynamicVector<void (*)(void)> mAtexitFunctions;
- //! Whether this loader instance is managing a TCM nanoapp binary.
- bool mIsTcmBinary = false;
-
- /**
- * Invokes all functions registered via atexit during static initialization.
- */
- void callAtexitFunctions();
-
- /**
- * Invokes all initialization functions in .init_array segment.
- *
- * @return true if static initialization succeeded.
- */
- bool callInitArray();
-
- /**
- * Invokes all termination functions in the .fini_array segment.
- */
- void callTerminatorArray();
-
- /**
- * Allocates memory for all load segments that need to be mapped into virtual
- * memory and copies the load segments into the newly allocated memory.
- *
- * @return true if the memory for mapping was allocated and the load segments
- * were formatted correctly.
- */
- bool createMappings();
-
- /**
- * Copies various sections and headers from the ELF while verifying that they
- * match the ELF format specification.
- *
- * @return true if all data was copied and verified.
- */
- bool copyAndVerifyHeaders();
-
- /**
- * Resolves all relocated symbols located in the DT_REL table.
- *
- * @return true if all relocated symbols were resolved.
- */
- bool fixRelocations();
-
- /**
- * Resolves entries in the Global Offset Table (GOT) to facility the ELF's
- * compiled using position independent code (PIC).
- *
- * @return true if all symbols were resolved.
- */
- bool resolveGot();
-
- /**
- * Verifies the ELF header has correct values based on the ELF spec.
- *
- * @return true if the header passed verification.
- */
- bool verifyElfHeader();
-
- /**
- * Verifies basic information about program headers.
- *
- * @return true if the headers passed verification.
- */
- bool verifyProgramHeaders();
-
- /**
- * Verifies basic information about section headers.
- *
- * @return true if the headers passed verification.
- */
- bool verifySectionHeaders();
-
- /**
- * Retrieves the symbol name of data located at the given position in the
- * symbol table.
- *
- * @param posInSymbolTable The position in the symbol table where information
- * about the symbol can be found.
- * @return The symbol's name or nullptr if not found.
- */
- const char *getDataName(size_t posInSymbolTable);
-
- /**
- * Retrieves the name of the section header located at the given offset in the
- * section name table.
- *
- * @param headerOffset The offset in the section names table where the header
- * is located.
- * @return The section's name or the empty string if the offset is 0.
- */
- const char *getSectionHeaderName(size_t headerOffset);
-
- /**
- * Rounds the given address down to the closest alignment boundary.
- *
- * @param virtualAddr The address to be rounded.
- * @return An address that is a multiple of the platform's alignment and is
- * less than or equal to virtualAddr.
- */
- uintptr_t roundDownToAlign(uintptr_t virtualAddr);
-
- /**
- * Frees any data that was allocated as part of loading the ELF into memory.
- */
- void freeAllocatedData();
-
- /**
- * Ensures the BSS section is properly mapped into memory. If there is a
- * difference between the size of the BSS section in the ELF binary and the
- * size it needs to be in memory, the rest of the section is zeroed out.
- *
- * @param header The ProgramHeader of the BSS section that is being mapped in.
- */
- void mapBss(const ProgramHeader *header);
-
- /**
- * Resolves the address of an undefined symbol located at the given position
- * in the symbol table. This symbol must be defined and exposed by the given
- * platform in order for it to be resolved successfully.
- *
- * @param posInSymbolTable The position of the undefined symbol in the symbol
- * table.
- * @return The address of the resolved symbol. nullptr if not found.
- */
- void *resolveData(size_t posInSymbolTable);
-
- /**
- * @return The address for the dynamic segment. nullptr if not found.
- */
- DynamicHeader *getDynamicHeader();
-
- /**
- * @return The address of the first read-only segment. nullptr if not found.
- */
- ProgramHeader *getFirstRoSegHeader();
-
- /**
- * Retrieves the section header with the given name.
- *
- * @param headerName The name of the section header to find.
- * @return The address of the section. nullptr if not found.
- */
- SectionHeader *getSectionHeader(const char *headerName);
-
- /**
- * @return The ELF header for the binary being loaded. nullptr if it doesn't
- * exist or no binary is being loaded.
- */
- ElfHeader *getElfHeader();
-
- /**
- * @return The array of program headers for the binary being loaded. nullptr
- * if it doesn't exist or no binary is being loaded.
- */
- ProgramHeader *getProgramHeaderArray();
-
- /**
- * @return The size of the array of program headers for the binary being
- * loaded. 0 if it doesn't exist or no binary is being loaded.
- */
- size_t getProgramHeaderArraySize();
-
- /**
- * @return An array of characters containing the symbol names for dynamic
- * symbols inside the binary being loaded. nullptr if it doesn't exist or
- * no binary is being loaded.
- */
- char *getDynamicStringTable();
-
- /**
- * @return An array of dynamic symbol information for the binary being loaded.
- * nullptr if it doesn't exist or no binary is being loaded.
- */
- uint8_t *getDynamicSymbolTable();
-
- /**
- * @return The size of the array of dynamic symbol information for the binary
- * being loaded. 0 if it doesn't exist or no binary is being loaded.
- */
- size_t getDynamicSymbolTableSize();
-
- /**
- * Returns the first entry in the dynamic header that has a tag that matches
- * the given field.
- *
- * @param dyn The dynamic header for the binary.
- * @param field The field to be searched for.
- * @return The value found at the entry. 0 if the entry isn't found.
- */
- static ElfWord getDynEntry(DynamicHeader *dyn, int field);
-};
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_SHARED_NANOAPP_LOADER_H_
diff --git a/platform/shared/include/chre/platform/shared/nanoapp_support_lib_dso.h b/platform/shared/include/chre/platform/shared/nanoapp_support_lib_dso.h
index aa93e97b..239206e3 100644
--- a/platform/shared/include/chre/platform/shared/nanoapp_support_lib_dso.h
+++ b/platform/shared/include/chre/platform/shared/nanoapp_support_lib_dso.h
@@ -41,15 +41,11 @@ extern "C" {
//! The minor version in the nanoapp info structure to determine which fields
//! are available to support backwards compatibility.
-#define CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION UINT8_C(3)
+#define CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION UINT8_C(2)
//! The symbol name expected from the nanoapp's definition of its info struct
#define CHRE_NSL_DSO_NANOAPP_INFO_SYMBOL_NAME "_chreNslDsoNanoappInfo"
-//! The symbol name expected from the nanoapp's definition of its unstable ID
-//! char array
-#define CHRE_NSL_DSO_NANOAPP_UNSTABLE_ID_SYMBOL_NAME "_chreNanoappUnstableId"
-
//! Maximum length of vendor and name strings
#define CHRE_NSL_DSO_NANOAPP_STRING_MAX_LEN (32)
@@ -110,13 +106,6 @@ struct chreNslNanoappInfo {
//!
//! @since minor version 2
const char *appVersionString;
-
- //! Set of permissions that determines what APIs the application is allowed to
- //! use. See chre/util/system/napp_permissions.h for more details on what
- //! permissions can be declared here and what their values are.
- //!
- //! @since minor version 3
- uint32_t appPermissions;
};
/**
diff --git a/platform/shared/include/chre/platform/shared/platform_log.h b/platform/shared/include/chre/platform/shared/platform_log.h
new file mode 100644
index 00000000..09b96c60
--- /dev/null
+++ b/platform/shared/include/chre/platform/shared/platform_log.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * 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 CHRE_PLATFORM_PLATFORM_LOG_H_
+#define CHRE_PLATFORM_PLATFORM_LOG_H_
+
+#include "chre/target_platform/platform_log_base.h"
+#include "chre/util/singleton.h"
+
+namespace chre {
+
+/**
+ * A logging class that platforms can supply an implementation and storage for.
+ * Only one instance of this class is created by CHRE and is accessed via the
+ * PlatformLogSingleton alias provided below.
+ */
+class PlatformLog : public PlatformLogBase {
+ public:
+ /**
+ * Allows the platform to initialize logging infrastructure.
+ */
+ PlatformLog();
+
+ /**
+ * Allows the platform to deinitialize logging infrastructure.
+ */
+ ~PlatformLog();
+
+ /**
+ * Logs message with printf-style arguments. No trailing newline is required
+ * for this method.
+ */
+ void log(const char *formatStr, ...);
+};
+
+//! Provides an alias to the PlatformLog singleton.
+typedef Singleton<PlatformLog> PlatformLogSingleton;
+
+} // namespace chre
+
+#endif // CHRE_PLATFORM_PLATFORM_LOG_H_
diff --git a/platform/shared/include/chre/target_platform/platform_cache_management.h b/platform/shared/include/chre/target_platform/platform_cache_management.h
deleted file mode 100644
index 123de174..00000000
--- a/platform/shared/include/chre/target_platform/platform_cache_management.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SHARED_CACHE_MANAGEMENT_H_
-#define CHRE_PLATFORM_SHARED_CACHE_MANAGEMENT_H_
-
-namespace chre {
-
-/**
- * Invalidates and/or cleans the system instruction and data caches.
- *
- * When nanoapps in CHRE are loaded dynamically, the data and
- * executable segments are parsed and relocated into memory. This operation
- * can cause cached instructions and data to be invalid when we start executing
- * the newly loaded nanoapp's instructions, and could possibly lead to an
- * exception. To support custom dynamic loading implementations (for example,
- * when it's not part of the underlying OS/system), the platform needs to
- * implement (or provide an empty stub for) the following method to invalidate
- * and/or clean the system data and instruction caches.
- */
-void wipeSystemCaches();
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_SHARED_CACHE_MANAGEMENT_H_
diff --git a/platform/shared/log_buffer.cc b/platform/shared/log_buffer.cc
deleted file mode 100644
index c0ccd8d9..00000000
--- a/platform/shared/log_buffer.cc
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/platform/shared/log_buffer.h"
-#include "chre/platform/assert.h"
-#include "chre/util/lock_guard.h"
-
-#include <cstdarg>
-#include <cstdio>
-
-namespace chre {
-
-LogBuffer::LogBuffer(LogBufferCallbackInterface *callback, void *buffer,
- size_t bufferSize)
- : mBufferData(static_cast<uint8_t *>(buffer)),
- mBufferMaxSize(bufferSize),
- mCallback(callback) {
- CHRE_ASSERT(bufferSize >= kBufferMinSize);
-}
-
-void LogBuffer::handleLog(LogBufferLogLevel logLevel, uint32_t timestampMs,
- const char *logFormat, ...) {
- va_list args;
- va_start(args, logFormat);
- handleLogVa(logLevel, timestampMs, logFormat, args);
- va_end(args);
-}
-
-void LogBuffer::handleLogVa(LogBufferLogLevel logLevel, uint32_t timestampMs,
- const char *logFormat, va_list args) {
- constexpr size_t maxLogLen = kLogMaxSize - kLogDataOffset;
- char tempBuffer[maxLogLen];
- int logLenSigned = vsnprintf(tempBuffer, maxLogLen, logFormat, args);
- if (logLenSigned > 0) {
- size_t logLen = static_cast<size_t>(logLenSigned);
- if (logLen >= maxLogLen) {
- // Leave space for nullptr to be copied on end
- logLen = maxLogLen - 1;
- }
- size_t totalLogSize = kLogDataOffset + logLen;
- {
- LockGuard<Mutex> lockGuard(mLock);
- // Invalidate memory allocated for log at head while the buffer is greater
- // than max size
- while (mBufferDataSize + totalLogSize > mBufferMaxSize) {
- mNumLogsDropped++;
- size_t logSize;
- mBufferDataHeadIndex = getNextLogIndex(mBufferDataHeadIndex, &logSize);
- mBufferDataSize -= logSize;
- }
- // The final log level as parsed by the daemon requires that the log level
- // be incremented.
- uint8_t logLevelAdjusted = static_cast<uint8_t>(logLevel) + 1;
- copyToBuffer(sizeof(logLevelAdjusted), &logLevelAdjusted);
- copyToBuffer(sizeof(timestampMs), &timestampMs);
- copyToBuffer(logLen, tempBuffer);
- copyToBuffer(1, reinterpret_cast<const void *>("\0"));
- }
- if (mCallback != nullptr) {
- switch (mNotificationSetting) {
- case LogBufferNotificationSetting::ALWAYS: {
- mCallback->onLogsReady();
- break;
- }
- case LogBufferNotificationSetting::NEVER: {
- break;
- }
- case LogBufferNotificationSetting::THRESHOLD: {
- if (mBufferDataSize > mNotificationThresholdBytes) {
- mCallback->onLogsReady();
- }
- break;
- }
- }
- }
- }
-}
-
-size_t LogBuffer::copyLogs(void *destination, size_t size,
- size_t *numLogsDropped) {
- LockGuard<Mutex> lock(mLock);
- return copyLogsLocked(destination, size, numLogsDropped);
-}
-
-bool LogBuffer::logWouldCauseOverflow(size_t logSize) {
- LockGuard<Mutex> lock(mLock);
- return (mBufferDataSize + logSize + kLogDataOffset + 1 /* nullptr */ >
- mBufferMaxSize);
-}
-
-void LogBuffer::transferTo(LogBuffer &buffer) {
- LockGuard<Mutex> lockGuardOther(buffer.mLock);
- size_t numLogsDropped;
- size_t bytesCopied;
- {
- LockGuard<Mutex> lockGuardThis(mLock);
- // The buffer being transferred to should be as big or bigger.
- CHRE_ASSERT(buffer.mBufferMaxSize >= mBufferMaxSize);
-
- buffer.resetLocked();
-
- bytesCopied = copyLogsLocked(buffer.mBufferData, buffer.mBufferMaxSize,
- &numLogsDropped);
-
- resetLocked();
- }
- buffer.mBufferDataTailIndex = bytesCopied % buffer.mBufferMaxSize;
- buffer.mBufferDataSize = bytesCopied;
- buffer.mNumLogsDropped = numLogsDropped;
-}
-
-void LogBuffer::updateNotificationSetting(LogBufferNotificationSetting setting,
- size_t thresholdBytes) {
- LockGuard<Mutex> lock(mLock);
-
- mNotificationSetting = setting;
- mNotificationThresholdBytes = thresholdBytes;
-}
-
-void LogBuffer::reset() {
- LockGuard<Mutex> lock(mLock);
- resetLocked();
-}
-
-const uint8_t *LogBuffer::getBufferData() {
- return mBufferData;
-}
-
-size_t LogBuffer::getBufferSize() {
- LockGuard<Mutex> lockGuard(mLock);
- return mBufferDataSize;
-}
-
-size_t LogBuffer::getNumLogsDropped() {
- LockGuard<Mutex> lockGuard(mLock);
- return mNumLogsDropped;
-}
-
-size_t LogBuffer::incrementAndModByBufferMaxSize(size_t originalVal,
- size_t incrementBy) const {
- return (originalVal + incrementBy) % mBufferMaxSize;
-}
-
-void LogBuffer::copyToBuffer(size_t size, const void *source) {
- const uint8_t *sourceBytes = static_cast<const uint8_t *>(source);
- if (mBufferDataTailIndex + size > mBufferMaxSize) {
- size_t firstSize = mBufferMaxSize - mBufferDataTailIndex;
- size_t secondSize = size - firstSize;
- memcpy(&mBufferData[mBufferDataTailIndex], sourceBytes, firstSize);
- memcpy(mBufferData, &sourceBytes[firstSize], secondSize);
- } else {
- memcpy(&mBufferData[mBufferDataTailIndex], sourceBytes, size);
- }
- mBufferDataSize += size;
- mBufferDataTailIndex =
- incrementAndModByBufferMaxSize(mBufferDataTailIndex, size);
-}
-
-void LogBuffer::copyFromBuffer(size_t size, void *destination) {
- uint8_t *destinationBytes = static_cast<uint8_t *>(destination);
- if (mBufferDataHeadIndex + size > mBufferMaxSize) {
- size_t firstSize = mBufferMaxSize - mBufferDataHeadIndex;
- size_t secondSize = size - firstSize;
- memcpy(destinationBytes, &mBufferData[mBufferDataHeadIndex], firstSize);
- memcpy(&destinationBytes[firstSize], mBufferData, secondSize);
- } else {
- memcpy(destinationBytes, &mBufferData[mBufferDataHeadIndex], size);
- }
- mBufferDataSize -= size;
- mBufferDataHeadIndex =
- incrementAndModByBufferMaxSize(mBufferDataHeadIndex, size);
-}
-
-size_t LogBuffer::copyLogsLocked(void *destination, size_t size,
- size_t *numLogsDropped) {
- size_t copySize = 0;
-
- if (size != 0 && destination != nullptr && mBufferDataSize != 0) {
- if (size >= mBufferDataSize) {
- copySize = mBufferDataSize;
- } else {
- size_t logSize;
- // There is guaranteed to be a null terminator within the max log length
- // number of bytes so logStartIndex will not be maxBytes + 1
- size_t logStartIndex = getNextLogIndex(mBufferDataHeadIndex, &logSize);
- while (copySize + logSize <= size &&
- copySize + logSize <= mBufferDataSize) {
- copySize += logSize;
- logStartIndex = getNextLogIndex(logStartIndex, &logSize);
- }
- }
- copyFromBuffer(copySize, destination);
- }
-
- *numLogsDropped = mNumLogsDropped;
-
- return copySize;
-}
-
-void LogBuffer::resetLocked() {
- mBufferDataHeadIndex = 0;
- mBufferDataTailIndex = 0;
- mBufferDataSize = 0;
- mNumLogsDropped = 0;
-}
-
-size_t LogBuffer::getNextLogIndex(size_t startingIndex, size_t *logSize) {
- size_t logDataStartIndex =
- incrementAndModByBufferMaxSize(startingIndex, kLogDataOffset);
-
- size_t logDataSize = getLogDataLength(logDataStartIndex);
- *logSize = kLogDataOffset + logDataSize;
- return incrementAndModByBufferMaxSize(startingIndex, *logSize);
-}
-
-size_t LogBuffer::getLogDataLength(size_t startingIndex) {
- size_t currentIndex = startingIndex;
- constexpr size_t maxBytes = kLogMaxSize - kLogDataOffset;
- size_t numBytes = maxBytes + 1;
-
- for (size_t i = 0; i < maxBytes; i++) {
- if (mBufferData[currentIndex] == '\0') {
- // +1 to include the null terminator
- numBytes = i + 1;
- break;
- }
- currentIndex = incrementAndModByBufferMaxSize(currentIndex, 1);
- }
- return numBytes;
-}
-
-} // namespace chre
diff --git a/platform/shared/log_buffer_manager.cc b/platform/shared/log_buffer_manager.cc
deleted file mode 100644
index 4c4b4c30..00000000
--- a/platform/shared/log_buffer_manager.cc
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/platform/shared/log_buffer_manager.h"
-
-#include "chre/core/event_loop_manager.h"
-#include "chre/util/lock_guard.h"
-
-void chrePlatformLogToBuffer(chreLogLevel chreLogLevel, const char *format,
- ...) {
- va_list args;
- va_start(args, format);
- if (chre::LogBufferManagerSingleton::isInitialized()) {
- chre::LogBufferManagerSingleton::get()->logVa(chreLogLevel, format, args);
- }
- va_end(args);
-}
-
-namespace chre {
-
-void LogBufferManager::onLogsReady() {
- LockGuard<Mutex> lockGuard(mFlushLogsMutex);
- if (!mLogFlushToHostPending) {
- if (EventLoopManagerSingleton::isInitialized() &&
- EventLoopManagerSingleton::get()
- ->getEventLoop()
- .getPowerControlManager()
- .hostIsAwake()) {
- mLogFlushToHostPending = true;
- mSendLogsToHostCondition.notify_one();
- }
- } else {
- mLogsBecameReadyWhileFlushPending = true;
- }
-}
-
-void LogBufferManager::flushLogs() {
- onLogsReady();
-}
-
-void LogBufferManager::onLogsSentToHost(bool success) {
- LockGuard<Mutex> lockGuard(mFlushLogsMutex);
- onLogsSentToHostLocked(success);
-}
-
-void LogBufferManager::startSendLogsToHostLoop() {
- LockGuard<Mutex> lockGuard(mFlushLogsMutex);
- // TODO(b/181871430): Allow this loop to exit for certain platforms
- while (true) {
- while (!mLogFlushToHostPending) {
- mSendLogsToHostCondition.wait(mFlushLogsMutex);
- }
- bool logWasSent = false;
- if (EventLoopManagerSingleton::get()
- ->getEventLoop()
- .getPowerControlManager()
- .hostIsAwake()) {
- auto &hostCommsMgr =
- EventLoopManagerSingleton::get()->getHostCommsManager();
- preSecondaryBufferUse();
- if (mSecondaryLogBuffer.getBufferSize() == 0) {
- // TODO (b/184178045): Transfer logs into the secondary buffer from
- // primary if there is room.
- mPrimaryLogBuffer.transferTo(mSecondaryLogBuffer);
- }
- // If the primary buffer was not flushed to the secondary buffer then set
- // the flag that will cause sendLogsToHost to be run again after
- // onLogsSentToHost has been called and the secondary buffer has been
- // cleared out.
- if (mPrimaryLogBuffer.getBufferSize() > 0) {
- mLogsBecameReadyWhileFlushPending = true;
- }
- if (mSecondaryLogBuffer.getBufferSize() > 0) {
- mNumLogsDroppedTotal += mSecondaryLogBuffer.getNumLogsDropped();
- mFlushLogsMutex.unlock();
- hostCommsMgr.sendLogMessageV2(mSecondaryLogBuffer.getBufferData(),
- mSecondaryLogBuffer.getBufferSize(),
- mNumLogsDroppedTotal);
- logWasSent = true;
- mFlushLogsMutex.lock();
- }
- }
- if (!logWasSent) {
- onLogsSentToHostLocked(false);
- }
- }
-}
-
-void LogBufferManager::log(chreLogLevel logLevel, const char *formatStr, ...) {
- va_list args;
- va_start(args, formatStr);
- logVa(logLevel, formatStr, args);
- va_end(args);
-}
-
-void LogBufferManager::logVa(chreLogLevel logLevel, const char *formatStr,
- va_list args) {
- LogBufferLogLevel logBufLogLevel = chreToLogBufferLogLevel(logLevel);
- uint64_t timeNs = SystemTime::getMonotonicTime().toRawNanoseconds();
- uint32_t timeMs =
- static_cast<uint32_t>(timeNs / kOneMillisecondInNanoseconds);
- // Copy the va_list before getting size from vsnprintf so that the next
- // argument that will be accessed in buffer.handleLogVa is the starting one.
- va_list getSizeArgs;
- va_copy(getSizeArgs, args);
- size_t logSize = vsnprintf(nullptr, 0, formatStr, getSizeArgs);
- va_end(getSizeArgs);
- if (mPrimaryLogBuffer.logWouldCauseOverflow(logSize)) {
- LockGuard<Mutex> lockGuard(mFlushLogsMutex);
- if (!mLogFlushToHostPending) {
- preSecondaryBufferUse();
- mPrimaryLogBuffer.transferTo(mSecondaryLogBuffer);
- }
- }
- mPrimaryLogBuffer.handleLogVa(logBufLogLevel, timeMs, formatStr, args);
-}
-
-LogBufferLogLevel LogBufferManager::chreToLogBufferLogLevel(
- chreLogLevel chreLogLevel) {
- switch (chreLogLevel) {
- case CHRE_LOG_ERROR:
- return LogBufferLogLevel::ERROR;
- case CHRE_LOG_WARN:
- return LogBufferLogLevel::WARN;
- case CHRE_LOG_INFO:
- return LogBufferLogLevel::INFO;
- default: // CHRE_LOG_DEBUG
- return LogBufferLogLevel::DEBUG;
- }
-}
-
-void LogBufferManager::onLogsSentToHostLocked(bool success) {
- if (success) {
- mSecondaryLogBuffer.reset();
- }
- // If there is a failure to send a log through do not try to send another
- // one to avoid an infinite loop occurring
- mLogFlushToHostPending = mLogsBecameReadyWhileFlushPending && success;
- mLogsBecameReadyWhileFlushPending = false;
- if (mLogFlushToHostPending) {
- mSendLogsToHostCondition.notify_one();
- }
-}
-
-//! Explicitly instantiate the EventLoopManagerSingleton to reduce codesize.
-template class Singleton<LogBufferManager>;
-
-} // namespace chre
diff --git a/platform/shared/memory_manager.cc b/platform/shared/memory_manager.cc
index 22c07578..d181c54b 100644
--- a/platform/shared/memory_manager.cc
+++ b/platform/shared/memory_manager.cc
@@ -27,8 +27,7 @@ void *MemoryManager::nanoappAlloc(Nanoapp *app, uint32_t bytes) {
LOGE("Failed to allocate memory from Nanoapp ID %" PRIu32
": allocation count exceeded limit.",
app->getInstanceId());
- } else if ((bytes > kMaxAllocationBytes) ||
- ((mTotalAllocatedBytes + bytes) > kMaxAllocationBytes)) {
+ } else if ((mTotalAllocatedBytes + bytes) > kMaxAllocationBytes) {
LOGE("Failed to allocate memory from Nanoapp ID %" PRIu32
": not enough space.",
app->getInstanceId());
diff --git a/platform/shared/nanoapp/nanoapp_dso_util.cc b/platform/shared/nanoapp/nanoapp_dso_util.cc
index 5ca8dd7d..5b4a26e3 100644
--- a/platform/shared/nanoapp/nanoapp_dso_util.cc
+++ b/platform/shared/nanoapp/nanoapp_dso_util.cc
@@ -25,7 +25,6 @@
namespace chre {
bool validateAppInfo(uint64_t expectedAppId, uint32_t expectedAppVersion,
- uint32_t expectedTargetApiVersion,
const struct chreNslNanoappInfo *appInfo) {
uint32_t ourApiMajorVersion = CHRE_EXTRACT_MAJOR_VERSION(chreGetApiVersion());
uint32_t targetApiMajorVersion =
@@ -45,11 +44,6 @@ bool validateAppInfo(uint64_t expectedAppId, uint32_t expectedAppVersion,
LOGE("Expected app version (0x%" PRIx32
") doesn't match internal one (0x%" PRIx32 ")",
expectedAppVersion, appInfo->appVersion);
- } else if (expectedTargetApiVersion != appInfo->targetApiVersion) {
- LOGE("Expected target API version (0x%" PRIx32
- ") doesn't match"
- " internal one (0x%" PRIx32 ")",
- expectedTargetApiVersion, appInfo->targetApiVersion);
} else if (targetApiMajorVersion != ourApiMajorVersion) {
LOGE("App targets a different major API version (%" PRIu32
") than what we provide (%" PRIu32 ")",
diff --git a/platform/shared/nanoapp/nanoapp_support_lib_dso.cc b/platform/shared/nanoapp/nanoapp_support_lib_dso.cc
index 1048f945..51cba033 100644
--- a/platform/shared/nanoapp/nanoapp_support_lib_dso.cc
+++ b/platform/shared/nanoapp/nanoapp_support_lib_dso.cc
@@ -20,10 +20,6 @@
#include "chre/platform/shared/debug_dump.h"
#include "chre/util/macros.h"
-#include "chre/util/system/napp_permissions.h"
-#ifdef CHRE_NANOAPP_USES_WIFI
-#include "chre/util/system/wifi_util.h"
-#endif
/**
* @file
@@ -35,42 +31,13 @@
namespace {
-constexpr uint32_t kNanoappPermissions = 0
-// DO NOT USE this macro outside of specific CHQTS nanoapps. This is only used
-// to allow testing of invalid permission declarations.
-#ifdef CHRE_TEST_NANOAPP_PERMS
- | CHRE_TEST_NANOAPP_PERMS
-#else
-#ifdef CHRE_NANOAPP_USES_AUDIO
- | static_cast<uint32_t>(
- chre::NanoappPermissions::
- CHRE_PERMS_AUDIO)
-#endif
-#ifdef CHRE_NANOAPP_USES_GNSS
- | static_cast<uint32_t>(
- chre::NanoappPermissions::
- CHRE_PERMS_GNSS)
-#endif
-#ifdef CHRE_NANOAPP_USES_WIFI
- | static_cast<uint32_t>(
- chre::NanoappPermissions::
- CHRE_PERMS_WIFI)
-#endif
-#ifdef CHRE_NANOAPP_USES_WWAN
- | static_cast<uint32_t>(
- chre::NanoappPermissions::
- CHRE_PERMS_WWAN)
-#endif
-#endif // CHRE_TEST_NANOAPP_PERMS
- ;
-
-#if defined(CHRE_SLPI_UIMG_ENABLED) || defined(CHRE_TCM_ENABLED)
+#ifdef CHRE_SLPI_UIMG_ENABLED
constexpr int kIsTcmNanoapp = 1;
#else
constexpr int kIsTcmNanoapp = 0;
#endif // CHRE_SLPI_UIMG_ENABLED
-#if !defined(CHRE_NANOAPP_DISABLE_BACKCOMPAT) && defined(CHRE_NANOAPP_USES_GNSS)
+#ifndef CHRE_NANOAPP_DISABLE_BACKCOMPAT
// Return a v1.3+ GnssLocationEvent for the nanoapp when running on a v1.2-
// platform.
chreGnssLocationEvent translateLegacyGnssLocation(
@@ -108,17 +75,6 @@ void nanoappHandleEventCompat(uint32_t senderInstanceId, uint16_t eventType,
} // anonymous namespace
-//! Used to determine the given unstable ID that was provided when building this
-//! nanoapp, if any. The symbol is placed in its own section so it can be
-//! stripped to determine if the nanoapp changed compared to a previous version.
-//! We also align the variable to match the minimum alignment of the surrounding
-//! sections, since for compilers with a default size-1 alignment, there might
-//! be a spill-over from the previous segment if not zero-padded, when we
-//! attempt to read the string.
-DLL_EXPORT extern "C" const char _chreNanoappUnstableId[]
- __attribute__((section(".unstable_id"))) __attribute__((aligned(8))) =
- NANOAPP_UNSTABLE_ID;
-
DLL_EXPORT extern "C" const struct chreNslNanoappInfo _chreNslDsoNanoappInfo = {
/* magic */ CHRE_NSL_NANOAPP_INFO_MAGIC,
/* structMinorVersion */ CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION,
@@ -136,15 +92,14 @@ DLL_EXPORT extern "C" const struct chreNslNanoappInfo _chreNslDsoNanoappInfo = {
/* entryPoints */
{
/* start */ nanoappStart,
-#if !defined(CHRE_NANOAPP_DISABLE_BACKCOMPAT) && defined(CHRE_NANOAPP_USES_GNSS)
+#ifndef CHRE_NANOAPP_DISABLE_BACKCOMPAT
/* handleEvent */ nanoappHandleEventCompat,
#else
/* handleEvent */ nanoappHandleEvent,
#endif
/* end */ nanoappEnd,
},
- /* appVersionString */ _chreNanoappUnstableId,
- /* appPermissions */ kNanoappPermissions,
+ /* appVersionString */ NANOAPP_VERSION_STRING,
};
// The code section below provides default implementations for new symbols
@@ -178,8 +133,6 @@ DLL_EXPORT extern "C" const struct chreNslNanoappInfo _chreNslDsoNanoappInfo = {
fptr; \
})
-#ifdef CHRE_NANOAPP_USES_AUDIO
-
WEAK_SYMBOL
bool chreAudioGetSource(uint32_t handle, struct chreAudioSource *audioSource) {
auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreAudioGetSource);
@@ -202,8 +155,6 @@ bool chreAudioGetStatus(uint32_t handle, struct chreAudioSourceStatus *status) {
return (fptr != nullptr) ? fptr(handle, status) : false;
}
-#endif /* CHRE_NANOAPP_USES_AUDIO */
-
WEAK_SYMBOL
void chreConfigureHostSleepStateEvents(bool enable) {
auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreConfigureHostSleepStateEvents);
@@ -218,35 +169,12 @@ bool chreIsHostAwake(void) {
return (fptr != nullptr) ? fptr() : false;
}
-#ifdef CHRE_NANOAPP_USES_GNSS
-
WEAK_SYMBOL
-bool chreGnssConfigurePassiveLocationListener(bool enable) {
- auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreGnssConfigurePassiveLocationListener);
+bool chreGnssConfigureLocationMonitor(bool enable) {
+ auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreGnssConfigureLocationMonitor);
return (fptr != nullptr) ? fptr(enable) : false;
}
-#endif /* CHRE_NANOAPP_USES_GNSS */
-
-#ifdef CHRE_NANOAPP_USES_WIFI
-
-WEAK_SYMBOL
-bool chreWifiRequestScanAsync(const struct chreWifiScanParams *params,
- const void *cookie) {
- auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreWifiRequestScanAsync);
-
- if (fptr == nullptr) {
- // Should never happen
- return false;
- } else if (chreGetApiVersion() < CHRE_API_VERSION_1_5) {
- const struct chreWifiScanParams legacyParams =
- chre::translateToLegacyWifiScanParams(params);
- return fptr(&legacyParams, cookie);
- } else {
- return fptr(params, cookie);
- }
-}
-
WEAK_SYMBOL
bool chreWifiRequestRangingAsync(const struct chreWifiRangingParams *params,
const void *cookie) {
@@ -254,20 +182,6 @@ bool chreWifiRequestRangingAsync(const struct chreWifiRangingParams *params,
return (fptr != nullptr) ? fptr(params, cookie) : false;
}
-#endif /* CHRE_NANOAPP_USES_WIFI */
-
-WEAK_SYMBOL
-bool chreSensorFind(uint8_t sensorType, uint8_t sensorIndex, uint32_t *handle) {
- auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreSensorFind);
- if (fptr != nullptr) {
- return fptr(sensorType, sensorIndex, handle);
- } else if (sensorIndex == 0) {
- return chreSensorFindDefault(sensorType, handle);
- } else {
- return false;
- }
-}
-
WEAK_SYMBOL
bool chreSensorConfigureBiasEvents(uint32_t sensorHandle, bool enable) {
auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreSensorConfigureBiasEvents);
@@ -306,37 +220,4 @@ void chreDebugDumpLog(const char *formatStr, ...) {
}
}
-WEAK_SYMBOL
-bool chreSendMessageWithPermissions(void *message, size_t messageSize,
- uint32_t messageType, uint16_t hostEndpoint,
- uint32_t messagePermissions,
- chreMessageFreeFunction *freeCallback) {
- auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreSendMessageWithPermissions);
- if (fptr != nullptr) {
- return fptr(message, messageSize, messageType, hostEndpoint,
- messagePermissions, freeCallback);
- } else {
- return chreSendMessageToHostEndpoint(message, messageSize, messageType,
- hostEndpoint, freeCallback);
- }
-}
-
-WEAK_SYMBOL
-int8_t chreUserSettingGetState(uint8_t setting) {
- int8_t settingState = CHRE_USER_SETTING_STATE_UNKNOWN;
- auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreUserSettingGetState);
- if (fptr != nullptr) {
- settingState = fptr(setting);
- }
- return settingState;
-}
-
-WEAK_SYMBOL
-void chreUserSettingConfigureEvents(uint8_t setting, bool enable) {
- auto *fptr = CHRE_NSL_LAZY_LOOKUP(chreUserSettingConfigureEvents);
- if (fptr != nullptr) {
- fptr(setting, enable);
- }
-}
-
#endif // CHRE_NANOAPP_DISABLE_BACKCOMPAT
diff --git a/platform/shared/nanoapp_loader.cc b/platform/shared/nanoapp_loader.cc
deleted file mode 100644
index d003fbbc..00000000
--- a/platform/shared/nanoapp_loader.cc
+++ /dev/null
@@ -1,931 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <dlfcn.h>
-#include <cctype>
-#include <cmath>
-#include <cstring>
-
-#include "chre/platform/shared/nanoapp_loader.h"
-
-#include "ash.h"
-#include "ash/profile.h"
-#include "chre.h"
-#include "chre/platform/assert.h"
-#include "chre/platform/fatal_error.h"
-#include "chre/platform/shared/debug_dump.h"
-#include "chre/platform/shared/memory.h"
-#include "chre/target_platform/platform_cache_management.h"
-#include "chre/util/dynamic_vector.h"
-#include "chre/util/macros.h"
-
-#ifndef CHRE_LOADER_ARCH
-#define CHRE_LOADER_ARCH EM_ARM
-#endif // CHRE_LOADER_ARCH
-
-namespace chre {
-namespace {
-
-using ElfHeader = ElfW(Ehdr);
-using ProgramHeader = ElfW(Phdr);
-
-struct ExportedData {
- void *data;
- const char *dataName;
-};
-
-//! If non-null, a nanoapp is currently being loaded. This allows certain C
-//! functions to access the nanoapp if called during static init.
-NanoappLoader *gCurrentlyLoadingNanoapp = nullptr;
-//! Indicates whether a failure occurred during static initialization.
-bool gStaticInitFailure = false;
-
-// The new operator is used by singleton.h which causes the delete operator to
-// be undefined in nanoapp binaries even though it's unused. Define this in case
-// a nanoapp actually tries to use the operator.
-void deleteOverride(void *ptr) {
- FATAL_ERROR("Nanoapp tried to free %p through delete operator", ptr);
-}
-
-// atexit is used to register functions that must be called when a binary is
-// removed from the system.
-int atexitOverride(void (*function)(void)) {
- LOGV("atexit invoked with %p", function);
- if (gCurrentlyLoadingNanoapp == nullptr) {
- CHRE_ASSERT_LOG(false,
- "atexit is only supported during static initialization.");
- return -1;
- }
-
- gCurrentlyLoadingNanoapp->registerAtexitFunction(function);
- return 0;
-}
-
-// The following functions from the cmath header need to be overridden, since
-// they're overloaded functions, and we need to specify explicit types of the
-// template for the compiler.
-double frexpOverride(double value, int *exp) {
- return frexp(value, exp);
-}
-
-double fmaxOverride(double x, double y) {
- return fmax(x, y);
-}
-
-double fminOverride(double x, double y) {
- return fmin(x, y);
-}
-
-double floorOverride(double value) {
- return floor(value);
-}
-
-double sinOverride(double rad) {
- return sin(rad);
-}
-
-double asinOverride(double val) {
- return asin(val);
-}
-
-double atan2Override(double y, double x) {
- return atan2(y, x);
-}
-
-double cosOverride(double rad) {
- return cos(rad);
-}
-
-float sqrtOverride(float val) {
- return sqrt(val);
-}
-
-double roundOverride(double val) {
- return round(val);
-}
-
-// This function is required to be exposed to nanoapps to handle errors from
-// invoking virtual functions.
-void __cxa_pure_virtual(void) {
- chreAbort(CHRE_ERROR /* abortCode */);
-}
-
-#define ADD_EXPORTED_SYMBOL(function_name, function_string) \
- { reinterpret_cast<void *>(function_name), function_string }
-#define ADD_EXPORTED_C_SYMBOL(function_name) \
- ADD_EXPORTED_SYMBOL(function_name, STRINGIFY(function_name))
-
-// TODO(karthikmb/stange): While this array was hand-coded for simple
-// "hello-world" prototyping, the list of exported symbols must be
-// generated to minimize runtime errors and build breaks.
-// clang-format off
-// Disable deprecation warning so that deprecated symbols in the array
-// can be exported for older nanoapps and tests.
-CHRE_DEPRECATED_PREAMBLE
-const ExportedData gExportedData[] = {
- /* libmath overrrides and symbols */
- ADD_EXPORTED_SYMBOL(asinOverride, "asin"),
- ADD_EXPORTED_SYMBOL(atan2Override, "atan2"),
- ADD_EXPORTED_SYMBOL(cosOverride, "cos"),
- ADD_EXPORTED_SYMBOL(frexpOverride, "frexp"),
- ADD_EXPORTED_SYMBOL(fmaxOverride, "fmax"),
- ADD_EXPORTED_SYMBOL(fminOverride, "fmin"),
- ADD_EXPORTED_SYMBOL(floorOverride, "floor"),
- ADD_EXPORTED_SYMBOL(roundOverride, "round"),
- ADD_EXPORTED_SYMBOL(sinOverride, "sin"),
- ADD_EXPORTED_SYMBOL(sqrtOverride, "sqrt"),
- ADD_EXPORTED_C_SYMBOL(acosf),
- ADD_EXPORTED_C_SYMBOL(asinf),
- ADD_EXPORTED_C_SYMBOL(atan2f),
- ADD_EXPORTED_C_SYMBOL(cosf),
- ADD_EXPORTED_C_SYMBOL(expf),
- ADD_EXPORTED_C_SYMBOL(floorf),
- ADD_EXPORTED_C_SYMBOL(fmaxf),
- ADD_EXPORTED_C_SYMBOL(fminf),
- ADD_EXPORTED_C_SYMBOL(fmodf),
- ADD_EXPORTED_C_SYMBOL(log10f),
- ADD_EXPORTED_C_SYMBOL(lroundf),
- ADD_EXPORTED_C_SYMBOL(roundf),
- ADD_EXPORTED_C_SYMBOL(sinf),
- ADD_EXPORTED_C_SYMBOL(sqrtf),
- ADD_EXPORTED_C_SYMBOL(tanhf),
- /* libc overrides and symbols */
- ADD_EXPORTED_C_SYMBOL(__cxa_pure_virtual),
- ADD_EXPORTED_SYMBOL(atexitOverride, "atexit"),
- ADD_EXPORTED_SYMBOL(deleteOverride, "_ZdlPv"),
- ADD_EXPORTED_C_SYMBOL(dlsym),
- ADD_EXPORTED_C_SYMBOL(memcmp),
- ADD_EXPORTED_C_SYMBOL(memcpy),
- ADD_EXPORTED_C_SYMBOL(memmove),
- ADD_EXPORTED_C_SYMBOL(memset),
- ADD_EXPORTED_C_SYMBOL(snprintf),
- ADD_EXPORTED_C_SYMBOL(strcmp),
- ADD_EXPORTED_C_SYMBOL(strlen),
- ADD_EXPORTED_C_SYMBOL(strncmp),
- ADD_EXPORTED_C_SYMBOL(tolower),
- /* ash symbols */
- ADD_EXPORTED_C_SYMBOL(ashProfileInit),
- ADD_EXPORTED_C_SYMBOL(ashProfileBegin),
- ADD_EXPORTED_C_SYMBOL(ashProfileEnd),
- ADD_EXPORTED_C_SYMBOL(ashLoadCalibrationParams),
- ADD_EXPORTED_C_SYMBOL(ashSaveCalibrationParams),
- ADD_EXPORTED_C_SYMBOL(ashSetCalibration),
- ADD_EXPORTED_C_SYMBOL(ashLoadMultiCalibrationParams),
- ADD_EXPORTED_C_SYMBOL(ashSaveMultiCalibrationParams),
- ADD_EXPORTED_C_SYMBOL(ashSetMultiCalibration),
- /* CHRE symbols */
- ADD_EXPORTED_C_SYMBOL(chreAbort),
- ADD_EXPORTED_C_SYMBOL(chreAudioConfigureSource),
- ADD_EXPORTED_C_SYMBOL(chreAudioGetSource),
- ADD_EXPORTED_C_SYMBOL(chreConfigureDebugDumpEvent),
- ADD_EXPORTED_C_SYMBOL(chreConfigureHostSleepStateEvents),
- ADD_EXPORTED_C_SYMBOL(chreConfigureNanoappInfoEvents),
- ADD_EXPORTED_C_SYMBOL(chreDebugDumpLog),
- ADD_EXPORTED_C_SYMBOL(chreGetApiVersion),
- ADD_EXPORTED_C_SYMBOL(chreGetAppId),
- ADD_EXPORTED_C_SYMBOL(chreGetInstanceId),
- ADD_EXPORTED_C_SYMBOL(chreGetEstimatedHostTimeOffset),
- ADD_EXPORTED_C_SYMBOL(chreGetNanoappInfoByAppId),
- ADD_EXPORTED_C_SYMBOL(chreGetNanoappInfoByInstanceId),
- ADD_EXPORTED_C_SYMBOL(chreGetPlatformId),
- ADD_EXPORTED_C_SYMBOL(chreGetSensorInfo),
- ADD_EXPORTED_C_SYMBOL(chreGetSensorSamplingStatus),
- ADD_EXPORTED_C_SYMBOL(chreGetTime),
- ADD_EXPORTED_C_SYMBOL(chreGetVersion),
- ADD_EXPORTED_C_SYMBOL(chreGnssConfigurePassiveLocationListener),
- ADD_EXPORTED_C_SYMBOL(chreGnssGetCapabilities),
- ADD_EXPORTED_C_SYMBOL(chreGnssLocationSessionStartAsync),
- ADD_EXPORTED_C_SYMBOL(chreGnssLocationSessionStopAsync),
- ADD_EXPORTED_C_SYMBOL(chreGnssMeasurementSessionStartAsync),
- ADD_EXPORTED_C_SYMBOL(chreGnssMeasurementSessionStopAsync),
- ADD_EXPORTED_C_SYMBOL(chreHeapAlloc),
- ADD_EXPORTED_C_SYMBOL(chreHeapFree),
- ADD_EXPORTED_C_SYMBOL(chreIsHostAwake),
- ADD_EXPORTED_C_SYMBOL(chreLog),
- ADD_EXPORTED_C_SYMBOL(chreSendEvent),
- ADD_EXPORTED_C_SYMBOL(chreSendMessageToHost),
- ADD_EXPORTED_C_SYMBOL(chreSendMessageToHostEndpoint),
- ADD_EXPORTED_C_SYMBOL(chreSendMessageWithPermissions),
- ADD_EXPORTED_C_SYMBOL(chreSensorConfigure),
- ADD_EXPORTED_C_SYMBOL(chreSensorConfigureBiasEvents),
- ADD_EXPORTED_C_SYMBOL(chreSensorFind),
- ADD_EXPORTED_C_SYMBOL(chreSensorFindDefault),
- ADD_EXPORTED_C_SYMBOL(chreSensorFlushAsync),
- ADD_EXPORTED_C_SYMBOL(chreSensorGetThreeAxisBias),
- ADD_EXPORTED_C_SYMBOL(chreTimerCancel),
- ADD_EXPORTED_C_SYMBOL(chreTimerSet),
- ADD_EXPORTED_C_SYMBOL(chreUserSettingConfigureEvents),
- ADD_EXPORTED_C_SYMBOL(chreUserSettingGetState),
- ADD_EXPORTED_C_SYMBOL(chreWifiConfigureScanMonitorAsync),
- ADD_EXPORTED_C_SYMBOL(chreWifiGetCapabilities),
- ADD_EXPORTED_C_SYMBOL(chreWifiRequestScanAsync),
- ADD_EXPORTED_C_SYMBOL(chreWifiRequestRangingAsync),
- ADD_EXPORTED_C_SYMBOL(chreWwanGetCapabilities),
- ADD_EXPORTED_C_SYMBOL(chreWwanGetCellInfoAsync),
- ADD_EXPORTED_C_SYMBOL(platform_chreDebugDumpVaLog),
-};
-CHRE_DEPRECATED_EPILOGUE
-// clang-format on
-
-} // namespace
-
-void *NanoappLoader::create(void *elfInput, bool mapIntoTcm) {
- void *instance = nullptr;
- NanoappLoader *loader = memoryAllocDram<NanoappLoader>(elfInput, mapIntoTcm);
- if (loader != nullptr) {
- if (loader->open()) {
- instance = loader;
- } else {
- memoryFreeDram(loader);
- }
- } else {
- LOG_OOM();
- }
-
- return instance;
-}
-
-void NanoappLoader::destroy(NanoappLoader *loader) {
- loader->close();
- // TODO(b/151847750): Modify utilities to support free'ing from regions other
- // than SRAM.
- loader->~NanoappLoader();
- memoryFreeDram(loader);
-}
-
-void *NanoappLoader::findExportedSymbol(const char *name) {
- size_t nameLen = strlen(name);
- for (size_t i = 0; i < ARRAY_SIZE(gExportedData); i++) {
- if (nameLen == strlen(gExportedData[i].dataName) &&
- strncmp(name, gExportedData[i].dataName, nameLen) == 0) {
- return gExportedData[i].data;
- }
- }
-
- LOGE("Unable to find %s", name);
- return nullptr;
-}
-
-bool NanoappLoader::open() {
- bool success = false;
- if (mBinary != nullptr) {
- if (!copyAndVerifyHeaders()) {
- LOGE("Failed to verify headers");
- } else if (!createMappings()) {
- LOGE("Failed to create mappings");
- } else if (!fixRelocations()) {
- LOGE("Failed to fix relocations");
- } else if (!resolveGot()) {
- LOGE("Failed to resolve GOT");
- } else {
- // Wipe caches before calling init array to ensure initializers are not in
- // the data cache.
- wipeSystemCaches();
- if (!callInitArray()) {
- LOGE("Failed to perform static init");
- } else {
- success = true;
- }
- }
- }
-
- if (!success) {
- freeAllocatedData();
- }
-
- return success;
-}
-
-void NanoappLoader::close() {
- callAtexitFunctions();
- callTerminatorArray();
- freeAllocatedData();
-}
-
-void *NanoappLoader::findSymbolByName(const char *name) {
- void *symbol = nullptr;
- uint8_t *index = mSymbolTablePtr;
- while (index < (mSymbolTablePtr + mSymbolTableSize)) {
- ElfSym *currSym = reinterpret_cast<ElfSym *>(index);
- const char *symbolName = &mStringTablePtr[currSym->st_name];
-
- if (strncmp(symbolName, name, strlen(name)) == 0) {
- symbol = mMapping + currSym->st_value;
- break;
- }
-
- index += sizeof(ElfSym);
- }
- return symbol;
-}
-
-void NanoappLoader::registerAtexitFunction(void (*function)(void)) {
- if (!mAtexitFunctions.push_back(function)) {
- LOG_OOM();
- gStaticInitFailure = true;
- }
-}
-
-void NanoappLoader::mapBss(const ProgramHeader *hdr) {
- // if the memory size of this segment exceeds the file size zero fill the
- // difference.
- LOGV("Program Hdr mem sz: %zu file size: %zu", hdr->p_memsz, hdr->p_filesz);
- if (hdr->p_memsz > hdr->p_filesz) {
- ElfAddr endOfFile = hdr->p_vaddr + hdr->p_filesz + mLoadBias;
- ElfAddr endOfMem = hdr->p_vaddr + hdr->p_memsz + mLoadBias;
- if (endOfMem > endOfFile) {
- auto deltaMem = endOfMem - endOfFile;
- LOGV("Zeroing out %zu from page %x", deltaMem, endOfFile);
- memset(reinterpret_cast<void *>(endOfFile), 0, deltaMem);
- }
- }
-}
-
-bool NanoappLoader::callInitArray() {
- bool success = true;
- // Sets global variable used by atexit in case it's invoked as part of
- // initializing static data.
- gCurrentlyLoadingNanoapp = this;
-
- // TODO(b/151847750): ELF can have other sections like .init, .preinit, .fini
- // etc. Be sure to look for those if they end up being something that should
- // be supported for nanoapps.
- for (size_t i = 0; i < mNumSectionHeaders; ++i) {
- const char *name = getSectionHeaderName(mSectionHeadersPtr[i].sh_name);
- if (strncmp(name, kInitArrayName, strlen(kInitArrayName)) == 0) {
- LOGV("Invoking init function");
- uintptr_t initArray = reinterpret_cast<uintptr_t>(
- mLoadBias + mSectionHeadersPtr[i].sh_addr);
- uintptr_t offset = 0;
- while (offset < mSectionHeadersPtr[i].sh_size) {
- ElfAddr *funcPtr = reinterpret_cast<ElfAddr *>(initArray + offset);
- uintptr_t initFunction = reinterpret_cast<uintptr_t>(*funcPtr);
- ((void (*)())initFunction)();
- offset += sizeof(initFunction);
- if (gStaticInitFailure) {
- success = false;
- break;
- }
- }
- break;
- }
- }
-
- //! Reset global state so it doesn't leak into the next load.
- gCurrentlyLoadingNanoapp = nullptr;
- gStaticInitFailure = false;
- return success;
-}
-
-uintptr_t NanoappLoader::roundDownToAlign(uintptr_t virtualAddr) {
- return virtualAddr & -kBinaryAlignment;
-}
-
-void NanoappLoader::freeAllocatedData() {
- if (mIsTcmBinary) {
- nanoappBinaryFree(mMapping);
- } else {
- nanoappBinaryDramFree(mMapping);
- }
- memoryFreeDram(mSectionHeadersPtr);
- memoryFreeDram(mSectionNamesPtr);
- memoryFreeDram(mSymbolTablePtr);
- memoryFreeDram(mStringTablePtr);
-}
-
-bool NanoappLoader::verifyElfHeader() {
- bool success = false;
- ElfHeader *elfHeader = getElfHeader();
- if (elfHeader != nullptr && (elfHeader->e_ident[EI_MAG0] == ELFMAG0) &&
- (elfHeader->e_ident[EI_MAG1] == ELFMAG1) &&
- (elfHeader->e_ident[EI_MAG2] == ELFMAG2) &&
- (elfHeader->e_ident[EI_MAG3] == ELFMAG3) &&
- (elfHeader->e_ehsize == sizeof(ElfHeader)) &&
- (elfHeader->e_phentsize == sizeof(ProgramHeader)) &&
- (elfHeader->e_shentsize == sizeof(SectionHeader)) &&
- (elfHeader->e_shstrndx < elfHeader->e_shnum) &&
- (elfHeader->e_version == EV_CURRENT) &&
- (elfHeader->e_machine == CHRE_LOADER_ARCH) &&
- (elfHeader->e_type == ET_DYN)) {
- success = true;
- }
- return success;
-}
-
-bool NanoappLoader::verifyProgramHeaders() {
- // This is a minimal check for now -
- // there should be at least one load segment.
- bool success = false;
- for (size_t i = 0; i < getProgramHeaderArraySize(); ++i) {
- if (getProgramHeaderArray()[i].p_type == PT_LOAD) {
- success = true;
- break;
- }
- }
- return success;
-}
-
-const char *NanoappLoader::getSectionHeaderName(size_t headerOffset) {
- if (headerOffset == 0) {
- return "";
- }
-
- return &mSectionNamesPtr[headerOffset];
-}
-
-NanoappLoader::SectionHeader *NanoappLoader::getSectionHeader(
- const char *headerName) {
- SectionHeader *rv = nullptr;
- for (size_t i = 0; i < mNumSectionHeaders; ++i) {
- const char *name = getSectionHeaderName(mSectionHeadersPtr[i].sh_name);
- if (strncmp(name, headerName, strlen(headerName)) == 0) {
- rv = &mSectionHeadersPtr[i];
- break;
- }
- }
- return rv;
-}
-
-ElfHeader *NanoappLoader::getElfHeader() {
- return reinterpret_cast<ElfHeader *>(mBinary);
-}
-
-ProgramHeader *NanoappLoader::getProgramHeaderArray() {
- ElfHeader *elfHeader = getElfHeader();
- ProgramHeader *programHeader = nullptr;
- if (elfHeader != nullptr) {
- programHeader =
- reinterpret_cast<ProgramHeader *>(mBinary + elfHeader->e_phoff);
- }
-
- return programHeader;
-}
-
-size_t NanoappLoader::getProgramHeaderArraySize() {
- ElfHeader *elfHeader = getElfHeader();
- size_t arraySize = 0;
- if (elfHeader != nullptr) {
- arraySize = elfHeader->e_phnum;
- }
-
- return arraySize;
-}
-
-char *NanoappLoader::getDynamicStringTable() {
- char *table = nullptr;
-
- SectionHeader *dynamicStringTablePtr = getSectionHeader(".dynstr");
- CHRE_ASSERT(dynamicStringTablePtr != nullptr);
- if (dynamicStringTablePtr != nullptr && mBinary != nullptr) {
- table =
- reinterpret_cast<char *>(mBinary + dynamicStringTablePtr->sh_offset);
- }
-
- return table;
-}
-
-uint8_t *NanoappLoader::getDynamicSymbolTable() {
- uint8_t *table = nullptr;
-
- SectionHeader *dynamicSymbolTablePtr = getSectionHeader(".dynsym");
- CHRE_ASSERT(dynamicSymbolTablePtr != nullptr);
- if (dynamicSymbolTablePtr != nullptr && mBinary != nullptr) {
- table = (mBinary + dynamicSymbolTablePtr->sh_offset);
- }
-
- return table;
-}
-
-size_t NanoappLoader::getDynamicSymbolTableSize() {
- size_t tableSize = 0;
-
- SectionHeader *dynamicSymbolTablePtr = getSectionHeader(".dynsym");
- CHRE_ASSERT(dynamicSymbolTablePtr != nullptr);
- if (dynamicSymbolTablePtr != nullptr) {
- tableSize = dynamicSymbolTablePtr->sh_size;
- }
-
- return tableSize;
-}
-
-bool NanoappLoader::verifySectionHeaders() {
- bool foundSymbolTableHeader = false;
- bool foundStringTableHeader = false;
-
- for (size_t i = 0; i < mNumSectionHeaders; ++i) {
- const char *name = getSectionHeaderName(mSectionHeadersPtr[i].sh_name);
-
- if (strncmp(name, kSymTableName, strlen(kSymTableName)) == 0) {
- foundSymbolTableHeader = true;
- } else if (strncmp(name, kStrTableName, strlen(kStrTableName)) == 0) {
- foundStringTableHeader = true;
- }
- }
-
- return foundSymbolTableHeader && foundStringTableHeader;
-}
-
-bool NanoappLoader::copyAndVerifyHeaders() {
- size_t offset = 0;
- bool success = false;
- uint8_t *pDataBytes = mBinary;
-
- // Verify the ELF Header
- ElfHeader *elfHeader = getElfHeader();
- success = verifyElfHeader();
-
- LOGV("Verified ELF header %d", success);
-
- // Verify Program Headers
- if (success) {
- success = verifyProgramHeaders();
- }
-
- LOGV("Verified Program headers %d", success);
-
- // Load Section Headers
- if (success) {
- offset = elfHeader->e_shoff;
- size_t sectionHeaderSizeBytes = sizeof(SectionHeader) * elfHeader->e_shnum;
- mSectionHeadersPtr =
- static_cast<SectionHeader *>(memoryAllocDram(sectionHeaderSizeBytes));
- if (mSectionHeadersPtr == nullptr) {
- success = false;
- LOG_OOM();
- } else {
- memcpy(mSectionHeadersPtr, (pDataBytes + offset), sectionHeaderSizeBytes);
- mNumSectionHeaders = elfHeader->e_shnum;
- }
- }
-
- LOGV("Loaded section headers %d", success);
-
- // Load section header names
- if (success) {
- SectionHeader &stringSection = mSectionHeadersPtr[elfHeader->e_shstrndx];
- size_t sectionSize = stringSection.sh_size;
- mSectionNamesPtr = static_cast<char *>(memoryAllocDram(sectionSize));
- if (mSectionNamesPtr == nullptr) {
- LOG_OOM();
- success = false;
- } else {
- memcpy(mSectionNamesPtr, mBinary + stringSection.sh_offset, sectionSize);
- }
- }
-
- LOGV("Loaded section header names %d", success);
-
- success = verifySectionHeaders();
- LOGV("Verified Section headers %d", success);
-
- // Load symbol table
- if (success) {
- SectionHeader *symbolTableHeader = getSectionHeader(kSymTableName);
- mSymbolTableSize = symbolTableHeader->sh_size;
- if (mSymbolTableSize == 0) {
- LOGE("No symbols to resolve");
- success = false;
- } else {
- mSymbolTablePtr =
- static_cast<uint8_t *>(memoryAllocDram(mSymbolTableSize));
- if (mSymbolTablePtr == nullptr) {
- LOG_OOM();
- success = false;
- } else {
- memcpy(mSymbolTablePtr, mBinary + symbolTableHeader->sh_offset,
- mSymbolTableSize);
- }
- }
- }
-
- LOGV("Loaded symbol table %d", success);
-
- // Load string table
- if (success) {
- SectionHeader *stringTableHeader = getSectionHeader(kStrTableName);
- size_t stringTableSize = stringTableHeader->sh_size;
- if (mSymbolTableSize == 0) {
- LOGE("No string table corresponding to symbols");
- success = false;
- } else {
- mStringTablePtr = static_cast<char *>(memoryAllocDram(stringTableSize));
- if (mStringTablePtr == nullptr) {
- LOG_OOM();
- success = false;
- } else {
- memcpy(mStringTablePtr, mBinary + stringTableHeader->sh_offset,
- stringTableSize);
- }
- }
- }
-
- LOGV("Loaded string table %d", success);
-
- return success;
-}
-
-bool NanoappLoader::createMappings() {
- // ELF needs pt_load segments to be in contiguous ascending order of
- // virtual addresses. So the first and last segs can be used to
- // calculate the entire address span of the image.
- ElfHeader *elfHeader = getElfHeader();
- ProgramHeader *programHeaderArray = getProgramHeaderArray();
- size_t numProgramHeaders = getProgramHeaderArraySize();
- const ProgramHeader *first = &programHeaderArray[0];
- const ProgramHeader *last = &programHeaderArray[numProgramHeaders - 1];
-
- // Find first load segment
- while (first->p_type != PT_LOAD && first <= last) {
- ++first;
- }
-
- bool success = false;
- if (first->p_type != PT_LOAD) {
- LOGE("Unable to find any load segments in the binary");
- } else {
- // Verify that the first load segment has a program header
- // first byte of a valid load segment can't be greater than the
- // program header offset
- bool valid =
- (first->p_offset < elfHeader->e_phoff) &&
- (first->p_filesz >
- (elfHeader->e_phoff + (numProgramHeaders * sizeof(ProgramHeader))));
- if (!valid) {
- LOGE("Load segment program header validation failed");
- } else {
- // Get the last load segment
- while (last > first && last->p_type != PT_LOAD) --last;
-
- size_t memorySpan = last->p_vaddr + last->p_memsz - first->p_vaddr;
- LOGV("Nanoapp image Memory Span: %u", memorySpan);
-
- if (mIsTcmBinary) {
- mMapping = static_cast<uint8_t *>(
- nanoappBinaryAlloc(memorySpan, kBinaryAlignment));
- } else {
- mMapping = static_cast<uint8_t *>(
- nanoappBinaryDramAlloc(memorySpan, kBinaryAlignment));
- }
-
- if (mMapping == nullptr) {
- LOG_OOM();
- } else {
- LOGV("Starting location of mappings %p", mMapping);
-
- // Calculate the load bias using the first load segment.
- uintptr_t adjustedFirstLoadSegAddr = roundDownToAlign(first->p_vaddr);
- mLoadBias =
- reinterpret_cast<uintptr_t>(mMapping) - adjustedFirstLoadSegAddr;
- LOGV("Load bias is %" PRIu32, mLoadBias);
-
- success = true;
- }
- }
- }
-
- if (success) {
- // Map the remaining segments
- for (const ProgramHeader *ph = first; ph <= last; ++ph) {
- if (ph->p_type == PT_LOAD) {
- ElfAddr segStart = ph->p_vaddr + mLoadBias;
- void *startPage = reinterpret_cast<void *>(segStart);
- void *binaryStartPage = mBinary + ph->p_offset;
- size_t segmentLen = ph->p_filesz;
-
- LOGV("Mapping start page %p from %p with length %zu", startPage,
- binaryStartPage, segmentLen);
- memcpy(startPage, binaryStartPage, segmentLen);
- mapBss(ph);
- } else {
- LOGE("Non-load segment found between load segments");
- success = false;
- break;
- }
- }
- }
-
- return success;
-}
-
-const char *NanoappLoader::getDataName(size_t posInSymbolTable) {
- size_t sectionSize = getDynamicSymbolTableSize();
- uint8_t *dynamicSymbolTable = getDynamicSymbolTable();
- size_t numElements = sectionSize / sizeof(ElfSym);
- CHRE_ASSERT(posInSymbolTable < numElements);
- char *dataName = nullptr;
- if (posInSymbolTable < numElements) {
- ElfSym *sym = reinterpret_cast<ElfSym *>(
- &dynamicSymbolTable[posInSymbolTable * sizeof(ElfSym)]);
- dataName = &getDynamicStringTable()[sym->st_name];
- }
- return dataName;
-}
-
-void *NanoappLoader::resolveData(size_t posInSymbolTable) {
- const char *dataName = getDataName(posInSymbolTable);
-
- if (dataName != nullptr) {
- LOGV("Resolving %s", dataName);
- return findExportedSymbol(dataName);
- }
-
- return nullptr;
-}
-
-NanoappLoader::DynamicHeader *NanoappLoader::getDynamicHeader() {
- DynamicHeader *dyn = nullptr;
- ProgramHeader *programHeaders = getProgramHeaderArray();
- for (size_t i = 0; i < getProgramHeaderArraySize(); ++i) {
- if (programHeaders[i].p_type == PT_DYNAMIC) {
- dyn = reinterpret_cast<DynamicHeader *>(programHeaders[i].p_offset +
- mBinary);
- break;
- }
- }
- return dyn;
-}
-
-NanoappLoader::ProgramHeader *NanoappLoader::getFirstRoSegHeader() {
- // return the first read only segment found
- ProgramHeader *ro = nullptr;
- ProgramHeader *programHeaders = getProgramHeaderArray();
- for (size_t i = 0; i < getProgramHeaderArraySize(); ++i) {
- if (!(programHeaders[i].p_flags & PF_W)) {
- ro = &programHeaders[i];
- break;
- }
- }
- return ro;
-}
-
-NanoappLoader::ElfWord NanoappLoader::getDynEntry(DynamicHeader *dyn,
- int field) {
- ElfWord rv = 0;
-
- while (dyn->d_tag != DT_NULL) {
- if (dyn->d_tag == field) {
- rv = dyn->d_un.d_val;
- break;
- }
- ++dyn;
- }
-
- return rv;
-}
-
-bool NanoappLoader::fixRelocations() {
- ElfAddr *addr;
- DynamicHeader *dyn = getDynamicHeader();
- ProgramHeader *roSeg = getFirstRoSegHeader();
-
- bool success = false;
- if ((dyn == nullptr) || (roSeg == nullptr)) {
- LOGE("Mandatory headers missing from shared object, aborting load");
- } else if (getDynEntry(dyn, DT_RELA) != 0) {
- LOGE("Elf binaries with a DT_RELA dynamic entry are unsupported");
- } else {
- ElfRel *reloc =
- reinterpret_cast<ElfRel *>(mBinary + getDynEntry(dyn, DT_REL));
- size_t relocSize = getDynEntry(dyn, DT_RELSZ);
- size_t nRelocs = relocSize / sizeof(ElfRel);
- LOGV("Relocation %zu entries in DT_REL table", nRelocs);
-
- size_t i;
- for (i = 0; i < nRelocs; ++i) {
- ElfRel *curr = &reloc[i];
- int relocType = ELFW_R_TYPE(curr->r_info);
- switch (relocType) {
- case R_ARM_RELATIVE:
- LOGV("Resolving ARM_RELATIVE at offset %" PRIx32, curr->r_offset);
- addr = reinterpret_cast<ElfAddr *>(mMapping + curr->r_offset);
- // TODO: When we move to DRAM allocations, we need to check if the
- // above address is in a Read-Only section of memory, and give it
- // temporary write permission if that is the case.
- *addr += reinterpret_cast<uintptr_t>(mMapping);
- break;
-
- case R_ARM_ABS32: {
- LOGV("Resolving ARM_ABS32 at offset %" PRIx32, curr->r_offset);
- addr = reinterpret_cast<ElfAddr *>(mMapping + curr->r_offset);
- size_t posInSymbolTable = ELFW_R_SYM(curr->r_info);
- auto *dynamicSymbolTable =
- reinterpret_cast<ElfSym *>(getDynamicSymbolTable());
- ElfSym *sym = &dynamicSymbolTable[posInSymbolTable];
- *addr = reinterpret_cast<uintptr_t>(mMapping + sym->st_value);
-
- break;
- }
-
- case R_ARM_GLOB_DAT: {
- LOGV("Resolving type ARM_GLOB_DAT at offset %" PRIx32,
- curr->r_offset);
- addr = reinterpret_cast<ElfAddr *>(mMapping + curr->r_offset);
- size_t posInSymbolTable = ELFW_R_SYM(curr->r_info);
- void *resolved = resolveData(posInSymbolTable);
- if (resolved == nullptr) {
- LOGV("Failed to resolve global symbol(%d) at offset 0x%x", i,
- curr->r_offset);
- return false;
- }
- // TODO: When we move to DRAM allocations, we need to check if the
- // above address is in a Read-Only section of memory, and give it
- // temporary write permission if that is the case.
- *addr = reinterpret_cast<ElfAddr>(resolved);
- break;
- }
-
- case R_ARM_COPY:
- LOGE("R_ARM_COPY is an invalid relocation for shared libraries");
- break;
- default:
- LOGE("Invalid relocation type %u", relocType);
- break;
- }
- }
-
- if (i != nRelocs) {
- LOGE("Unable to resolve all symbols in the binary");
- } else {
- success = true;
- }
- }
-
- return success;
-}
-
-bool NanoappLoader::resolveGot() {
- ElfAddr *addr;
- ElfRel *reloc = reinterpret_cast<ElfRel *>(
- mMapping + getDynEntry(getDynamicHeader(), DT_JMPREL));
- size_t relocSize = getDynEntry(getDynamicHeader(), DT_PLTRELSZ);
- size_t nRelocs = relocSize / sizeof(ElfRel);
- LOGV("Resolving GOT with %zu relocations", nRelocs);
-
- for (size_t i = 0; i < nRelocs; ++i) {
- ElfRel *curr = &reloc[i];
- int relocType = ELFW_R_TYPE(curr->r_info);
-
- switch (relocType) {
- case R_ARM_JUMP_SLOT: {
- LOGV("Resolving ARM_JUMP_SLOT at offset %" PRIx32, curr->r_offset);
- addr = reinterpret_cast<ElfAddr *>(mMapping + curr->r_offset);
- size_t posInSymbolTable = ELFW_R_SYM(curr->r_info);
- void *resolved = resolveData(posInSymbolTable);
- if (resolved == nullptr) {
- LOGV("Failed to resolve symbol(%d) at offset 0x%x", i,
- curr->r_offset);
- return false;
- }
- *addr = reinterpret_cast<ElfAddr>(resolved);
- break;
- }
-
- default:
- LOGE("Unsupported relocation type: %u for symbol %s", relocType,
- getDataName(ELFW_R_SYM(curr->r_info)));
- return false;
- }
- }
- return true;
-}
-
-void NanoappLoader::callAtexitFunctions() {
- while (!mAtexitFunctions.empty()) {
- LOGV("Calling atexit at %p", mAtexitFunctions.back());
- mAtexitFunctions.back()();
- mAtexitFunctions.pop_back();
- }
-}
-
-void NanoappLoader::callTerminatorArray() {
- for (size_t i = 0; i < mNumSectionHeaders; ++i) {
- const char *name = getSectionHeaderName(mSectionHeadersPtr[i].sh_name);
- if (strncmp(name, kFiniArrayName, strlen(kFiniArrayName)) == 0) {
- uintptr_t finiArray = reinterpret_cast<uintptr_t>(
- mLoadBias + mSectionHeadersPtr[i].sh_addr);
- uintptr_t offset = 0;
- while (offset < mSectionHeadersPtr[i].sh_size) {
- ElfAddr *funcPtr = reinterpret_cast<ElfAddr *>(finiArray + offset);
- uintptr_t finiFunction = reinterpret_cast<uintptr_t>(*funcPtr);
- ((void (*)())finiFunction)();
- offset += sizeof(finiFunction);
- }
- break;
- }
- }
-}
-
-} // namespace chre
diff --git a/platform/shared/platform_gnss.cc b/platform/shared/platform_gnss.cc
index c7309c6d..903e89a2 100644
--- a/platform/shared/platform_gnss.cc
+++ b/platform/shared/platform_gnss.cc
@@ -86,9 +86,7 @@ void PlatformGnss::releaseLocationEvent(chreGnssLocationEvent *event) {
}
void PlatformGnssBase::requestStateResyncCallback() {
- EventLoopManagerSingleton::get()
- ->getGnssManager()
- .handleRequestStateResyncCallback();
+ // TODO: Implement this.
}
void PlatformGnssBase::locationStatusChangeCallback(bool enabled,
@@ -125,16 +123,6 @@ void PlatformGnss::releaseMeasurementDataEvent(chreGnssDataEvent *event) {
}
}
-bool PlatformGnss::configurePassiveLocationListener(bool enable) {
- bool success = false;
- if (mGnssApi != nullptr &&
- mGnssApi->moduleVersion >= CHRE_PAL_GNSS_API_V1_2) {
- prePalApiCall();
- success = mGnssApi->configurePassiveLocationListener(enable);
- }
- return success;
-}
-
void PlatformGnssBase::measurementStatusChangeCallback(bool enabled,
uint8_t errorCode) {
EventLoopManagerSingleton::get()
diff --git a/platform/shared/platform_sensor_manager.cc b/platform/shared/platform_sensor_manager.cc
index dd47fcdf..e137992e 100644
--- a/platform/shared/platform_sensor_manager.cc
+++ b/platform/shared/platform_sensor_manager.cc
@@ -150,13 +150,6 @@ void PlatformSensorManagerBase::flushCompleteCallback(uint32_t sensorHandle,
.handleFlushCompleteEvent(sensorHandle, flushRequestId, errorCode);
}
-uint16_t PlatformSensorManager::getTargetGroupId(
- const Nanoapp & /*nanoapp*/) const {
- // Target group IDs are not supported for PALs so always assume 1 since
- // all sensors group masks are 0xFFFF.
- return 1;
-}
-
void PlatformSensorManager::releaseSamplingStatusUpdate(
struct chreSensorSamplingStatus *status) {
mSensorApi->releaseSamplingStatusEvent(status);
diff --git a/platform/shared/platform_wifi.cc b/platform/shared/platform_wifi.cc
index 54653797..5418e75f 100644
--- a/platform/shared/platform_wifi.cc
+++ b/platform/shared/platform_wifi.cc
@@ -21,7 +21,6 @@
#include "chre/core/event_loop_manager.h"
#include "chre/platform/log.h"
#include "chre/platform/shared/pal_system_api.h"
-#include "chre/util/system/wifi_util.h"
namespace chre {
@@ -88,14 +87,7 @@ bool PlatformWifi::requestRanging(const struct chreWifiRangingParams *params) {
bool PlatformWifi::requestScan(const struct chreWifiScanParams *params) {
if (mWifiApi != nullptr) {
prePalApiCall();
-
- if (mWifiApi->moduleVersion < CHRE_PAL_WIFI_API_V1_5) {
- const struct chreWifiScanParams paramsCompat =
- translateToLegacyWifiScanParams(params);
- return mWifiApi->requestScan(&paramsCompat);
- } else {
- return mWifiApi->requestScan(params);
- }
+ return mWifiApi->requestScan(params);
} else {
return false;
}
diff --git a/platform/shared/version.cc b/platform/shared/version.cc
deleted file mode 100644
index 9640459c..00000000
--- a/platform/shared/version.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 "chre/platform/version.h"
-#include "chre/util/macros.h"
-
-#ifndef CHRE_VERSION_STRING
-#define CHRE_VERSION_STRING "undefined"
-#endif // CHRE_VERSION_STRING
-
-namespace chre {
-
-//! The CHRE version string is placed in its own section so that it can be
-//! removed before hashing to check whether there has been a change in the
-//! compiled binary.
-DLL_EXPORT extern "C" const char _chreVersionString[]
- __attribute__((section(".unstable_id"))) __attribute__((aligned(8))) =
- CHRE_VERSION_STRING;
-
-const char *getChreVersionString() {
- return _chreVersionString;
-}
-
-} // namespace chre
diff --git a/platform/slpi/chre_api_re.cc b/platform/slpi/chre_api_re.cc
index 0fb46c36..0f059b3e 100644
--- a/platform/slpi/chre_api_re.cc
+++ b/platform/slpi/chre_api_re.cc
@@ -14,11 +14,7 @@
* limitations under the License.
*/
-#include "chre/platform/assert.h"
#include "chre/platform/log.h"
-#ifdef CHRE_USE_BUFFERED_LOGGING
-#include "chre/platform/shared/log_buffer_manager.h"
-#endif
#include "chre/util/macros.h"
#include "chre_api/chre/re.h"
@@ -40,7 +36,8 @@ inline void logToFarf(enum chreLogLevel level, const char *logStr) {
}
}
-#elif !defined(CHRE_USE_BUFFERED_LOGGING)
+#else // CHRE_USE_FARF_LOGGING
+
inline ashLogLevel chreLogLevelToAshLogLevel(enum chreLogLevel level) {
enum ashLogLevel ashLevel;
switch (level) {
@@ -59,16 +56,14 @@ inline ashLogLevel chreLogLevelToAshLogLevel(enum chreLogLevel level) {
}
return ashLevel;
}
-#endif // !defined(CHRE_USE_BUFFERED_LOGGING)
+
+#endif // CHRE_USE_FARF_LOGGING
DLL_EXPORT void chreLog(enum chreLogLevel level, const char *formatStr, ...) {
va_list args;
va_start(args, formatStr);
-#ifdef CHRE_USE_BUFFERED_LOGGING
- CHRE_ASSERT(chre::LogBufferManagerSingleton::isInitialized());
- chre::LogBufferManagerSingleton::get()->logVa(level, formatStr, args);
-#elif defined(CHRE_USE_FARF_LOGGING)
+#ifdef CHRE_USE_FARF_LOGGING
// The same size is used in the implmentation of ashVaLog().
constexpr size_t kDebugMaxLogEntrySize = 128;
// FARF doesn't provide a method that takes va_list as an input so write the
diff --git a/platform/slpi/fatal_error.cc b/platform/slpi/fatal_error.cc
index c19d61fc..276648f3 100644
--- a/platform/slpi/fatal_error.cc
+++ b/platform/slpi/fatal_error.cc
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include "chre/platform/fatal_error.h"
+#include "chre/target_platform/assert.h"
namespace chre {
diff --git a/platform/slpi/host_link.cc b/platform/slpi/host_link.cc
index a8bdfec9..8a316d34 100644
--- a/platform/slpi/host_link.cc
+++ b/platform/slpi/host_link.cc
@@ -28,25 +28,22 @@
#include "chre/platform/log.h"
#include "chre/platform/memory.h"
#include "chre/platform/shared/host_protocol_chre.h"
-#include "chre/platform/shared/nanoapp_load_manager.h"
-#ifdef CHRE_USE_BUFFERED_LOGGING
-#include "chre/platform/shared/log_buffer_manager.h"
-#endif
#include "chre/platform/slpi/fastrpc.h"
+#include "chre/platform/slpi/nanoapp_load_manager.h"
#include "chre/platform/slpi/power_control_util.h"
#include "chre/platform/slpi/system_time.h"
#include "chre/platform/system_time.h"
#include "chre/platform/system_timer.h"
#include "chre/util/fixed_size_blocking_queue.h"
-#include "chre/util/flatbuffers/helpers.h"
#include "chre/util/macros.h"
-#include "chre/util/nested_data_ptr.h"
#include "chre/util/unique_ptr.h"
#include "chre_api/chre/version.h"
#include <inttypes.h>
#include <limits.h>
+using flatbuffers::FlatBufferBuilder;
+
namespace chre {
namespace {
@@ -57,6 +54,14 @@ constexpr size_t kOutboundQueueSize = 32;
//! TODO: Make this a member of HostLinkBase
Nanoseconds gLastTimeSyncRequestNanos(0);
+//! Used to pass the client ID through the user data pointer in deferCallback
+union HostClientIdCallbackData {
+ uint16_t hostClientId;
+ void *ptr;
+};
+static_assert(sizeof(uint16_t) <= sizeof(void *),
+ "Pointer must at least fit a u16 for passing the host client ID");
+
struct LoadNanoappCallbackData {
uint64_t appId;
uint32_t transactionId;
@@ -66,7 +71,7 @@ struct LoadNanoappCallbackData {
};
struct NanoappListData {
- ChreFlatBufferBuilder *builder;
+ FlatBufferBuilder *builder;
DynamicVector<NanoappListEntryOffset> nanoappEntries;
uint16_t hostClientId;
};
@@ -84,7 +89,6 @@ enum class PendingMessageType {
LowPowerMicAccessRequest,
LowPowerMicAccessRelease,
EncodedLogMessage,
- SelfTestResponse,
};
struct PendingMessage {
@@ -99,7 +103,7 @@ struct PendingMessage {
data.msgToHost = msgToHost;
}
- PendingMessage(PendingMessageType msgType, ChreFlatBufferBuilder *builder) {
+ PendingMessage(PendingMessageType msgType, FlatBufferBuilder *builder) {
type = msgType;
data.builder = builder;
}
@@ -108,7 +112,7 @@ struct PendingMessage {
union {
const MessageToHost *msgToHost;
uint16_t hostClientId;
- ChreFlatBufferBuilder *builder;
+ FlatBufferBuilder *builder;
} data;
};
@@ -122,14 +126,12 @@ struct UnloadNanoappCallbackData {
/**
* @see buildAndEnqueueMessage()
*/
-typedef void(MessageBuilderFunction)(ChreFlatBufferBuilder &builder,
- void *cookie);
+typedef void(MessageBuilderFunction)(FlatBufferBuilder &builder, void *cookie);
FixedSizeBlockingQueue<PendingMessage, kOutboundQueueSize> gOutboundQueue;
-int copyToHostBuffer(const ChreFlatBufferBuilder &builder,
- unsigned char *buffer, size_t bufferSize,
- unsigned int *messageLen) {
+int copyToHostBuffer(const FlatBufferBuilder &builder, unsigned char *buffer,
+ size_t bufferSize, unsigned int *messageLen) {
uint8_t *data = builder.GetBufferPointer();
size_t size = builder.GetSize();
int result;
@@ -171,12 +173,11 @@ bool enqueueMessage(PendingMessage message) {
/**
* Helper function that takes care of the boilerplate for allocating a
- * ChreFlatBufferBuilder on the heap and adding it to the outbound message
- * queue.
+ * FlatBufferBuilder on the heap and adding it to the outbound message queue.
*
* @param msgType Identifies the message while in the outboud queue
* @param initialBufferSize Number of bytes to reserve when first allocating the
- * ChreFlatBufferBuilder
+ * FlatBufferBuilder
* @param buildMsgFunc Synchronous callback used to encode the FlatBuffer
* message. Will not be invoked if allocation fails.
* @param cookie Opaque pointer that will be passed through to buildMsgFunc
@@ -188,7 +189,7 @@ bool buildAndEnqueueMessage(PendingMessageType msgType,
MessageBuilderFunction *msgBuilder, void *cookie) {
bool pushed = false;
- auto builder = MakeUnique<ChreFlatBufferBuilder>(initialBufferSize);
+ auto builder = MakeUnique<FlatBufferBuilder>(initialBufferSize);
if (builder.isNull()) {
LOGE("Couldn't allocate memory for message type %d",
static_cast<int>(msgType));
@@ -210,15 +211,14 @@ bool buildAndEnqueueMessage(PendingMessageType msgType,
}
/**
- * FlatBuffer message builder callback used with handleNanoappListRequest()
+ * FlatBuffer message builder callback used with constructNanoappListCallback()
*/
-void buildNanoappListResponse(ChreFlatBufferBuilder &builder, void *cookie) {
+void buildNanoappListResponse(FlatBufferBuilder &builder, void *cookie) {
auto nanoappAdderCallback = [](const Nanoapp *nanoapp, void *data) {
auto *cbData = static_cast<NanoappListData *>(data);
HostProtocolChre::addNanoappListEntry(
*(cbData->builder), cbData->nanoappEntries, nanoapp->getAppId(),
- nanoapp->getAppVersion(), true /*enabled*/, nanoapp->isSystemNanoapp(),
- nanoapp->getAppPermissions());
+ nanoapp->getAppVersion(), true /*enabled*/, nanoapp->isSystemNanoapp());
};
// Add a NanoappListEntry to the FlatBuffer for each nanoapp
@@ -230,9 +230,31 @@ void buildNanoappListResponse(ChreFlatBufferBuilder &builder, void *cookie) {
cbData->hostClientId);
}
-void finishLoadingNanoappCallback(SystemCallbackType /*type*/,
- UniquePtr<LoadNanoappCallbackData> &&data) {
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
+void constructNanoappListCallback(uint16_t /*eventType*/, void *deferCbData) {
+ HostClientIdCallbackData clientIdCbData;
+ clientIdCbData.ptr = deferCbData;
+
+ NanoappListData cbData = {};
+ cbData.hostClientId = clientIdCbData.hostClientId;
+
+ const EventLoop &eventLoop = EventLoopManagerSingleton::get()->getEventLoop();
+ size_t expectedNanoappCount = eventLoop.getNanoappCount();
+ if (!cbData.nanoappEntries.reserve(expectedNanoappCount)) {
+ LOG_OOM();
+ } else {
+ constexpr size_t kFixedOverhead = 48;
+ constexpr size_t kPerNanoappSize = 32;
+ size_t initialBufferSize =
+ (kFixedOverhead + expectedNanoappCount * kPerNanoappSize);
+
+ buildAndEnqueueMessage(PendingMessageType::NanoappListResponse,
+ initialBufferSize, buildNanoappListResponse,
+ &cbData);
+ }
+}
+
+void finishLoadingNanoappCallback(uint16_t /*eventType*/, void *data) {
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
auto *cbData = static_cast<LoadNanoappCallbackData *>(cookie);
EventLoop &eventLoop = EventLoopManagerSingleton::get()->getEventLoop();
@@ -244,14 +266,17 @@ void finishLoadingNanoappCallback(SystemCallbackType /*type*/,
cbData->fragmentId);
};
+ // Re-wrap the callback data struct, so it is destructed and freed, ensuring
+ // we don't leak the embedded UniquePtr<Nanoapp>
+ UniquePtr<LoadNanoappCallbackData> dataWrapped(
+ static_cast<LoadNanoappCallbackData *>(data));
constexpr size_t kInitialBufferSize = 48;
buildAndEnqueueMessage(PendingMessageType::LoadNanoappResponse,
- kInitialBufferSize, msgBuilder, data.get());
+ kInitialBufferSize, msgBuilder, data);
}
-void handleUnloadNanoappCallback(SystemCallbackType /*type*/,
- UniquePtr<UnloadNanoappCallbackData> &&data) {
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
+void handleUnloadNanoappCallback(uint16_t /*eventType*/, void *data) {
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
auto *cbData = static_cast<UnloadNanoappCallbackData *>(cookie);
bool success = false;
@@ -270,7 +295,8 @@ void handleUnloadNanoappCallback(SystemCallbackType /*type*/,
constexpr size_t kInitialBufferSize = 52;
buildAndEnqueueMessage(PendingMessageType::UnloadNanoappResponse,
- kInitialBufferSize, msgBuilder, data.get());
+ kInitialBufferSize, msgBuilder, data);
+ memoryFree(data);
}
int generateMessageToHost(const MessageToHost *msgToHost, unsigned char *buffer,
@@ -278,12 +304,11 @@ int generateMessageToHost(const MessageToHost *msgToHost, unsigned char *buffer,
// TODO: ideally we'd construct our flatbuffer directly in the
// host-supplied buffer
constexpr size_t kFixedSizePortion = 80;
- ChreFlatBufferBuilder builder(msgToHost->message.size() + kFixedSizePortion);
+ FlatBufferBuilder builder(msgToHost->message.size() + kFixedSizePortion);
HostProtocolChre::encodeNanoappMessage(
builder, msgToHost->appId, msgToHost->toHostData.messageType,
msgToHost->toHostData.hostEndpoint, msgToHost->message.data(),
- msgToHost->message.size(), msgToHost->toHostData.appPermissions,
- msgToHost->toHostData.messagePermissions);
+ msgToHost->message.size());
int result = copyToHostBuffer(builder, buffer, bufferSize, messageLen);
@@ -313,7 +338,7 @@ int generateHubInfoResponse(uint16_t hostClientId, unsigned char *buffer,
constexpr float kPeakPower = 15;
// Note that this may execute prior to EventLoopManager::lateInit() completing
- ChreFlatBufferBuilder builder(kInitialBufferSize);
+ FlatBufferBuilder builder(kInitialBufferSize);
HostProtocolChre::encodeHubInfoResponse(
builder, kHubName, kVendor, kToolchain, kLegacyPlatformVersion,
kLegacyToolchainVersion, kPeakMips, kStoppedPower, kSleepPower,
@@ -323,22 +348,12 @@ int generateHubInfoResponse(uint16_t hostClientId, unsigned char *buffer,
return copyToHostBuffer(builder, buffer, bufferSize, messageLen);
}
-int generateMessageFromBuilder(ChreFlatBufferBuilder *builder,
+int generateMessageFromBuilder(FlatBufferBuilder *builder,
unsigned char *buffer, size_t bufferSize,
- unsigned int *messageLen,
- bool isEncodedLogMessage) {
+ unsigned int *messageLen) {
CHRE_ASSERT(builder != nullptr);
int result = copyToHostBuffer(*builder, buffer, bufferSize, messageLen);
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
- if (isEncodedLogMessage && LogBufferManagerSingleton::isInitialized()) {
- LogBufferManagerSingleton::get()->onLogsSentToHost();
- }
-#else
- UNUSED_VAR(isEncodedLogMessage);
-#endif
-
- builder->~ChreFlatBufferBuilder();
+ builder->~FlatBufferBuilder();
memoryFree(builder);
return result;
}
@@ -351,7 +366,7 @@ void sendDebugDumpData(uint16_t hostClientId, const char *debugStr,
size_t debugStrSize;
};
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
const auto *data = static_cast<const DebugDumpMessageData *>(cookie);
HostProtocolChre::encodeDebugDumpData(builder, data->hostClientId,
data->debugStr, data->debugStrSize);
@@ -374,7 +389,7 @@ void sendDebugDumpResponse(uint16_t hostClientId, bool success,
uint32_t dataCount;
};
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
const auto *data = static_cast<const DebugDumpResponseData *>(cookie);
HostProtocolChre::encodeDebugDumpResponse(builder, data->hostClientId,
data->success, data->dataCount);
@@ -389,26 +404,6 @@ void sendDebugDumpResponse(uint16_t hostClientId, bool success,
msgBuilder, &data);
}
-void sendSelfTestResponse(uint16_t hostClientId, bool success) {
- struct SelfTestResponseData {
- uint16_t hostClientId;
- bool success;
- };
-
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
- const auto *data = static_cast<const SelfTestResponseData *>(cookie);
- HostProtocolChre::encodeSelfTestResponse(builder, data->hostClientId,
- data->success);
- };
-
- constexpr size_t kInitialSize = 52;
- SelfTestResponseData data;
- data.hostClientId = hostClientId;
- data.success = success;
- buildAndEnqueueMessage(PendingMessageType::SelfTestResponse, kInitialSize,
- msgBuilder, &data);
-}
-
void sendFragmentResponse(uint16_t hostClientId, uint32_t transactionId,
uint32_t fragmentId, bool success) {
struct FragmentedLoadInfoResponse {
@@ -418,7 +413,7 @@ void sendFragmentResponse(uint16_t hostClientId, uint32_t transactionId,
bool success;
};
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
auto *cbData = static_cast<FragmentedLoadInfoResponse *>(cookie);
HostProtocolChre::encodeLoadNanoappResponse(
builder, cbData->hostClientId, cbData->transactionId, cbData->success,
@@ -440,7 +435,7 @@ void sendFragmentResponse(uint16_t hostClientId, uint32_t transactionId,
* Sends a request to the host for a time sync message.
*/
void sendTimeSyncRequest() {
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
HostProtocolChre::encodeTimeSyncRequest(builder);
};
@@ -501,8 +496,7 @@ UniquePtr<Nanoapp> handleLoadNanoappFile(uint16_t hostClientId,
if (nanoapp.isNull()) {
LOG_OOM();
- } else if (!nanoapp->setAppInfo(appId, appVersion, appFilename,
- targetApiVersion) ||
+ } else if (!nanoapp->setAppInfo(appId, appVersion, appFilename) ||
!nanoapp->isLoaded()) {
nanoapp.reset(nullptr);
}
@@ -518,7 +512,6 @@ UniquePtr<Nanoapp> handleLoadNanoappFile(uint16_t hostClientId,
* @param transactionId the ID of the transaction
* @param appId the ID of the app to load
* @param appVersion the version of the app to load
- * @param appFlags The flags provided by the app being loaded
* @param targetApiVersion the API version this nanoapp is targeted for
* @param buffer the nanoapp binary data. May be only part of the nanoapp's
* binary if it's being sent over multiple fragments
@@ -529,23 +522,20 @@ UniquePtr<Nanoapp> handleLoadNanoappFile(uint16_t hostClientId,
* @return A valid pointer to a nanoapp that can be loaded into the system. A
* nullptr if the preparation process fails.
*/
-UniquePtr<Nanoapp> handleLoadNanoappData(uint16_t hostClientId,
- uint32_t transactionId, uint64_t appId,
- uint32_t appVersion, uint32_t appFlags,
- uint32_t targetApiVersion,
- const void *buffer, size_t bufferLen,
- uint32_t fragmentId,
- size_t appBinaryLen) {
+UniquePtr<Nanoapp> handleLoadNanoappData(
+ uint16_t hostClientId, uint32_t transactionId, uint64_t appId,
+ uint32_t appVersion, uint32_t targetApiVersion, const void *buffer,
+ size_t bufferLen, uint32_t fragmentId, size_t appBinaryLen) {
static NanoappLoadManager sLoadManager;
bool success = true;
if (fragmentId == 0 || fragmentId == 1) { // first fragment
size_t totalAppBinaryLen = (fragmentId == 0) ? bufferLen : appBinaryLen;
LOGD("Load nanoapp request for app ID 0x%016" PRIx64 " ver 0x%" PRIx32
- " flags 0x%" PRIx32 " target API 0x%08" PRIx32
- " size %zu (txnId %" PRIu32 " client %" PRIu16 ")",
- appId, appVersion, appFlags, targetApiVersion, totalAppBinaryLen,
- transactionId, hostClientId);
+ " target API 0x%08" PRIx32 " size %zu (txnId %" PRIu32
+ " client %" PRIu16 ")",
+ appId, appVersion, targetApiVersion, totalAppBinaryLen, transactionId,
+ hostClientId);
if (sLoadManager.hasPendingLoadTransaction()) {
FragmentedLoadInfo info = sLoadManager.getTransactionInfo();
@@ -555,8 +545,7 @@ UniquePtr<Nanoapp> handleLoadNanoappData(uint16_t hostClientId,
}
success = sLoadManager.prepareForLoad(hostClientId, transactionId, appId,
- appVersion, appFlags,
- totalAppBinaryLen, targetApiVersion);
+ appVersion, totalAppBinaryLen);
}
success &= sLoadManager.copyNanoappFragment(
hostClientId, transactionId, (fragmentId == 0) ? 1 : fragmentId, buffer,
@@ -571,6 +560,38 @@ UniquePtr<Nanoapp> handleLoadNanoappData(uint16_t hostClientId,
return nanoapp;
}
+bool getSettingFromFbs(fbs::Setting setting, Setting *chreSetting) {
+ bool success = true;
+ switch (setting) {
+ case fbs::Setting::LOCATION:
+ *chreSetting = Setting::LOCATION;
+ break;
+ default:
+ LOGE("Unknown setting %" PRIu8, setting);
+ success = false;
+ }
+
+ return success;
+}
+
+bool getSettingStateFromFbs(fbs::SettingState state,
+ SettingState *chreSettingState) {
+ bool success = true;
+ switch (state) {
+ case fbs::SettingState::DISABLED:
+ *chreSettingState = SettingState::DISABLED;
+ break;
+ case fbs::SettingState::ENABLED:
+ *chreSettingState = SettingState::ENABLED;
+ break;
+ default:
+ LOGE("Unknown state %" PRIu8, state);
+ success = false;
+ }
+
+ return success;
+}
+
/**
* FastRPC method invoked by the host to block on messages
*
@@ -622,10 +643,8 @@ extern "C" int chre_slpi_get_message_to_host(unsigned char *buffer,
case PendingMessageType::LowPowerMicAccessRequest:
case PendingMessageType::LowPowerMicAccessRelease:
case PendingMessageType::EncodedLogMessage:
- case PendingMessageType::SelfTestResponse:
- result = generateMessageFromBuilder(
- pendingMsg.data.builder, buffer, bufferSize, messageLen,
- pendingMsg.type == PendingMessageType::EncodedLogMessage);
+ result = generateMessageFromBuilder(pendingMsg.data.builder, buffer,
+ bufferSize, messageLen);
break;
default:
@@ -717,51 +736,6 @@ bool HostLinkBase::flushOutboundQueue() {
return (waitCount >= 0);
}
-void HostLinkBase::sendLogMessage(const uint8_t *logMessage,
- size_t logMessageSize) {
- struct LogMessageData {
- const uint8_t *logMsg;
- size_t logMsgSize;
- };
-
- LogMessageData logMessageData;
-
- logMessageData.logMsg = logMessage;
- logMessageData.logMsgSize = logMessageSize;
-
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
- const auto *data = static_cast<const LogMessageData *>(cookie);
- HostProtocolChre::encodeLogMessages(builder, data->logMsg,
- data->logMsgSize);
- };
-
- constexpr size_t kInitialSize = 128;
- buildAndEnqueueMessage(PendingMessageType::EncodedLogMessage, kInitialSize,
- msgBuilder, &logMessageData);
-}
-
-void HostLinkBase::sendLogMessageV2(const uint8_t *logMessage,
- size_t logMessageSize,
- uint32_t numLogsDropped) {
- struct LogMessageData {
- const uint8_t *logMsg;
- size_t logMsgSize;
- uint32_t numLogsDropped;
- };
-
- LogMessageData logMessageData{logMessage, logMessageSize, numLogsDropped};
-
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
- const auto *data = static_cast<const LogMessageData *>(cookie);
- HostProtocolChre::encodeLogMessagesV2(
- builder, data->logMsg, data->logMsgSize, data->numLogsDropped);
- };
-
- constexpr size_t kInitialSize = 128;
- buildAndEnqueueMessage(PendingMessageType::EncodedLogMessage, kInitialSize,
- msgBuilder, &logMessageData);
-}
-
void HostLinkBase::shutdown() {
// Push a null message so the blocking call in chre_slpi_get_message_to_host()
// returns and the host can exit cleanly. If the queue is full, try again to
@@ -792,7 +766,7 @@ void HostLinkBase::shutdown() {
}
void sendAudioRequest() {
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
HostProtocolChre::encodeLowPowerMicAccessRequest(builder);
};
@@ -802,7 +776,7 @@ void sendAudioRequest() {
}
void sendAudioRelease() {
- auto msgBuilder = [](ChreFlatBufferBuilder &builder, void *cookie) {
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
HostProtocolChre::encodeLowPowerMicAccessRelease(builder);
};
@@ -835,48 +809,28 @@ void HostMessageHandlers::handleHubInfoRequest(uint16_t hostClientId) {
}
void HostMessageHandlers::handleNanoappListRequest(uint16_t hostClientId) {
- auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
- uint16_t cbHostClientId = NestedDataPtr<uint16_t>(data);
-
- NanoappListData cbData = {};
- cbData.hostClientId = cbHostClientId;
-
- size_t expectedNanoappCount =
- EventLoopManagerSingleton::get()->getEventLoop().getNanoappCount();
- if (!cbData.nanoappEntries.reserve(expectedNanoappCount)) {
- LOG_OOM();
- } else {
- constexpr size_t kFixedOverhead = 48;
- constexpr size_t kPerNanoappSize = 32;
- size_t initialBufferSize =
- (kFixedOverhead + expectedNanoappCount * kPerNanoappSize);
-
- buildAndEnqueueMessage(PendingMessageType::NanoappListResponse,
- initialBufferSize, buildNanoappListResponse,
- &cbData);
- }
- };
-
LOGD("Nanoapp list request from client ID %" PRIu16, hostClientId);
+ HostClientIdCallbackData cbData = {};
+ cbData.hostClientId = hostClientId;
EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::NanoappListResponse,
- NestedDataPtr<uint16_t>(hostClientId), callback);
+ SystemCallbackType::NanoappListResponse, cbData.ptr,
+ constructNanoappListCallback);
}
void HostMessageHandlers::handleLoadNanoappRequest(
uint16_t hostClientId, uint32_t transactionId, uint64_t appId,
- uint32_t appVersion, uint32_t appFlags, uint32_t targetApiVersion,
- const void *buffer, size_t bufferLen, const char *appFileName,
- uint32_t fragmentId, size_t appBinaryLen, bool respondBeforeStart) {
+ uint32_t appVersion, uint32_t targetApiVersion, const void *buffer,
+ size_t bufferLen, const char *appFileName, uint32_t fragmentId,
+ size_t appBinaryLen) {
UniquePtr<Nanoapp> pendingNanoapp;
if (appFileName != nullptr) {
pendingNanoapp =
handleLoadNanoappFile(hostClientId, transactionId, appId, appVersion,
targetApiVersion, appFileName);
} else {
- pendingNanoapp = handleLoadNanoappData(
- hostClientId, transactionId, appId, appVersion, appFlags,
- targetApiVersion, buffer, bufferLen, fragmentId, appBinaryLen);
+ pendingNanoapp = handleLoadNanoappData(hostClientId, transactionId, appId,
+ appVersion, targetApiVersion, buffer,
+ bufferLen, fragmentId, appBinaryLen);
}
if (!pendingNanoapp.isNull()) {
@@ -893,7 +847,7 @@ void HostMessageHandlers::handleLoadNanoappRequest(
// Note that if this fails, we'll generate the error response in
// the normal deferred callback
EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::FinishLoadingNanoapp, std::move(cbData),
+ SystemCallbackType::FinishLoadingNanoapp, cbData.release(),
finishLoadingNanoappCallback);
}
}
@@ -905,7 +859,7 @@ void HostMessageHandlers::handleUnloadNanoappRequest(
LOGD("Unload nanoapp request (txnID %" PRIu32 ") for appId 0x%016" PRIx64
" system %d",
transactionId, appId, allowSystemNanoappUnload);
- auto cbData = MakeUnique<UnloadNanoappCallbackData>();
+ auto *cbData = memoryAlloc<UnloadNanoappCallbackData>();
if (cbData == nullptr) {
LOG_OOM();
} else {
@@ -915,7 +869,7 @@ void HostMessageHandlers::handleUnloadNanoappRequest(
cbData->allowSystemNanoappUnload = allowSystemNanoappUnload;
EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::HandleUnloadNanoapp, std::move(cbData),
+ SystemCallbackType::HandleUnloadNanoapp, cbData,
handleUnloadNanoappCallback);
}
}
@@ -938,20 +892,36 @@ void HostMessageHandlers::handleDebugDumpRequest(uint16_t hostClientId) {
}
}
+void HostLink::sendLogMessage(const char *logMessage, size_t logMessageSize) {
+ struct LogMessageData {
+ const char *logMsg;
+ size_t logMsgSize;
+ };
+
+ LogMessageData logMessageData;
+
+ logMessageData.logMsg = logMessage;
+ logMessageData.logMsgSize = logMessageSize;
+
+ auto msgBuilder = [](FlatBufferBuilder &builder, void *cookie) {
+ const auto *data = static_cast<const LogMessageData *>(cookie);
+ HostProtocolChre::encodeLogMessages(builder, data->logMsg,
+ data->logMsgSize);
+ };
+
+ constexpr size_t kInitialSize = 128;
+ buildAndEnqueueMessage(PendingMessageType::EncodedLogMessage, kInitialSize,
+ msgBuilder, &logMessageData);
+}
+
void HostMessageHandlers::handleSettingChangeMessage(fbs::Setting setting,
fbs::SettingState state) {
Setting chreSetting;
SettingState chreSettingState;
- if (HostProtocolChre::getSettingFromFbs(setting, &chreSetting) &&
- HostProtocolChre::getSettingStateFromFbs(state, &chreSettingState)) {
+ if (getSettingFromFbs(setting, &chreSetting) &&
+ getSettingStateFromFbs(state, &chreSettingState)) {
postSettingChange(chreSetting, chreSettingState);
}
}
-void HostMessageHandlers::handleSelfTestRequest(uint16_t hostClientId) {
- // TODO(b/182201569): Run test
- bool success = true;
- sendSelfTestResponse(hostClientId, success);
-}
-
} // namespace chre
diff --git a/platform/shared/include/chre/platform/shared/nanoapp_load_manager.h b/platform/slpi/include/chre/platform/slpi/nanoapp_load_manager.h
index d98af032..43f13ddb 100644
--- a/platform/shared/include/chre/platform/shared/nanoapp_load_manager.h
+++ b/platform/slpi/include/chre/platform/slpi/nanoapp_load_manager.h
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-#ifndef CHRE_PLATFORM_SHARED_NANOAPP_LOAD_MANAGER_H_
-#define CHRE_PLATFORM_SHARED_NANOAPP_LOAD_MANAGER_H_
+#ifndef CHRE_PLATFORM_SLPI_NANOAPP_LOAD_MANAGER_H_
+#define CHRE_PLATFORM_SLPI_NANOAPP_LOAD_MANAGER_H_
#include <cstddef>
#include <cstdint>
@@ -52,15 +52,13 @@ class NanoappLoadManager : public NonCopyable {
* @param transactionId the ID of the transaction
* @param appId the ID of the app to load
* @param appVersion the version of the app to load
- * @param appFlags the flags provided by the app being loaded
* @param totalBinaryLen the total nanoapp binary length
- * @param targetApiVersion the target API version of the nanoapp to load
*
* @return true if the preparation was successful, false otherwise
*/
bool prepareForLoad(uint16_t hostClientId, uint32_t transactionId,
- uint64_t appId, uint32_t appVersion, uint32_t appFlags,
- size_t totalBinaryLen, uint32_t targetApiVersion);
+ uint64_t appId, uint32_t appVersion,
+ size_t totalBinaryLen);
/**
* Copies a fragment of a nanoapp binary. If the parameters do not match the
@@ -142,4 +140,4 @@ class NanoappLoadManager : public NonCopyable {
} // namespace chre
-#endif // CHRE_PLATFORM_SHARED_NANOAPP_LOAD_MANAGER_H_
+#endif // CHRE_PLATFORM_SLPI_NANOAPP_LOAD_MANAGER_H_
diff --git a/platform/slpi/include/chre/platform/slpi/qsh/qsh_shim.h b/platform/slpi/include/chre/platform/slpi/qsh/qsh_shim.h
deleted file mode 100644
index 0200ff6c..00000000
--- a/platform/slpi/include/chre/platform/slpi/qsh/qsh_shim.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_PLATFORM_SLPI_QSH_QSH_SHIM_H_
-#define CHRE_PLATFORM_SLPI_QSH_QSH_SHIM_H_
-
-namespace chre {
-
-/**
- * Opens the QSH shim. This must be invoked prior to the CHRE event loop being
- * started to ensure QSH is initialized.
- */
-void openQsh();
-
-/**
- * Closes the QSH shim and allows it to clean up any resources it has allocated.
- * This must be invoked directly after chre::deinit to ensure resources are
- * torn down only after nanoapps have been unloaded.
- */
-void closeQsh();
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_SLPI_QSH_QSH_SHIM_H_
diff --git a/platform/slpi/include/chre/platform/slpi/see/island_vote_client.h b/platform/slpi/include/chre/platform/slpi/see/island_vote_client.h
index 05501af8..119a9a45 100644
--- a/platform/slpi/include/chre/platform/slpi/see/island_vote_client.h
+++ b/platform/slpi/include/chre/platform/slpi/see/island_vote_client.h
@@ -23,9 +23,7 @@
extern "C" {
-#ifdef CHRE_SLPI_UIMG_ENABLED
#include "sns_island_util.h"
-#endif // CHRE_SLPI_UIMG_ENABLED
} // extern "C"
diff --git a/platform/slpi/include/chre/platform/slpi/see/see_cal_helper.h b/platform/slpi/include/chre/platform/slpi/see/see_cal_helper.h
index 9bbd7022..52c1e34b 100644
--- a/platform/slpi/include/chre/platform/slpi/see/see_cal_helper.h
+++ b/platform/slpi/include/chre/platform/slpi/see/see_cal_helper.h
@@ -74,9 +74,6 @@ class SeeCalHelper : public NonCopyable {
/**
* Configures calibration updates for the given SUID.
*
- * If enabled, the SeeHelper instance should then pass decoded calibration
- * data to updateCalibration() and use applyCalibration() as needed.
- *
* @param suid The cached SUID of a calibration sensor
* @param enable Whether to enable or disable updates
* @param helper SeeHelper used to configure updates
@@ -96,16 +93,17 @@ class SeeCalHelper : public NonCopyable {
const sns_std_suid *getCalSuidFromSensorType(uint8_t sensorType) const;
/**
- * Uses the supplied SeeHelper instance to find SEE calibration sensors that
- * can be used to register for calibration updates.
+ * Uses the supplied SeeHelper instance to register for updates to all
+ * supported SEE calibration sensors. The SeeHelper instance should then pass
+ * decoded calibration data to updateCalibration() and use applyCalibration()
+ * as needed.
*
* @param seeHelper SeeHelper instance to use when looking up calibration
- * sensor SUIDs
+ * sensor SUIDs and registering for their output
*
- * @return true if all expected SEE calibration sensors were successfully
- * found
+ * @return true if all SEE calibration sensors were successfully registered
*/
- bool findCalibrationSensors(SeeHelper &seeHelper);
+ bool registerForCalibrationUpdates(SeeHelper &seeHelper);
/**
* Updates the cached calibration data used in subsequent calls to
diff --git a/std_overrides/include/assert.h b/platform/slpi/include/chre/target_platform/assert.h
index d077e169..78a183e0 100644
--- a/std_overrides/include/assert.h
+++ b/platform/slpi/include/chre/target_platform/assert.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,17 +14,16 @@
* limitations under the License.
*/
-#include "chre/util/nanoapp/assert.h"
+#ifndef CHRE_PLATFORM_SLPI_ASSERT_H_
+#define CHRE_PLATFORM_SLPI_ASSERT_H_
-#ifdef NDEBUG
-#define assert(cond) ((void)0)
-#else
-#define assert(cond) \
+#include "chre/platform/fatal_error.h"
+
+#define CHRE_ASSERT(condition) \
do { \
- if (!(cond)) { \
- chreLog(CHRE_LOG_ERROR, "CHRE_ASSERT in %s at %s:%d", __FUNCTION__, \
- __FILE__, __LINE__); \
- chreAbort(0); \
+ if (!(condition)) { \
+ FATAL_ERROR("Assertion failure at %s:%d", CHRE_FILENAME, __LINE__); \
} \
} while (0)
-#endif // NDEBUG
+
+#endif // CHRE_PLATFORM_SLPI_ASSERT_H_
diff --git a/platform/slpi/include/chre/target_platform/condition_variable_base.h b/platform/slpi/include/chre/target_platform/condition_variable_base.h
index 047febca..6189cffa 100644
--- a/platform/slpi/include/chre/target_platform/condition_variable_base.h
+++ b/platform/slpi/include/chre/target_platform/condition_variable_base.h
@@ -37,9 +37,6 @@ class ConditionVariableBase {
//! Set to true when the timeout timer is initialized.
bool mTimerInitialized = false;
-
- //! Set to true if the timeout timer timed out.
- bool mTimedOut = false;
};
} // namespace chre
diff --git a/platform/slpi/include/chre/target_platform/condition_variable_impl.h b/platform/slpi/include/chre/target_platform/condition_variable_impl.h
index 2101c297..912f43a0 100644
--- a/platform/slpi/include/chre/target_platform/condition_variable_impl.h
+++ b/platform/slpi/include/chre/target_platform/condition_variable_impl.h
@@ -51,14 +51,20 @@ inline bool ConditionVariable::wait_for(Mutex &mutex, Nanoseconds timeout) {
}
}
- mTimedOut = false;
+ struct TimeoutCallbackData {
+ ConditionVariable *cvPtr;
+ bool timedOut;
+ };
auto callback = [](void *data) {
- auto cbData = static_cast<ConditionVariable *>(data);
- cbData->mTimedOut = true;
- cbData->notify_one();
+ auto cbData = static_cast<TimeoutCallbackData *>(data);
+ cbData->timedOut = true;
+ cbData->cvPtr->notify_one();
};
- if (!mTimeoutTimer.set(callback, this, timeout)) {
+ TimeoutCallbackData callbackData;
+ callbackData.cvPtr = this;
+ callbackData.timedOut = false;
+ if (!mTimeoutTimer.set(callback, &callbackData, timeout)) {
LOGE("Failed to set condition variable timer");
}
@@ -68,7 +74,7 @@ inline bool ConditionVariable::wait_for(Mutex &mutex, Nanoseconds timeout) {
LOGD("Failed to cancel condition variable timer");
}
}
- return !mTimedOut;
+ return !callbackData.timedOut;
}
} // namespace chre
diff --git a/platform/slpi/include/chre/target_platform/host_link_base.h b/platform/slpi/include/chre/target_platform/host_link_base.h
index ef052c77..74969e63 100644
--- a/platform/slpi/include/chre/target_platform/host_link_base.h
+++ b/platform/slpi/include/chre/target_platform/host_link_base.h
@@ -45,29 +45,6 @@ class HostLinkBase {
static bool flushOutboundQueue();
/**
- * Enqueues a log message to be sent to the host.
- *
- * @param logMessage Pointer to a buffer that has the log message. Note that
- * the message might be encoded
- *
- * @param logMessageSize length of the log message buffer
- */
- void sendLogMessage(const uint8_t *logMessage, size_t logMessageSize);
-
- /**
- * Enqueues a V2 log message to be sent to the host.
- *
- * @param logMessage Pointer to a buffer that has the log message. Note that
- * the message might be encoded
- *
- * @param logMessageSize length of the log message buffer
- *
- * @param numLogsDropped number of logs dropped since CHRE start
- */
- void sendLogMessageV2(const uint8_t *logMessage, size_t logMessageSize,
- uint32_t numLogsDropped);
-
- /**
* Attempts to flush the outbound queue and gracefully inform the host that we
* are exiting.
*/
diff --git a/platform/slpi/include/chre/target_platform/log.h b/platform/slpi/include/chre/target_platform/log.h
index 93057e3d..ab88f5d0 100644
--- a/platform/slpi/include/chre/target_platform/log.h
+++ b/platform/slpi/include/chre/target_platform/log.h
@@ -17,48 +17,18 @@
#ifndef CHRE_PLATFORM_SLPI_LOG_H_
#define CHRE_PLATFORM_SLPI_LOG_H_
+#ifdef CHRE_USE_FARF_LOGGING
+#include "HAP_farf.h"
+#else // CHRE_USE_FARF_LOGGING
+#include "ash/debug.h"
+#endif // CHRE_USE_FARF_LOGGING
#include "chre/util/toolchain.h"
#ifndef __FILENAME__
#define __FILENAME__ CHRE_FILENAME
#endif
-#if defined(CHRE_USE_BUFFERED_LOGGING)
-#include "chre_api/chre/re.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Log via the PlatformLogBufferSingleton vaLog method.
- *
- * Defined in platform/shared/log_buffer_manager.cc
- *
- * @param chreLogLevel The log level.
- * @param format The format string.
- * @param ... The arguments to print into the final log.
- */
-void chrePlatformLogToBuffer(enum chreLogLevel chreLogLevel, const char *format,
- ...);
-
-#ifdef __cplusplus
-}
-#endif
-
-#define CHRE_BUFFER_LOG(level, fmt, ...) \
- do { \
- CHRE_LOG_PREAMBLE \
- chrePlatformLogToBuffer(level, fmt, ##__VA_ARGS__); \
- CHRE_LOG_EPILOGUE \
- } while (0)
-#define LOGE(fmt, ...) CHRE_BUFFER_LOG(CHRE_LOG_ERROR, fmt, ##__VA_ARGS__)
-#define LOGW(fmt, ...) CHRE_BUFFER_LOG(CHRE_LOG_WARN, fmt, ##__VA_ARGS__)
-#define LOGI(fmt, ...) CHRE_BUFFER_LOG(CHRE_LOG_INFO, fmt, ##__VA_ARGS__)
-#define LOGD(fmt, ...) CHRE_BUFFER_LOG(CHRE_LOG_DEBUG, fmt, ##__VA_ARGS__)
-#define LOGV(fmt, ...) CHRE_BUFFER_LOG(CHRE_LOG_VERBOSE, fmt, ##__VA_ARGS__)
-
-#elif defined(CHRE_USE_TOKENIZED_LOGGING)
+#if defined(CHRE_USE_TOKENIZED_LOGGING)
#include "pw_tokenizer/tokenize.h"
#define CHRE_SEND_TOKENIZED_LOG(level, fmt, ...) \
do { \
@@ -75,40 +45,8 @@ void chrePlatformLogToBuffer(enum chreLogLevel chreLogLevel, const char *format,
CHRE_SEND_TOKENIZED_LOG(CHRE_LOG_LEVEL_INFO, fmt, ##__VA_ARGS__)
#define LOGD(fmt, ...) \
CHRE_SEND_TOKENIZED_LOG(CHRE_LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__)
-#define LOGV(fmt, ...) \
- CHRE_SEND_TOKENIZED_LOG(CHRE_LOG_LEVEL_VERBOSE, fmt, ##__VA_ARGS__)
#elif defined(CHRE_USE_FARF_LOGGING)
-// Define FARF_X macros depending on the CHRE log level to ensure that FARF
-// doesn't strip out logs that CHRE intends to log.
-#if CHRE_MINIMUM_LOG_LEVEL >= CHRE_LOG_LEVEL_ERROR
-#ifndef FARF_ERROR
-#define FARF_ERROR 1
-#endif
-#endif
-
-#if CHRE_MINIMUM_LOG_LEVEL >= CHRE_LOG_LEVEL_WARN
-#ifndef FARF_HIGH
-#define FARF_HIGH 1
-#endif
-#endif
-
-#if CHRE_MINIMUM_LOG_LEVEL >= CHRE_LOG_LEVEL_INFO
-#ifndef FARF_MEDIUM
-#define FARF_MEDIUM 1
-#endif
-#endif
-
-#if CHRE_MINIMUM_LOG_LEVEL >= CHRE_LOG_LEVEL_DEBUG
-#ifndef FARF_LOW
-#define FARF_LOW 1
-#endif
-#endif
-
-#ifdef CHRE_USE_FARF_LOGGING
-#include "HAP_farf.h"
-#endif
-
#define CHRE_SLPI_LOG(level, fmt, ...) \
do { \
CHRE_LOG_PREAMBLE \
@@ -117,14 +55,11 @@ void chrePlatformLogToBuffer(enum chreLogLevel chreLogLevel, const char *format,
} while (0)
#define LOGE(fmt, ...) CHRE_SLPI_LOG(ERROR, fmt, ##__VA_ARGS__)
-#define LOGW(fmt, ...) CHRE_SLPI_LOG(HIGH, fmt, ##__VA_ARGS__)
-#define LOGI(fmt, ...) CHRE_SLPI_LOG(MEDIUM, fmt, ##__VA_ARGS__)
-#define LOGD(fmt, ...) CHRE_SLPI_LOG(LOW, fmt, ##__VA_ARGS__)
-#define LOGV(fmt, ...) CHRE_SLPI_LOG(LOW, fmt, ##__VA_ARGS__)
+#define LOGD(fmt, ...) CHRE_SLPI_LOG(HIGH, fmt, ##__VA_ARGS__)
+#define LOGW(fmt, ...) CHRE_SLPI_LOG(MEDIUM, fmt, ##__VA_ARGS__)
+#define LOGI(fmt, ...) CHRE_SLPI_LOG(ALWAYS, fmt, ##__VA_ARGS__)
#else
-
-#include "ash/debug.h"
#define CHRE_SLPI_LOG(level, fmt, ...) \
do { \
CHRE_LOG_PREAMBLE \
@@ -136,7 +71,6 @@ void chrePlatformLogToBuffer(enum chreLogLevel chreLogLevel, const char *format,
#define LOGW(fmt, ...) CHRE_SLPI_LOG(ASH_LOG_WARN, fmt, ##__VA_ARGS__)
#define LOGI(fmt, ...) CHRE_SLPI_LOG(ASH_LOG_INFO, fmt, ##__VA_ARGS__)
#define LOGD(fmt, ...) CHRE_SLPI_LOG(ASH_LOG_DEBUG, fmt, ##__VA_ARGS__)
-#define LOGV(fmt, ...) CHRE_SLPI_LOG(ASH_LOG_VERBOSE, fmt, ##__VA_ARGS__)
#endif // CHRE_USE_FARF_LOGGING
#endif // CHRE_PLATFORM_SLPI_LOG_H_
diff --git a/platform/slpi/include/chre/target_platform/platform_nanoapp_base.h b/platform/slpi/include/chre/target_platform/platform_nanoapp_base.h
index 45ed3eab..72aeb611 100644
--- a/platform/slpi/include/chre/target_platform/platform_nanoapp_base.h
+++ b/platform/slpi/include/chre/target_platform/platform_nanoapp_base.h
@@ -37,12 +37,10 @@ class PlatformNanoappBase {
* @param appId The unique app identifier associated with this binary
* @param appVersion An application-defined version number
* @param appFilename The filename of the app that should be loaded from disk
- * @param targetApiVersion The target API version the nanoapp was compiled for
*
* @return true if the info was successfully stored
*/
- bool setAppInfo(uint64_t appId, uint32_t appVersion, const char *appFilename,
- uint32_t targetApiVersion);
+ bool setAppInfo(uint64_t appId, uint32_t appVersion, const char *appFilename);
/**
* Reserves buffer space for a nanoapp's binary. This method should be called
@@ -50,13 +48,11 @@ class PlatformNanoappBase {
*
* @param appId The unique app identifier associated with this binary
* @param appVersion An application-defined version number
- * @param appFlags The flags provided by the app being loaded
* @param appBinaryLen Size of appBinary, in bytes
*
* @return true if the allocation was successful, false otherwise
*/
- bool reserveBuffer(uint64_t appId, uint32_t appVersion, uint32_t appFlags,
- size_t appBinarylen, uint32_t targetApiVersion);
+ bool reserveBuffer(uint64_t appId, uint32_t appVersion, size_t appBinarylen);
/**
* Copies the (possibly fragmented) application binary data into the allocated
@@ -108,9 +104,6 @@ class PlatformNanoappBase {
//! against) mAppInfo.
uint32_t mExpectedAppVersion = 0;
- //! The app target API version in the metadata alongside the nanoapp binary.
- uint32_t mExpectedTargetApiVersion = 0;
-
//! Buffer containing the complete DSO binary - only populated if
//! copyNanoappFragment() was used to load this nanoapp
void *mAppBinary = nullptr;
diff --git a/platform/slpi/include/chre/target_platform/platform_sensor_type_helpers_base.h b/platform/slpi/include/chre/target_platform/platform_sensor_type_helpers_base.h
index 69ad6dcf..638c286a 100644
--- a/platform/slpi/include/chre/target_platform/platform_sensor_type_helpers_base.h
+++ b/platform/slpi/include/chre/target_platform/platform_sensor_type_helpers_base.h
@@ -44,20 +44,10 @@ enum class SensorSampleType {
Vendor7,
Vendor8,
Vendor9,
- Vendor10,
Unknown,
};
/**
- * The group IDs that the SEE sensor driver supports placing nanoapps into such
- * that they can be targeted separately by the sensor driver.
- */
-enum NanoappGroupIds {
- MicroImage = 1 << 0,
- BigImage = 1 << 1,
-};
-
-/**
* Exposes SLPI-specific methods used by platform code and the SLPI-specific
* PlatformSensorTypeHelpers implementation to transform sensor types as needed.
*/
@@ -91,15 +81,17 @@ class PlatformSensorTypeHelpersBase {
static uint8_t toCalibratedSensorType(uint8_t sensorType);
/**
- * @return Whether the given sensor type reports bias events.
+ * @param sensorType The sensor type.
+ * @return The corresponding uncalibrated sensor type. If the sensor does not
+ * have one or is already uncalibrated, then the input sensorType is
+ * returned.
*/
- static bool reportsBias(uint8_t sensorType);
+ static uint8_t toUncalibratedSensorType(uint8_t sensorType);
/**
- * Rewrites a big-image sensorType to its regular CHRE counterpart leaving
- * regular CHRE sensor types unchanged.
+ * @return Whether the given sensor type reports bias events.
*/
- static void rewriteToChreSensorType(uint8_t *sensorType);
+ static bool reportsBias(uint8_t sensorType);
};
} // namespace chre
diff --git a/platform/slpi/include/chre/target_platform/static_nanoapp_init.h b/platform/slpi/include/chre/target_platform/static_nanoapp_init.h
index 59dc21cd..98ad95be 100644
--- a/platform/slpi/include/chre/target_platform/static_nanoapp_init.h
+++ b/platform/slpi/include/chre/target_platform/static_nanoapp_init.h
@@ -30,9 +30,8 @@
* when creating the global instance of the nanoapp.
* @param appId the app's unique 64-bit ID
* @param appVersion the application-defined 32-bit version number
- * @param appPerms the declared CHRE_PERMS_ permissions for the nanoapp.
*/
-#define CHRE_STATIC_NANOAPP_INIT(appName, appId_, appVersion_, appPerms) \
+#define CHRE_STATIC_NANOAPP_INIT(appName, appId_, appVersion_) \
namespace chre { \
\
UniquePtr<Nanoapp> initializeStaticNanoapp##appName() { \
@@ -51,7 +50,6 @@
appInfo.entryPoints.handleEvent = nanoappHandleEvent; \
appInfo.entryPoints.end = nanoappEnd; \
appInfo.appVersionString = "<undefined>"; \
- appInfo.appPermissions = appPerms; \
if (nanoapp.isNull()) { \
FATAL_ERROR("Failed to allocate nanoapp " #appName); \
} else { \
diff --git a/platform/slpi/init.cc b/platform/slpi/init.cc
index 1558fd04..b22f0864 100644
--- a/platform/slpi/init.cc
+++ b/platform/slpi/init.cc
@@ -40,14 +40,6 @@ extern "C" {
#include "chre/platform/slpi/see/island_vote_client.h"
#endif
-#ifdef CHRE_QSH_ENABLED
-#include "chre/platform/slpi/qsh/qsh_shim.h"
-#endif
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
-#include "chre/platform/shared/log_buffer_manager.h"
-#endif
-
using chre::EventLoop;
using chre::EventLoopManagerSingleton;
using chre::LockGuard;
@@ -101,37 +93,17 @@ bool gThreadRunning;
int gTlsKey;
bool gTlsKeyValid;
-// TODO(b/181871430): Enable buffered logging for QSH. The QSH implementation
-// will not log currently.
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
-
-//! Primary and secondary log buffers for the LogBufferManager
-uint8_t gPrimaryLogBufferData[CHRE_LOG_BUFFER_DATA_SIZE];
-uint8_t gSecondaryLogBufferData[CHRE_LOG_BUFFER_DATA_SIZE];
-
-#endif
-
/**
* Entry point for the QuRT thread that runs CHRE.
*
* @param data Argument passed to qurt_thread_create()
*/
void chreThreadEntry(void * /*data*/) {
-#ifdef CHRE_QSH_ENABLED
- chre::openQsh();
-#endif // CHRE_QSH_ENABLED
-
EventLoopManagerSingleton::get()->lateInit();
chre::loadStaticNanoapps();
EventLoopManagerSingleton::get()->getEventLoop().run();
chre::deinit();
-
-#ifdef CHRE_QSH_ENABLED
- chre::closeQsh();
-#endif // CHRE_QSH_ENABLED
-
#if defined(CHRE_SLPI_SEE) && !defined(IMPORT_CHRE_UTILS)
chre::IslandVoteClientSingleton::deinit();
#endif
@@ -171,12 +143,6 @@ extern "C" int chre_slpi_start_thread(void) {
LockGuard<Mutex> lock(gThreadMutex);
int fastRpcResult = CHRE_FASTRPC_ERROR;
-#ifdef CHRE_USE_BUFFERED_LOGGING
- chre::LogBufferManagerSingleton::init(gPrimaryLogBufferData,
- gSecondaryLogBufferData,
- sizeof(gPrimaryLogBufferData));
-#endif
-
if (gThreadRunning) {
LOGE("CHRE thread already running");
} else {
diff --git a/platform/slpi/log_buffer_manager.cc b/platform/slpi/log_buffer_manager.cc
deleted file mode 100644
index 52177671..00000000
--- a/platform/slpi/log_buffer_manager.cc
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "chre/platform/shared/log_buffer_manager.h"
-
-namespace chre {
-
-void LogBufferManager::preSecondaryBufferUse() const {
- // Do nothing
-}
-
-} // namespace chre
diff --git a/platform/slpi/memory.cc b/platform/slpi/memory.cc
index 8ac624d1..d948fede 100644
--- a/platform/slpi/memory.cc
+++ b/platform/slpi/memory.cc
@@ -25,10 +25,8 @@
extern "C" {
-#ifdef CHRE_SLPI_UIMG_ENABLED
#include "sns_island_util.h"
#include "sns_memmgr.h"
-#endif // CHRE_SLPI_UIMG_ENABLED
} // extern "C"
diff --git a/platform/shared/nanoapp_load_manager.cc b/platform/slpi/nanoapp_load_manager.cc
index 67de637d..46dd44a5 100644
--- a/platform/shared/nanoapp_load_manager.cc
+++ b/platform/slpi/nanoapp_load_manager.cc
@@ -14,21 +14,19 @@
* limitations under the License.
*/
-#include "chre/platform/shared/nanoapp_load_manager.h"
+#include "chre/platform/slpi/nanoapp_load_manager.h"
namespace chre {
bool NanoappLoadManager::prepareForLoad(uint16_t hostClientId,
uint32_t transactionId, uint64_t appId,
- uint32_t appVersion, uint32_t appFlags,
- size_t totalBinaryLen,
- uint32_t targetApiVersion) {
+ uint32_t appVersion,
+ size_t totalBinaryLen) {
if (hasPendingLoadTransaction()) {
LOGW(
"Pending load transaction already exists. Overriding previous"
" transaction.");
}
-
mCurrentLoadInfo.hostClientId = hostClientId;
mCurrentLoadInfo.transactionId = transactionId;
mCurrentLoadInfo.nextFragmentId = 1;
@@ -38,8 +36,7 @@ bool NanoappLoadManager::prepareForLoad(uint16_t hostClientId,
if (mNanoapp.isNull()) {
LOG_OOM();
} else {
- success = mNanoapp->reserveBuffer(appId, appVersion, appFlags,
- totalBinaryLen, targetApiVersion);
+ success = mNanoapp->reserveBuffer(appId, appVersion, totalBinaryLen);
}
if (!success) {
diff --git a/platform/slpi/platform_audio.cc b/platform/slpi/platform_audio.cc
index 404dc6b1..627b26e5 100644
--- a/platform/slpi/platform_audio.cc
+++ b/platform/slpi/platform_audio.cc
@@ -51,10 +51,10 @@ PlatformAudio::PlatformAudio() {}
PlatformAudio::~PlatformAudio() {
if (mAudioApi != nullptr) {
- LOGV("Platform audio closing");
+ LOGD("Platform audio closing");
prePalApiCall();
mAudioApi->close();
- LOGV("Platform audio closed");
+ LOGD("Platform audio closed");
}
}
diff --git a/platform/slpi/platform_debug_dump_manager.cc b/platform/slpi/platform_debug_dump_manager.cc
index 9df01ea3..3496e599 100644
--- a/platform/slpi/platform_debug_dump_manager.cc
+++ b/platform/slpi/platform_debug_dump_manager.cc
@@ -67,9 +67,6 @@ void PlatformDebugDumpManager::sendDebugDump(const char *debugStr,
#endif // CHRE_ENABLE_ASH_DEBUG_DUMP
}
-void PlatformDebugDumpManager::logStateToBuffer(
- DebugDumpWrapper & /* debugDump */) {}
-
PlatformDebugDumpManagerBase::PlatformDebugDumpManagerBase() {
#ifdef CHRE_ENABLE_ASH_DEBUG_DUMP
if (!ashRegisterDebugDumpCallback("CHRE", onDebugDumpTriggered,
diff --git a/platform/slpi/platform_nanoapp.cc b/platform/slpi/platform_nanoapp.cc
index 02b15acc..e0b4e29b 100644
--- a/platform/slpi/platform_nanoapp.cc
+++ b/platform/slpi/platform_nanoapp.cc
@@ -25,7 +25,6 @@
#include "chre/platform/slpi/memory.h"
#include "chre/platform/slpi/power_control_util.h"
#include "chre/util/system/debug_dump.h"
-#include "chre/util/system/napp_permissions.h"
#include "chre_api/chre/version.h"
#include "dlfcn.h"
@@ -34,6 +33,102 @@
#include <string.h>
namespace chre {
+#if defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
+namespace {
+void rewriteToChreEventType(uint16_t *eventType) {
+ CHRE_ASSERT(eventType);
+
+ // HACK: as SEE does not support software batching in uimg via
+ // QCM/uQSockets, we rewrite requests for accel and uncal accel/gyro/mag
+ // from big image nanoapps to respective vendor types in
+ // chreSensorFindDefault(), which is implemented as sensor data routed
+ // through CM/QMI and supports batching. Rewrite sensor data arriving
+ // on this event type to the vanilla sensor event type so that this appears
+ // transparent to the nanoapp.
+ // TODO(P2-5673a9): work with QC to determine a better long-term solution
+ constexpr uint16_t kAccelBigImageEventType =
+ (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_VENDOR_START + 3);
+ constexpr uint16_t kUncalAccelBigImageEventType =
+ (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_VENDOR_START + 6);
+ constexpr uint16_t kUncalGyroBigImageEventType =
+ (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_VENDOR_START + 7);
+ constexpr uint16_t kUncalMagBigImageEventType =
+ (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_VENDOR_START + 8);
+ constexpr uint16_t kLightBigImageEventType =
+ (CHRE_EVENT_SENSOR_DATA_EVENT_BASE + CHRE_SENSOR_TYPE_VENDOR_START + 9);
+
+ if (*eventType == kAccelBigImageEventType) {
+ *eventType = CHRE_EVENT_SENSOR_ACCELEROMETER_DATA;
+ } else if (*eventType == kUncalAccelBigImageEventType) {
+ *eventType = CHRE_EVENT_SENSOR_UNCALIBRATED_ACCELEROMETER_DATA;
+ } else if (*eventType == kUncalGyroBigImageEventType) {
+ *eventType = CHRE_EVENT_SENSOR_UNCALIBRATED_GYROSCOPE_DATA;
+ } else if (*eventType == kUncalMagBigImageEventType) {
+ *eventType = CHRE_EVENT_SENSOR_UNCALIBRATED_GEOMAGNETIC_FIELD_DATA;
+ } else if (*eventType == kLightBigImageEventType) {
+ *eventType = CHRE_EVENT_SENSOR_LIGHT_DATA;
+ }
+}
+
+/**
+ * Helper function to get the sensor type of a big-image variant of a sensor.
+ *
+ * @param sensorType The sensor type to convert from.
+ *
+ * @return The sensor type of the corresponding big-image sensor, or the input
+ * sensor type if one does not exist.
+ */
+uint8_t getBigImageSensorType(uint8_t sensorType) {
+ switch (sensorType) {
+ case CHRE_SENSOR_TYPE_ACCELEROMETER:
+ return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_ACCEL;
+ case CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER:
+ return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_ACCEL;
+ case CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE:
+ return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_GYRO;
+ case CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD:
+ return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_MAG;
+ case CHRE_SENSOR_TYPE_LIGHT:
+ return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_LIGHT;
+ default:
+ return sensorType;
+ }
+}
+
+/**
+ * Helper function to get the handle of a big-image variant of a sensor.
+ *
+ * @param sensorHandle The sensor handle to convert from.
+ *
+ * @return The handle of the corresponding big-image sensor, or the input sensor
+ * handle if one does not exist.
+ */
+uint32_t getBigImageSensorHandle(uint32_t sensorHandle) {
+ Sensor *sensor =
+ EventLoopManagerSingleton::get()->getSensorRequestManager().getSensor(
+ sensorHandle);
+ uint8_t bigImageType = getBigImageSensorType(sensor->getSensorType());
+ uint32_t bigImageHandle;
+ EventLoopManagerSingleton::get()->getSensorRequestManager().getSensorHandle(
+ bigImageType, &bigImageHandle);
+ return bigImageHandle;
+}
+
+/**
+ * @return true if the given event type is a bias info event.
+ */
+bool isBiasEventType(uint16_t eventType) {
+ return eventType == CHRE_EVENT_SENSOR_ACCELEROMETER_BIAS_INFO ||
+ eventType == CHRE_EVENT_SENSOR_UNCALIBRATED_ACCELEROMETER_BIAS_INFO ||
+ eventType == CHRE_EVENT_SENSOR_GYROSCOPE_BIAS_INFO ||
+ eventType == CHRE_EVENT_SENSOR_UNCALIBRATED_GYROSCOPE_BIAS_INFO ||
+ eventType == CHRE_EVENT_SENSOR_GEOMAGNETIC_FIELD_BIAS_INFO ||
+ eventType ==
+ CHRE_EVENT_SENSOR_UNCALIBRATED_GEOMAGNETIC_FIELD_BIAS_INFO;
+}
+
+} // anonymous namespace
+#endif // defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
PlatformNanoapp::~PlatformNanoapp() {
closeNanoapp();
@@ -55,8 +150,25 @@ void PlatformNanoapp::handleEvent(uint32_t senderInstanceId, uint16_t eventType,
const void *eventData) {
if (!isUimgApp()) {
slpiForceBigImage();
+
+#if defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
+ rewriteToChreEventType(&eventType);
+#endif // defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
}
+#if defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
+ // NOTE: Since SeeCalHelper does not internally differentiate calibration
+ // between big/micro image, convert the sensor handle to the appropriate
+ // one when delivering a bias info event to the nanoapp.
+ chreSensorThreeAxisData bias;
+ if (eventData != nullptr && !isUimgApp() && isBiasEventType(eventType)) {
+ bias = *static_cast<const chreSensorThreeAxisData *>(eventData);
+ bias.header.sensorHandle =
+ getBigImageSensorHandle(bias.header.sensorHandle);
+ eventData = &bias;
+ }
+#endif // defined(CHRE_SLPI_SEE) && defined(CHRE_SLPI_UIMG_ENABLED)
+
mAppInfo->entryPoints.handleEvent(senderInstanceId, eventType, eventData);
}
@@ -70,12 +182,10 @@ void PlatformNanoapp::end() {
}
bool PlatformNanoappBase::setAppInfo(uint64_t appId, uint32_t appVersion,
- const char *appFilename,
- uint32_t targetApiVersion) {
+ const char *appFilename) {
CHRE_ASSERT(!isLoaded());
mExpectedAppId = appId;
mExpectedAppVersion = appVersion;
- mExpectedTargetApiVersion = targetApiVersion;
size_t appFilenameLen = strlen(appFilename) + 1;
mAppFilename = static_cast<char *>(memoryAllocBigImage(appFilenameLen));
@@ -91,9 +201,7 @@ bool PlatformNanoappBase::setAppInfo(uint64_t appId, uint32_t appVersion,
}
bool PlatformNanoappBase::reserveBuffer(uint64_t appId, uint32_t appVersion,
- uint32_t /* appFlags */,
- size_t appBinaryLen,
- uint32_t targetApiVersion) {
+ size_t appBinaryLen) {
CHRE_ASSERT(!isLoaded());
bool success = false;
constexpr size_t kMaxAppSize = 2 * 1024 * 1024; // 2 MiB
@@ -108,7 +216,6 @@ bool PlatformNanoappBase::reserveBuffer(uint64_t appId, uint32_t appVersion,
} else {
mExpectedAppId = appId;
mExpectedAppVersion = appVersion;
- mExpectedTargetApiVersion = targetApiVersion;
mAppBinaryLen = appBinaryLen;
success = true;
}
@@ -227,20 +334,15 @@ bool PlatformNanoappBase::verifyNanoappInfo() {
if (mAppInfo == nullptr) {
LOGE("Failed to find app info symbol: %s", dlerror());
} else {
- success = validateAppInfo(mExpectedAppId, mExpectedAppVersion,
- mExpectedTargetApiVersion, mAppInfo);
+ success = validateAppInfo(mExpectedAppId, mExpectedAppVersion, mAppInfo);
if (!success) {
mAppInfo = nullptr;
} else {
- LOGI("Nanoapp loaded: %s (0x%016" PRIx64 ") version 0x%" PRIx32
- " (%s) uimg %d system %d",
+ LOGI("Successfully loaded nanoapp: %s (0x%016" PRIx64
+ ") version 0x%" PRIx32 " (%s) uimg %d system %d",
mAppInfo->name, mAppInfo->appId, mAppInfo->appVersion,
getAppVersionString(), mAppInfo->isTcmNanoapp,
mAppInfo->isSystemNanoapp);
- if (mAppInfo->structMinorVersion >=
- CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION) {
- LOGI("Nanoapp permissions: 0x%" PRIx32, mAppInfo->appPermissions);
- }
}
}
}
@@ -279,20 +381,7 @@ uint32_t PlatformNanoapp::getAppVersion() const {
}
uint32_t PlatformNanoapp::getTargetApiVersion() const {
- return (mAppInfo != nullptr) ? mAppInfo->targetApiVersion
- : mExpectedTargetApiVersion;
-}
-
-bool PlatformNanoapp::supportsAppPermissions() const {
- return (mAppInfo != nullptr) ? (mAppInfo->structMinorVersion >=
- CHRE_NSL_NANOAPP_INFO_STRUCT_MINOR_VERSION)
- : false;
-}
-
-uint32_t PlatformNanoapp::getAppPermissions() const {
- return (supportsAppPermissions())
- ? mAppInfo->appPermissions
- : static_cast<uint32_t>(chre::NanoappPermissions::CHRE_PERMS_NONE);
+ return (mAppInfo != nullptr) ? mAppInfo->targetApiVersion : 0;
}
const char *PlatformNanoapp::getAppName() const {
diff --git a/platform/slpi/platform_sensor_type_helpers.cc b/platform/slpi/platform_sensor_type_helpers.cc
index 6e7bd188..d64f9b91 100644
--- a/platform/slpi/platform_sensor_type_helpers.cc
+++ b/platform/slpi/platform_sensor_type_helpers.cc
@@ -174,6 +174,23 @@ uint8_t PlatformSensorTypeHelpersBase::toCalibratedSensorType(
return sensorType;
}
+uint8_t PlatformSensorTypeHelpersBase::toUncalibratedSensorType(
+ uint8_t sensorType) {
+ switch (sensorType) {
+ case CHRE_SENSOR_TYPE_ACCELEROMETER:
+ return CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER;
+ case CHRE_SENSOR_TYPE_GYROSCOPE:
+ return CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE;
+ case CHRE_SENSOR_TYPE_GEOMAGNETIC_FIELD:
+ return CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD;
+ default:
+ /* empty */
+ break;
+ }
+
+ return sensorType;
+}
+
bool PlatformSensorTypeHelpersBase::reportsBias(uint8_t sensorType) {
switch (sensorType) {
case CHRE_SENSOR_TYPE_ACCELEROMETER:
@@ -192,21 +209,4 @@ bool PlatformSensorTypeHelpersBase::reportsBias(uint8_t sensorType) {
}
}
-void PlatformSensorTypeHelpersBase::rewriteToChreSensorType(
- uint8_t *sensorType) {
- CHRE_ASSERT(sensorType);
-
- if (*sensorType == CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_ACCEL) {
- *sensorType = CHRE_SENSOR_TYPE_ACCELEROMETER;
- } else if (*sensorType == CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_ACCEL) {
- *sensorType = CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER;
- } else if (*sensorType == CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_GYRO) {
- *sensorType = CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE;
- } else if (*sensorType == CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_MAG) {
- *sensorType = CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD;
- } else if (*sensorType == CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_LIGHT) {
- *sensorType = CHRE_SENSOR_TYPE_LIGHT;
- }
-}
-
} // namespace chre
diff --git a/platform/slpi/qsh/qsh_shim.cc b/platform/slpi/qsh/qsh_shim.cc
deleted file mode 100644
index 332a1fda..00000000
--- a/platform/slpi/qsh/qsh_shim.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 <cstdint>
-#include <dlfcn.h>
-
-extern "C" {
-
-#include "qsh_na_api.h"
-
-} // extern "C"
-
-#include "chre/core/event_loop_manager.h"
-#include "chre/core/nanoapp.h"
-#include "chre/platform/assert.h"
-#include "chre/platform/log.h"
-#include "chre/platform/memory.h"
-#include "chre/platform/slpi/qsh/qsh_shim.h"
-#include "chre/sensor.h"
-#include "chre/util/macros.h"
-
-namespace chre {
-namespace {
-
-//! Function pointer to store QSH's version of chreSensorFlushAsync
-decltype(chreSensorFlushAsync) *gFlushFuncPtr = nullptr;
-
-/*
- * Used by QSH to obtain the currently running nanoapp instance ID when nanoapps
- * invoke CHRE APIs implemented by its shim.
- */
-bool getCurrentNanoappInstanceId(uint32_t *nanoappInstId) {
- CHRE_ASSERT(nanoappInstId != nullptr);
- if (nanoappInstId == nullptr) {
- return false;
- }
-
- bool success = false;
- Nanoapp *currentNanoapp =
- EventLoopManagerSingleton::get()->getEventLoop().getCurrentNanoapp();
- if (currentNanoapp == nullptr) {
- LOGE("No nanoapp currently executing");
- } else {
- *nanoappInstId = currentNanoapp->getInstanceId();
- success = true;
- }
- return success;
-}
-
-/*
- * Used by QSH to post events to the CHRE event loop. The caller continues to
- * own the event pointer after returning so a copy must be made of the data.
- */
-bool postEventFromQsh(uint16_t eventType, void *event, uint32_t eventLen,
- uint32_t nanoappInstId) {
- // Default success to true if the event is empty since an empty event can
- // still be sent to CHRE.
- bool success = false;
- void *eventCopy = nullptr;
- if (eventLen == 0) {
- CHRE_ASSERT(event == nullptr);
- if (event != nullptr) {
- LOGE("Event len 0 with non-null event data");
- } else {
- success = true;
- }
- } else {
- CHRE_ASSERT(event != nullptr);
- if (event != nullptr) {
- eventCopy = memoryAlloc(eventLen);
- if (eventCopy == nullptr) {
- LOG_OOM();
- } else {
- memcpy(eventCopy, event, eventLen);
- success = true;
- }
- }
- }
-
- if (success) {
- EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
- eventType, eventCopy, freeEventDataCallback, nanoappInstId);
- }
- return success;
-}
-
-const qsh_na_api_callbacks gQshCallbacks = {
- getCurrentNanoappInstanceId, /* get_current_nanoapp_inst_id */
- postEventFromQsh, /* post_event */
-};
-
-} // anonymous namespace
-
-void openQsh() {
- if (!qsh_na_open(&gQshCallbacks)) {
- LOGE("QSH failed to open");
- } else {
- LOGI("QSH opened");
- gFlushFuncPtr = reinterpret_cast<decltype(gFlushFuncPtr)>(
- dlsym(RTLD_NEXT, STRINGIFY(chreSensorFlushAsync)));
- if (gFlushFuncPtr == nullptr) {
- LOGE("Flush function not found!");
- }
- }
-}
-
-void closeQsh() {
- qsh_na_close();
-}
-
-} // namespace chre
-
-// Define the delete operator so that SLPI doesn't have to expose this symbol
-// since CHRE will never call it directly
-void operator delete (void* ptr) noexcept {
- free(ptr);
-}
-
-// Export the chreSensorFlushAsync symbol from CHRE and then used the previously
-// looked up symbol to WAR loader issue where nanoapps can't see QSH symbols.
-DLL_EXPORT extern "C" bool chreSensorFlushAsync(uint32_t sensorHandle,
- const void *cookie) {
- return (chre::gFlushFuncPtr != nullptr)
- ? chre::gFlushFuncPtr(sensorHandle, cookie)
- : false;
-} \ No newline at end of file
diff --git a/platform/slpi/see/include/chre/target_platform/platform_sensor_base.h b/platform/slpi/see/include/chre/target_platform/platform_sensor_base.h
index b9d26f3d..550c8eb6 100644
--- a/platform/slpi/see/include/chre/target_platform/platform_sensor_base.h
+++ b/platform/slpi/see/include/chre/target_platform/platform_sensor_base.h
@@ -39,8 +39,7 @@ class PlatformSensorBase {
* Initializes various members of PlatformSensorBase.
*/
void initBase(uint8_t sensorType, uint64_t minInterval,
- const char *sensorName, bool passiveSupported,
- uint16_t targetGroupMask);
+ const char *sensorName, bool passiveSupported);
//! Stores the last received sampling status from SEE for this sensor making
//! it easier to dedup updates that come in later from SEE.
@@ -52,9 +51,6 @@ class PlatformSensorBase {
//! The minimum interval of this sensor.
uint64_t mMinInterval;
- //! The group mask events from this sensor must target.
- uint16_t mTargetGroupMask;
-
//! The sensor type of this sensor.
uint8_t mSensorType;
diff --git a/platform/slpi/see/include/chre/target_platform/platform_sensor_manager_base.h b/platform/slpi/see/include/chre/target_platform/platform_sensor_manager_base.h
index 9b84b4c2..a74a547a 100644
--- a/platform/slpi/see/include/chre/target_platform/platform_sensor_manager_base.h
+++ b/platform/slpi/see/include/chre/target_platform/platform_sensor_manager_base.h
@@ -35,20 +35,20 @@ class PlatformSensorManagerBase : public SeeHelperCallbackInterface {
#endif // CHRE_SLPI_UIMG_ENABLED
/**
- * Helper function to retrieve the SeeHelper for a given sensor.
- * @param sensor The sensor
+ * Helper function to retrieve the SeeHelper for a given sensor type.
+ * @param sensorType the sensor type
* @return A reference to the appropriate (bimg or uimg) SeeHelper
*/
- SeeHelper &getSeeHelperForSensor(const Sensor &sensor);
+ SeeHelper &getSeeHelperForSensorType(uint8_t sensorType);
- const SeeHelper &getSeeHelperForSensor(const Sensor &sensor) const {
+ const SeeHelper &getSeeHelperForSensorType(uint8_t sensorType) const {
// The following cast is done to share code between this method and
- // getSeeHelperForSensor so we can expose either a const or non-const
+ // getSeeHelperForSensorType so we can expose either a const or non-const
// SeeHelper depending on the requirements of the caller. The non-const
- // version of getSeeHelperForSensor will not modify
+ // version of getSeeHelperForSensorType will not modify
// PlatformSensorManagerBase so this should be safe.
- return const_cast<PlatformSensorManagerBase *>(this)->getSeeHelperForSensor(
- sensor);
+ return const_cast<PlatformSensorManagerBase *>(this)
+ ->getSeeHelperForSensorType(sensorType);
}
#ifdef CHRE_SLPI_UIMG_ENABLED
diff --git a/platform/slpi/see/platform_sensor.cc b/platform/slpi/see/platform_sensor.cc
index 24d45eeb..e3685b74 100644
--- a/platform/slpi/see/platform_sensor.cc
+++ b/platform/slpi/see/platform_sensor.cc
@@ -19,14 +19,13 @@
namespace chre {
void PlatformSensorBase::initBase(uint8_t sensorType, uint64_t minInterval,
- const char *sensorName, bool passiveSupported,
- uint16_t targetGroupMask) {
+ const char *sensorName,
+ bool passiveSupported) {
mSensorType = sensorType;
mMinInterval = minInterval;
memcpy(mSensorName, sensorName, kSensorNameMaxLen);
mPassiveSupported = passiveSupported;
- mTargetGroupMask = targetGroupMask;
}
uint8_t PlatformSensor::getSensorType() const {
@@ -49,25 +48,16 @@ const char *PlatformSensor::getSensorName() const {
return mSensorName;
}
-uint16_t PlatformSensor::getTargetGroupMask() const {
- return mTargetGroupMask;
-}
-
PlatformSensor::PlatformSensor(PlatformSensor &&other) {
*this = std::move(other);
}
-uint8_t PlatformSensor::getSensorIndex() const {
- return CHRE_SENSOR_INDEX_DEFAULT;
-}
-
PlatformSensor &PlatformSensor::operator=(PlatformSensor &&other) {
// Note: if this implementation is ever changed to depend on "this" containing
// initialized values, the move constructor implementation must be updated.
mSensorType = other.mSensorType;
mMinInterval = other.mMinInterval;
mPassiveSupported = other.mPassiveSupported;
- mTargetGroupMask = other.mTargetGroupMask;
memcpy(mSensorName, other.mSensorName, kSensorNameMaxLen);
diff --git a/platform/slpi/see/platform_sensor_manager.cc b/platform/slpi/see/platform_sensor_manager.cc
index 91922931..d798d5c0 100644
--- a/platform/slpi/see/platform_sensor_manager.cc
+++ b/platform/slpi/see/platform_sensor_manager.cc
@@ -27,7 +27,6 @@
#include "chre/platform/log.h"
#include "chre/platform/slpi/power_control_util.h"
#include "chre/platform/system_time.h"
-#include "chre/util/nested_data_ptr.h"
#include "chre_api/chre/sensor.h"
#ifdef CHREX_SENSOR_SUPPORT
@@ -84,18 +83,6 @@ const char *kSeeDataTypes[] = {
#error "CHRE extensions are required for micro-image SEE support"
#endif // CHREX_SENSOR_SUPPORT
-bool isBigImageSensor(const Sensor &sensor) {
- return sensor.getTargetGroupMask() == NanoappGroupIds::BigImage;
-}
-
-bool sensorTypeSupportsBigImage(uint8_t sensorType) {
- return (sensorType == CHRE_SENSOR_TYPE_ACCELEROMETER ||
- sensorType == CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER ||
- sensorType == CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE ||
- sensorType == CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD ||
- sensorType == CHRE_SENSOR_TYPE_LIGHT);
-}
-
bool isBigImageSensorType(uint8_t sensorType) {
return (sensorType == CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_ACCEL ||
sensorType == CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_ACCEL ||
@@ -104,21 +91,29 @@ bool isBigImageSensorType(uint8_t sensorType) {
sensorType == CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_LIGHT);
}
-uint8_t getBigImageSensorType(uint8_t sensorType) {
- switch (sensorType) {
- case CHRE_SENSOR_TYPE_ACCELEROMETER:
- return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_ACCEL;
- case CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER:
- return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_ACCEL;
- case CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE:
- return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_GYRO;
- case CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD:
- return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_MAG;
- case CHRE_SENSOR_TYPE_LIGHT:
- return CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_LIGHT;
- default:
- return sensorType;
+/**
+ * Obtains the big-image sensor type given the specified data type and whether
+ * the sensor is runtime-calibrated or not.
+ */
+bool getBigImageSensorTypeFromDataType(const char *dataType, bool calibrated,
+ uint8_t *sensorType) {
+ bool found = true;
+ if (strcmp(dataType, "accel") == 0) {
+ if (calibrated) {
+ *sensorType = CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_ACCEL;
+ } else {
+ *sensorType = CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_ACCEL;
+ }
+ } else if (strcmp(dataType, "gyro") == 0 && !calibrated) {
+ *sensorType = CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_GYRO;
+ } else if (strcmp(dataType, "mag") == 0 && !calibrated) {
+ *sensorType = CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_MAG;
+ } else if (strcmp(dataType, "ambient_light") == 0 && calibrated) {
+ *sensorType = CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_LIGHT;
+ } else {
+ found = false;
}
+ return found;
}
/**
@@ -130,15 +125,15 @@ uint8_t getBigImageSensorType(uint8_t sensorType) {
*/
uint8_t getUimgSensorType(uint8_t sensorType) {
switch (sensorType) {
- case CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_ACCEL:
+ case (CHRE_SENSOR_TYPE_VENDOR_START + 3):
return CHRE_SENSOR_TYPE_ACCELEROMETER;
- case CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_ACCEL:
+ case (CHRE_SENSOR_TYPE_VENDOR_START + 6):
return CHRE_SENSOR_TYPE_UNCALIBRATED_ACCELEROMETER;
- case CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_GYRO:
+ case (CHRE_SENSOR_TYPE_VENDOR_START + 7):
return CHRE_SENSOR_TYPE_UNCALIBRATED_GYROSCOPE;
- case CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_UNCAL_MAG:
+ case (CHRE_SENSOR_TYPE_VENDOR_START + 8):
return CHRE_SENSOR_TYPE_UNCALIBRATED_GEOMAGNETIC_FIELD;
- case CHRE_SLPI_SENSOR_TYPE_BIG_IMAGE_LIGHT:
+ case (CHRE_SENSOR_TYPE_VENDOR_START + 9):
return CHRE_SENSOR_TYPE_LIGHT;
default:
return sensorType;
@@ -147,18 +142,6 @@ uint8_t getUimgSensorType(uint8_t sensorType) {
#endif // CHRE_SLPI_UIMG_ENABLED
-#ifndef CHRE_LOG_ONLY_NO_SENSOR
-/**
- * Callback function which will run after a delay if a required sensor is not
- * found.
- */
-void crashAfterSensorNotFoundCallback(uint16_t /* eventType */,
- void * /* data */,
- void * /* extraData */) {
- FATAL_ERROR("Missing required sensor(s)");
-}
-#endif
-
void handleMissingSensor() {
// Try rebooting if a sensor is missing, which might help recover from a
// transient failure/race condition at startup. But to avoid endless crashes,
@@ -168,13 +151,12 @@ void handleMissingSensor() {
// SLPI SSR).
#ifndef CHRE_LOG_ONLY_NO_SENSOR
if (SystemTime::getMonotonicTime() < (kDefaultSeeWaitTimeout + Seconds(15))) {
- Nanoseconds delay(5 * Seconds(60).toRawNanoseconds()); // 5 minutes
- EventLoopManagerSingleton::get()->setDelayedCallback(
- SystemCallbackType::DelayedFatalError, nullptr,
- crashAfterSensorNotFoundCallback, delay);
- }
+ FATAL_ERROR("Missing required sensor(s)");
+ } else
#endif
- LOGE("Missing required sensor(s)");
+ {
+ LOGE("Missing required sensor(s)");
+ }
}
/**
@@ -184,7 +166,7 @@ void handleMissingSensor() {
* @return Whether a sensor type was found for the given data type.
*/
bool getSensorTypeFromDataType(const char *dataType, bool calibrated,
- uint8_t *sensorType, bool bigImage = false) {
+ uint8_t *sensorType) {
bool success = true;
if (strcmp(dataType, "accel") == 0) {
if (calibrated) {
@@ -226,13 +208,6 @@ bool getSensorTypeFromDataType(const char *dataType, bool calibrated,
success = false;
}
#endif
-
-#ifdef CHRE_SLPI_UIMG_ENABLED
- if (bigImage && !sensorTypeSupportsBigImage(*sensorType)) {
- success = false;
- }
-#endif
-
return success;
}
@@ -263,18 +238,19 @@ void mergeUpdatedStatus(
* @param sensorType The sensor type to post the event for.
* @param bias The bias data.
*/
-void postSensorBiasEvent(uint8_t sensorType, uint16_t targetGroupMask,
+void postSensorBiasEvent(uint8_t sensorType,
const chreSensorThreeAxisData &bias) {
- uint32_t sensorHandle;
- if (getSensorRequestManager().getSensorHandle(
- sensorType, 0 /* sensorIndex */, targetGroupMask, &sensorHandle)) {
+ uint16_t eventType;
+ if (SensorTypeHelpers::getBiasEventType(sensorType, &eventType)) {
auto *event = memoryAlloc<struct chreSensorThreeAxisData>();
if (event == nullptr) {
LOG_OOM();
} else {
*event = bias;
- event->header.sensorHandle = sensorHandle;
- getSensorRequestManager().handleBiasEvent(sensorHandle, event);
+ getSensorRequestManager().getSensorHandle(sensorType,
+ &event->header.sensorHandle);
+ EventLoopManagerSingleton::get()->getEventLoop().postEventOrDie(
+ eventType, event, freeEventDataCallback);
}
}
}
@@ -314,14 +290,13 @@ bool isSameStatusUpdate(
*
* @param seeHelper SeeHelper instance to register sensor with
* @param sensorType The sensor type of the sensor.
- * @param targetGroupMask The mask of target groups this sensor supports.
* @param suid The SUID of the sensor as provided by SEE.
* @param attr A reference to SeeAttrbutes.
* @param sensors The sensor list.
*/
void addSensor(SeeHelper &seeHelper, uint8_t sensorType,
- uint16_t targetGroupMask, const sns_std_suid &suid,
- const SeeAttributes &attr, DynamicVector<Sensor> *sensors) {
+ const sns_std_suid &suid, const SeeAttributes &attr,
+ DynamicVector<Sensor> *sensors) {
// Concatenate vendor and name with a space in between.
char sensorName[kSensorNameMaxLen];
strlcpy(sensorName, attr.vendor, sizeof(sensorName));
@@ -347,20 +322,12 @@ void addSensor(SeeHelper &seeHelper, uint8_t sensorType,
// The sensor base class must be initialized before the main Sensor init()
// can be invoked as init() is allowed to invoke base class methods.
sensors->back().initBase(sensorType, minInterval, sensorName,
- attr.passiveRequest, targetGroupMask);
+ attr.passiveRequest);
sensors->back().init();
+ // Resample big image sensors to reduce system load during sw flush.
#ifdef CHRE_SLPI_UIMG_ENABLED
- bool resample = false;
- if (sensorTypeSupportsBigImage(sensorType) &&
- targetGroupMask == NanoappGroupIds::BigImage) {
- // Resample big image sensors to reduce system load during sw flush.
- resample = true;
- // Use the big-image sensor type so that it's clear which samples are coming
- // from the big-image SEE helper. This type is mapped back to the standard
- // CHRE type before anything is sent to nanoapps.
- sensorType = getBigImageSensorType(sensorType);
- }
+ bool resample = isBigImageSensorType(sensorType);
#else
bool resample = false;
#endif
@@ -409,7 +376,7 @@ bool getSuidAndAttrs(SeeHelper &seeHelper, const char *dataType,
if (!success) {
LOGE("Failed to find sensor '%s'", dataType);
} else {
- LOGV("Num of SUIDs found for '%s': %zu", dataType, suids.size());
+ LOGD("Num of SUIDs found for '%s': %zu", dataType, suids.size());
for (const auto &suid : suids) {
SeeAttributes attr;
@@ -418,7 +385,7 @@ bool getSuidAndAttrs(SeeHelper &seeHelper, const char *dataType,
LOGE("Failed to get attributes of SUID 0x%" PRIx64 " %" PRIx64,
suid.suid_high, suid.suid_low);
} else {
- LOGV("%s %s, hw id %" PRId64 ", max ODR %f Hz, stream type %" PRIu8
+ LOGI("%s %s, hw id %" PRId64 ", max ODR %f Hz, stream type %" PRIu8
" passive %d",
attr.vendor, attr.name, attr.hwId, attr.maxSampleRate,
attr.streamType, attr.passiveRequest);
@@ -458,7 +425,6 @@ bool sensorHwMatch(const SeeAttributes &attr0, const SeeAttributes &attr1) {
* info to use for adding temp sensors associated with this sensor type
* @param dataType SEE data type string
* @param sensorType CHRE sensor type associated with dataType
- * @param targetGroupMask Group mask sensors that are added should target
* @param skipAdditionalTypes if true, don't attempt to add
* calibrated/temperature sensor types associated with this sensorType
* @param sensors Vector to append found sensor(s) to
@@ -466,7 +432,6 @@ bool sensorHwMatch(const SeeAttributes &attr0, const SeeAttributes &attr1) {
void findAndAddSensorsForType(SeeHelper &seeHelper,
const DynamicVector<SuidAttr> &temperatureSensors,
const char *dataType, uint8_t sensorType,
- uint16_t targetGroupMask,
bool skipAdditionalTypes,
DynamicVector<Sensor> *sensors) {
DynamicVector<SuidAttr> primarySensors;
@@ -483,7 +448,7 @@ void findAndAddSensorsForType(SeeHelper &seeHelper,
// If there are more than one SUIDs that support the data type,
// choose the first one that has the expected stream type.
if (isStreamTypeCorrect(sensorType, attr.streamType)) {
- addSensor(seeHelper, sensorType, targetGroupMask, suid, attr, sensors);
+ addSensor(seeHelper, sensorType, suid, attr, sensors);
if (!skipAdditionalTypes) {
// Check if this sensor has a runtime-calibrated version.
@@ -491,17 +456,7 @@ void findAndAddSensorsForType(SeeHelper &seeHelper,
if (getSensorTypeFromDataType(dataType, true /* calibrated */,
&calibratedType) &&
calibratedType != sensorType) {
- uint16_t calTargetGroupMask = targetGroupMask;
-#ifdef CHRE_SLPI_UIMG_ENABLED
- if (!sensorTypeSupportsBigImage(calibratedType)) {
- // Override the target group mask if the calibrated type isn't
- // supported in big-image to enforce that the calibrated type is
- // exposed to big-image nanoapps.
- calTargetGroupMask = kDefaultTargetGroupMask;
- }
-#endif
- addSensor(seeHelper, calibratedType, calTargetGroupMask, suid, attr,
- sensors);
+ addSensor(seeHelper, calibratedType, suid, attr, sensors);
}
// Check if this sensor has a secondary temperature sensor.
@@ -521,13 +476,10 @@ void findAndAddSensorsForType(SeeHelper &seeHelper,
#else
if (sensorHwMatch(attr, tempAttr)) {
#endif
- LOGV("Found matching temperature sensor type");
+ LOGD("Found matching temperature sensor type");
tempFound = true;
- // Temp sensors aren't currently separated for big-image / uimg
- // so always use the default mask when adding them.
- constexpr uint16_t kTempGroupMask = kDefaultTargetGroupMask;
- addSensor(seeHelper, temperatureType, kTempGroupMask, tempSuid,
- tempAttr, sensors);
+ addSensor(seeHelper, temperatureType, tempSuid, tempAttr,
+ sensors);
break;
}
}
@@ -542,41 +494,6 @@ void findAndAddSensorsForType(SeeHelper &seeHelper,
}
}
-void postSamplingUpdateForSensor(
- Sensor *sensor, uint32_t sensorHandle,
- UniquePtr<SeeHelperCallbackInterface::SamplingStatusData> &&status) {
- // Ignore the enabled flag from status update if this is not a passive mode
- // supported sensor because this may cause the sampling status in CHRE to
- // go out of sync with reality
- if (!sensor->supportsPassiveMode()) {
- status->status.enabled = sensor->mLastReceivedSamplingStatus.status.enabled;
- status->enabledValid = sensor->mLastReceivedSamplingStatus.enabledValid;
- }
- if (!isSameStatusUpdate(sensor->mLastReceivedSamplingStatus, *status.get())) {
- sensor->mLastReceivedSamplingStatus = *status.get();
-
- auto callback = [](uint16_t /* type */, void *data, void *extraData) {
- uint32_t sensorHandle = NestedDataPtr<uint32_t>(extraData);
- auto *samplingStatus =
- static_cast<SeeHelperCallbackInterface::SamplingStatusData *>(data);
-
- // This memory will be freed via releaseSamplingStatusUpdate()
- struct chreSensorSamplingStatus *status =
- memoryAlloc<struct chreSensorSamplingStatus>();
- mergeUpdatedStatus(sensorHandle, *samplingStatus, status);
-
- getSensorRequestManager().handleSamplingStatusUpdate(sensorHandle,
- status);
- memoryFree(samplingStatus);
- };
- // Schedule a deferred callback to handle sensor status change in the main
- // thread.
- EventLoopManagerSingleton::get()->deferCallback(
- SystemCallbackType::SensorStatusUpdate, status.release(), callback,
- NestedDataPtr<uint32_t>(sensorHandle));
- }
-}
-
} // namespace
PlatformSensorManager::~PlatformSensorManager() {}
@@ -594,19 +511,10 @@ void PlatformSensorManager::init() {
#endif // CHRE_SLPI_UIMG_ENABLED
}
-uint16_t PlatformSensorManager::getTargetGroupId(const Nanoapp &nanoapp) const {
-#ifdef CHRE_SLPI_UIMG_ENABLED
- return (nanoapp.isUimgApp()) ? NanoappGroupIds::MicroImage
- : NanoappGroupIds::BigImage;
-#else
- return NanoappGroupIds::BigImage;
-#endif
-}
-
-SeeHelper &PlatformSensorManagerBase::getSeeHelperForSensor(
- const Sensor &sensor) {
+SeeHelper &PlatformSensorManagerBase::getSeeHelperForSensorType(
+ uint8_t sensorType) {
#ifdef CHRE_SLPI_UIMG_ENABLED
- if (isBigImageSensor(sensor)) {
+ if (isBigImageSensorType(sensorType)) {
slpiForceBigImage();
return mBigImageSeeHelper;
} else
@@ -632,18 +540,16 @@ void PlatformSensorManagerBase::getBigImageSensors(
};
DynamicVector<SuidAttr> nullTemperatureSensorList;
- constexpr uint16_t kTargetGroupMask = NanoappGroupIds::BigImage;
for (size_t i = 0; i < ARRAY_SIZE(kBigImageDataTypes); i++) {
const char *dataType = kBigImageDataTypes[i];
// Loop through potential cal/uncal sensors.
for (size_t j = 0; j < 2; j++) {
uint8_t sensorType;
- if (getSensorTypeFromDataType(dataType, (j == 0) /* calibrated */,
- &sensorType),
- true /* bigImage */) {
+ if (getBigImageSensorTypeFromDataType(dataType, (j == 0) /* calibrated */,
+ &sensorType)) {
findAndAddSensorsForType(mBigImageSeeHelper, nullTemperatureSensorList,
- dataType, sensorType, kTargetGroupMask,
+ dataType, sensorType,
true /* skipAdditionalTypes */, sensors);
}
}
@@ -689,15 +595,8 @@ DynamicVector<Sensor> PlatformSensorManager::getSensors() {
}
#endif
- uint16_t targetGroupMask = kDefaultTargetGroupMask;
-#ifdef CHRE_SLPI_UIMG_ENABLED
- if (sensorTypeSupportsBigImage(sensorType)) {
- targetGroupMask = NanoappGroupIds::MicroImage;
- }
-#endif
-
findAndAddSensorsForType(mSeeHelper, tempSensors, dataType, sensorType,
- targetGroupMask, skipAdditionalTypes, &sensors);
+ skipAdditionalTypes, &sensors);
}
#ifdef CHRE_SLPI_UIMG_ENABLED
@@ -709,15 +608,8 @@ DynamicVector<Sensor> PlatformSensorManager::getSensors() {
bool PlatformSensorManager::configureSensor(Sensor &sensor,
const SensorRequest &request) {
- uint8_t sensorType = sensor.getSensorType();
-#ifdef CHRE_SLPI_UIMG_ENABLED
- if (isBigImageSensor(sensor)) {
- sensorType = getBigImageSensorType(sensorType);
- }
-#endif
-
SeeSensorRequest req = {
- .sensorType = sensorType,
+ .sensorType = sensor.getSensorType(),
.enable = (request.getMode() != SensorMode::Off),
.passive = sensorModeIsPassive(request.getMode()),
.samplingRateHz = static_cast<float>(
@@ -726,7 +618,8 @@ bool PlatformSensorManager::configureSensor(Sensor &sensor,
// ensure one sample per batch so that nanoapps do not miss state changes.
.batchPeriodUs =
#ifdef CHRE_SLPI_UIMG_ENABLED
- (!sensor.isContinuous() && !isBigImageSensor(sensor))
+ (!sensor.isContinuous() &&
+ !isBigImageSensorType(sensor.getSensorType()))
? 0
:
#endif
@@ -734,10 +627,40 @@ bool PlatformSensorManager::configureSensor(Sensor &sensor,
kOneMicrosecondInNanoseconds),
};
- SeeHelper &seeHelper = getSeeHelperForSensor(sensor);
+ SeeHelper &seeHelper = getSeeHelperForSensorType(sensor.getSensorType());
bool wasInUImage = slpiInUImage();
- bool success = seeHelper.makeRequest(req);
+ bool success = true;
+
+ // TODO(b/150144912): Merge the two implementations to avoid having separate
+ // code paths.
+#ifdef CHRE_SLPI_DEFAULT_BUILD
+ // Calibration updates are not enabled automatically in the default build.
+ SeeCalHelper *calHelper = seeHelper.getCalHelper();
+
+ const sns_std_suid *suid =
+ calHelper->getCalSuidFromSensorType(sensor.getSensorType());
+ bool wereCalUpdatesEnabled = false;
+ if (suid != nullptr) {
+ wereCalUpdatesEnabled = calHelper->areCalUpdatesEnabled(*suid);
+ success = calHelper->configureCalUpdates(*suid, req.enable, seeHelper);
+ }
+#endif
+
+ if (success) {
+ success = seeHelper.makeRequest(req);
+ }
+
+#ifdef CHRE_SLPI_DEFAULT_BUILD
+ // If any part of the configuration process failed, reset our subscription
+ // for calibration updates to its previous value to attempt to restore state.
+ if (suid != nullptr && !success) {
+ bool areCalUpdatesEnabled = calHelper->areCalUpdatesEnabled(*suid);
+ if (areCalUpdatesEnabled != wereCalUpdatesEnabled) {
+ calHelper->configureCalUpdates(*suid, wereCalUpdatesEnabled, seeHelper);
+ }
+ }
+#endif
// If we dropped into micro-image during that blocking call to SEE, go back
// to big image. This won't happen if the calling nanoapp is a big image one,
@@ -768,48 +691,35 @@ bool PlatformSensorManager::configureSensor(Sensor &sensor,
return success;
}
-bool PlatformSensorManager::configureBiasEvents(const Sensor &sensor,
- bool enable,
+bool PlatformSensorManager::configureBiasEvents(const Sensor & /* sensor */,
+ bool /* enable */,
uint64_t /* latencyNs */) {
- // Big-image sensor types will be mapped into micro-image sensors so assume
- // using mSeeHelper is OK.
- SeeCalHelper *calHelper = mSeeHelper.getCalHelper();
-
- // Make sure it's the calibrated sensor type since SeeCalHelper only deals
- // with calibrated types.
- uint8_t calibratedType =
- PlatformSensorTypeHelpers::toCalibratedSensorType(sensor.getSensorType());
-
- const sns_std_suid *suid =
- calHelper->getCalSuidFromSensorType(calibratedType);
- bool success = false;
- if (suid != nullptr) {
- if (enable != calHelper->areCalUpdatesEnabled(*suid)) {
- success = calHelper->configureCalUpdates(*suid, enable, mSeeHelper);
- } else {
- // Return true since updates are already configured to the right state.
- // This can happen when configuring big-image sensors since they currently
- // map to the micro-image sensor type which may already be enabled.
- success = true;
- }
- }
- return success;
+ // TODO: Allow enabling / disabling bias events rather than enabling all
+ // bias sensors at init.
+ return true;
}
bool PlatformSensorManager::getThreeAxisBias(
const Sensor &sensor, struct chreSensorThreeAxisData *bias) const {
- SeeCalHelper *calHelper = getSeeHelperForSensor(sensor).getCalHelper();
+ uint8_t sensorType = sensor.getSensorType();
+ SeeCalHelper *calHelper =
+ getSeeHelperForSensorType(sensorType).getCalHelper();
bool success = sensor.reportsBiasEvents();
if (success) {
- uint8_t sensorType = sensor.getSensorType();
-
// We use the runtime-calibrated sensor type here, per documentation
// of SeeCalHelper::getBias(), but overwrite the sensorHandle to that of
// the current sensor, because the calibration data itself is equivalent
// for both calibrated/uncalibrated sensor types.
+#ifdef CHRE_SLPI_UIMG_ENABLED
+ // Use the uimg runtime-calibrated sensor type to get the calibration
+ // bias, since SeeCalHelper is unaware of the bimg/uimg differentiation.
+ uint8_t calSensorType = PlatformSensorTypeHelpers::toCalibratedSensorType(
+ getUimgSensorType(sensorType));
+#else
uint8_t calSensorType =
PlatformSensorTypeHelpers::toCalibratedSensorType(sensorType);
+#endif
if (!calHelper->getBias(calSensorType, bias)) {
// Set to zero bias + unknown accuracy per CHRE API requirements.
memset(bias, 0, sizeof(chreSensorThreeAxisData));
@@ -818,8 +728,7 @@ bool PlatformSensorManager::getThreeAxisBias(
}
// Overwrite sensorHandle to match the request type.
- getSensorRequestManager().getSensorHandle(sensorType, 0 /* sensorIndex */,
- sensor.getTargetGroupMask(),
+ getSensorRequestManager().getSensorHandle(sensorType,
&bias->header.sensorHandle);
}
@@ -829,12 +738,7 @@ bool PlatformSensorManager::getThreeAxisBias(
bool PlatformSensorManager::flush(const Sensor &sensor,
uint32_t *flushRequestId) {
uint8_t sensorType = sensor.getSensorType();
-#ifdef CHRE_SLPI_UIMG_ENABLED
- if (isBigImageSensor(sensor)) {
- sensorType = getBigImageSensorType(sensorType);
- }
-#endif
- return getSeeHelperForSensor(sensor).flush(sensorType);
+ return getSeeHelperForSensorType(sensorType).flush(sensorType);
}
void PlatformSensorManager::releaseSamplingStatusUpdate(
@@ -853,39 +757,54 @@ void PlatformSensorManager::releaseBiasEvent(void *biasData) {
void PlatformSensorManagerBase::onSamplingStatusUpdate(
UniquePtr<SeeHelperCallbackInterface::SamplingStatusData> &&status) {
uint32_t sensorHandle;
-#ifdef CHRE_SLPI_UIMG_ENABLED
- uint16_t targetGroupMask = NanoappGroupIds::MicroImage;
- if (isBigImageSensorType(status->sensorType)) {
- status->sensorType = getUimgSensorType(status->sensorType);
- targetGroupMask = NanoappGroupIds::BigImage;
- }
-#else
- uint16_t targetGroupMask = NanoappGroupIds::BigImage;
-#endif
- getSensorRequestManager().getSensorHandle(
- status->sensorType, 0 /* sensorIndex */, targetGroupMask, &sensorHandle);
+ getSensorRequestManager().getSensorHandle(status->sensorType, &sensorHandle);
Sensor *sensor = getSensorRequestManager().getSensor(sensorHandle);
+ // TODO: Once the latency field is actually filled in by SEE, modify this
+ // logic to avoid reacting if the latency and interval of the sensor are
+ // updated separately, but contain the same info as before.
if (sensor != nullptr) {
- postSamplingUpdateForSensor(sensor, sensorHandle, std::move(status));
+ // Ignore the enabled flag from status update if this is not a passive mode
+ // supported sensor because this may cause the sampling status in CHRE to
+ // go out of sync with reality
+ if (!sensor->supportsPassiveMode()) {
+ status->status.enabled =
+ sensor->mLastReceivedSamplingStatus.status.enabled;
+ status->enabledValid = sensor->mLastReceivedSamplingStatus.enabledValid;
+ }
+ if (!isSameStatusUpdate(sensor->mLastReceivedSamplingStatus,
+ *status.get())) {
+ sensor->mLastReceivedSamplingStatus = *status.get();
+
+ auto callback = [](uint16_t /* type */, void *data) {
+ auto cbData = UniquePtr<SeeHelperCallbackInterface::SamplingStatusData>(
+ static_cast<SeeHelperCallbackInterface::SamplingStatusData *>(
+ data));
+
+ uint32_t sensorHandle;
+ getSensorRequestManager().getSensorHandle(cbData->sensorType,
+ &sensorHandle);
+
+ // Memory will be freed after core framework performs its updates.
+ struct chreSensorSamplingStatus *status =
+ memoryAlloc<struct chreSensorSamplingStatus>();
+ mergeUpdatedStatus(sensorHandle, *cbData.get(), status);
+
+ getSensorRequestManager().handleSamplingStatusUpdate(sensorHandle,
+ status);
+ };
+ // Schedule a deferred callback to handle sensor status change in the main
+ // thread.
+ EventLoopManagerSingleton::get()->deferCallback(
+ SystemCallbackType::SensorStatusUpdate, status.release(), callback);
+ }
}
}
void PlatformSensorManagerBase::onSensorDataEvent(
uint8_t sensorType, UniquePtr<uint8_t> &&eventData) {
uint32_t sensorHandle;
-#ifdef CHRE_SLPI_UIMG_ENABLED
- uint16_t targetGroupMask = NanoappGroupIds::MicroImage;
- if (isBigImageSensorType(sensorType)) {
- sensorType = getUimgSensorType(sensorType);
- targetGroupMask = NanoappGroupIds::BigImage;
- }
-#else
- uint16_t targetGroupMask = NanoappGroupIds::BigImage;
-#endif
-
- getSensorRequestManager().getSensorHandle(sensorType, 0 /* sensorIndex */,
- targetGroupMask, &sensorHandle);
+ getSensorRequestManager().getSensorHandle(sensorType, &sensorHandle);
auto *header =
reinterpret_cast<struct chreSensorDataHeader *>(eventData.get());
header->sensorHandle = sensorHandle;
@@ -907,31 +826,23 @@ void PlatformSensorManagerBase::onHostWakeSuspendEvent(bool awake) {
void PlatformSensorManagerBase::onSensorBiasEvent(
uint8_t sensorType, UniquePtr<struct chreSensorThreeAxisData> &&biasData) {
- // A single bias update is sent for both uncal / cal types that also needs to
- // be sent for any big-image calibrated sensors. Currently, this requires that
- // we post up to 4 separate events for a single invocation of this method.
+ uint32_t sensorHandle;
+ if (getSensorRequestManager().getSensorHandle(sensorType, &sensorHandle)) {
+ biasData->header.sensorHandle = sensorHandle;
+ Sensor *sensor = getSensorRequestManager().getSensor(sensorHandle);
+ if (!sensor->reportsBiasEvents()) {
+ LOGE("Received bias event for unsupported sensor type %" PRIu8,
+ sensorType);
+ } else {
+ // Posts newly allocated event for the uncalibrated type
+ postSensorBiasEvent(
+ PlatformSensorTypeHelpers::toUncalibratedSensorType(sensorType),
+ *biasData);
- uint16_t targetGroupMask;
- uint8_t uncalSensorType =
- SensorTypeHelpers::toUncalibratedSensorType(sensorType);
-#ifdef CHRE_SLPI_UIMG_ENABLED
- targetGroupMask = NanoappGroupIds::BigImage;
- if (sensorTypeSupportsBigImage(sensorType)) {
- postSensorBiasEvent(sensorType, targetGroupMask, *biasData);
- }
- if (sensorTypeSupportsBigImage(uncalSensorType)) {
- postSensorBiasEvent(uncalSensorType, targetGroupMask, *biasData);
+ getSensorRequestManager().handleBiasEvent(sensorHandle,
+ biasData.release());
+ }
}
-#endif
-
- targetGroupMask =
-#ifdef CHRE_SLPI_UIMG_ENABLED
- NanoappGroupIds::MicroImage;
-#else
- NanoappGroupIds::BigImage;
-#endif
- postSensorBiasEvent(sensorType, targetGroupMask, *biasData);
- postSensorBiasEvent(uncalSensorType, targetGroupMask, *biasData);
}
void PlatformSensorManagerBase::onFlushCompleteEvent(uint8_t sensorType) {
@@ -940,18 +851,7 @@ void PlatformSensorManagerBase::onFlushCompleteEvent(uint8_t sensorType) {
if (EventLoopManagerSingleton::isInitialized()) {
// TODO: Have SEE pass flush request IDs through the flush complete event
uint32_t sensorHandle;
-#ifdef CHRE_SLPI_UIMG_ENABLED
- uint16_t targetGroupMask = NanoappGroupIds::MicroImage;
- if (isBigImageSensorType(sensorType)) {
- targetGroupMask = NanoappGroupIds::BigImage;
- sensorType = getUimgSensorType(sensorType);
- }
-#else
- uint16_t targetGroupMask = NanoappGroupIds::BigImage;
-#endif
-
- getSensorRequestManager().getSensorHandle(sensorType, 0 /* sensorIndex */,
- targetGroupMask, &sensorHandle);
+ getSensorRequestManager().getSensorHandle(sensorType, &sensorHandle);
getSensorRequestManager().handleFlushCompleteEvent(
sensorHandle, UINT32_MAX, /* invalid flush request ID */
CHRE_ERROR_NONE);
diff --git a/platform/slpi/see/power_control_manager.cc b/platform/slpi/see/power_control_manager.cc
index 66fffd5a..d76a698e 100644
--- a/platform/slpi/see/power_control_manager.cc
+++ b/platform/slpi/see/power_control_manager.cc
@@ -21,10 +21,6 @@
#include "chre/platform/system_time.h"
#include "chre/util/lock_guard.h"
-#ifdef CHRE_USE_BUFFERED_LOGGING
-#include "chre/platform/shared/log_buffer_manager.h"
-#endif
-
namespace chre {
PowerControlManagerBase::PowerControlManagerBase() : mHostIsAwake(true) {
@@ -59,8 +55,7 @@ void PowerControlManagerBase::onHostWakeSuspendEvent(bool awake) {
#ifdef CHRE_AUDIO_SUPPORT_ENABLED
if (awake) {
- auto callback = [](uint16_t /*type*/, void * /*data*/,
- void * /*extraData*/) {
+ auto callback = [](uint16_t /* eventType */, void * /* eventData*/) {
EventLoopManagerSingleton::get()
->getAudioRequestManager()
.getPlatformAudio()
@@ -71,12 +66,6 @@ void PowerControlManagerBase::onHostWakeSuspendEvent(bool awake) {
SystemCallbackType::AudioHandleHostAwake, nullptr, callback);
}
#endif // CHRE_AUDIO_SUPPORT_ENABLED
-
-#ifdef CHRE_USE_BUFFERED_LOGGING
- if (awake) {
- LogBufferManagerSingleton::get()->flushLogs();
- }
-#endif
}
}
diff --git a/platform/slpi/see/see_cal_helper.cc b/platform/slpi/see/see_cal_helper.cc
index bf3aa1d5..16744776 100644
--- a/platform/slpi/see/see_cal_helper.cc
+++ b/platform/slpi/see/see_cal_helper.cc
@@ -110,9 +110,11 @@ const sns_std_suid *SeeCalHelper::getCalSuidFromSensorType(
return nullptr;
}
-bool SeeCalHelper::findCalibrationSensors(SeeHelper &seeHelper) {
+bool SeeCalHelper::registerForCalibrationUpdates(SeeHelper &seeHelper) {
bool success = true;
+ // Find the cal sensor's SUID, assign it to mCalInfo, and make cal sensor data
+ // request.
DynamicVector<sns_std_suid> suids;
for (size_t i = 0; i < ARRAY_SIZE(mCalInfo); i++) {
const char *calType = getDataTypeForCalSensorIndex(i);
@@ -121,6 +123,13 @@ bool SeeCalHelper::findCalibrationSensors(SeeHelper &seeHelper) {
LOGE("Failed to find sensor '%s'", calType);
} else {
mCalInfo[i].suid = suids[0];
+
+#ifndef CHRE_SLPI_DEFAULT_BUILD
+ if (!seeHelper.configureOnChangeSensor(suids[0], true /* enable */)) {
+ success = false;
+ LOGE("Failed to request '%s' data", calType);
+ }
+#endif
}
}
diff --git a/platform/slpi/see/see_helper.cc b/platform/slpi/see/see_helper.cc
index 1de9502a..a8da0de0 100644
--- a/platform/slpi/see/see_helper.cc
+++ b/platform/slpi/see/see_helper.cc
@@ -876,15 +876,6 @@ void populateEventSample(SeeInfoArg *info, const float *val) {
timestampDelta = &event->readings[index].timestampDelta;
break;
}
-
- case SensorSampleType::Vendor10: {
- auto *event =
- reinterpret_cast<chrexSensorVendor10Data *>(data->event.get());
- memcpy(event->readings[index].values, val,
- sizeof(event->readings[index].values));
- timestampDelta = &event->readings[index].timestampDelta;
- break;
- }
#endif // CHREX_SENSOR_SUPPORT
default:
@@ -1443,10 +1434,6 @@ void *allocateEvent(uint8_t sensorType, size_t numSamples) {
case SensorSampleType::Vendor9:
sampleSize = sizeof(chrexSensorVendor9SampleData);
break;
-
- case SensorSampleType::Vendor10:
- sampleSize = sizeof(chrexSensorVendor10SampleData);
- break;
#endif // CHREX_SENSOR_SUPPORT
default:
@@ -1720,21 +1707,11 @@ bool SeeHelper::init(SeeHelperCallbackInterface *cbIf, Microseconds timeout,
sns_client *client;
// Initialize cal/remote_proc_state sensors before making sensor data request.
- bool success = waitForService(&client, timeout) &&
- mSeeClients.push_back(client) && initResamplerSensor();
- if (success && !skipDefaultSensorInit) {
- if (!mCalHelper->findCalibrationSensors(*this)) {
-#ifdef CHRE_LOG_ONLY_NO_CAL_SENSOR
- LOGW("Bypassing failure to find calibrated sensor");
-#else // CHRE_LOG_ONLY_NO_CAL_SENSOR
- success = false;
-#endif // CHRE_LOG_ONLY_NO_CAL_SENSOR
- }
- if (success) {
- success = initRemoteProcSensor();
- }
- }
- return success;
+ return (waitForService(&client, timeout) && mSeeClients.push_back(client) &&
+ initResamplerSensor() &&
+ (skipDefaultSensorInit ||
+ (mCalHelper->registerForCalibrationUpdates(*this) &&
+ initRemoteProcSensor())));
}
bool SeeHelper::makeRequest(const SeeSensorRequest &request) {
diff --git a/platform/tests/log_buffer_test.cc b/platform/tests/log_buffer_test.cc
deleted file mode 100644
index 4dba3a99..00000000
--- a/platform/tests/log_buffer_test.cc
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 <gtest/gtest.h>
-#include <string>
-
-#include "chre/platform/atomic.h"
-#include "chre/platform/condition_variable.h"
-#include "chre/platform/mutex.h"
-#include "chre/platform/shared/log_buffer.h"
-
-namespace chre {
-
-// TODO(b/146164384): Test that the onLogsReady callback is called
-// asynchronously
-
-class TestLogBufferCallback : public LogBufferCallbackInterface {
- public:
- void onLogsReady() {
- // Do nothing
- }
-};
-
-static constexpr size_t kDefaultBufferSize = 1024;
-static constexpr size_t kBytesBeforeLogData = 5;
-
-// Helpers
-void copyStringWithOffset(char *destination, const char *source,
- size_t sourceOffset) {
- size_t strlength = strlen(source + sourceOffset);
- // +1 to copy nullbyte on the end
- memcpy(destination, source + sourceOffset, strlength + 1);
-}
-
-TEST(LogBuffer, HandleOneLogAndCopy) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 20;
- char outBuffer[kOutBufferSize];
- const char *testLogStr = "test";
- char testedBuffer[kOutBufferSize];
- TestLogBufferCallback callback;
-
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testLogStr);
- size_t numLogsDropped;
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
-
- EXPECT_EQ(bytesCopied, strlen(testLogStr) +
- kBytesBeforeLogData /*loglevel, timestamp*/ + 1);
- copyStringWithOffset(testedBuffer, outBuffer, strlen(testLogStr) + 1);
- EXPECT_TRUE(strcmp(testedBuffer, testLogStr) == 0);
-}
-
-TEST(LogBuffer, HandleTwoLogsAndCopy) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 30;
- char outBuffer[kOutBufferSize];
- const char *testLogStr = "test";
- const char *testLogStr2 = "test2";
- char testedBuffer[kOutBufferSize];
- TestLogBufferCallback callback;
-
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testLogStr);
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testLogStr2);
- size_t numLogsDropped;
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
-
- EXPECT_EQ(bytesCopied, strlen(testLogStr) + strlen(testLogStr2) +
- 2 * kBytesBeforeLogData /*loglevel, timestamp*/ +
- 2);
- copyStringWithOffset(testedBuffer, outBuffer, kBytesBeforeLogData);
- EXPECT_TRUE(strcmp(testedBuffer, testLogStr) == 0);
- copyStringWithOffset(testedBuffer, outBuffer,
- 2 * kBytesBeforeLogData + strlen(testLogStr) + 1);
- EXPECT_TRUE(strcmp(testedBuffer, testLogStr2) == 0);
-}
-
-TEST(LogBuffer, FailOnMoreCopyThanHandle) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 20;
- char outBuffer[kOutBufferSize];
- const char *testLogStr = "test";
- TestLogBufferCallback callback;
-
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testLogStr);
- size_t numLogsDropped;
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
-
- EXPECT_EQ(bytesCopied, 0);
-}
-
-TEST(LogBuffer, FailOnHandleLargerLogThanBufferSize) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 20;
- char outBuffer[kOutBufferSize];
- // Note the size of this log is too big to fit in the buffer that we are
- // using for the LogBuffer object
- std::string testLogStrStr(1025, 'a');
- TestLogBufferCallback callback;
-
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testLogStrStr.c_str());
- size_t numLogsDropped;
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
-
- // Should not be able to read this log out because there should be no log in
- // the first place
- EXPECT_EQ(bytesCopied, 0);
-}
-
-TEST(LogBuffer, LogOverwritten) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 200;
- char outBuffer[kOutBufferSize];
- char testedBuffer[kOutBufferSize];
- TestLogBufferCallback callback;
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
-
- // This for loop adds 1060 bytes of data through the buffer which is > than
- // 1024
- for (size_t i = 0; i < 10; i++) {
- std::string testLogStrStr(100, 'a' + i);
- const char *testLogStr = testLogStrStr.c_str();
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testLogStr);
- }
- size_t numLogsDropped;
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
- memcpy(testedBuffer, outBuffer + kBytesBeforeLogData, 101);
-
- // Should have read out the second from front test log string which is 'a' + 1
- // = 'b'
- EXPECT_TRUE(strcmp(testedBuffer, std::string(100, 'b').c_str()) == 0);
- EXPECT_EQ(bytesCopied, kBytesBeforeLogData + 100 + 1);
- // Should have dropped the first log
- EXPECT_EQ(numLogsDropped, 1);
-}
-
-TEST(LogBuffer, CopyIntoEmptyBuffer) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 0;
- char outBuffer[kOutBufferSize];
- TestLogBufferCallback callback;
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
-
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, "test");
- size_t numLogsDropped;
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
-
- EXPECT_EQ(bytesCopied, 0);
-}
-
-TEST(LogBuffer, NoCopyInfoBufferAfterHandleEmptyLog) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 200;
- char outBuffer[kOutBufferSize];
- TestLogBufferCallback callback;
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
-
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, "");
- size_t numLogsDropped;
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
-
- EXPECT_EQ(bytesCopied, 0);
-}
-
-TEST(LogBuffer, HandleLogOfNullBytes) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 200;
- char outBuffer[kOutBufferSize];
- TestLogBufferCallback callback;
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
-
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, "\0\0\0");
- size_t numLogsDropped;
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
-
- EXPECT_EQ(bytesCopied, 0);
-}
-
-TEST(LogBuffer, TruncateLongLog) {
- char buffer[kDefaultBufferSize];
- constexpr size_t kOutBufferSize = 500;
- char outBuffer[kOutBufferSize];
- TestLogBufferCallback callback;
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
- std::string testStr(256, 'a');
-
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testStr.c_str());
- size_t numLogsDropped;
- size_t bytesCopied =
- logBuffer.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
-
- // Should truncate the logs down to the kLogMaxSize value of 255 by the time
- // it is copied out.
- EXPECT_EQ(bytesCopied, 255);
-}
-
-TEST(LogBuffer, WouldCauseOverflowTest) {
- char buffer[kDefaultBufferSize];
- TestLogBufferCallback callback;
- LogBuffer logBuffer(&callback, buffer, kDefaultBufferSize);
-
- // With an empty buffer inerting one character should not overflow
- // ASSERT because if this fails the next ASSERT statement is undefined most
- // likely.
- ASSERT_FALSE(logBuffer.logWouldCauseOverflow(1));
-
- // This for loop adds 1000 bytes of data. There is 24 bytes of space left in
- // the buffer after this loop.
- for (size_t i = 0; i < 10; i++) {
- std::string testLogStrStr(94, 'a');
- const char *testLogStr = testLogStrStr.c_str();
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testLogStr);
- }
-
- std::string testLogStrStr(11, 'a');
- const char *testLogStr = testLogStrStr.c_str();
- // After this log entry there is room enough for a log of character size 1.
- logBuffer.handleLog(LogBufferLogLevel::INFO, 0, testLogStr);
-
- // There should be just enough space for this log
- ASSERT_FALSE(logBuffer.logWouldCauseOverflow(1));
-
- // Inserting any more than a one char log should cause overflow
- ASSERT_TRUE(logBuffer.logWouldCauseOverflow(2));
-}
-
-TEST(LogBuffer, TransferTest) {
- char buffer[kDefaultBufferSize];
- const size_t kOutBufferSize = 10;
- char outBuffer[kOutBufferSize];
- size_t numLogsDropped;
- TestLogBufferCallback callback;
- LogBuffer logBufferFrom(&callback, buffer, kDefaultBufferSize);
- LogBuffer logBufferTo(&callback, buffer, kDefaultBufferSize);
-
- const char *str1 = "str1";
- const char *str2 = "str2";
- const char *str3 = "str3";
-
- logBufferFrom.handleLog(LogBufferLogLevel::INFO, 0, str1);
- logBufferFrom.handleLog(LogBufferLogLevel::INFO, 0, str2);
- logBufferFrom.handleLog(LogBufferLogLevel::INFO, 0, str3);
-
- logBufferFrom.transferTo(logBufferTo);
-
- // The logs should have the text of each of the logs pushed onto the From
- // buffer in FIFO ordering.
- logBufferTo.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
- ASSERT_TRUE(strcmp(outBuffer + kBytesBeforeLogData, str1) == 0);
- logBufferTo.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
- ASSERT_TRUE(strcmp(outBuffer + kBytesBeforeLogData, str2) == 0);
- logBufferTo.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
- ASSERT_TRUE(strcmp(outBuffer + kBytesBeforeLogData, str3) == 0);
-
- size_t bytesCopied =
- logBufferTo.copyLogs(outBuffer, kOutBufferSize, &numLogsDropped);
- // There should have been no logs left in the To buffer for that last copyLogs
- ASSERT_EQ(bytesCopied, 0);
-}
-
-// TODO(srok): Add multithreaded tests
-
-} // namespace chre
diff --git a/run_pal_impl_tests.sh b/run_pal_impl_tests.sh
deleted file mode 100755
index 4b0daedb..00000000
--- a/run_pal_impl_tests.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/bin/bash
-
-# Quit if any command produces an error.
-set -e
-
-# Build and run the CHRE unit test binary.
-JOB_COUNT=$((`grep -c ^processor /proc/cpuinfo`))
-
-# Export the variant Makefile.
-export CHRE_VARIANT_MK_INCLUDES="$CHRE_VARIANT_MK_INCLUDES \
- variant/googletest/variant.mk"
-
-export RUN_PAL_IMPL_TESTS=true
-
-make clean
-make google_x86_googletest_debug -j$JOB_COUNT
-./out/google_x86_googletest_debug/libchre $1
diff --git a/std_overrides/README.md b/std_overrides/README.md
deleted file mode 100644
index 06398c0f..00000000
--- a/std_overrides/README.md
+++ /dev/null
@@ -1,18 +0,0 @@
-### CHRE Overrides
-
-CHRE provides nanoapps with a minimal list of overrides to standard library
-functions that are not supported by CHRE, but can be redirected to a supported
-function, or when failing silently should be of minimal consequences to the
-nanoapp. Two possible scenarios where the developers might need to use these
-overrides are:
-
-* Generated code
-* Third-party code/libraries
-
-The overrides makefile is included in the nanoapp build by default, but the
-developers need to enable it by setting a flag in the nanoapp Makefile:
-`CHRE_STD_OVERRIDES_ALLOWED = true`
-
-It is expected that the nanoapp developers only leverage these overrides while
-working towards zero overrides usage.
-
diff --git a/std_overrides/std_overrides.mk b/std_overrides/std_overrides.mk
deleted file mode 100644
index b36ff953..00000000
--- a/std_overrides/std_overrides.mk
+++ /dev/null
@@ -1,12 +0,0 @@
-#
-# Std library overrides Makefile
-#
-
-ifeq ($(CHRE_STD_OVERRIDES_ALLOWED),true)
-# Common Compiler Flags ########################################################
-COMMON_CFLAGS += -I$(CHRE_PREFIX)/std_overrides/include
-
-# Common Source Files ##########################################################
-COMMON_SRCS += $(CHRE_PREFIX)/std_overrides/stdlib_wrapper.cc
-endif
-
diff --git a/std_overrides/stdlib_wrapper.cc b/std_overrides/stdlib_wrapper.cc
deleted file mode 100644
index 66182985..00000000
--- a/std_overrides/stdlib_wrapper.cc
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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.
- */
-
-/**
- * @file stdlib_wrapper.cc
- *
- * This file provides nanoapps with wrapper functions for standard library
- * functions in the standard library functions that are not supported alongside
- * CHRE, which either redirect the function to an analogous CHRE function, or
- * fail silently. The targeted usage of this is expected to be only for third-
- * party or generated functions, where changes to either the upstream third-
- * party code or the code generators might not be straightforward. It is
- * expected that the nanoapp developers are aware of the 'fail silently' clause
- * in the wrappers, and handle those cases appropriately.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <chre.h>
-#include "chre/util/nanoapp/assert.h"
-
-#if defined(stderr) && !defined(_CSTD)
-// Provides a definition for stderr when the macro has been defined, but the
-// file has been externed. Some platforms might define their own macros for
-// stderr (vs the glibc style of matching the macro to the filename), in which
-// case we have to guard against those definitions as well (eg: _CSTD check
-// above).
-FILE *stderr = NULL;
-#endif
-
-void *malloc(size_t size) {
- // On platforms where size(size_t) might be 8 bytes, we need a cast to
- // maintain adherence to CHRE's heap alloc API. The size check to reject
- // requests of size > 4Gb could be used for debugging, though any requests
- // that even remotely approach this limit is bound to fail anyway.
- return size > UINT32_MAX ? nullptr
- : chreHeapAlloc(static_cast<uint32_t>(size));
-}
-
-void free(void *ptr) {
- chreHeapFree(ptr);
-}
-
-void *realloc(void * /*ptr*/, size_t /*newSize*/) {
- // realloc() is not supported, verify that there's no call to it!
- CHRE_ASSERT(false);
- return NULL;
-}
-
-void exit(int exitCode) {
- chreAbort(static_cast<uint32_t>(exitCode));
- // Add an explicit forever-loop to bypass compilation warnings on platforms
- // that might have defined exit with a noreturn tag. The loop shouldn't ever
- // execute, since abort terminates the program.
- while (42)
- ;
-}
-
-int fprintf(FILE * /*stream*/, const char * /*fmt*/, ...) {
- return 0;
-}
-
-size_t fwrite(const void * /*ptr*/, size_t /*size*/, size_t /*count*/,
- FILE * /*stream*/) {
- return 0;
-}
diff --git a/test/README.md b/test/README.md
deleted file mode 100644
index e91ea6ce..00000000
--- a/test/README.md
+++ /dev/null
@@ -1,64 +0,0 @@
-### CHRE Unit Test Framework
-
-#### Background
-
-The framework aims to provide an environment to test CHRE (and its users) code
-on-device, using [Pigweed's][PW_URL] Unit Test [Framework][PW_UT_URL]. Test
-instantiations are syntactically identical to [Googletest][GT_URL], so
-modifications to on-host unit tests to run on-device are easier.
-
-CHRE recommends running the same host-side gtests on-device using this
-framework, to catch subtle bugs. For example, the target CPU may raise an
-exception on unaligned access, when the same code would run without any
-problems on a local x86-based machine.
-
-###### Note
-
-One key difference is to run the tests via a call to `chre::runAllTests` in
-_chre/test/common/unit_test.h_, which basically wraps the gtest `RUN_ALL_TESTS`
-macro, and implements CHRE specific event handlers for Pigweed's UT Framework.
-
-#### Running Tests
-
-Under the current incarnation of the CHRE Unit Test Framework, the following
-steps need to be taken to run the on-device tests:
-* Set to true and export an environment variable called `CHRE_ON_DEVICE_TESTS_ENABLED`
-from your Makefile invocation before CHRE is built.
- * Ensure that this flag is not always set to avoid codesize bloat.
-* Append your test source file to `COMMON_SRCS` either in _test/test.mk_ or in
-your own Makefile.
-* Call `chre::runAllTests` from somewhere in your code.
-
-##### Sample code
-
-In _math_test.cc_
-```cpp
-#include <gtest/gtest.h>
-
-TEST(MyMath, Add) {
- int x = 1, y = 2;
- int result = myAdd(x, y);
- EXPECT_EQ(result, 3);
-}
-```
-
-In _some_source.cc_
-```cpp
-#include "chre/test/common/unit_test.h"
-
-void utEntryFunc() {
- chre::runAllTests();
-}
-```
-
-#### Caveats
-
-Some advanced features of gtest (SCOPED_TRACE, etc.) are unsupported by Pigweed.
-
-#### Compatibility
-
-The framework has been tested with Pigweed's git revision ee460238b8a7ec0a6b4f61fe7e67a12231db6d3e
-
-[PW_URL]: https://pigweed.dev
-[PW_UT_URL]: https://pigweed.googlesource.com/pigweed/pigweed/+/refs/heads/master/pw_unit_test
-[GT_URL]: https://github.com/google/googletest
diff --git a/test/common/include/chre/test/common/macros.h b/test/common/include/chre/test/common/macros.h
deleted file mode 100644
index 04b86c8a..00000000
--- a/test/common/include/chre/test/common/macros.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 CHRE_TEST_COMMON_MACROS_H_
-#define CHRE_TEST_COMMON_MACROS_H_
-
-#include <gtest/gtest.h>
-
-// For platforms that do not support SCOPED_TRACE.
-#ifndef SCOPED_TRACE
-#define SCOPED_TRACE(x)
-#endif
-
-#endif // CHRE_TEST_COMMON_MACROS_H_
diff --git a/test/common/include/chre/test/common/unit_test.h b/test/common/include/chre/test/common/unit_test.h
deleted file mode 100644
index 4bdd97dc..00000000
--- a/test/common/include/chre/test/common/unit_test.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_TEST_COMMON_UNIT_TEST_H_
-#define CHRE_TEST_COMMON_UNIT_TEST_H_
-
-namespace chre {
-
-void runAllTests();
-
-} // namespace chre
-
-#endif // CHRE_TEST_COMMON_UNIT_TEST_H_
diff --git a/test/common/run_tests.cc b/test/common/run_tests.cc
deleted file mode 100644
index a68b783e..00000000
--- a/test/common/run_tests.cc
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 "chre/platform/log.h"
-#include "chre/test/common/unit_test.h"
-#include "chre/util/macros.h"
-#include "gtest/gtest.h"
-
-namespace chre {
-namespace {
-
-using pw::unit_test::EventHandler;
-using pw::unit_test::RunTestsSummary;
-using pw::unit_test::TestCase;
-using pw::unit_test::TestExpectation;
-using pw::unit_test::TestResult;
-
-class PwEventHandler : public EventHandler {
- void RunAllTestsStart() override {
- LOGD("[==========] Running all tests.");
- }
-
- void RunAllTestsEnd(const RunTestsSummary &run_tests_summary) override {
- LOGD("[==========] Done running all tests.");
- LOGD("[ PASSED ] %d test(s).", run_tests_summary.passed_tests);
- if (run_tests_summary.failed_tests) {
- LOGD("[ FAILED ] %d test(s).", run_tests_summary.failed_tests);
- }
- }
-
- void TestCaseStart(const TestCase &test_case) override {
- LOGD("[ RUN ] %s.%s", test_case.suite_name, test_case.test_name);
- }
-
- void TestCaseEnd(const TestCase &test_case, TestResult result) override {
- switch (result) {
- case TestResult::kSuccess:
- LOGD("[ OK ] %s.%s", test_case.suite_name, test_case.test_name);
- break;
- case TestResult::kFailure:
- LOGD("[ FAILED ] %s.%s", test_case.suite_name, test_case.test_name);
- break;
- }
- }
-
- void TestCaseExpect(const TestCase &test_case,
- const TestExpectation &expectation) override {
- if (!expectation.success) {
- LOGD("%s:%d: Failure", test_case.file_name, expectation.line_number);
- LOGD(" Expected: %s", expectation.expression);
- LOGD(" Actual: %s", expectation.evaluated_expression);
- }
- }
-
- void TestCaseDisabled(const TestCase &test_case) override {
- LOGD("Skipping disabled test %s.%s", test_case.suite_name,
- test_case.test_name);
- }
-};
-
-} // namespace
-
-DLL_EXPORT void runAllTests() {
- PwEventHandler eventHandler;
- pw::unit_test::RegisterEventHandler(&eventHandler);
- int rc = RUN_ALL_TESTS();
- LOGD("Ran all tests with rc: %d", rc);
-}
-
-} // namespace chre
diff --git a/test/test.mk b/test/test.mk
deleted file mode 100644
index 37ea4972..00000000
--- a/test/test.mk
+++ /dev/null
@@ -1,42 +0,0 @@
-#
-# Test Makefile
-#
-
-# TODO (b/175919480) - General improvements to make adding tests easier
-# - How best to configure it at build time? For example, is it sufficient
-# to supply an env var when invoking make, or would a different build
-# target be useful (similar to how we have *_debug targets)?
-# - How can we add tests for one specific platform without impacting a
-# different platform where it doesn't apply (and may not compile)?
-# - Can we also loop in tests for common code, which are currently
-# executed off-target via ./run_tests.sh (those added via GOOGLETEST_SRCS,
-# e.g. core/tests/*, util/tests/*)
-
-ifeq ($(CHRE_ON_DEVICE_TESTS_ENABLED),true)
-include $(CHRE_PREFIX)/build/pw_unit_test.mk
-COMMON_CFLAGS += $(PW_UT_CFLAGS)
-COMMON_CFLAGS += -I$(CHRE_PREFIX)/test/common/include
-COMMON_SRCS += $(CHRE_PREFIX)/test/common/run_tests.cc
-
-COMMON_CFLAGS += -DCHRE_ON_DEVICE_TESTS_ENABLED
-
-COMMON_SRCS += $(PW_UT_SRCS)
-
-# Core unit tests
-COMMON_SRCS += $(CHRE_PREFIX)/core/tests/audio_util_test.cc
-COMMON_SRCS += $(CHRE_PREFIX)/core/tests/memory_manager_test.cc
-COMMON_SRCS += $(CHRE_PREFIX)/core/tests/request_multiplexer_test.cc
-COMMON_SRCS += $(CHRE_PREFIX)/core/tests/sensor_request_test.cc
-COMMON_SRCS += $(CHRE_PREFIX)/core/tests/wifi_scan_request_test.cc
-
-# CHPP tests
-COMMON_SRCS += $(CHRE_PREFIX)/chpp/test/wifi_convert_test.cpp
-COMMON_SRCS += $(CHRE_PREFIX)/chpp/test/wwan_convert_test.cpp
-
-# PAL unit tests
-COMMON_CFLAGS += -I$(CHRE_PREFIX)/pal/tests/include
-
-COMMON_SRCS += $(CHRE_PREFIX)/pal/tests/src/version_test.cc
-COMMON_SRCS += $(CHRE_PREFIX)/pal/tests/src/wwan_test.cc
-
-endif
diff --git a/util/container_support.cc b/util/container_support.cc
index e9d3d1cf..20760b3a 100644
--- a/util/container_support.cc
+++ b/util/container_support.cc
@@ -17,12 +17,9 @@
#include <chre.h>
#include <cinttypes>
-#include <cstdarg>
#include <cstdio>
#include <cstdlib>
-#include "chre/util/macros.h"
-
/**
* @file
*
@@ -44,12 +41,3 @@ void chreAbort(uint32_t abortCode) {
fprintf(stderr, "Aborting with code %" PRIu32 "\n", abortCode);
abort();
}
-
-WEAK_SYMBOL
-void chreLog(enum chreLogLevel level, const char *formatStr, ...) {
- UNUSED_VAR(level);
- va_list argList;
- va_start(argList, formatStr);
- vprintf(formatStr, argList);
- va_end(argList);
-} \ No newline at end of file
diff --git a/util/include/chre/util/always_false.h b/util/include/chre/util/always_false.h
deleted file mode 100644
index 56db44d5..00000000
--- a/util/include/chre/util/always_false.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_UTIL_ALWAYS_FALSE_H_
-#define CHRE_UTIL_ALWAYS_FALSE_H_
-
-#include <type_traits>
-
-namespace chre {
-
-/**
- * Simple helper which can be used when a type-dependent expression is needed
- * that evaluates to false. Useful with static_assert in templates, for example:
- *
- * <code>
- * template<typename T>
- * class MyClass {
- * static_assert(AlwaysFalse<T>::value,
- * "Use one of the supported template specializations");
- * };
- *
- * template<>
- * class MyClass<int> {
- * // (valid implementation)
- * };
- * </code>
- */
-template <typename... T>
-struct AlwaysFalse : std::false_type {};
-
-} // namespace chre
-
-#endif // CHRE_UTIL_ALWAYS_FALSE_H_
diff --git a/util/include/chre/util/flatbuffers/helpers.h b/util/include/chre/util/flatbuffers/helpers.h
deleted file mode 100644
index 5ecb3385..00000000
--- a/util/include/chre/util/flatbuffers/helpers.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright 2020 Google Inc. All rights reserved.
- *
- * 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 CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_
-#define CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_
-
-#include "chre/util/container_support.h"
-#include "chre/util/dynamic_vector.h"
-
-#include "flatbuffers/flatbuffers.h"
-
-namespace chre {
-
-//! CHRE-specific flatbuffers allocator that routes to CHRE's alloc / free
-//! functions.
-class FlatBufferAllocator : public flatbuffers::Allocator {
- public:
- uint8_t *allocate(size_t size) override {
- return static_cast<uint8_t *>(memoryAlloc(size));
- }
-
- void deallocate(uint8_t *p, size_t) override {
- memoryFree(p);
- }
-};
-
-//! CHRE-specific FlatBufferBuilder that utilizes CHRE's allocator and adds
-//! additional helper methods that make use of CHRE utilities.
-class ChreFlatBufferBuilder : public flatbuffers::FlatBufferBuilder {
- public:
- explicit ChreFlatBufferBuilder(size_t initialSize = 1024)
- : flatbuffers::FlatBufferBuilder(initialSize, &mAllocator) {}
-
- // This is defined in flatbuffers::FlatBufferBuilder, but must be further
- // defined here since template functions aren't inherited.
- template <typename T>
- flatbuffers::Offset<flatbuffers::Vector<T>> CreateVector(const T *v,
- size_t len) {
- return flatbuffers::FlatBufferBuilder::CreateVector(v, len);
- }
-
- /**
- * Serialize a DyanmicVector into a FlatBuffer `vector`.
- *
- * @tparam T The data type of the DynamicVector elements.
- * @param v A const reference to the DynamicVector to serialize into the
- * buffer as a `vector`.
- * @return Returns a typed `Offset` into the serialized data indicating
- * where the vector is stored.
- */
- template <typename T>
- flatbuffers::Offset<flatbuffers::Vector<T>> CreateVector(
- const DynamicVector<T> &v) {
- return flatbuffers::FlatBufferBuilder::CreateVector(v.data(), v.size());
- }
-
- private:
- FlatBufferAllocator mAllocator;
-};
-
-} // namespace chre
-
-#endif // CHRE_PLATFORM_SHARED_FLATBUFFERS_HELPERS_H_
diff --git a/util/include/chre/util/log_common.h b/util/include/chre/util/log_common.h
index c98a04a8..97b2e807 100644
--- a/util/include/chre/util/log_common.h
+++ b/util/include/chre/util/log_common.h
@@ -45,21 +45,19 @@ inline void chreLogNull(const char *fmt, ...) {
CHRE_LOG_EPILOGUE \
} while (0)
-// Each log level below increases with value as verbosity increases, such that
-// we can set a threshold for verbosity at compile time
-
-//! Used with CHRE_MINIMUM_LOG_LEVEL to indicate that no logs should be included
+//! The logging level to specify that no logs are output.
#define CHRE_LOG_LEVEL_MUTE 0
+//! The logging level to specify that only LOGE is output.
#define CHRE_LOG_LEVEL_ERROR 1
+
+//! The logging level to specify that LOGW and LOGE are output.
#define CHRE_LOG_LEVEL_WARN 2
+
+//! The logging level to specify that LOGI, LOGW and LOGE are output.
#define CHRE_LOG_LEVEL_INFO 3
-#define CHRE_LOG_LEVEL_DEBUG 4
-#define CHRE_LOG_LEVEL_VERBOSE 5
-/**
- * Logs an out of memory error with file and line number.
- */
-#define LOG_OOM() LOGE("OOM at %s:%d", CHRE_FILENAME, __LINE__)
+//! The logging level to specify that LOGD, LOGI, LOGW and LOGE are output.
+#define CHRE_LOG_LEVEL_DEBUG 4
#endif // CHRE_UTIL_LOG_COMMON_H_
diff --git a/util/include/chre/util/macros.h b/util/include/chre/util/macros.h
index 475cd456..92160b80 100644
--- a/util/include/chre/util/macros.h
+++ b/util/include/chre/util/macros.h
@@ -24,44 +24,14 @@
/**
* Obtains the number of elements in a C-style array.
*/
-#ifndef ARRAY_SIZE
#define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
-#endif
-
-#ifndef ARRAY_END
#define ARRAY_END(array) (array + ARRAY_SIZE(array))
-#endif
-
-/** Determines if the provided bit is set in the provided value. */
-#ifndef IS_BIT_SET
-#define IS_BIT_SET(value, bit) (((value) & (bit)) == (bit))
-#endif
/**
* Performs macro expansion then converts the value into a string literal
*/
-#ifndef STRINGIFY
#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x
-#endif
-
-/**
- * Checks if a bitmask contains the specified value
- */
-#ifndef BITMASK_HAS_VALUE
-#define BITMASK_HAS_VALUE(mask, value) ((mask & value) == value)
-#endif
-
-/**
- * Min/max macros.
- */
-#ifndef MIN
-#define MIN(a, b) ((a) < (b) ? (a) : (b))
-#endif
-
-#ifndef MAX
-#define MAX(a, b) ((a) > (b) ? (a) : (b))
-#endif
// Compiler-specific functionality
#if defined(__clang__) || defined(__GNUC__)
diff --git a/util/include/chre/util/nanoapp/app_id.h b/util/include/chre/util/nanoapp/app_id.h
index 838d74a9..5622a93c 100644
--- a/util/include/chre/util/nanoapp/app_id.h
+++ b/util/include/chre/util/nanoapp/app_id.h
@@ -76,7 +76,7 @@ constexpr uint64_t kWwanWorldAppId = makeExampleNanoappId(7);
// 8 = reserved (previously used by ImuCal)
constexpr uint64_t kSpammerAppId = makeExampleNanoappId(9);
constexpr uint64_t kUnloadTesterAppId = makeExampleNanoappId(10);
-// 11 = reserved (previously used by AshWorld)
+constexpr uint64_t kAshWorldAppId = makeExampleNanoappId(11);
constexpr uint64_t kAudioWorldAppId = makeExampleNanoappId(12);
constexpr uint64_t kHostAwakeWorldAppId = makeExampleNanoappId(13);
constexpr uint64_t kAudioStressTestAppId = makeExampleNanoappId(14);
diff --git a/util/include/chre/util/nanoapp/log.h b/util/include/chre/util/nanoapp/log.h
index 60c44f47..d5907040 100644
--- a/util/include/chre/util/nanoapp/log.h
+++ b/util/include/chre/util/nanoapp/log.h
@@ -25,7 +25,6 @@
*
* The typical format for the LOG_TAG macro is: "[AppName]"
*/
-#ifdef CHRE_IS_NANOAPP_BUILD
#include <chre/re.h>
@@ -35,6 +34,10 @@
#error "NANOAPP_MINIMUM_LOG_LEVEL must be defined"
#endif // NANOAPP_MINIMUM_LOG_LEVEL
+/**
+ * Logs an out of memory error with file and line number.
+ */
+#define LOG_OOM() LOGE("OOM at %s:%d", CHRE_FILENAME, __LINE__)
/*
* Supply a stub implementation of the LOGx macros when the build is
@@ -81,28 +84,6 @@
#endif
#define LOGD(fmt, ...) LOGD_TAG(LOG_TAG, fmt, ##__VA_ARGS__)
-// Map LOGV to LOGD as CHRE doesn't support it yet.
-#if NANOAPP_MINIMUM_LOG_LEVEL >= CHRE_LOG_LEVEL_VERBOSE
-#define LOGV_TAG(tag, fmt, ...) \
- CHRE_LOG_TAG(CHRE_LOG_DEBUG, tag, fmt, ##__VA_ARGS__)
-#else
-#define LOGV_TAG(tag, fmt, ...) CHRE_LOG_NULL(fmt, ##__VA_ARGS__)
-#endif
-#define LOGV(fmt, ...) LOGV_TAG(LOG_TAG, fmt, ##__VA_ARGS__)
-
-#else
-
-// For static nanoapps, reroute to the internal framework logging macro so that
-// things are consistent across all the source code statically linked into the
-// binary that contains the framework.
-// This loses out on LOG_TAG prepending, and follows CHRE_MINIMUM_LOG_LEVEL
-// rather than NANOAPP_MINIMUM_LOG_LEVEL, but means that anything using the
-// container support library will have a consistent definition regardless of
-// whether it's used in framework code or static nanoapp code.
-#include "chre/platform/log.h"
-
-#endif // CHRE_IS_NANOAPP_BUILD
-
// Use this macro when including privacy-sensitive information like the user's
// location.
#ifdef LOG_INCLUDE_SENSITIVE_INFO
@@ -114,8 +95,6 @@
#define LOGI_TAG_SENSITIVE_INFO LOGI_TAG
#define LOGD_SENSITIVE_INFO LOGD
#define LOGD_TAG_SENSITIVE_INFO LOGD_TAG
-#define LOGV_SENSITIVE_INFO LOGV
-#define LOGV_TAG_SENSITIVE_INFO LOGV_TAG
#else
#define LOGE_SENSITIVE_INFO(fmt, ...) CHRE_LOG_NULL(fmt, ##__VA_ARGS__)
#define LOGE_TAG_SENSITIVE_INFO(tag, fmt, ...) CHRE_LOG_NULL(fmt, ##__VA_ARGS__)
@@ -125,8 +104,6 @@
#define LOGI_TAG_SENSITIVE_INFO(tag, fmt, ...) CHRE_LOG_NULL(fmt, ##__VA_ARGS__)
#define LOGD_SENSITIVE_INFO(fmt, ...) CHRE_LOG_NULL(fmt, ##__VA_ARGS__)
#define LOGD_TAG_SENSITIVE_INFO(tag, fmt, ...) CHRE_LOG_NULL(fmt, ##__VA_ARGS__)
-#define LOGV_SENSITIVE_INFO(fmt, ...) CHRE_LOG_NULL(fmt, ##__VA_ARGS__)
-#define LOGV_TAG_SENSITIVE_INFO(tag, fmt, ...) CHRE_LOG_NULL(fmt, ##__VA_ARGS__)
#endif
#endif // CHRE_UTIL_NANOAPP_LOG_H_
diff --git a/util/include/chre/util/nanoapp/wifi.h b/util/include/chre/util/nanoapp/wifi.h
index 6d1b34d8..b1ae6920 100644
--- a/util/include/chre/util/nanoapp/wifi.h
+++ b/util/include/chre/util/nanoapp/wifi.h
@@ -31,16 +31,6 @@ constexpr size_t kMaxSsidStrLen = CHRE_WIFI_SSID_MAX_LEN + 1;
constexpr size_t kBssidStrLen = 18;
/**
- * Logs the contents of a chreWifiScanResult using the LOGX macro.
- *
- * @param result The WiFi scan result to log.
- * @param logSsidOnly If true, only log the SSID of the WiFi scan result,
- * otherwise logs other fields as well.
- */
-void logChreWifiResult(const chreWifiScanResult &result,
- bool logSsidOnly = false);
-
-/**
* @param buffer a pointer to a buffer to format into.
* @param bufferLen a buffer to format into.
* @param a pointer to SSID data.
diff --git a/util/include/chre/util/nested_data_ptr.h b/util/include/chre/util/nested_data_ptr.h
index 0b5a03f6..86a92717 100644
--- a/util/include/chre/util/nested_data_ptr.h
+++ b/util/include/chre/util/nested_data_ptr.h
@@ -17,62 +17,34 @@
#ifndef UTIL_CHRE_NESTED_DATA_PTR_H_
#define UTIL_CHRE_NESTED_DATA_PTR_H_
-#include <string.h>
-#include <type_traits>
-
namespace chre {
/**
- * Template which provides type punning capability between the template type and
- * void*. Note that this void* representation must not be dereferenced - it is
- * only safe as a temporary representation of the underlying type, for example
- * passed through to a callback which accepts an opaque void* parameter.
+ * A template that provides the ability to store data inside of a void pointer
+ * to avoid allocating space on the heap in the case where the data is smaller
+ * than the size of a void pointer.
*/
template <typename DataType>
union NestedDataPtr {
- static_assert(sizeof(DataType) <= sizeof(void *),
- "Requested data type must fit in a void* to use NestedDataPtr");
- // If the sizeof() check passes, then this is unlikely to be an issue, and in
- // many usage scenarios this wouldn't be an issue (e.g. reinterpreting a value
- // stored in a register), but it's included here just to be safe.
- static_assert(alignof(DataType) <= alignof(void *),
- "Additional alignment in NestedDataPtr can't be guaranteed");
- static_assert(std::is_trivially_copyable<DataType>::value,
- "Only trivially copyable types may be used in NestedDataPtr");
-
- NestedDataPtr() = default;
-
- explicit NestedDataPtr(DataType nestedData) : data(nestedData) {}
- explicit NestedDataPtr(void *ptr) {
- // We use memcpy here and in the void* conversion operator, as the C++11
- // language standard defines that accessing any field of a union other than
- // most recently set value is undefined behavior, unless it's a structure
- // with a common prefix to the active field. Most compilers (e.g. GCC,
- // clang) allow for this anyways as it's permitted in C, but to avoid the UB
- // we do the conversion via memcpy. Note that compilers will recognize this
- // as a simple store operation and produce equivalent assembly as if we were
- // assigning to mUnusedPtr.
- memcpy(&data, &ptr, sizeof(ptr));
+ NestedDataPtr(DataType nestedData) : data(nestedData) {
+ assertSize();
}
- // Implicit conversions
- operator DataType() const {
- return data;
+ explicit NestedDataPtr() {
+ assertSize();
}
-
- operator void *() const {
- void *result;
- static_assert(sizeof(data) <= sizeof(result), "Broken assumption");
- memcpy(&result, &data, sizeof(data));
- return result;
- }
-
+ void *dataPtr;
DataType data;
private:
- // Here to force that this union has at least the alignment + size of a
- // pointer, but we don't access it directly
- void *mUnusedPtr;
+ /**
+ * Ensures both constructors make the same assertion about the size of the
+ * struct.
+ */
+ void assertSize() {
+ static_assert(sizeof(NestedDataPtr<DataType>) == sizeof(void *),
+ "Size of NestedDataPtr must be equal to that of void *");
+ }
};
} // namespace chre
diff --git a/util/include/chre/util/system/debug_dump.h b/util/include/chre/util/system/debug_dump.h
index 3df454ed..b0320622 100644
--- a/util/include/chre/util/system/debug_dump.h
+++ b/util/include/chre/util/system/debug_dump.h
@@ -52,7 +52,7 @@ class DebugDumpWrapper {
/**
* A version of print that takes arguments as a variable list.
*/
- void printVaList(const char *formatStr, va_list argList);
+ void print(const char *formatStr, va_list argList);
/**
* @return The buffers collected that total up to the full debug dump.
diff --git a/util/include/chre/util/system/napp_header_utils.h b/util/include/chre/util/system/napp_header_utils.h
deleted file mode 100644
index e9ab416c..00000000
--- a/util/include/chre/util/system/napp_header_utils.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_UTIL_SYSTEM_NAPP_HEADER_UTILS_H_
-#define CHRE_UTIL_SYSTEM_NAPP_HEADER_UTILS_H_
-
-//! Defines various constants used in the nanoapp headers defined inside
-//! build/build_template.mk.
-#define CHRE_NAPP_HEADER_SIGNED 0x00000001
-#define CHRE_NAPP_HEADER_ENCRYPTED 0x00000002
-#define CHRE_NAPP_HEADER_TCM_CAPABLE 0x00000004
-
-#endif // CHRE_UTIL_SYSTEM_NAPP_HEADER_UTILS_H_
diff --git a/util/include/chre/util/system/napp_permissions.h b/util/include/chre/util/system/napp_permissions.h
deleted file mode 100644
index 49fc8975..00000000
--- a/util/include/chre/util/system/napp_permissions.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2021 The Android Open Source Project
- *
- * 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 CHRE_UTIL_SYSTEM_NAPP_PERMISSONS
-#define CHRE_UTIL_SYSTEM_NAPP_PERMISSONS
-
-#include <stdint.h>
-
-namespace chre {
-
-/**
- * Enum declaring the various CHRE permissions that can be declared. Nanoapps
- * built against CHRE API v1.5+ must contain the respective permission for the
- * set of APIs they attempt to call. For example, CHRE_NANOAPP_USES_WIFI must
- * be declared by the nanoapp in order for it to make use of any WiFi APIs.
- *
- * The 8 most-significant bits (MSBs) are reserved for vendor use and must be
- * used if a vendor API allows access to privacy sensitive information that is
- * guarded by a permission on the Android side (e.g. location).
- */
-enum NanoappPermissions : uint32_t {
- CHRE_PERMS_NONE = 0,
- CHRE_PERMS_AUDIO = 1,
- CHRE_PERMS_GNSS = 1 << 1,
- CHRE_PERMS_WIFI = 1 << 2,
- CHRE_PERMS_WWAN = 1 << 3,
- CHRE_PERMS_ALL = 0xffffffff,
-};
-
-} // namespace chre
-
-#endif // CHRE_UTIL_SYSTEM_NAPP_PERMISSONS
diff --git a/util/include/chre/util/system/wifi_util.h b/util/include/chre/util/system/wifi_util.h
deleted file mode 100644
index d1c63188..00000000
--- a/util/include/chre/util/system/wifi_util.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * 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 CHRE_UTIL_SYSTEM_WIFI_UTIL_H_
-#define CHRE_UTIL_SYSTEM_WIFI_UTIL_H_
-
-#include <chre.h>
-
-namespace chre {
-
-// Return a v1.4-compliant chreWifiScanParams from a v1.5+ one.
-struct chreWifiScanParams translateToLegacyWifiScanParams(
- const struct chreWifiScanParams *params) {
- // Copy v1.4-compliant fields over.
- struct chreWifiScanParams legacyParams = {};
- legacyParams.scanType = params->scanType;
- legacyParams.maxScanAgeMs = params->maxScanAgeMs;
- legacyParams.frequencyListLen = params->frequencyListLen;
- legacyParams.frequencyList = params->frequencyList;
- legacyParams.ssidListLen = params->ssidListLen;
- legacyParams.ssidList = params->ssidList;
- legacyParams.radioChainPref = params->radioChainPref;
-
- // channelSet is ignored by v1.4- platforms.
-
- if (params->scanType == CHRE_WIFI_SCAN_TYPE_NO_PREFERENCE) {
- if (params->channelSet == CHRE_WIFI_CHANNEL_SET_NON_DFS) {
- legacyParams.scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE;
- } else {
- legacyParams.scanType = CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS;
- }
- }
-
- return legacyParams;
-}
-
-} // namespace chre
-
-#endif // CHRE_UTIL_SYSTEM_WIFI_UTIL_H_
diff --git a/util/include/chre/util/toolchain.h b/util/include/chre/util/toolchain.h
index 14cf2f00..9b49e0df 100644
--- a/util/include/chre/util/toolchain.h
+++ b/util/include/chre/util/toolchain.h
@@ -41,43 +41,10 @@
#define CHRE_DEPRECATED_EPILOGUE _Pragma("GCC diagnostic pop")
-// Instructs the compiler to warn about unused results.
-// When annotating a function, this macro must appear before the function name
-// in the declaration.
-// Example Usage:
-// bool CHRE_MUST_USE_RESULT pleaseUseMyResult();
-//
-// A cast-to-void to suppress this warning only works on clang and not on gcc
-// because of this bug:
-// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425
-//
-// A possible workaround (other than just filtering out this macro) may be
-// just negating the return value before a void-cast as follows::
-// void void_cast_should_not_warn() {
-// (void) !foo();
-// // ^-- here
-// }
-#if defined __has_attribute
-#if __has_attribute(warn_unused_result)
-#define CHRE_MUST_USE_RESULT __attribute__((warn_unused_result))
-#endif
-#endif
-#ifndef CHRE_MUST_USE_RESULT
-#define CHRE_MUST_USE_RESULT
-#endif
-
-#elif defined(IS_CHPP_BUILD)
-// These macros need to be defined for CHPP on other compilers
-
-#define CHRE_LOG_PREAMBLE
-#define CHRE_LOG_EPILOGUE
-#define CHRE_DEPRECATED_PREAMBLE
-#define CHRE_DEPRECATED_EPILOGUE
-#define CHRE_MUST_USE_RESULT
-
-#else
+#else // if !defined(__GNUC__) && !defined(__clang__)
#error Need to add support for new compiler
#endif
+
#endif // CHRE_UTIL_TOOLCHAIN_H_
diff --git a/util/nanoapp/wifi.cc b/util/nanoapp/wifi.cc
index 4ec6da3b..a31bae72 100644
--- a/util/nanoapp/wifi.cc
+++ b/util/nanoapp/wifi.cc
@@ -16,12 +16,6 @@
#include "chre/util/nanoapp/wifi.h"
-#ifdef CHRE_IS_NANOAPP_BUILD
-#include "util/nanoapp/log.h"
-#else
-#include "chre/platform/log.h"
-#endif // CHRE_IS_NANOAPP_BUILD
-
#include <cctype>
#include <cinttypes>
#include <cstdio>
@@ -29,39 +23,6 @@
namespace chre {
-void logChreWifiResult(const chreWifiScanResult &result, bool logSsidOnly) {
- const char *ssidStr = "<non-printable>";
- char ssidBuffer[kMaxSsidStrLen];
- if (result.ssidLen == 0) {
- ssidStr = "<empty>";
- } else if (parseSsidToStr(ssidBuffer, sizeof(ssidBuffer), result.ssid,
- result.ssidLen)) {
- ssidStr = ssidBuffer;
- }
-
- LOGI("Found network with SSID: %s", ssidStr);
- if (!logSsidOnly) {
- const char *bssidStr = "<non-printable>";
- char bssidBuffer[kBssidStrLen];
- if (parseBssidToStr(result.bssid, bssidBuffer, sizeof(bssidBuffer))) {
- bssidStr = bssidBuffer;
- }
-
- LOGI(" age (ms): %" PRIu32, result.ageMs);
- LOGI(" capability info: %" PRIx16, result.capabilityInfo);
- LOGI(" bssid: %s", bssidStr);
- LOGI(" flags: %" PRIx8, result.flags);
- LOGI(" rssi: %" PRId8 "dBm", result.rssi);
- LOGI(" band: %s (%" PRIu8 ")", parseChreWifiBand(result.band),
- result.band);
- LOGI(" primary channel: %" PRIu32, result.primaryChannel);
- LOGI(" center frequency primary: %" PRIu32, result.centerFreqPrimary);
- LOGI(" center frequency secondary: %" PRIu32, result.centerFreqSecondary);
- LOGI(" channel width: %" PRIu8, result.channelWidth);
- LOGI(" security mode: %" PRIx8, result.securityMode);
- }
-}
-
bool parseSsidToStr(char *buffer, size_t bufferLen, const uint8_t *ssid,
uint8_t ssidLen) {
// Ensure that there is enough space in the buffer to copy the SSID and
diff --git a/util/system/debug_dump.cc b/util/system/debug_dump.cc
index 8583ce5d..85cbc7a0 100644
--- a/util/system/debug_dump.cc
+++ b/util/system/debug_dump.cc
@@ -25,11 +25,11 @@ namespace chre {
void DebugDumpWrapper::print(const char *formatStr, ...) {
va_list argList;
va_start(argList, formatStr);
- printVaList(formatStr, argList);
+ print(formatStr, argList);
va_end(argList);
}
-void DebugDumpWrapper::printVaList(const char *formatStr, va_list argList) {
+void DebugDumpWrapper::print(const char *formatStr, va_list argList) {
va_list argListCopy;
va_copy(argListCopy, argList);
diff --git a/util/tests/array_queue_test.cc b/util/tests/array_queue_test.cc
index 851b1575..bd9b229c 100644
--- a/util/tests/array_queue_test.cc
+++ b/util/tests/array_queue_test.cc
@@ -13,16 +13,16 @@ int destructor_count[kMaxTestCapacity];
int constructor_count;
int total_destructor_count;
-class FakeElement {
+class DummyElement {
public:
- FakeElement() {
+ DummyElement() {
constructor_count++;
};
- FakeElement(int i) {
+ DummyElement(int i) {
val_ = i;
constructor_count++;
};
- ~FakeElement() {
+ ~DummyElement() {
total_destructor_count++;
if (val_ >= 0 && val_ < kMaxTestCapacity) {
destructor_count[val_]++;
@@ -221,8 +221,8 @@ TEST(ArrayQueueTest, DestructorCalledOnPop) {
destructor_count[i] = 0;
}
- ArrayQueue<FakeElement, 3> q;
- FakeElement e;
+ ArrayQueue<DummyElement, 3> q;
+ DummyElement e;
q.push(e);
q.push(e);
@@ -243,8 +243,8 @@ TEST(ArrayQueueTest, ElementsDestructedWhenQueueDestructed) {
// Put q and e in the scope so their destructor will be called going
// out of scope.
{
- ArrayQueue<FakeElement, 4> q;
- FakeElement e;
+ ArrayQueue<DummyElement, 4> q;
+ DummyElement e;
for (size_t i = 0; i < 3; ++i) {
q.push(e);
@@ -268,7 +268,7 @@ TEST(ArrayQueueTest, ElementsDestructedWhenQueueDestructed) {
TEST(ArrayQueueTest, EmplaceTest) {
constructor_count = 0;
- ArrayQueue<FakeElement, 2> q;
+ ArrayQueue<DummyElement, 2> q;
EXPECT_TRUE(q.emplace(0));
EXPECT_EQ(1, constructor_count);
@@ -518,7 +518,7 @@ TEST(ArrayQueueTest, ElementsDestructedArrayClear) {
}
total_destructor_count = 0;
- ArrayQueue<FakeElement, 4> q;
+ ArrayQueue<DummyElement, 4> q;
for (size_t i = 0; i < 3; ++i) {
q.emplace(i);
}
diff --git a/util/tests/debug_dump_test.cc b/util/tests/debug_dump_test.cc
index 6567331b..374bd59d 100644
--- a/util/tests/debug_dump_test.cc
+++ b/util/tests/debug_dump_test.cc
@@ -95,9 +95,12 @@ TEST(DebugDumpWrapper, StringForcesNewBufferWithPartlyFilledBuffer) {
TEST(DebugDumpWrapper, ManyNewBuffersAllocated) {
DebugDumpWrapper debugDump(kStandardBufferSize);
- const char *str = "aaaaaaaaa";
- // Should be 12000 chars added to debugDump
+ constexpr size_t kSizeStrings = 10;
constexpr size_t kNumPrints = 1200;
+ // Should be about 12000 chars added to debugDump
+ char str[kSizeStrings];
+ memset(str, 'a', sizeof(char) * kSizeStrings);
+ str[kSizeStrings - 1] = '\0';
for (size_t i = 0; i < kNumPrints; i++) {
debugDump.print("%s", str);
}
@@ -136,7 +139,7 @@ TEST(DebugDumpWrapper, BuffersClear) {
void printVaList(DebugDumpWrapper *debugDump, const char *formatStr, ...) {
va_list args;
va_start(args, formatStr);
- debugDump->printVaList(formatStr, args);
+ debugDump->print(formatStr, args);
va_end(args);
}
diff --git a/util/tests/dynamic_vector_test.cc b/util/tests/dynamic_vector_test.cc
index 297ff6e2..7e75bfa5 100644
--- a/util/tests/dynamic_vector_test.cc
+++ b/util/tests/dynamic_vector_test.cc
@@ -16,11 +16,6 @@
#include "gtest/gtest.h"
-#ifdef GTEST
-#include "chre/platform/linux/expect_assert.h"
-#endif
-
-#include "chre/platform/assert.h"
#include "chre/util/dynamic_vector.h"
#include "chre/util/macros.h"
@@ -32,9 +27,9 @@ namespace {
constexpr int kMaxTestCapacity = 10;
int gDestructorCount[kMaxTestCapacity];
-class DestructorCounter {
+class Dummy {
public:
- ~DestructorCounter() {
+ ~Dummy() {
if (mValue >= 0) {
gDestructorCount[mValue]++;
}
@@ -128,7 +123,7 @@ class MovableButNonCopyable : public chre::NonCopyable {
}
MovableButNonCopyable &operator=(MovableButNonCopyable &&other) {
- CHRE_ASSERT(mMagic == kConstructedMagic);
+ assert(mMagic == kConstructedMagic);
mValue = other.mValue;
other.mValue = -1;
return *this;
@@ -172,7 +167,7 @@ class CopyableButNonMovable {
}
CopyableButNonMovable &operator=(const CopyableButNonMovable &other) {
- CHRE_ASSERT(mMagic == kConstructedMagic);
+ assert(mMagic == kConstructedMagic);
mValue = other.mValue;
return *this;
}
@@ -222,7 +217,7 @@ class MovableAndCopyable {
}
MovableAndCopyable &operator=(const MovableAndCopyable &other) {
- CHRE_ASSERT(mMagic == kConstructedMagic);
+ assert(mMagic == kConstructedMagic);
mValue = other.mValue;
return *this;
}
@@ -429,7 +424,7 @@ TEST(DynamicVector, FindWithElements) {
TEST(DynamicVector, EraseDestructorCalled) {
resetDestructorCounts();
- DynamicVector<DestructorCounter> vector;
+ DynamicVector<Dummy> vector;
vector.reserve(4);
for (size_t i = 0; i < 4; ++i) {
vector.emplace_back();
@@ -461,7 +456,7 @@ TEST(DynamicVector, EraseDestructorCalled) {
TEST(DynamicVector, Clear) {
resetDestructorCounts();
- DynamicVector<DestructorCounter> vector;
+ DynamicVector<Dummy> vector;
vector.reserve(4);
for (size_t i = 0; i < 4; ++i) {
vector.emplace_back();
@@ -775,4 +770,4 @@ TEST(DynamicVector, Resize) {
// Reset index for future tests
FancyInt::index = 0;
-}
+} \ No newline at end of file
diff --git a/util/tests/priority_queue_test.cc b/util/tests/priority_queue_test.cc
index 88986fec..59fa0058 100644
--- a/util/tests/priority_queue_test.cc
+++ b/util/tests/priority_queue_test.cc
@@ -4,14 +4,14 @@
using chre::PriorityQueue;
namespace {
-class FakeElement {
+class DummyElement {
public:
- FakeElement(){};
- FakeElement(int index, int value) {
+ DummyElement(){};
+ DummyElement(int index, int value) {
mValue = value;
mIndex = index;
};
- ~FakeElement(){};
+ ~DummyElement(){};
void setValue(int value) {
mValue = value;
}
@@ -27,13 +27,13 @@ class FakeElement {
int mValue = -1;
};
-bool compareFunction(const FakeElement &left, const FakeElement &right) {
+bool compareFunction(const DummyElement &left, const DummyElement &right) {
return left.getValue() > right.getValue();
};
class CompareClass {
public:
- bool operator()(const FakeElement &left, const FakeElement &right) const {
+ bool operator()(const DummyElement &left, const DummyElement &right) const {
return left.getValue() > right.getValue();
}
};
@@ -167,10 +167,10 @@ TEST(PriorityQueueTest, CompareGreater) {
}
TEST(PriorityQueueTest, EmplaceCompareLambda) {
- auto cmp = [](const FakeElement &left, const FakeElement &right) {
+ auto cmp = [](const DummyElement &left, const DummyElement &right) {
return left.getValue() > right.getValue();
};
- PriorityQueue<FakeElement, decltype(cmp)> q(cmp);
+ PriorityQueue<DummyElement, decltype(cmp)> q(cmp);
EXPECT_TRUE(q.emplace(0, 0));
EXPECT_TRUE(q.emplace(1, 2));
@@ -190,8 +190,8 @@ TEST(PriorityQueueTest, EmplaceCompareLambda) {
}
TEST(PriorityQueueTest, EmplaceCompareFunction) {
- PriorityQueue<FakeElement,
- std::function<bool(const FakeElement &, const FakeElement &)>>
+ PriorityQueue<DummyElement,
+ std::function<bool(const DummyElement &, const DummyElement &)>>
q(compareFunction);
EXPECT_TRUE(q.emplace(0, 0));
@@ -212,7 +212,7 @@ TEST(PriorityQueueTest, EmplaceCompareFunction) {
}
TEST(PriorityQueueTest, EmplaceCompareClass) {
- PriorityQueue<FakeElement, CompareClass> q;
+ PriorityQueue<DummyElement, CompareClass> q;
EXPECT_TRUE(q.emplace(0, 0));
EXPECT_TRUE(q.emplace(1, 2));
diff --git a/variant/googletest/variant.mk b/variant/googletest/variant.mk
index 0dc4b454..ac282fe0 100644
--- a/variant/googletest/variant.mk
+++ b/variant/googletest/variant.mk
@@ -6,6 +6,5 @@
CHRE_AUDIO_SUPPORT_ENABLED = true
CHRE_GNSS_SUPPORT_ENABLED = true
-CHRE_SENSORS_SUPPORT_ENABLED = true
CHRE_WIFI_SUPPORT_ENABLED = true
CHRE_WWAN_SUPPORT_ENABLED = true
diff --git a/variant/simulator/variant.mk b/variant/simulator/variant.mk
index 30914233..d979a5ba 100644
--- a/variant/simulator/variant.mk
+++ b/variant/simulator/variant.mk
@@ -23,7 +23,6 @@ GOOGLE_X86_LINUX_CFLAGS += -fexceptions
CHRE_AUDIO_SUPPORT_ENABLED = true
CHRE_GNSS_SUPPORT_ENABLED = true
-CHRE_SENSORS_SUPPORT_ENABLED = true
CHRE_WIFI_SUPPORT_ENABLED = true
CHRE_WWAN_SUPPORT_ENABLED = true
@@ -31,3 +30,6 @@ CHRE_WWAN_SUPPORT_ENABLED = true
COMMON_SRCS += variant/simulator/static_nanoapps.cc
+# Makefile Includes ############################################################
+
+include apps/ash_world/ash_world.mk