• R/O
  • HTTP
  • SSH
  • HTTPS

Commit

Tags
Keine Tags

Frequently used words (click to add to your profile)

javaandroidc++linuxc#objective-ccocoa誰得qtrubypythongamewindowsbathyscaphephpguic翻訳omegattwitterframeworktestbtronarduinovb.net計画中(planning stage)directxpreviewerゲームエンジンdom

system/bt


Commit MetaInfo

Revision225144cb6435f564009e88056fbf8bf06df5da9c (tree)
Zeit2017-08-10 03:32:24
AutorJaap Jan Meijer <jjmeijer88@gmai...>
CommiterJaap Jan Meijer

Log Message

vendor_lib: remove test, it's broken and should be reworked

Ändern Zusammenfassung

  • delete: vendor_libs/test_vendor_lib/Android.mk
  • delete: vendor_libs/test_vendor_lib/BUILD.gn
  • delete: vendor_libs/test_vendor_lib/data/controller_properties.json
  • delete: vendor_libs/test_vendor_lib/include/command_packet.h
  • delete: vendor_libs/test_vendor_lib/include/dual_mode_controller.h
  • delete: vendor_libs/test_vendor_lib/include/event_packet.h
  • delete: vendor_libs/test_vendor_lib/include/hci_transport.h
  • delete: vendor_libs/test_vendor_lib/include/packet.h
  • delete: vendor_libs/test_vendor_lib/include/packet_stream.h
  • delete: vendor_libs/test_vendor_lib/include/test_channel_transport.h
  • delete: vendor_libs/test_vendor_lib/include/vendor_manager.h
  • delete: vendor_libs/test_vendor_lib/scripts/build_and_run.sh
  • delete: vendor_libs/test_vendor_lib/scripts/test_channel.py
  • delete: vendor_libs/test_vendor_lib/src/bt_vendor.cc
  • delete: vendor_libs/test_vendor_lib/src/command_packet.cc
  • delete: vendor_libs/test_vendor_lib/src/dual_mode_controller.cc
  • delete: vendor_libs/test_vendor_lib/src/event_packet.cc
  • delete: vendor_libs/test_vendor_lib/src/hci_transport.cc
  • delete: vendor_libs/test_vendor_lib/src/packet.cc
  • delete: vendor_libs/test_vendor_lib/src/packet_stream.cc
  • delete: vendor_libs/test_vendor_lib/src/test_channel_transport.cc
  • delete: vendor_libs/test_vendor_lib/src/vendor_manager.cc
  • delete: vendor_libs/test_vendor_lib/test/hci_transport_unittest.cc
  • delete: vendor_libs/test_vendor_lib/test/packet_stream_unittest.cc

Diff

--- a/vendor_libs/test_vendor_lib/Android.mk
+++ /dev/null
@@ -1,77 +0,0 @@
1-LOCAL_PATH := $(call my-dir)
2-
3-# test-vendor shared library for target
4-# ========================================================
5-include $(CLEAR_VARS)
6-
7-BT_DIR := $(TOP_DIR)system/bt
8-
9-LOCAL_SRC_FILES := \
10- src/bt_vendor.cc \
11- src/command_packet.cc \
12- src/dual_mode_controller.cc \
13- src/event_packet.cc \
14- src/hci_transport.cc \
15- src/packet.cc \
16- src/packet_stream.cc \
17- src/test_channel_transport.cc \
18- src/vendor_manager.cc
19-
20-# We pull in gtest because base/files/file_util.h, which is used to read the
21-# controller properties file, needs gtest/gtest_prod.h.
22-LOCAL_C_INCLUDES := \
23- $(LOCAL_PATH)/include \
24- $(BT_DIR) \
25- $(BT_DIR)/hci/include \
26- $(BT_DIR)/stack/include \
27- $(BT_DIR)/third_party/gtest/include
28-
29-LOCAL_SHARED_LIBRARIES := \
30- liblog \
31- libchrome
32-
33-LOCAL_CPP_EXTENSION := .cc
34-LOCAL_MODULE := test-vendor
35-LOCAL_MODULE_TAGS := optional
36-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
37-
38-LOCAL_CFLAGS += $(bluetooth_CFLAGS)
39-LOCAL_CONLYFLAGS += $(bluetooth_CONLYFLAGS)
40-LOCAL_CPPFLAGS += $(bluetooth_CPPFLAGS)
41-
42-include $(BUILD_SHARED_LIBRARY)
43-
44-# test-vendor unit tests for host
45-# ========================================================
46-ifeq ($(HOST_OS), linux)
47-include $(CLEAR_VARS)
48-
49-LOCAL_SRC_FILES := \
50- src/command_packet.cc \
51- src/event_packet.cc \
52- src/hci_transport.cc \
53- src/packet.cc \
54- src/packet_stream.cc \
55- test/hci_transport_unittest.cc \
56- test/packet_stream_unittest.cc
57-
58-LOCAL_C_INCLUDES := \
59- $(LOCAL_PATH)/include \
60- $(BT_DIR) \
61- $(BT_DIR)/hci/include \
62- $(BT_DIR)/stack/include
63-
64-LOCAL_SHARED_LIBRARIES := \
65- liblog \
66- libchrome
67-
68-LOCAL_CPP_EXTENSION := .cc
69-LOCAL_MODULE := test-vendor_test_host
70-LOCAL_MODULE_TAGS := tests
71-
72-LOCAL_CFLAGS += $(bluetooth_CFLAGS)
73-LOCAL_CONLYFLAGS += $(bluetooth_CONLYFLAGS)
74-LOCAL_CPPFLAGS += $(bluetooth_CPPFLAGS)
75-
76-include $(BUILD_HOST_NATIVE_TEST)
77-endif
--- a/vendor_libs/test_vendor_lib/BUILD.gn
+++ /dev/null
@@ -1,55 +0,0 @@
1-shared_library("test_vendor_lib") {
2- sources = [
3- "src/bt_vendor.cc",
4- "src/command_packet.cc",
5- "src/dual_mode_controller.cc",
6- "src/event_packet.cc",
7- "src/hci_transport.cc",
8- "src/packet.cc",
9- "src/packet_stream.cc",
10- "src/test_channel_transport.cc",
11- "src/vendor_manager.cc",
12- ]
13-
14- include_dirs = [
15- "include",
16- "//",
17-
18- # TODO(dennischeng): Ideally we should need to have the lines below for
19- # indirect includes.
20- "//stack/include",
21- "//third_party/libchrome:base",
22- ]
23-}
24-
25-executable("test_vendor_lib_test") {
26- testonly = true
27- sources = [
28- "src/command_packet.cc",
29- "src/event_packet.cc",
30- "src/packet.cc",
31- "src/packet_stream.cc",
32- "test/hci_transport_unittest.cc",
33- "test/packet_stream_unittest.cc",
34- ]
35-
36- include_dirs = [
37- "include",
38- "//",
39- "//btcore/include",
40- "//hci/include",
41- "//stack/include",
42- ]
43-
44- deps = [
45- "//third_party/googletest:gtest_main",
46- "//third_party/libchrome:base",
47- "//vendor_libs/test_vendor_lib",
48- ]
49-
50- libs = [
51- "-lpthread",
52- "-lrt",
53- "-ldl",
54- ]
55-}
--- a/vendor_libs/test_vendor_lib/data/controller_properties.json
+++ /dev/null
@@ -1,13 +0,0 @@
1-{
2- "AclDataPacketSize": "1024",
3- "ScoDataPacketSize": "255",
4- "NumAclDataPackets": "10",
5- "NumScoDataPackets": "10",
6- "Version": "4",
7- "Revision": "0",
8- "LmpPalVersion": "0",
9- "ManufacturerName": "0",
10- "LmpPalSubversion": "0",
11- "MaximumPageNumber": "0",
12- "BdAddress": "123456"
13-}
--- a/vendor_libs/test_vendor_lib/include/command_packet.h
+++ /dev/null
@@ -1,80 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#pragma once
18-
19-#include <cstdint>
20-#include <vector>
21-
22-#include "base/macros.h"
23-#include "vendor_libs/test_vendor_lib/include/packet.h"
24-
25-namespace test_vendor_lib {
26-
27-// The following is specified in the Bluetooth Core Specification Version 4.2,
28-// Volume 2, Part E, Section 5.4.1 (page 470). Command Packets begin with a 3
29-// octet header formatted as follows:
30-// - Opcode: 2 octets
31-// - Opcode Group Field (OGF): Upper bits 10-15
32-// - Opcode Command Field (OCF): Lower bits 0-9
33-// - Payload size (in octets): 1 octet
34-// The header is followed by the payload, which contains command specific
35-// parameters and has a maximum size of 255 octets. Valid command opcodes are
36-// defined in stack/include/hcidefs.h. The OGF ranges from 0x00 to 0x3F, with
37-// 0x3F reserved for vendor-specific debug functions. The OCF ranges from
38-// 0x0000 to 0x03FF. Note that the payload size is the size in octets of the
39-// command parameters and not the number of parameters. Finally, although the
40-// parameters contained in the payload are command specific (including the size
41-// and number of parameters), each parameter will be an integer number of octets
42-// in size.
43-class CommandPacket : public Packet {
44- public:
45- CommandPacket();
46-
47- virtual ~CommandPacket() override = default;
48-
49- // Returns the command opcode as defined in stack/include/hcidefs.h.
50- // See the Bluetooth Core Specification Version 4.2, Volume 2, Part E,
51- // Section 7 for more information about each HCI commands and for a listing
52- // of their specific opcodes/OGF and OCF values.
53- uint16_t GetOpcode() const;
54-
55- // Returns the 6 bit opcode group field that specifies the general category of
56- // the command. The OGF can be one of seven values:
57- // - 0x01: Link control commands
58- // - 0x02: Link policy commands
59- // - 0x03: Controller and baseband commands
60- // - 0x04: Informational parameters commands
61- // - 0x05: Status parameters commands
62- // - 0x06: Testing commands
63- // - 0x08: Low energy controller commands
64- // The upper 2 bits will be zero filled.
65- uint8_t GetOGF() const;
66-
67- // Returns the 10 bit opcode command field that specifies an exact command
68- // within an opcode group field. The upper 6 bits will be zero filled.
69- uint16_t GetOCF() const;
70-
71- // Size in octets of a command packet header, which consists of a 2 octet
72- // opcode and a 1 octet payload size.
73- static const size_t kCommandHeaderSize = 3;
74-
75- private:
76- // Disallow any copies of the singleton to be made.
77- DISALLOW_COPY_AND_ASSIGN(CommandPacket);
78-};
79-
80-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/include/dual_mode_controller.h
+++ /dev/null
@@ -1,369 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#pragma once
18-
19-#include <cstdint>
20-#include <memory>
21-#include <string>
22-#include <vector>
23-#include <unordered_map>
24-
25-#include "base/json/json_value_converter.h"
26-#include "base/time/time.h"
27-#include "vendor_libs/test_vendor_lib/include/command_packet.h"
28-#include "vendor_libs/test_vendor_lib/include/hci_transport.h"
29-#include "vendor_libs/test_vendor_lib/include/test_channel_transport.h"
30-
31-namespace test_vendor_lib {
32-
33-// Emulates a dual mode BR/EDR + LE controller by maintaining the link layer
34-// state machine detailed in the Bluetooth Core Specification Version 4.2,
35-// Volume 6, Part B, Section 1.1 (page 30). Provides methods corresponding to
36-// commands sent by the HCI. These methods will be registered as callbacks from
37-// a controller instance with the HciHandler. To implement a new Bluetooth
38-// command, simply add the method declaration below, with return type void and a
39-// single const std::vector<uint8_t>& argument. After implementing the
40-// method, simply register it with the HciHandler using the SET_HANDLER macro in
41-// the controller's default constructor. Be sure to name your method after the
42-// corresponding Bluetooth command in the Core Specification with the prefix
43-// "Hci" to distinguish it as a controller command.
44-class DualModeController {
45- public:
46- class Properties {
47- public:
48- // TODO(dennischeng): Add default initialization and use that to instantiate
49- // a default configured controller if the config file is invalid or not
50- // provided.
51- Properties(const std::string& file_name);
52-
53- // Aggregates and returns the result for the Read Local Extended Features
54- // command. This result contains the |maximum_page_number_| property (among
55- // other things not in the Properties object). See the Bluetooth Core
56- // Specification Version 4.2, Volume 2, Part E, Section 7.4.4 (page 792).
57- const std::vector<uint8_t> GetBdAddress();
58-
59- // Aggregates and returns the result for the Read Buffer Size command. This
60- // result consists of the |acl_data_packet_size_|, |sco_data_packet_size_|,
61- // |num_acl_data_packets_|, and |num_sco_data_packets_| properties. See the
62- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.5
63- // (page 794).
64- const std::vector<uint8_t> GetBufferSize();
65-
66- // Returns the result for the Read BD_ADDR command. This result is the
67- // |bd_address_| property. See the Bluetooth Core Specification Version
68- // 4.2, Volume 2, Part E, Section 7.4.6 (page 796).
69- const std::vector<uint8_t> GetLocalExtendedFeatures(uint8_t page_number);
70-
71- // Returns the result for the Read Local Name command. See the Bluetooth
72- // Core Specification Version 4.2, Volume 2, Part E, Section 7.3.12
73- // (page 664).
74- const std::vector<uint8_t> GetLocalName();
75-
76- // Returns the result for the Read Local Supported Commands command. See the
77- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.2
78- // (page 790).
79- const std::vector<uint8_t> GetLocalSupportedCommands();
80-
81- // Aggregates and returns the Read Local Version Information result. This
82- // consists of the |version_|, |revision_|, |lmp_pal_version_|,
83- // |manufacturer_name_|, and |lmp_pal_subversion_|. See the Bluetooth Core
84- // Specification Version 4.2, Volume 2, Part E, Section 7.4.1 (page 788).
85- const std::vector<uint8_t> GetLocalVersionInformation();
86-
87- static void RegisterJSONConverter(
88- base::JSONValueConverter<Properties>* converter);
89-
90- private:
91- uint16_t acl_data_packet_size_;
92- uint8_t sco_data_packet_size_;
93- uint16_t num_acl_data_packets_;
94- uint16_t num_sco_data_packets_;
95- uint8_t version_;
96- uint16_t revision_;
97- uint8_t lmp_pal_version_;
98- uint16_t manufacturer_name_;
99- uint16_t lmp_pal_subversion_;
100- uint8_t maximum_page_number_;
101- uint8_t local_supported_commands_size_;
102- uint8_t local_name_size_;
103- std::vector<uint8_t> bd_address_;
104- };
105-
106- // Sets all of the methods to be used as callbacks in the HciHandler.
107- DualModeController();
108-
109- ~DualModeController() = default;
110-
111- // Preprocesses the command, primarily checking testh channel hooks. If
112- // possible, dispatches the corresponding controller method corresponding to
113- // carry out the command.
114- void HandleCommand(std::unique_ptr<CommandPacket> command_packet);
115-
116- // Dispatches the test channel action corresponding to the command specified
117- // by |name|.
118- void HandleTestChannelCommand(const std::string& name,
119- const std::vector<std::string>& args);
120-
121- // Sets the controller Handle* methods as callbacks for the transport to call
122- // when data is received.
123- void RegisterHandlersWithHciTransport(HciTransport& transport);
124-
125- // Sets the test channel handler with the transport dedicated to test channel
126- // communications.
127- void RegisterHandlersWithTestChannelTransport(
128- TestChannelTransport& transport);
129-
130- // Sets the callback to be used for sending events back to the HCI.
131- // TODO(dennischeng): Once PostDelayedTask works, get rid of this and only use
132- // |RegisterDelayedEventChannel|.
133- void RegisterEventChannel(
134- std::function<void(std::unique_ptr<EventPacket>)> send_event);
135-
136- void RegisterDelayedEventChannel(
137- std::function<void(std::unique_ptr<EventPacket>, base::TimeDelta)>
138- send_event);
139-
140- // Controller commands. For error codes, see the Bluetooth Core Specification,
141- // Version 4.2, Volume 2, Part D (page 370).
142-
143- // OGF: 0x0003
144- // OCF: 0x0003
145- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.2
146- void HciReset(const std::vector<uint8_t>& args);
147-
148- // OGF: 0x0004
149- // OGF: 0x0005
150- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.4.5
151- void HciReadBufferSize(const std::vector<uint8_t>& args);
152-
153- // OGF: 0x0003
154- // OCF: 0x0033
155- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.39
156- void HciHostBufferSize(const std::vector<uint8_t>& args);
157-
158- // OGF: 0x0004
159- // OCF: 0x0001
160- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.4.1
161- void HciReadLocalVersionInformation(const std::vector<uint8_t>& args);
162-
163- // OGF: 0x0004
164- // OCF: 0x0009
165- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.4.6
166- void HciReadBdAddr(const std::vector<uint8_t>& args);
167-
168- // OGF: 0x0004
169- // OCF: 0x0002
170- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.4.2
171- void HciReadLocalSupportedCommands(const std::vector<uint8_t>& args);
172-
173- // OGF: 0x0004
174- // OCF: 0x0004
175- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.4.4
176- void HciReadLocalExtendedFeatures(const std::vector<uint8_t>& args);
177-
178- // OGF: 0x0003
179- // OCF: 0x0056
180- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.59
181- void HciWriteSimplePairingMode(const std::vector<uint8_t>& args);
182-
183- // OGF: 0x0003
184- // OCF: 0x006D
185- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.79
186- void HciWriteLeHostSupport(const std::vector<uint8_t>& args);
187-
188- // OGF: 0x0003
189- // OCF: 0x0001
190- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.1
191- void HciSetEventMask(const std::vector<uint8_t>& args);
192-
193- // OGF: 0x0003
194- // OCF: 0x0045
195- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.50
196- void HciWriteInquiryMode(const std::vector<uint8_t>& args);
197-
198- // OGF: 0x0003
199- // OCF: 0x0047
200- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.52
201- void HciWritePageScanType(const std::vector<uint8_t>& args);
202-
203- // OGF: 0x0003
204- // OCF: 0x0043
205- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.48
206- void HciWriteInquiryScanType(const std::vector<uint8_t>& args);
207-
208- // OGF: 0x0003
209- // OCF: 0x0024
210- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.26
211- void HciWriteClassOfDevice(const std::vector<uint8_t>& args);
212-
213- // OGF: 0x0003
214- // OCF: 0x0018
215- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.16
216- void HciWritePageTimeout(const std::vector<uint8_t>& args);
217-
218- // OGF: 0x0002
219- // OCF: 0x000F
220- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.2.12
221- void HciWriteDefaultLinkPolicySettings(const std::vector<uint8_t>& args);
222-
223- // OGF: 0x0003
224- // OCF: 0x0014
225- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.12
226- void HciReadLocalName(const std::vector<uint8_t>& args);
227-
228- // OGF: 0x0003
229- // OCF: 0x0013
230- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.11
231- void HciWriteLocalName(const std::vector<uint8_t>& args);
232-
233- // OGF: 0x0003
234- // OCF: 0x0052
235- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.56
236- void HciWriteExtendedInquiryResponse(const std::vector<uint8_t>& args);
237-
238- // OGF: 0x0003
239- // OCF: 0x0026
240- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.28
241- void HciWriteVoiceSetting(const std::vector<uint8_t>& args);
242-
243- // OGF: 0x0003
244- // OCF: 0x003A
245- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.45
246- void HciWriteCurrentIacLap(const std::vector<uint8_t>& args);
247-
248- // OGF: 0x0003
249- // OCF: 0x001E
250- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.22
251- void HciWriteInquiryScanActivity(const std::vector<uint8_t>& args);
252-
253- // OGF: 0x0003
254- // OCF: 0x001A
255- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.18
256- void HciWriteScanEnable(const std::vector<uint8_t>& args);
257-
258- // OGF: 0x0003
259- // OCF: 0x0005
260- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.3
261- void HciSetEventFilter(const std::vector<uint8_t>& args);
262-
263- // OGF: 0x0001
264- // OCF: 0x0001
265- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.1.1
266- void HciInquiry(const std::vector<uint8_t>& args);
267-
268- // OGF: 0x0001
269- // OCF: 0x0002
270- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.1.2
271- void HciInquiryCancel(const std::vector<uint8_t>& args);
272-
273- // OGF: 0x0003
274- // OCF: 0x0012
275- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.3.10
276- void HciDeleteStoredLinkKey(const std::vector<uint8_t>& args);
277-
278- // OGF: 0x0001
279- // OCF: 0x0019
280- // Bluetooth Core Specification Version 4.2 Volume 2 Part E 7.1.19
281- void HciRemoteNameRequest(const std::vector<uint8_t>& args);
282-
283- // Test Channel commands:
284-
285- // Clears all test channel modifications.
286- void TestChannelClear(const std::vector<std::string>& args);
287-
288- // Sets the response delay for events to 0.
289- void TestChannelClearEventDelay(const std::vector<std::string>& args);
290-
291- // Discovers a fake device.
292- void TestChannelDiscover(const std::vector<std::string>& args);
293-
294- // Causes events to be sent after a delay.
295- void TestChannelSetEventDelay(const std::vector<std::string>& args);
296-
297- // Causes all future HCI commands to timeout.
298- void TestChannelTimeoutAll(const std::vector<std::string>& args);
299-
300- private:
301- // Current link layer state of the controller.
302- enum State {
303- kStandby, // Not receiving/transmitting any packets from/to other devices.
304- kInquiry, // The controller is discovering other nearby devices.
305- };
306-
307- enum TestChannelState {
308- kNone, // The controller is running normally.
309- kTimeoutAll, // All commands should time out, i.e. send no response.
310- kDelayedResponse, // Event responses are sent after a delay.
311- };
312-
313- // Creates a command complete event and sends it back to the HCI.
314- void SendCommandComplete(uint16_t command_opcode,
315- const std::vector<uint8_t>& return_parameters) const;
316-
317- // Sends a command complete event with no return parameters. This event is
318- // typically sent for commands that can be completed immediately.
319- void SendCommandCompleteSuccess(uint16_t command_opcode) const;
320-
321- // Creates a command status event and sends it back to the HCI.
322- void SendCommandStatus(uint8_t status, uint16_t command_opcode) const;
323-
324- // Sends a command status event with default event parameters.
325- void SendCommandStatusSuccess(uint16_t command_opcode) const;
326-
327- // Sends an inquiry response for a fake device.
328- void SendInquiryResult() const;
329-
330- // Sends an extended inquiry response for a fake device.
331- void SendExtendedInquiryResult(const std::string& name,
332- const std::string& address) const;
333-
334- void SetEventDelay(int64_t delay);
335-
336- // Callback provided to send events from the controller back to the HCI.
337- std::function<void(std::unique_ptr<EventPacket>)> send_event_;
338-
339- std::function<void(std::unique_ptr<EventPacket>, base::TimeDelta)>
340- send_delayed_event_;
341-
342- // Maintains the commands to be registered and used in the HciHandler object.
343- // Keys are command opcodes and values are the callbacks to handle each
344- // command.
345- std::unordered_map<uint16_t, std::function<void(const std::vector<uint8_t>&)>>
346- active_hci_commands_;
347-
348- std::unordered_map<std::string,
349- std::function<void(const std::vector<std::string>&)>>
350- active_test_channel_commands_;
351-
352- // Specifies the format of Inquiry Result events to be returned during the
353- // Inquiry command.
354- // 0x00: Standard Inquiry Result event format (default).
355- // 0x01: Inquiry Result format with RSSI.
356- // 0x02 Inquiry Result with RSSI format or Extended Inquiry Result format.
357- // 0x03-0xFF: Reserved.
358- uint8_t inquiry_mode_;
359-
360- State state_;
361-
362- Properties properties_;
363-
364- TestChannelState test_channel_state_;
365-
366- DISALLOW_COPY_AND_ASSIGN(DualModeController);
367-};
368-
369-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/include/event_packet.h
+++ /dev/null
@@ -1,161 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#pragma once
18-
19-#include <cstdint>
20-#include <memory>
21-#include <vector>
22-
23-#include "base/logging.h"
24-#include "vendor_libs/test_vendor_lib/include/packet.h"
25-
26-namespace test_vendor_lib {
27-
28-// The following is specified in the Bluetooth Core Specification Version 4.2,
29-// Volume 2, Part E, Section 5.4.4 (page 477). Event Packets begin with a 2
30-// octet header formatted as follows:
31-// - Event code: 1 octet
32-// - Payload size (in octets): 1 octet
33-// The header is followed by the payload, which contains event specific
34-// parameters and has a maximum size of 255 octets. Valid event codes are
35-// listed in stack/include/hcidefs.h. They can range from 0x00 to 0xFF, with
36-// 0xFF reserved for vendor specific debug events. Note the payload size
37-// describes the total size of the event parameters and not the number of
38-// parameters. The event parameters contained in the payload will be an integer
39-// number of octets in size. Each flavor of event packet is created via a static
40-// factory function that takes the event type-specific parameters and returns an
41-// initialized event packet from that data.
42-class EventPacket : public Packet {
43- public:
44- virtual ~EventPacket() override = default;
45-
46- uint8_t GetEventCode() const;
47-
48- // Static functions for creating event packets:
49-
50- // Creates and returns a command complete event packet. See the Bluetooth
51- // Core Specification Version 4.2, Volume 2, Part E, Section 7.7.14 (page 861)
52- // for more information about the command complete event.
53- // Event Parameters:
54- // |num_hci_command_packets|
55- // Indicates the number of HCI command packets the host can send to the
56- // controller. If |num_hci_command_packets| is 0, the controller would
57- // like to stop receiving commands from the host (to indicate
58- // readiness again, the controller sends a command complete event with
59- // |command_opcode| to 0x0000 (no op) and |num_hci_command_packets| > 1).
60- // |command_opcode|
61- // The opcode of the command that caused this event.
62- // |return_parameters|
63- // Contains any event specific parameters that should
64- // be sent to the host.
65- static std::unique_ptr<EventPacket> CreateCommandCompleteEvent(
66- uint8_t num_hci_command_packets, uint16_t command_opcode,
67- const std::vector<uint8_t>& event_return_parameters);
68-
69- // Creates and returns a command complete event packet. See the Bluetooth
70- // Core Specification Version 4.2, Volume 2, Part E, Section 7.7.15 (page 862)
71- // for more information about the command complete event.
72- // Event Parameters:
73- // Status
74- // 0x00: Command currently in pending.
75- // 0x01-0xFF: Command failed.
76- // |num_hci_command_packets|
77- // Indicates the number of HCI command packets the host can send to the
78- // controller. If |num_hci_command_packets| is 0, the controller would
79- // like to stop receiving commands from the host (to indicate
80- // readiness again, the controller sends a command complete event with
81- // |command_opcode| to 0x0000 (no op) and |num_hci_command_packets| > 1).
82- // |command_opcode|
83- // The opcode of the command that caused this event.
84- static std::unique_ptr<EventPacket> CreateCommandStatusEvent(
85- uint8_t status, uint8_t num_hci_command_packets, uint16_t command_opcode);
86-
87- // Creates and returns an inquiry result event packet. See the Bluetooth
88- // Core Specification Version 4.2, Volume 2, Part E, Section 7.7.2 (page 844)
89- // for more information about the command complete event.
90- // Event Parameters:
91- // Num Responses (1 octet)
92- // 0xXX: Number of responses from the inquiry.
93- // Bd Addresses (6 octets * Num Responses)
94- // 0xXXXXXXXXXXX: Bd Address for each device which responded.
95- // Page Scan Repetition Mode (1 octet * Num Responses)
96- // 0x00: R0
97- // 0x01: R1
98- // 0x02: R2
99- // 0x03-0xFF: Reserved.
100- // Reserved 1 (1 octet * Num Responses)
101- // Originally Page Scan Period Mode parameter. No longer in use.
102- // Reserved 2 (1 octet * Num Responses)
103- // Originally Page Scan Mode parameter. No longer in use.
104- // Class of Device (3 octet * Num Responses)
105- // 0xXXXXXX: Class of device.
106- // Clock Offset (2 octet * Num Responses)
107- // Bits 14-0: Bits 16-2 of CLKNslave-CLK.
108- // Bits 15: Reserved.
109- static std::unique_ptr<EventPacket> CreateInquiryResultEvent(
110- uint8_t num_responses, const std::vector<uint8_t>& bd_addresses,
111- const std::vector<uint8_t>& page_scan_repetition_mode,
112- const std::vector<uint8_t>& page_scan_period_mode,
113- const std::vector<uint8_t>& page_scan_mode,
114- const std::vector<uint8_t>& class_of_device,
115- const std::vector<uint8_t>& clock_offset);
116-
117- // Creates and returns an inquiry result event packet. See the Bluetooth
118- // Core Specification Version 4.2, Volume 2, Part E, Section 7.7.38 (page 896)
119- // for more information about the command complete event.
120- // Event Parameters:
121- // Num Responses (1 octet)
122- // 0x01: Always contains a single response.
123- // Bd Addresses (6 octets * Num Responses)
124- // 0xXXXXXXXXXXX: Bd Address for each device which responded.
125- // Page Scan Repetition Mode (1 octet * Num Responses)
126- // 0x00: R0
127- // 0x01: R1
128- // 0x02: R2
129- // 0x03-0xFF: Reserved.
130- // Reserved 1 (1 octet * Num Responses)
131- // Originally Page Scan Period Mode parameter. No longer in use.
132- // Class of Device (3 octet * Num Responses)
133- // 0xXXXXXX: Class of device.
134- // Clock Offset (2 octet * Num Responses)
135- // Bits 14-0: Bits 16-2 of CLKNslave-CLK.
136- // Bits 15: Reserved.
137- // RSSI (1 octet)
138- // 0xXX: Ranges from -127 to +20. Units are dBm.
139- // Extended Inquiry Response (240 octets)
140- // Defined in Volumne 2, Part C, Section 8. Also see the Supplement to the
141- // Bluetooth Core Specificiation for data type definitions and formats.
142- static std::unique_ptr<EventPacket> CreateExtendedInquiryResultEvent(
143- const std::vector<uint8_t>& bd_address,
144- const std::vector<uint8_t>& page_scan_repetition_mode,
145- const std::vector<uint8_t>& page_scan_period_mode,
146- const std::vector<uint8_t>& class_of_device,
147- const std::vector<uint8_t>& clock_offset,
148- const std::vector<uint8_t>& rssi,
149- const std::vector<uint8_t>& extended_inquiry_response);
150-
151- // Size in octets of a data packet header, which consists of a 1 octet
152- // event code and a 1 octet payload size.
153- static const size_t kEventHeaderSize = 2;
154-
155- private:
156- // Takes in the event parameters in |payload|. These parameters vary by event
157- // and are detailed in the Bluetooth Core Specification.
158- EventPacket(uint8_t event_code, const std::vector<uint8_t>& payload);
159-};
160-
161-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/include/hci_transport.h
+++ /dev/null
@@ -1,134 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#pragma once
18-
19-#include <functional>
20-#include <memory>
21-#include <list>
22-
23-extern "C" {
24-#include <sys/epoll.h>
25-} // extern "C"
26-
27-#include "base/files/scoped_file.h"
28-#include "base/memory/weak_ptr.h"
29-#include "base/message_loop/message_loop.h"
30-#include "base/time/time.h"
31-#include "vendor_libs/test_vendor_lib/include/command_packet.h"
32-#include "vendor_libs/test_vendor_lib/include/event_packet.h"
33-#include "vendor_libs/test_vendor_lib/include/packet.h"
34-#include "vendor_libs/test_vendor_lib/include/packet_stream.h"
35-
36-namespace test_vendor_lib {
37-
38-// Manages communication channel between HCI and the controller by providing the
39-// socketing mechanisms for reading/writing between the HCI and the controller.
40-class HciTransport : public base::MessageLoopForIO::Watcher {
41- public:
42- HciTransport();
43-
44- virtual ~HciTransport() = default;
45-
46- void CloseHciFd();
47-
48- void CloseVendorFd();
49-
50- int GetHciFd() const;
51-
52- int GetVendorFd() const;
53-
54- // Creates the underlying socketpair to be used as a communication channel
55- // between the HCI and the vendor library/controller. Returns false if an
56- // error occurs.
57- bool SetUp();
58-
59- // Sets the callback that is run when command packets are received.
60- void RegisterCommandHandler(
61- std::function<void(std::unique_ptr<CommandPacket>)> callback);
62-
63- // Posts the event onto |outbound_events_| to be written sometime in the
64- // future when the vendor file descriptor is ready for writing.
65- void PostEventResponse(std::unique_ptr<EventPacket> event);
66-
67- // Posts the event onto |outbound_events_| after |delay| ms. A call to
68- // |PostEventResponse| with |delay| 0 is equivalent to a call to |PostEvent|.
69- void PostDelayedEventResponse(std::unique_ptr<EventPacket> event,
70- base::TimeDelta delay);
71-
72- private:
73- // Wrapper class for sending events on a delay. The TimeStampedEvent object
74- // takes ownership of a given event packet.
75- class TimeStampedEvent {
76- public:
77- TimeStampedEvent(std::unique_ptr<EventPacket> event, base::TimeDelta delay);
78-
79- // Using this constructor is equivalent to calling the 2-argument
80- // constructor with a |delay| of 0. It is used to generate event responses
81- // with no delay.
82- TimeStampedEvent(std::unique_ptr<EventPacket> event);
83-
84- const base::TimeTicks& GetTimeStamp() const;
85-
86- const EventPacket& GetEvent();
87-
88- private:
89- std::shared_ptr<EventPacket> event_;
90-
91- // The time associated with the event, indicating the earliest time at which
92- // |event_| will be sent.
93- base::TimeTicks time_stamp_;
94- };
95-
96- // base::MessageLoopForIO::Watcher overrides:
97- void OnFileCanReadWithoutBlocking(int fd) override;
98-
99- void OnFileCanWriteWithoutBlocking(int fd) override;
100-
101- // Reads in a command packet and calls the command ready callback,
102- // |command_handler_|, passing ownership of the command packet to the handler.
103- void ReceiveReadyCommand() const;
104-
105- void AddEventToOutboundEvents(std::unique_ptr<TimeStampedEvent> event);
106-
107- // Write queue for sending events to the HCI. Event packets are removed from
108- // the queue and written when write-readiness is signalled by the message
109- // loop. After being written, the event packets are destructed.
110- std::list<std::unique_ptr<TimeStampedEvent>> outbound_events_;
111-
112- // Callback executed in ReceiveReadyCommand() to pass the incoming command
113- // over to the handler for further processing.
114- std::function<void(std::unique_ptr<CommandPacket>)> command_handler_;
115-
116- // For performing packet-based IO.
117- PacketStream packet_stream_;
118-
119- // The two ends of the socketpair. |hci_fd_| is handed back to the HCI in
120- // bt_vendor.cc and |vendor_fd_| is used by |packet_stream_| to receive/send
121- // data from/to the HCI. Both file descriptors are owned and managed by the
122- // transport object, although |hci_fd_| can be closed by the HCI in
123- // TestVendorOp().
124- std::unique_ptr<base::ScopedFD> hci_fd_;
125- std::unique_ptr<base::ScopedFD> vendor_fd_;
126-
127- // This should remain the last member so it'll be destroyed and invalidate
128- // its weak pointers before any other members are destroyed.
129- base::WeakPtrFactory<HciTransport> weak_ptr_factory_;
130-
131- DISALLOW_COPY_AND_ASSIGN(HciTransport);
132-};
133-
134-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/include/packet.h
+++ /dev/null
@@ -1,78 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#pragma once
18-
19-#include <cstdint>
20-#include <vector>
21-
22-extern "C" {
23-#include "hci/include/hci_hal.h"
24-} // extern "C"
25-
26-namespace test_vendor_lib {
27-
28-// Abstract base class that is subclassed to provide type-specifc accessors on
29-// data. Manages said data's memory and guarantees the data's persistence for IO
30-// operations.
31-class Packet {
32- public:
33- virtual ~Packet() = default;
34-
35- // Returns the size in octets of the entire packet, which consists of the type
36- // octet, the header, and the payload.
37- size_t GetPacketSize() const;
38-
39- const std::vector<uint8_t>& GetPayload() const;
40-
41- uint8_t GetPayloadSize() const;
42-
43- const std::vector<uint8_t>& GetHeader() const;
44-
45- uint8_t GetHeaderSize() const;
46-
47- serial_data_type_t GetType() const;
48-
49- // Validates the packet by checking that the payload size in the header is
50- // accurate. If the size is not valid, returns false. Otherwise, the data in
51- // |header| and |payload| is copied into |header_| and |payload_|
52- // respectively. If an error occurs while the data is being copied, the
53- // contents of |header| and |payload| are guaranteed to be preserved. The
54- // packet object will assume ownership of the copied data for its entire
55- // lifetime.
56- bool Encode(const std::vector<uint8_t>& header,
57- const std::vector<uint8_t>& payload);
58-
59- protected:
60- // Constructs an empty packet of type |type|. A call to Encode() shall be made
61- // to check and fill in the packet's data.
62- Packet(serial_data_type_t type);
63-
64- private:
65- // Underlying containers for storing the actual packet, broken down into the
66- // packet header and the packet payload. Data is copied into the vectors
67- // during the constructor and becomes accessible (read only) to children
68- // through GetHeader() and GetPayload().
69- std::vector<uint8_t> header_;
70-
71- std::vector<uint8_t> payload_;
72-
73- // The packet type is one of DATA_TYPE_ACL, DATA_TYPE_COMMAND,
74- // DATA_TYPE_EVENT, or DATA_TYPE_SCO.
75- serial_data_type_t type_;
76-};
77-
78-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/include/packet_stream.h
+++ /dev/null
@@ -1,66 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#pragma once
18-
19-#include <cstdint>
20-#include <vector>
21-#include <memory>
22-
23-#include "vendor_libs/test_vendor_lib/include/command_packet.h"
24-#include "vendor_libs/test_vendor_lib/include/event_packet.h"
25-#include "vendor_libs/test_vendor_lib/include/packet.h"
26-
27-namespace test_vendor_lib {
28-
29-// Provides abstractions for IO with Packet objects. Used to receive commands
30-// and data from the HCI and to send controller events back to the host.
31-class PacketStream {
32- public:
33- PacketStream() = default;
34-
35- virtual ~PacketStream() = default;
36-
37- // Reads a command packet from the file descriptor at |fd| and returns the
38- // packet back to the caller, along with the responsibility of managing the
39- // packet.
40- std::unique_ptr<CommandPacket> ReceiveCommand(int fd) const;
41-
42- // Reads a single octet from |fd| and interprets it as a packet type octet.
43- // Validates the type octet for correctness.
44- serial_data_type_t ReceivePacketType(int fd) const;
45-
46- // Sends an event to file descriptor |fd|. The ownership of the event is left
47- // with the caller.
48- bool SendEvent(const EventPacket& event, int fd) const;
49-
50- private:
51- // Checks if |type| is in the valid range from DATA_TYPE_COMMAND to
52- // DATA_TYPE_SCO.
53- bool ValidateTypeOctet(serial_data_type_t type) const;
54-
55- // Attempts to receive |num_octets_to_receive| into |destination| from |fd|,
56- // returning false if an error occurs.
57- bool ReceiveAll(std::vector<uint8_t>& destination,
58- size_t num_octets_to_receive, int fd) const;
59-
60- // Attempts to send |num_octets_to_send| from |source| to |fd|, returning
61- // false if an error occurs.
62- bool SendAll(const std::vector<uint8_t>& source, size_t num_octets_to_send,
63- int fd) const;
64-};
65-
66-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/include/test_channel_transport.h
+++ /dev/null
@@ -1,77 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#pragma once
18-
19-#include <string>
20-#include <memory>
21-
22-#include "base/files/scoped_file.h"
23-#include "base/message_loop/message_loop.h"
24-
25-namespace test_vendor_lib {
26-
27-// Manages communications between test channel and the controller. Mirrors the
28-// HciTransport for the test channel.
29-class TestChannelTransport : public base::MessageLoopForIO::Watcher {
30- public:
31- TestChannelTransport(bool enabled, int port);
32-
33- ~TestChannelTransport() = default;
34-
35- // Waits for a connection request from the test channel program and
36- // allocates the file descriptor to watch for run-time parameters at. This
37- // file descriptor gets stored in |fd_|.
38- bool SetUp();
39-
40- int GetFd();
41-
42- // Because it imposes a different flow of work, the test channel must be
43- // actively enabled to be used. |enabled_| is set by the vendor manager.
44- bool IsEnabled();
45-
46- // Turns the test channel off for use in circumstances where an error occurs
47- // and leaving the channel on would crash Bluetooth (e.g. if the test channel
48- // is unable to bind to its socket, Bluetooth should still start without the
49- // channel enabled).
50- void Disable();
51-
52- // Sets the callback that fires when data is read in
53- // |OnFileCanReadWithoutBlocking|.
54- void RegisterCommandHandler(
55- std::function<void(const std::string&, const std::vector<std::string>&)>
56- callback);
57-
58- private:
59- // base::MessageLoopForIO::Watcher overrides:
60- void OnFileCanReadWithoutBlocking(int fd) override;
61-
62- void OnFileCanWriteWithoutBlocking(int fd) override;
63-
64- std::function<void(const std::string&, const std::vector<std::string>&)>
65- command_handler_;
66-
67- // File descriptor to watch for test hook data.
68- std::unique_ptr<base::ScopedFD> fd_;
69-
70- // TODO(dennischeng): Get port and enabled flag from a config file.
71- int port_;
72- bool enabled_;
73-
74- DISALLOW_COPY_AND_ASSIGN(TestChannelTransport);
75-};
76-
77-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/include/vendor_manager.h
+++ /dev/null
@@ -1,118 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#include "base/macros.h"
18-#include "base/memory/weak_ptr.h"
19-#include "base/threading/thread.h"
20-#include "base/time/time.h"
21-#include "hci/include/bt_vendor_lib.h"
22-#include "vendor_libs/test_vendor_lib/include/dual_mode_controller.h"
23-#include "vendor_libs/test_vendor_lib/include/event_packet.h"
24-#include "vendor_libs/test_vendor_lib/include/hci_transport.h"
25-#include "vendor_libs/test_vendor_lib/include/test_channel_transport.h"
26-
27-#include <memory>
28-
29-namespace test_vendor_lib {
30-
31-// Contains the three core objects that make up the test vendor library: the
32-// HciTransport for communication, the HciHandler for processing commands, and
33-// the Controller for actual command implementations. The VendorManager shall
34-// operate as a global singleton and be used in bt_vendor.cc to perform vendor
35-// specific operations, via |vendor_callbacks_|, and to provide access to the
36-// test controller by setting up a message loop (on another thread) that the HCI
37-// will talk to and controller methods will execute on.
38-class VendorManager {
39- public:
40- // Functions that operate on the global manager instance. Initialize()
41- // is called by the vendor library's TestVendorInitialize() function to create
42- // the global manager and must be called before Get() and CleanUp().
43- // CleanUp() should be called when a call to TestVendorCleanUp() is made
44- // since the global manager should live throughout the entire time the test
45- // vendor library is in use.
46- static void CleanUp();
47-
48- static VendorManager* Get();
49-
50- static void Initialize();
51-
52- void CloseHciFd();
53-
54- int GetHciFd() const;
55-
56- const bt_vendor_callbacks_t& GetVendorCallbacks() const;
57-
58- // Stores a copy of the vendor specific configuration callbacks passed into
59- // the vendor library from the HCI in TestVendorInit().
60- void SetVendorCallbacks(const bt_vendor_callbacks_t& callbacks);
61-
62- // Returns true if |thread_| is able to be started and the
63- // StartingWatchingOnThread() task has been posted to the task runner.
64- bool Run();
65-
66- private:
67- VendorManager();
68-
69- ~VendorManager() = default;
70-
71- // Posts a callback to |thread_|'s task runner. Equivalent to calling
72- // |PostDelayedTask| with a delay of 0.
73- bool PostTask(const base::Closure& task);
74-
75- // Posts a callback to be run after |delay| ms (or longer) have passed.
76- bool PostDelayedTask(const base::Closure& task, base::TimeDelta delay);
77-
78- // Starts watching for incoming data from the HCI and the test hook.
79- void StartWatchingOnThread();
80-
81- // Creates the HCI's communication channel and overrides IO callbacks to
82- // receive and send packets.
83- HciTransport transport_;
84-
85- // The controller object that provides implementations of Bluetooth commands.
86- DualModeController controller_;
87-
88- // The two test channel objects that perform functions corresponding to the
89- // HciTransport and HciHandler.
90- TestChannelTransport test_channel_transport_;
91-
92- // Configuration callbacks provided by the HCI for use in TestVendorOp().
93- bt_vendor_callbacks_t vendor_callbacks_;
94-
95- // True if the underlying message loop (in |thread_|) is running.
96- bool running_;
97-
98- // Dedicated thread for managing the message loop to receive and send packets
99- // from the HCI and to receive additional parameters from the test hook file
100- // descriptor.
101- base::Thread thread_;
102-
103- // Used to handle further watching of the vendor's/test channel's file
104- // descriptor after WatchFileDescriptor() is called.
105- base::MessageLoopForIO::FileDescriptorWatcher hci_watcher_;
106-
107- // Used to handle further watching of the test channel's file descriptor after
108- // WatchFileDescriptor() is called.
109- base::MessageLoopForIO::FileDescriptorWatcher test_channel_watcher_;
110-
111- // This should remain the last member so it'll be destroyed and invalidate
112- // its weak pointers before any other members are destroyed.
113- base::WeakPtrFactory<VendorManager> weak_ptr_factory_;
114-
115- DISALLOW_COPY_AND_ASSIGN(VendorManager);
116-};
117-
118-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/scripts/build_and_run.sh
+++ /dev/null
@@ -1,127 +0,0 @@
1-#!/bin/bash
2-
3-#
4-# Copyright 2015 The Android Open Source Project
5-#
6-# Licensed under the Apache License, Version 2.0 (the "License");
7-# you may not use this file except in compliance with the License.
8-# You may obtain a copy of the License at
9-#
10-# http://www.apache.org/licenses/LICENSE-2.0
11-#
12-# Unless required by applicable law or agreed to in writing, software
13-# distributed under the License is distributed on an "AS IS" BASIS,
14-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15-# See the License for the specific language governing permissions and
16-# limitations under the License.
17-#
18-
19-# Builds and pushes the test vendor library to a connected device and starts
20-# logcat with project-specific tag filters. If the --test-channel flag is set,
21-# logcat is started in a separate process and the test channel is run in the
22-# current shell. The kTestChannelEnabled flag must be set in the vendor manager
23-# if the test channel is to be used. Also ensure that 'lunch' has been run for
24-# the appropriate device.
25-
26-if [[ "$#" -ne 2 && "$#" -ne 4 ]]; then
27- echo "Usage:"
28- echo "./build_and_run.sh [/path/to/aosp] [device_name] or"
29- echo "./build_and_run.sh [/path/to/aosp] [device_name] --test-channel [port]"
30- exit 1
31-fi
32-
33-# Exit the script if any command fails.
34-set -e
35-
36-# The home directory for AOSP.
37-AOSP_ABS=$1
38-# The name of the device to build for.
39-DEVICE=$2
40-
41-# The location of Bluetooth within AOSP.
42-BT_REL=/system/bt
43-BT_ABS=${AOSP_ABS}${BT_REL}
44-
45-# The location of the test vendor library.
46-TEST_VENDOR_LIB_REL=/vendor_libs/test_vendor_lib
47-TEST_VENDOR_LIB_ABS=${BT_ABS}${TEST_VENDOR_LIB_REL}
48-
49-DEVICE_TARGET_REL=/out/target/product
50-DEVICE_TARGET_ABS=${AOSP_ABS}${DEVICE_TARGET_REL}
51-
52-VENDOR_SYMBOLS_REL=/symbols/system/vendor/lib
53-VENDOR_SYMBOLS_ABS=${DEVICE_TARGET_ABS}/${DEVICE}/${VENDOR_SYMBOLS_REL}
54-
55-# The name of the object built by the test vendor library.
56-TEST_VENDOR_LIB=test-vendor.so
57-# The name of the regular vendor object to be replaced by $TEST_VENDOR_LIB.
58-VENDOR_LIB=libbt-vendor.so
59-# The config file specifying controller properties.
60-CONTROLLER_PROPERTIES=controller_properties.json
61-
62-if [[ "$#" -eq 4 && $3 == "--test-channel" ]]; then
63- TEST_CHANNEL_PORT=$4
64- TEST_CHANNEL_REL=/scripts
65- TEST_CHANNEL_ABS=${TEST_VENDOR_LIB_ABS}${TEST_CHANNEL_REL}
66-
67- # Start logcat in a subshell.
68- x-terminal-emulator -e "scripts/build_and_run.sh ${AOSP_ABS} ${DEVICE}"
69-
70- echo "Setting up build environment."
71- cd ${AOSP_ABS}
72- source build/envsetup.sh
73-
74- # Forward local port to the same port on the device.
75- echo "Forwarding port ${TEST_CHANNEL_PORT} to device."
76- adb forward tcp:${TEST_CHANNEL_PORT} tcp:${TEST_CHANNEL_PORT}
77-
78- # Turn Bluetooth on. Requires user approval via a dialog on the device.
79- echo "Enabling Bluetooth. Please see dialog on device."
80- adb shell am start -a android.bluetooth.adapter.action.REQUEST_ENABLE
81-
82- # Start the test channel once Bluetooth is on and logcat has started.
83- read -p "Press [ENTER] once Bluetooth is enabling AND logcat has started."
84-
85- # Start the test channel.
86- python ${TEST_CHANNEL_ABS}/test_channel.py localhost ${TEST_CHANNEL_PORT}
87-else
88- echo "Setting up build environment."
89- cd ${AOSP_ABS}
90- source build/envsetup.sh
91-
92- echo "Navigating to test vendor library: ${TEST_VENDOR_LIB_ABS}"
93- cd ${TEST_VENDOR_LIB_ABS}
94-
95- echo "Building test vendor library."
96- mm
97-
98- echo "Remounting device rootfs."
99- adb shell mount -o remount,rw /
100- adb remount
101-
102- # Replace the actual vendor library with the test vendor library.
103- mv ${DEVICE_TARGET_ABS}/${DEVICE}/system/lib/${TEST_VENDOR_LIB} \
104- ${VENDOR_SYMBOLS_ABS}/${VENDOR_LIB}
105-
106- # Push the test vendor library to the device.
107- echo "Pushing the test vendor library to device: $DEVICE"
108- adb push ${VENDOR_SYMBOLS_ABS}/${VENDOR_LIB} /vendor/lib
109-
110- echo "Pushing controller properties."
111- adb push ${TEST_VENDOR_LIB_ABS}/data/${CONTROLLER_PROPERTIES} /etc/bluetooth/
112-
113- echo "Pushing libevent."
114- adb push ${DEVICE_TARGET_ABS}/${DEVICE}/system/lib/libevent.so /system/lib/
115-
116- echo "Pushing libchrome."
117- adb push ${DEVICE_TARGET_ABS}/${DEVICE}/system/lib/libchrome.so /system/lib/
118-
119- # Clear logcat.
120- adb logcat -c
121-
122- # Run logcat with filters.
123- adb logcat bt_btif:D bt_btif_core:D bt_hci:D bt_main:D bt_vendor:D \
124- bte_logmsg:D command_packet:D dual_mode_controller:D event_packet:D \
125- hci_transport:D hci_handler:D packet:D packet_stream:D \
126- test_channel_transport:D vendor_manager:D *:S
127-fi
--- a/vendor_libs/test_vendor_lib/scripts/test_channel.py
+++ /dev/null
@@ -1,247 +0,0 @@
1-#
2-# Copyright 2015 The Android Open Source Project
3-#
4-# Licensed under the Apache License, Version 2.0 (the "License");
5-# you may not use this file except in compliance with the License.
6-# You may obtain a copy of the License at
7-#
8-# http://www.apache.org/licenses/LICENSE-2.0
9-#
10-# Unless required by applicable law or agreed to in writing, software
11-# distributed under the License is distributed on an "AS IS" BASIS,
12-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-# See the License for the specific language governing permissions and
14-# limitations under the License.
15-#
16-
17-"""Script for sending testing parameters and commands to a Bluetooth device.
18-
19-This script provides a simple shell interface for sending data at run-time to a
20-Bluetooth device. It is intended to be used in tandem with the test vendor
21-library project.
22-
23-Usage:
24- Option A: Script
25- 1. Run build_and_run.sh in scripts/ with the --test-channel flag set and the
26- port to use for the test channel.
27- Option B: Manual
28- 1. Choose a port to use for the test channel. Use 'adb forward tcp:<port>
29- tcp:<port>' to forward the port to the device.
30- 2. In a separate shell, build and push the test vendor library to the device
31- using the script mentioned in option A (i.e. without the --test-channel flag
32- set).
33- 3. Once logcat has started, turn Bluetooth on from the device.
34- 4. Run this program, in the shell from step 1, the port, also from step 1,
35- as arguments.
36-"""
37-
38-#!/usr/bin/env python
39-
40-import cmd
41-import random
42-import socket
43-import string
44-import struct
45-import sys
46-
47-DEVICE_NAME_LENGTH = 6
48-DEVICE_ADDRESS_LENGTH = 6
49-
50-# Used to generate fake device names and addresses during discovery.
51-def generate_random_name():
52- return ''.join(random.SystemRandom().choice(string.ascii_uppercase + \
53- string.digits) for _ in range(DEVICE_NAME_LENGTH))
54-
55-def generate_random_address():
56- return ''.join(random.SystemRandom().choice(string.digits) for _ in \
57- range(DEVICE_ADDRESS_LENGTH))
58-
59-class Connection(object):
60- """Simple wrapper class for a socket object.
61-
62- Attributes:
63- socket: The underlying socket created for the specified address and port.
64- """
65-
66- def __init__(self, port):
67- self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
68- self._socket.connect(('localhost', port))
69-
70- def close(self):
71- self._socket.close()
72-
73- def send(self, data):
74- self._socket.sendall(data)
75-
76-class TestChannel(object):
77- """Checks outgoing commands and sends them once verified.
78-
79- Attributes:
80- connection: The connection to the test vendor library that commands are sent
81- on.
82- """
83-
84- def __init__(self, port):
85- self._connection = Connection(port)
86- self._discovered_devices = DeviceManager()
87-
88- def discover_new_device(self, name=None, address=None):
89- device = Device(name, address)
90- self._discovered_devices.add_device(device)
91- return device
92-
93- def close(self):
94- self._connection.close()
95-
96- def send_command(self, name, args):
97- name_size = len(name)
98- args_size = len(args)
99- self.lint_command(name, args, name_size, args_size)
100- encoded_name = chr(name_size) + name
101- encoded_args = chr(args_size) + ''.join(chr(len(arg)) + arg for arg in args)
102- command = encoded_name + encoded_args
103- self._connection.send(command)
104-
105- def lint_command(self, name, args, name_size, args_size):
106- assert name_size == len(name) and args_size == len(args)
107- try:
108- name.encode('utf-8')
109- for arg in args:
110- arg.encode('utf-8')
111- except UnicodeError:
112- print 'Unrecognized characters.'
113- raise
114- if name_size > 255 or args_size > 255:
115- raise ValueError # Size must be encodable in one octet.
116- for arg in args:
117- if len(arg) > 255:
118- raise ValueError # Size must be encodable in one octet.
119-
120-class DeviceManager(object):
121- """Maintains the active fake devices that have been "discovered".
122-
123- Attributes:
124- device_list: Maps device addresses (keys) to devices (values).
125- """
126-
127- def __init__(self):
128- self.device_list = {}
129-
130- def add_device(self, device):
131- self.device_list[device.get_address()] = device
132-
133-class Device(object):
134- """A fake device to be returned in inquiry and scan results. Note that if an
135- explicit name or address is not provided, a random string of characters
136- is used.
137-
138- Attributes:
139- name: The device name for use in extended results.
140- address: The BD address of the device.
141- """
142-
143- def __init__(self, name=None, address=None):
144- # TODO(dennischeng): Generate device properties more robustly.
145- self._name = generate_random_name() if name is None else name
146- self._address = generate_random_address() if address is None else address
147-
148- def get_name(self):
149- return self._name
150-
151- def get_address(self):
152- return self._address
153-
154-class TestChannelShell(cmd.Cmd):
155- """Shell for sending test channel data to controller.
156-
157- Manages the test channel to the controller and defines a set of commands the
158- user can send to the controller as well. These commands are processed parallel
159- to commands sent from the device stack and used to provide additional
160- debugging/testing capabilities.
161-
162- Attributes:
163- test_channel: The communication channel to send data to the controller.
164- """
165-
166- def __init__(self, test_channel):
167- print 'Type \'help\' for more information.'
168- cmd.Cmd.__init__(self)
169- self._test_channel = test_channel
170-
171- def do_clear(self, args):
172- """
173- Arguments: None.
174- Resets the controller to its original, unmodified state.
175- """
176- self._test_channel.send_command('CLEAR', [])
177-
178- def do_clear_event_delay(self, args):
179- """
180- Arguments: None.
181- Clears the response delay set by set_event_delay.
182- """
183- self._test_channel.send_command('CLEAR_EVENT_DELAY', args.split())
184-
185- def do_discover(self, args):
186- """
187- Arguments: name_1 name_2 ...
188- Sends an inquiry result for named device(s). If no names are provided, a
189- random name is used instead.
190- """
191- if len(args) == 0:
192- args = generate_random_name()
193- device_list = [self._test_channel.discover_new_device(arg) for arg in \
194- args.split()]
195- device_names_and_addresses = []
196- for device in device_list:
197- device_names_and_addresses.append(device.get_name())
198- device_names_and_addresses.append(device.get_address())
199- self._test_channel.send_command('DISCOVER', device_names_and_addresses)
200-
201- def do_set_event_delay(self, args):
202- """
203- Arguments: interval_in_ms
204- Sets the response delay for all event packets sent from the controller back
205- to the HCI.
206- """
207- self._test_channel.send_command('SET_EVENT_DELAY', args.split())
208-
209- def do_timeout_all(self, args):
210- """
211- Arguments: None.
212- Causes all HCI commands to timeout.
213- """
214- self._test_channel.send_command('TIMEOUT_ALL', [])
215-
216- def do_quit(self, args):
217- """
218- Arguments: None.
219- Exits the test channel.
220- """
221- self._test_channel.send_command('CLOSE_TEST_CHANNEL', [])
222- self._test_channel.close()
223- print 'Goodbye.'
224- return True
225-
226-def main(argv):
227- if len(argv) != 2:
228- print 'Usage: python test_channel.py [port]'
229- return
230- try:
231- port = int(argv[1])
232- except ValueError:
233- print 'Error parsing port.'
234- else:
235- try:
236- test_channel = TestChannel(port)
237- except socket.error, e:
238- print 'Error connecting to socket: %s' % e
239- except:
240- print 'Error creating test channel (check argument).'
241- else:
242- test_channel_shell = TestChannelShell(test_channel)
243- test_channel_shell.prompt = '$ '
244- test_channel_shell.cmdloop()
245-
246-if __name__ == '__main__':
247- main(sys.argv)
--- a/vendor_libs/test_vendor_lib/src/bt_vendor.cc
+++ /dev/null
@@ -1,107 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "bt_vendor"
18-
19-#include "vendor_manager.h"
20-
21-#include "base/logging.h"
22-
23-extern "C" {
24-#include "osi/include/log.h"
25-
26-#include <unistd.h>
27-} // extern "C"
28-
29-namespace test_vendor_lib {
30-
31-// Initializes vendor manager for test controller. |p_cb| are the callbacks to
32-// be in TestVendorOp(). |local_bdaddr| points to the address of the Bluetooth
33-// device. Returns 0 on success, -1 on error.
34-static int TestVendorInitialize(const bt_vendor_callbacks_t* p_cb,
35- unsigned char* /* local_bdaddr */) {
36- LOG_INFO(LOG_TAG, "Initializing test controller.");
37- CHECK(p_cb);
38-
39- VendorManager::Initialize();
40- VendorManager* manager = VendorManager::Get();
41- manager->SetVendorCallbacks(*(const_cast<bt_vendor_callbacks_t*>(p_cb)));
42- return manager->Run() ? 0 : -1;
43-}
44-
45-// Vendor specific operations. |opcode| is the opcode for Bluedroid's vendor op
46-// definitions. |param| points to operation specific arguments. Return value is
47-// dependent on the operation invoked, or -1 on error.
48-static int TestVendorOp(bt_vendor_opcode_t opcode, void* param) {
49- LOG_INFO(LOG_TAG, "Opcode received in vendor library: %d", opcode);
50-
51- VendorManager* manager = VendorManager::Get();
52- CHECK(manager);
53-
54- switch (opcode) {
55- case BT_VND_OP_POWER_CTRL: {
56- LOG_INFO(LOG_TAG, "Doing op: BT_VND_OP_POWER_CTRL");
57- int* state = static_cast<int*>(param);
58- if (*state == BT_VND_PWR_OFF)
59- LOG_INFO(LOG_TAG, "Turning Bluetooth off.");
60- else if (*state == BT_VND_PWR_ON)
61- LOG_INFO(LOG_TAG, "Turning Bluetooth on.");
62- return 0;
63- }
64-
65- // Give the HCI its fd to communicate with the HciTransport.
66- case BT_VND_OP_USERIAL_OPEN: {
67- LOG_INFO(LOG_TAG, "Doing op: BT_VND_OP_USERIAL_OPEN");
68- int* fd_list = static_cast<int*>(param);
69- fd_list[0] = manager->GetHciFd();
70- LOG_INFO(LOG_TAG, "Setting HCI's fd to: %d", fd_list[0]);
71- return 1;
72- }
73-
74- // Close the HCI's file descriptor.
75- case BT_VND_OP_USERIAL_CLOSE:
76- LOG_INFO(LOG_TAG, "Doing op: BT_VND_OP_USERIAL_CLOSE");
77- LOG_INFO(LOG_TAG, "Closing HCI's fd (fd: %d)", manager->GetHciFd());
78- manager->CloseHciFd();
79- return 1;
80-
81- case BT_VND_OP_FW_CFG:
82- LOG_INFO(LOG_TAG, "Unsupported op: BT_VND_OP_FW_CFG");
83- manager->GetVendorCallbacks().fwcfg_cb(BT_VND_OP_RESULT_FAIL);
84- return -1;
85-
86- default:
87- LOG_INFO(LOG_TAG, "Op not recognized.");
88- return -1;
89- }
90- return 0;
91-}
92-
93-// Closes the vendor interface and cleans up the global vendor manager object.
94-static void TestVendorCleanUp(void) {
95- LOG_INFO(LOG_TAG, "Cleaning up vendor library.");
96- VendorManager::CleanUp();
97-}
98-
99-} // namespace test_vendor_lib
100-
101-// Entry point of DLib.
102-const bt_vendor_interface_t BLUETOOTH_VENDOR_LIB_INTERFACE = {
103- sizeof(bt_vendor_interface_t),
104- test_vendor_lib::TestVendorInitialize,
105- test_vendor_lib::TestVendorOp,
106- test_vendor_lib::TestVendorCleanUp
107-};
--- a/vendor_libs/test_vendor_lib/src/command_packet.cc
+++ /dev/null
@@ -1,43 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "command_packet"
18-
19-#include "vendor_libs/test_vendor_lib/include/command_packet.h"
20-
21-extern "C" {
22-#include "hci/include/hci_hal.h"
23-#include "osi/include/log.h"
24-#include "stack/include/hcidefs.h"
25-} // extern "C"
26-
27-namespace test_vendor_lib {
28-
29-CommandPacket::CommandPacket() : Packet(DATA_TYPE_COMMAND) {}
30-
31-uint16_t CommandPacket::GetOpcode() const {
32- return 0 | (GetHeader()[0] | (GetHeader()[1] << 8));
33-}
34-
35-uint8_t CommandPacket::GetOGF() const {
36- return HCI_OGF(GetOpcode());
37-}
38-
39-uint16_t CommandPacket::GetOCF() const {
40- return HCI_OCF(GetOpcode());
41-}
42-
43-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/src/dual_mode_controller.cc
+++ /dev/null
@@ -1,561 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "dual_mode_controller"
18-
19-#include "vendor_libs/test_vendor_lib/include/dual_mode_controller.h"
20-
21-#include "base/logging.h"
22-#include "base/files/file_util.h"
23-#include "base/json/json_reader.h"
24-#include "base/values.h"
25-#include "vendor_libs/test_vendor_lib/include/event_packet.h"
26-#include "vendor_libs/test_vendor_lib/include/hci_transport.h"
27-
28-extern "C" {
29-#include "stack/include/hcidefs.h"
30-#include "osi/include/log.h"
31-} // extern "C"
32-
33-namespace {
34-
35-// Included in certain events to indicate success (specific to the event
36-// context).
37-const uint8_t kSuccessStatus = 0;
38-
39-// The default number encoded in event packets to indicate to the HCI how many
40-// command packets it can send to the controller.
41-const uint8_t kNumHciCommandPackets = 1;
42-
43-// The location of the config file loaded to populate controller attributes.
44-const std::string kControllerPropertiesFile =
45- "/etc/bluetooth/controller_properties.json";
46-
47-// Inquiry modes for specifiying inquiry result formats.
48-const uint8_t kStandardInquiry = 0x00;
49-const uint8_t kRssiInquiry = 0x01;
50-const uint8_t kExtendedOrRssiInquiry = 0x02;
51-
52-// The bd address of another (fake) device.
53-const std::vector<uint8_t> kOtherDeviceBdAddress = {6, 5, 4, 3, 2, 1};
54-
55-// Fake inquiry response for a fake device.
56-const std::vector<uint8_t> kPageScanRepetitionMode = {0};
57-const std::vector<uint8_t> kPageScanPeriodMode = {0};
58-const std::vector<uint8_t> kPageScanMode = {0};
59-const std::vector<uint8_t> kClassOfDevice = {1, 2, 3};
60-const std::vector<uint8_t> kClockOffset = {1, 2};
61-
62-void LogCommand(const char* command) {
63- LOG_INFO(LOG_TAG, "Controller performing command: %s", command);
64-}
65-
66-// Functions used by JSONValueConverter to read stringified JSON into Properties
67-// object.
68-bool ParseUint8t(const base::StringPiece& value, uint8_t* field) {
69- *field = std::stoi(value.as_string());
70- return true;
71-}
72-
73-bool ParseUint16t(const base::StringPiece& value, uint16_t* field) {
74- *field = std::stoi(value.as_string());
75- return true;
76-}
77-
78-bool ParseUint8tVector(const base::StringPiece& value,
79- std::vector<uint8_t>* field) {
80- for (char& c : value.as_string())
81- field->push_back(c - '0');
82- return true;
83-}
84-
85-} // namespace
86-
87-namespace test_vendor_lib {
88-
89-void DualModeController::SendCommandComplete(
90- uint16_t command_opcode,
91- const std::vector<uint8_t>& return_parameters) const {
92- std::unique_ptr<EventPacket> command_complete =
93- EventPacket::CreateCommandCompleteEvent(
94- kNumHciCommandPackets, command_opcode, return_parameters);
95- send_event_(std::move(command_complete));
96-}
97-
98-void DualModeController::SendCommandCompleteSuccess(
99- uint16_t command_opcode) const {
100- SendCommandComplete(command_opcode, {kSuccessStatus});
101-}
102-
103-void DualModeController::SendCommandStatus(uint8_t status,
104- uint16_t command_opcode) const {
105- std::unique_ptr<EventPacket> command_status =
106- EventPacket::CreateCommandStatusEvent(status, kNumHciCommandPackets,
107- command_opcode);
108- send_event_(std::move(command_status));
109-}
110-
111-void DualModeController::SendCommandStatusSuccess(
112- uint16_t command_opcode) const {
113- SendCommandStatus(kSuccessStatus, command_opcode);
114-}
115-
116-void DualModeController::SendInquiryResult() const {
117- std::unique_ptr<EventPacket> inquiry_result =
118- EventPacket::CreateInquiryResultEvent(
119- 1, kOtherDeviceBdAddress, kPageScanRepetitionMode,
120- kPageScanPeriodMode, kPageScanMode, kClassOfDevice, kClockOffset);
121- send_event_(std::move(inquiry_result));
122-}
123-
124-void DualModeController::SendExtendedInquiryResult(
125- const std::string& name, const std::string& address) const {
126- std::vector<uint8_t> rssi = {0};
127- std::vector<uint8_t> extended_inquiry_data = {name.length() + 1, 0x09};
128- std::copy(name.begin(), name.end(),
129- std::back_inserter(extended_inquiry_data));
130- std::vector<uint8_t> bd_address(address.begin(), address.end());
131- // TODO(dennischeng): Use constants for parameter sizes, here and elsewhere.
132- while (extended_inquiry_data.size() < 240) {
133- extended_inquiry_data.push_back(0);
134- }
135- std::unique_ptr<EventPacket> extended_inquiry_result =
136- EventPacket::CreateExtendedInquiryResultEvent(
137- bd_address, kPageScanRepetitionMode, kPageScanPeriodMode,
138- kClassOfDevice, kClockOffset, rssi, extended_inquiry_data);
139- send_event_(std::move(extended_inquiry_result));
140-}
141-
142-DualModeController::DualModeController()
143- : state_(kStandby),
144- test_channel_state_(kNone),
145- properties_(kControllerPropertiesFile) {
146-#define SET_HANDLER(opcode, method) \
147- active_hci_commands_[opcode] = \
148- std::bind(&DualModeController::method, this, std::placeholders::_1);
149- SET_HANDLER(HCI_RESET, HciReset);
150- SET_HANDLER(HCI_READ_BUFFER_SIZE, HciReadBufferSize);
151- SET_HANDLER(HCI_HOST_BUFFER_SIZE, HciHostBufferSize);
152- SET_HANDLER(HCI_READ_LOCAL_VERSION_INFO, HciReadLocalVersionInformation);
153- SET_HANDLER(HCI_READ_BD_ADDR, HciReadBdAddr);
154- SET_HANDLER(HCI_READ_LOCAL_SUPPORTED_CMDS, HciReadLocalSupportedCommands);
155- SET_HANDLER(HCI_READ_LOCAL_EXT_FEATURES, HciReadLocalExtendedFeatures);
156- SET_HANDLER(HCI_WRITE_SIMPLE_PAIRING_MODE, HciWriteSimplePairingMode);
157- SET_HANDLER(HCI_WRITE_LE_HOST_SUPPORT, HciWriteLeHostSupport);
158- SET_HANDLER(HCI_SET_EVENT_MASK, HciSetEventMask);
159- SET_HANDLER(HCI_WRITE_INQUIRY_MODE, HciWriteInquiryMode);
160- SET_HANDLER(HCI_WRITE_PAGESCAN_TYPE, HciWritePageScanType);
161- SET_HANDLER(HCI_WRITE_INQSCAN_TYPE, HciWriteInquiryScanType);
162- SET_HANDLER(HCI_WRITE_CLASS_OF_DEVICE, HciWriteClassOfDevice);
163- SET_HANDLER(HCI_WRITE_PAGE_TOUT, HciWritePageTimeout);
164- SET_HANDLER(HCI_WRITE_DEF_POLICY_SETTINGS, HciWriteDefaultLinkPolicySettings);
165- SET_HANDLER(HCI_READ_LOCAL_NAME, HciReadLocalName);
166- SET_HANDLER(HCI_CHANGE_LOCAL_NAME, HciWriteLocalName);
167- SET_HANDLER(HCI_WRITE_EXT_INQ_RESPONSE, HciWriteExtendedInquiryResponse);
168- SET_HANDLER(HCI_WRITE_VOICE_SETTINGS, HciWriteVoiceSetting);
169- SET_HANDLER(HCI_WRITE_CURRENT_IAC_LAP, HciWriteCurrentIacLap);
170- SET_HANDLER(HCI_WRITE_INQUIRYSCAN_CFG, HciWriteInquiryScanActivity);
171- SET_HANDLER(HCI_WRITE_SCAN_ENABLE, HciWriteScanEnable);
172- SET_HANDLER(HCI_SET_EVENT_FILTER, HciSetEventFilter);
173- SET_HANDLER(HCI_INQUIRY, HciInquiry);
174- SET_HANDLER(HCI_INQUIRY_CANCEL, HciInquiryCancel);
175- SET_HANDLER(HCI_DELETE_STORED_LINK_KEY, HciDeleteStoredLinkKey);
176- SET_HANDLER(HCI_RMT_NAME_REQUEST, HciRemoteNameRequest);
177-#undef SET_HANDLER
178-
179-#define SET_TEST_HANDLER(command_name, method) \
180- active_test_channel_commands_[command_name] = \
181- std::bind(&DualModeController::method, this, std::placeholders::_1);
182- SET_TEST_HANDLER("CLEAR", TestChannelClear);
183- SET_TEST_HANDLER("CLEAR_EVENT_DELAY", TestChannelClearEventDelay);
184- SET_TEST_HANDLER("DISCOVER", TestChannelDiscover);
185- SET_TEST_HANDLER("SET_EVENT_DELAY", TestChannelSetEventDelay);
186- SET_TEST_HANDLER("TIMEOUT_ALL", TestChannelTimeoutAll);
187-#undef SET_TEST_HANDLER
188-}
189-
190-void DualModeController::RegisterHandlersWithHciTransport(
191- HciTransport& transport) {
192- transport.RegisterCommandHandler(std::bind(&DualModeController::HandleCommand,
193- this, std::placeholders::_1));
194-}
195-
196-void DualModeController::RegisterHandlersWithTestChannelTransport(
197- TestChannelTransport& transport) {
198- transport.RegisterCommandHandler(
199- std::bind(&DualModeController::HandleTestChannelCommand, this,
200- std::placeholders::_1, std::placeholders::_2));
201-}
202-
203-void DualModeController::HandleTestChannelCommand(
204- const std::string& name, const std::vector<std::string>& args) {
205- if (active_test_channel_commands_.count(name) == 0)
206- return;
207- active_test_channel_commands_[name](args);
208-}
209-
210-void DualModeController::HandleCommand(
211- std::unique_ptr<CommandPacket> command_packet) {
212- uint16_t opcode = command_packet->GetOpcode();
213- LOG_INFO(LOG_TAG, "Command opcode: 0x%04X, OGF: 0x%04X, OCF: 0x%04X", opcode,
214- command_packet->GetOGF(), command_packet->GetOCF());
215-
216- // The command hasn't been registered with the handler yet. There is nothing
217- // to do.
218- if (active_hci_commands_.count(opcode) == 0)
219- return;
220- else if (test_channel_state_ == kTimeoutAll)
221- return;
222- active_hci_commands_[opcode](command_packet->GetPayload());
223-}
224-
225-void DualModeController::RegisterEventChannel(
226- std::function<void(std::unique_ptr<EventPacket>)> callback) {
227- send_event_ = callback;
228-}
229-
230-void DualModeController::RegisterDelayedEventChannel(
231- std::function<void(std::unique_ptr<EventPacket>, base::TimeDelta)>
232- callback) {
233- send_delayed_event_ = callback;
234- SetEventDelay(0);
235-}
236-
237-void DualModeController::SetEventDelay(int64_t delay) {
238- if (delay < 0)
239- delay = 0;
240- send_event_ = std::bind(send_delayed_event_, std::placeholders::_1,
241- base::TimeDelta::FromMilliseconds(delay));
242-}
243-
244-void DualModeController::TestChannelClear(
245- const std::vector<std::string>& args) {
246- LogCommand("TestChannel Clear");
247- test_channel_state_ = kNone;
248- SetEventDelay(0);
249-}
250-
251-void DualModeController::TestChannelDiscover(
252- const std::vector<std::string>& args) {
253- LogCommand("TestChannel Discover");
254- for (size_t i = 0; i < args.size()-1; i+=2)
255- SendExtendedInquiryResult(args[i], args[i+1]);
256-}
257-
258-void DualModeController::TestChannelTimeoutAll(
259- const std::vector<std::string>& args) {
260- LogCommand("TestChannel Timeout All");
261- test_channel_state_ = kTimeoutAll;
262-}
263-
264-void DualModeController::TestChannelSetEventDelay(
265- const std::vector<std::string>& args) {
266- LogCommand("TestChannel Set Event Delay");
267- test_channel_state_ = kDelayedResponse;
268- SetEventDelay(std::stoi(args[0]));
269-}
270-
271-void DualModeController::TestChannelClearEventDelay(
272- const std::vector<std::string>& args) {
273- LogCommand("TestChannel Clear Event Delay");
274- test_channel_state_ = kNone;
275- SetEventDelay(0);
276-}
277-
278-void DualModeController::HciReset(const std::vector<uint8_t>& /* args */) {
279- LogCommand("Reset");
280- state_ = kStandby;
281- SendCommandCompleteSuccess(HCI_RESET);
282-}
283-
284-void DualModeController::HciReadBufferSize(
285- const std::vector<uint8_t>& /* args */) {
286- LogCommand("Read Buffer Size");
287- SendCommandComplete(HCI_READ_BUFFER_SIZE, properties_.GetBufferSize());
288-}
289-
290-void DualModeController::HciHostBufferSize(
291- const std::vector<uint8_t>& /* args */) {
292- LogCommand("Host Buffer Size");
293- SendCommandCompleteSuccess(HCI_HOST_BUFFER_SIZE);
294-}
295-
296-void DualModeController::HciReadLocalVersionInformation(
297- const std::vector<uint8_t>& /* args */) {
298- LogCommand("Read Local Version Information");
299- SendCommandComplete(HCI_READ_LOCAL_VERSION_INFO,
300- properties_.GetLocalVersionInformation());
301-}
302-
303-void DualModeController::HciReadBdAddr(const std::vector<uint8_t>& /* args */) {
304- LogCommand("Read Bd Addr");
305- std::vector<uint8_t> bd_address_with_status = properties_.GetBdAddress();
306- bd_address_with_status.insert(bd_address_with_status.begin(),
307- kSuccessStatus);
308- SendCommandComplete(HCI_READ_BD_ADDR, bd_address_with_status);
309-}
310-
311-void DualModeController::HciReadLocalSupportedCommands(
312- const std::vector<uint8_t>& /* args */) {
313- LogCommand("Read Local Supported Commands");
314- SendCommandComplete(HCI_READ_LOCAL_SUPPORTED_CMDS,
315- properties_.GetLocalSupportedCommands());
316-}
317-
318-void DualModeController::HciReadLocalExtendedFeatures(
319- const std::vector<uint8_t>& args) {
320- LogCommand("Read Local Extended Features");
321- SendCommandComplete(HCI_READ_LOCAL_EXT_FEATURES,
322- properties_.GetLocalExtendedFeatures(args[0]));
323-}
324-
325-void DualModeController::HciWriteSimplePairingMode(
326- const std::vector<uint8_t>& /* args */) {
327- LogCommand("Write Simple Pairing Mode");
328- SendCommandCompleteSuccess(HCI_WRITE_SIMPLE_PAIRING_MODE);
329-}
330-
331-void DualModeController::HciWriteLeHostSupport(
332- const std::vector<uint8_t>& /* args */) {
333- LogCommand("Write Le Host Support");
334- SendCommandCompleteSuccess(HCI_WRITE_LE_HOST_SUPPORT);
335-}
336-
337-void DualModeController::HciSetEventMask(
338- const std::vector<uint8_t>& /* args */) {
339- LogCommand("Set Event Mask");
340- SendCommandCompleteSuccess(HCI_SET_EVENT_MASK);
341-}
342-
343-void DualModeController::HciWriteInquiryMode(const std::vector<uint8_t>& args) {
344- LogCommand("Write Inquiry Mode");
345- CHECK(args.size() == 1);
346- inquiry_mode_ = args[0];
347- SendCommandCompleteSuccess(HCI_WRITE_INQUIRY_MODE);
348-}
349-
350-void DualModeController::HciWritePageScanType(
351- const std::vector<uint8_t>& /* args */) {
352- LogCommand("Write Page Scan Type");
353- SendCommandCompleteSuccess(HCI_WRITE_PAGESCAN_TYPE);
354-}
355-
356-void DualModeController::HciWriteInquiryScanType(
357- const std::vector<uint8_t>& /* args */) {
358- LogCommand("Write Inquiry Scan Type");
359- SendCommandCompleteSuccess(HCI_WRITE_INQSCAN_TYPE);
360-}
361-
362-void DualModeController::HciWriteClassOfDevice(
363- const std::vector<uint8_t>& /* args */) {
364- LogCommand("Write Class Of Device");
365- SendCommandCompleteSuccess(HCI_WRITE_CLASS_OF_DEVICE);
366-}
367-
368-void DualModeController::HciWritePageTimeout(
369- const std::vector<uint8_t>& /* args */) {
370- LogCommand("Write Page Timeout");
371- SendCommandCompleteSuccess(HCI_WRITE_PAGE_TOUT);
372-}
373-
374-void DualModeController::HciWriteDefaultLinkPolicySettings(
375- const std::vector<uint8_t>& /* args */) {
376- LogCommand("Write Default Link Policy Settings");
377- SendCommandCompleteSuccess(HCI_WRITE_DEF_POLICY_SETTINGS);
378-}
379-
380-void DualModeController::HciReadLocalName(
381- const std::vector<uint8_t>& /* args */) {
382- LogCommand("Get Local Name");
383- SendCommandComplete(HCI_READ_LOCAL_NAME, properties_.GetLocalName());
384-}
385-
386-void DualModeController::HciWriteLocalName(
387- const std::vector<uint8_t>& /* args */) {
388- LogCommand("Write Local Name");
389- SendCommandCompleteSuccess(HCI_CHANGE_LOCAL_NAME);
390-}
391-
392-void DualModeController::HciWriteExtendedInquiryResponse(
393- const std::vector<uint8_t>& /* args */) {
394- LogCommand("Write Extended Inquiry Response");
395- SendCommandCompleteSuccess(HCI_WRITE_EXT_INQ_RESPONSE);
396-}
397-
398-void DualModeController::HciWriteVoiceSetting(
399- const std::vector<uint8_t>& /* args */) {
400- LogCommand("Write Voice Setting");
401- SendCommandCompleteSuccess(HCI_WRITE_VOICE_SETTINGS);
402-}
403-
404-void DualModeController::HciWriteCurrentIacLap(
405- const std::vector<uint8_t>& /* args */) {
406- LogCommand("Write Current IAC LAP");
407- SendCommandCompleteSuccess(HCI_WRITE_CURRENT_IAC_LAP);
408-}
409-
410-void DualModeController::HciWriteInquiryScanActivity(
411- const std::vector<uint8_t>& /* args */) {
412- LogCommand("Write Inquiry Scan Activity");
413- SendCommandCompleteSuccess(HCI_WRITE_INQUIRYSCAN_CFG);
414-}
415-
416-void DualModeController::HciWriteScanEnable(
417- const std::vector<uint8_t>& /* args */) {
418- LogCommand("Write Scan Enable");
419- SendCommandCompleteSuccess(HCI_WRITE_SCAN_ENABLE);
420-}
421-
422-void DualModeController::HciSetEventFilter(
423- const std::vector<uint8_t>& /* args */) {
424- LogCommand("Set Event Filter");
425- SendCommandCompleteSuccess(HCI_SET_EVENT_FILTER);
426-}
427-
428-void DualModeController::HciInquiry(const std::vector<uint8_t>& /* args */) {
429- LogCommand("Inquiry");
430- state_ = kInquiry;
431- SendCommandStatusSuccess(HCI_INQUIRY);
432- switch (inquiry_mode_) {
433- case (kStandardInquiry):
434- SendInquiryResult();
435- break;
436-
437- case (kRssiInquiry):
438- LOG_INFO(LOG_TAG, "RSSI Inquiry Mode currently not supported.");
439- break;
440-
441- case (kExtendedOrRssiInquiry):
442- SendExtendedInquiryResult("FooBar", "123456");
443- break;
444- }
445-}
446-
447-void DualModeController::HciInquiryCancel(
448- const std::vector<uint8_t>& /* args */) {
449- LogCommand("Inquiry Cancel");
450- CHECK(state_ == kInquiry);
451- state_ = kStandby;
452- SendCommandCompleteSuccess(HCI_INQUIRY_CANCEL);
453-}
454-
455-void DualModeController::HciDeleteStoredLinkKey(
456- const std::vector<uint8_t>& args) {
457- LogCommand("Delete Stored Link Key");
458- /* Check the last octect in |args|. If it is 0, delete only the link key for
459- * the given BD_ADDR. If is is 1, delete all stored link keys. */
460- SendCommandComplete(HCI_DELETE_STORED_LINK_KEY, {1});
461-}
462-
463-void DualModeController::HciRemoteNameRequest(
464- const std::vector<uint8_t>& args) {
465- LogCommand("Remote Name Request");
466- SendCommandStatusSuccess(HCI_RMT_NAME_REQUEST);
467-}
468-
469-DualModeController::Properties::Properties(const std::string& file_name)
470- : local_supported_commands_size_(64), local_name_size_(248) {
471- std::string properties_raw;
472- if (!base::ReadFileToString(base::FilePath(file_name), &properties_raw))
473- LOG_INFO(LOG_TAG, "Error reading controller properties from file.");
474-
475- scoped_ptr<base::Value> properties_value_ptr =
476- base::JSONReader::Read(properties_raw);
477- if (properties_value_ptr.get() == nullptr)
478- LOG_INFO(LOG_TAG,
479- "Error controller properties may consist of ill-formed JSON.");
480-
481- // Get the underlying base::Value object, which is of type
482- // base::Value::TYPE_DICTIONARY, and read it into member variables.
483- base::Value& properties_dictionary = *(properties_value_ptr.get());
484- base::JSONValueConverter<DualModeController::Properties> converter;
485-
486- if (!converter.Convert(properties_dictionary, this))
487- LOG_INFO(LOG_TAG,
488- "Error converting JSON properties into Properties object.");
489-}
490-
491-const std::vector<uint8_t> DualModeController::Properties::GetBufferSize() {
492- return std::vector<uint8_t>(
493- {kSuccessStatus, acl_data_packet_size_, acl_data_packet_size_ >> 8,
494- sco_data_packet_size_, num_acl_data_packets_, num_acl_data_packets_ >> 8,
495- num_sco_data_packets_, num_sco_data_packets_ >> 8});
496-}
497-
498-const std::vector<uint8_t>
499-DualModeController::Properties::GetLocalVersionInformation() {
500- return std::vector<uint8_t>({kSuccessStatus, version_, revision_,
501- revision_ >> 8, lmp_pal_version_,
502- manufacturer_name_, manufacturer_name_ >> 8,
503- lmp_pal_subversion_, lmp_pal_subversion_ >> 8});
504-}
505-
506-const std::vector<uint8_t> DualModeController::Properties::GetBdAddress() {
507- return bd_address_;
508-}
509-
510-const std::vector<uint8_t>
511-DualModeController::Properties::GetLocalExtendedFeatures(uint8_t page_number) {
512- return std::vector<uint8_t>({kSuccessStatus, page_number,
513- maximum_page_number_, 0xFF, 0xFF, 0xFF, 0xFF,
514- 0xFF, 0xFF, 0xFF, 0xFF});
515-}
516-
517-const std::vector<uint8_t>
518-DualModeController::Properties::GetLocalSupportedCommands() {
519- std::vector<uint8_t> local_supported_commands;
520- local_supported_commands.push_back(kSuccessStatus);
521- for (uint8_t i = 0; i < local_supported_commands_size_; ++i)
522- local_supported_commands.push_back(0xFF);
523- return local_supported_commands;
524-}
525-
526-const std::vector<uint8_t> DualModeController::Properties::GetLocalName() {
527- std::vector<uint8_t> local_name;
528- local_name.push_back(kSuccessStatus);
529- for (uint8_t i = 0; i < local_name_size_; ++i)
530- local_name.push_back(0xFF);
531- return local_name;
532-}
533-
534-// static
535-void DualModeController::Properties::RegisterJSONConverter(
536- base::JSONValueConverter<DualModeController::Properties>* converter) {
537- // TODO(dennischeng): Use RegisterIntField() here?
538-#define REGISTER_UINT8_T(field_name, field) \
539- converter->RegisterCustomField<uint8_t>( \
540- field_name, &DualModeController::Properties::field, &ParseUint8t);
541-#define REGISTER_UINT16_T(field_name, field) \
542- converter->RegisterCustomField<uint16_t>( \
543- field_name, &DualModeController::Properties::field, &ParseUint16t);
544- REGISTER_UINT16_T("AclDataPacketSize", acl_data_packet_size_);
545- REGISTER_UINT8_T("ScoDataPacketSize", sco_data_packet_size_);
546- REGISTER_UINT16_T("NumAclDataPackets", num_acl_data_packets_);
547- REGISTER_UINT16_T("NumScoDataPackets", num_sco_data_packets_);
548- REGISTER_UINT8_T("Version", version_);
549- REGISTER_UINT16_T("Revision", revision_);
550- REGISTER_UINT8_T("LmpPalVersion", lmp_pal_version_);
551- REGISTER_UINT16_T("ManufacturerName", manufacturer_name_);
552- REGISTER_UINT16_T("LmpPalSubversion", lmp_pal_subversion_);
553- REGISTER_UINT8_T("MaximumPageNumber", maximum_page_number_);
554- converter->RegisterCustomField<std::vector<uint8_t>>(
555- "BdAddress", &DualModeController::Properties::bd_address_,
556- &ParseUint8tVector);
557-#undef REGISTER_UINT8_T
558-#undef REGISTER_UINT16_T
559-}
560-
561-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/src/event_packet.cc
+++ /dev/null
@@ -1,131 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "event_packet"
18-
19-#define VECTOR_COPY_TO_END(source, destination) \
20- std::copy(source.begin(), source.end(), std::back_inserter(destination));
21-
22-#include "vendor_libs/test_vendor_lib/include/event_packet.h"
23-
24-extern "C" {
25-#include "osi/include/log.h"
26-#include "stack/include/hcidefs.h"
27-} // extern "C"
28-
29-namespace test_vendor_lib {
30-
31-EventPacket::EventPacket(uint8_t event_code,
32- const std::vector<uint8_t>& payload)
33- : Packet(DATA_TYPE_EVENT) {
34- Encode({event_code, static_cast<uint8_t>(payload.size())}, payload);
35-}
36-
37-uint8_t EventPacket::GetEventCode() const {
38- return GetHeader()[0];
39-}
40-
41-// static
42-std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteEvent(
43- uint8_t num_hci_command_packets, uint16_t command_opcode,
44- const std::vector<uint8_t>& event_return_parameters) {
45- size_t payload_size = sizeof(num_hci_command_packets) +
46- sizeof(command_opcode) + event_return_parameters.size();
47-
48- std::vector<uint8_t> payload;
49- payload.reserve(payload_size);
50- payload.push_back(num_hci_command_packets);
51- payload.push_back(command_opcode);
52- payload.push_back(command_opcode >> 8);
53- VECTOR_COPY_TO_END(event_return_parameters, payload);
54-
55- return std::unique_ptr<EventPacket>(
56- new EventPacket(HCI_COMMAND_COMPLETE_EVT, payload));
57-}
58-
59-// static
60-std::unique_ptr<EventPacket> EventPacket::CreateCommandStatusEvent(
61- uint8_t status, uint8_t num_hci_command_packets, uint16_t command_opcode) {
62- size_t payload_size =
63- sizeof(status) + sizeof(num_hci_command_packets) + sizeof(command_opcode);
64-
65- std::vector<uint8_t> payload;
66- payload.reserve(payload_size);
67- payload.push_back(status);
68- payload.push_back(num_hci_command_packets);
69- payload.push_back(command_opcode);
70- payload.push_back(command_opcode >> 8);
71-
72- return std::unique_ptr<EventPacket>(
73- new EventPacket(HCI_COMMAND_STATUS_EVT, payload));
74-}
75-
76-//static
77-std::unique_ptr<EventPacket> EventPacket::CreateInquiryResultEvent(
78- uint8_t num_responses, const std::vector<uint8_t>& bd_addresses,
79- const std::vector<uint8_t>& page_scan_repetition_mode,
80- const std::vector<uint8_t>& page_scan_period_mode,
81- const std::vector<uint8_t>& page_scan_mode,
82- const std::vector<uint8_t>& class_of_device,
83- const std::vector<uint8_t>& clock_offset) {
84- size_t payload_size = sizeof(num_responses) + bd_addresses.size() +
85- page_scan_repetition_mode.size() +
86- page_scan_period_mode.size() + page_scan_mode.size() +
87- class_of_device.size() + clock_offset.size();
88-
89- std::vector<uint8_t> payload;
90- payload.reserve(payload_size);
91- payload.push_back(num_responses);
92- VECTOR_COPY_TO_END(bd_addresses, payload);
93- VECTOR_COPY_TO_END(page_scan_repetition_mode, payload);
94- VECTOR_COPY_TO_END(page_scan_mode, payload);
95- VECTOR_COPY_TO_END(class_of_device, payload);
96- VECTOR_COPY_TO_END(clock_offset, payload);
97-
98- return std::unique_ptr<EventPacket>(
99- new EventPacket(HCI_INQUIRY_RESULT_EVT, payload));
100-}
101-
102-//static
103-std::unique_ptr<EventPacket> EventPacket::CreateExtendedInquiryResultEvent(
104- const std::vector<uint8_t>& bd_address,
105- const std::vector<uint8_t>& page_scan_repetition_mode,
106- const std::vector<uint8_t>& page_scan_period_mode,
107- const std::vector<uint8_t>& class_of_device,
108- const std::vector<uint8_t>& clock_offset,
109- const std::vector<uint8_t>& rssi,
110- const std::vector<uint8_t>& extended_inquiry_response) {
111- size_t payload_size =
112- 1 + bd_address.size() + page_scan_repetition_mode.size() +
113- page_scan_period_mode.size() + class_of_device.size() +
114- clock_offset.size() + rssi.size() + extended_inquiry_response.size();
115-
116- std::vector<uint8_t> payload;
117- payload.reserve(payload_size);
118- payload.push_back(1); // Each extended inquiry result contains one device.
119- VECTOR_COPY_TO_END(bd_address, payload);
120- VECTOR_COPY_TO_END(page_scan_repetition_mode, payload);
121- VECTOR_COPY_TO_END(page_scan_period_mode, payload);
122- VECTOR_COPY_TO_END(class_of_device, payload);
123- VECTOR_COPY_TO_END(clock_offset, payload);
124- VECTOR_COPY_TO_END(rssi, payload);
125- VECTOR_COPY_TO_END(extended_inquiry_response, payload);
126-
127- return std::unique_ptr<EventPacket>(
128- new EventPacket(HCI_EXTENDED_INQUIRY_RESULT_EVT, payload));
129-}
130-
131-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/src/hci_transport.cc
+++ /dev/null
@@ -1,173 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "hci_transport"
18-
19-#include "vendor_libs/test_vendor_lib/include/hci_transport.h"
20-
21-#include "base/logging.h"
22-#include "base/bind.h"
23-#include "base/thread_task_runner_handle.h"
24-
25-extern "C" {
26-#include <inttypes.h>
27-#include <sys/socket.h>
28-#include "stack/include/hcidefs.h"
29-#include "osi/include/log.h"
30-} // extern "C"
31-
32-namespace test_vendor_lib {
33-
34-HciTransport::HciTransport() : weak_ptr_factory_(this) {}
35-
36-void HciTransport::CloseHciFd() {
37- hci_fd_.reset(nullptr);
38-}
39-
40-void HciTransport::CloseVendorFd() {
41- vendor_fd_.reset(nullptr);
42-}
43-
44-int HciTransport::GetHciFd() const {
45- return hci_fd_->get();
46-}
47-
48-int HciTransport::GetVendorFd() const {
49- return vendor_fd_->get();
50-}
51-
52-bool HciTransport::SetUp() {
53- int socketpair_fds[2];
54- // TODO(dennischeng): Use SOCK_SEQPACKET here.
55- const int success = socketpair(AF_LOCAL, SOCK_STREAM, 0, socketpair_fds);
56- if (success < 0)
57- return false;
58- hci_fd_.reset(new base::ScopedFD(socketpair_fds[0]));
59- vendor_fd_.reset(new base::ScopedFD(socketpair_fds[1]));
60- return true;
61-}
62-
63-void HciTransport::OnFileCanReadWithoutBlocking(int fd) {
64- CHECK(fd == GetVendorFd());
65- LOG_INFO(LOG_TAG, "Event ready in HciTransport on fd: %d.", fd);
66-
67- const serial_data_type_t packet_type = packet_stream_.ReceivePacketType(fd);
68- switch (packet_type) {
69- case (DATA_TYPE_COMMAND): {
70- ReceiveReadyCommand();
71- break;
72- }
73-
74- case (DATA_TYPE_ACL): {
75- LOG_INFO(LOG_TAG, "ACL data packets not currently supported.");
76- break;
77- }
78-
79- case (DATA_TYPE_SCO): {
80- LOG_INFO(LOG_TAG, "SCO data packets not currently supported.");
81- break;
82- }
83-
84- // TODO(dennischeng): Add debug level assert here.
85- default: {
86- LOG_INFO(LOG_TAG, "Error received an invalid packet type from the HCI.");
87- break;
88- }
89- }
90-}
91-
92-void HciTransport::ReceiveReadyCommand() const {
93- std::unique_ptr<CommandPacket> command =
94- packet_stream_.ReceiveCommand(GetVendorFd());
95- LOG_INFO(LOG_TAG, "Received command packet.");
96- command_handler_(std::move(command));
97-}
98-
99-void HciTransport::RegisterCommandHandler(
100- std::function<void(std::unique_ptr<CommandPacket>)> callback) {
101- command_handler_ = callback;
102-}
103-
104-void HciTransport::OnFileCanWriteWithoutBlocking(int fd) {
105- CHECK(fd == GetVendorFd());
106- if (!outbound_events_.empty()) {
107- base::TimeTicks current_time = base::TimeTicks::Now();
108- // Check outbound events for events that can be sent, i.e. events with a
109- // timestamp before the current time. Stop sending events when
110- // |packet_stream_| fails writing.
111- for (auto it = outbound_events_.begin(); it != outbound_events_.end();) {
112- if ((*it)->GetTimeStamp() > current_time) {
113- ++it;
114- continue;
115- }
116- if (!packet_stream_.SendEvent((*it)->GetEvent(), fd))
117- return;
118- it = outbound_events_.erase(it);
119- }
120- }
121-}
122-
123-void HciTransport::AddEventToOutboundEvents(
124- std::unique_ptr<TimeStampedEvent> event) {
125- outbound_events_.push_back(std::move(event));
126-}
127-
128-void HciTransport::PostEventResponse(std::unique_ptr<EventPacket> event) {
129- AddEventToOutboundEvents(
130- std::make_unique<TimeStampedEvent>(std::move(event)));
131-}
132-
133-void HciTransport::PostDelayedEventResponse(std::unique_ptr<EventPacket> event,
134- base::TimeDelta delay) {
135- // TODO(dennischeng): When it becomes available for MessageLoopForIO, use the
136- // thread's task runner to post |PostEventResponse| as a delayed task, being
137- // sure to CHECK the appropriate task runner attributes using
138- // base::ThreadTaskRunnerHandle.
139-
140- // The system does not support high resolution timing and the clock could be
141- // as coarse as ~15.6 ms so the event is sent without a delay to avoid
142- // inconsistent event responses.
143- if (!base::TimeTicks::IsHighResolution()) {
144- LOG_INFO(LOG_TAG,
145- "System does not support high resolution timing. Sending event "
146- "without delay.");
147- PostEventResponse(std::move(event));
148- }
149-
150- LOG_INFO(LOG_TAG, "Posting event response with delay of %" PRId64 " ms.",
151- delay.InMilliseconds());
152-
153- AddEventToOutboundEvents(
154- std::make_unique<TimeStampedEvent>(std::move(event), delay));
155-}
156-
157-HciTransport::TimeStampedEvent::TimeStampedEvent(
158- std::unique_ptr<EventPacket> event, base::TimeDelta delay)
159- : event_(std::move(event)), time_stamp_(base::TimeTicks::Now() + delay) {}
160-
161-HciTransport::TimeStampedEvent::TimeStampedEvent(
162- std::unique_ptr<EventPacket> event)
163- : event_(std::move(event)), time_stamp_(base::TimeTicks::UnixEpoch()) {}
164-
165-const base::TimeTicks& HciTransport::TimeStampedEvent::GetTimeStamp() const {
166- return time_stamp_;
167-}
168-
169-const EventPacket& HciTransport::TimeStampedEvent::GetEvent() {
170- return *(event_.get());
171-}
172-
173-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/src/packet.cc
+++ /dev/null
@@ -1,69 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "packet"
18-
19-#include "vendor_libs/test_vendor_lib/include/packet.h"
20-
21-#include "base/logging.h"
22-
23-#include <algorithm>
24-
25-extern "C" {
26-#include "osi/include/log.h"
27-} // extern "C"
28-
29-namespace test_vendor_lib {
30-
31-Packet::Packet(serial_data_type_t type) : type_(type) {}
32-
33-bool Packet::Encode(const std::vector<uint8_t>& header,
34- const std::vector<uint8_t>& payload) {
35- if (header.back() != payload.size())
36- return false;
37- header_ = header;
38- payload_ = payload;
39- return true;
40-}
41-
42-const std::vector<uint8_t>& Packet::GetHeader() const {
43- // Every packet must have a header.
44- CHECK(GetHeaderSize() > 0);
45- return header_;
46-}
47-
48-uint8_t Packet::GetHeaderSize() const {
49- return header_.size();
50-}
51-
52-size_t Packet::GetPacketSize() const {
53- // Add one for the type octet.
54- return 1 + header_.size() + payload_.size();
55-}
56-
57-const std::vector<uint8_t>& Packet::GetPayload() const {
58- return payload_;
59-}
60-
61-uint8_t Packet::GetPayloadSize() const {
62- return payload_.size();
63-}
64-
65-serial_data_type_t Packet::GetType() const {
66- return type_;
67-}
68-
69-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/src/packet_stream.cc
+++ /dev/null
@@ -1,134 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "packet_stream"
18-
19-#include "vendor_libs/test_vendor_lib/include/packet_stream.h"
20-
21-#include "base/logging.h"
22-
23-extern "C" {
24-#include <errno.h>
25-#include <unistd.h>
26-
27-#include "osi/include/log.h"
28-} // extern "C"
29-
30-namespace test_vendor_lib {
31-
32-std::unique_ptr<CommandPacket> PacketStream::ReceiveCommand(int fd) const {
33- std::vector<uint8_t> header;
34- std::vector<uint8_t> payload;
35-
36- if (!ReceiveAll(header, CommandPacket::kCommandHeaderSize, fd)) {
37- LOG_ERROR(LOG_TAG, "Error: receiving command header.");
38- return std::unique_ptr<CommandPacket>(nullptr);
39- }
40-
41- if (!ReceiveAll(payload, header.back(), fd)) {
42- LOG_ERROR(LOG_TAG, "Error: receiving command payload.");
43- return std::unique_ptr<CommandPacket>(nullptr);
44- }
45-
46- std::unique_ptr<CommandPacket> command(new CommandPacket());
47- if (!command->Encode(header, payload)) {
48- LOG_ERROR(LOG_TAG, "Error: encoding command packet.");
49- command.reset(nullptr);
50- }
51- return command;
52-}
53-
54-serial_data_type_t PacketStream::ReceivePacketType(int fd) const {
55- LOG_INFO(LOG_TAG, "Receiving packet type.");
56-
57- std::vector<uint8_t> raw_type_octet;
58-
59- if (!ReceiveAll(raw_type_octet, 1, fd)) {
60- // TODO(dennischeng): Proper error handling.
61- LOG_ERROR(LOG_TAG, "Error: Could not receive packet type.");
62- }
63-
64- // Check that the type octet received is in the valid range, i.e. the packet
65- // must be a command or data packet.
66- const serial_data_type_t type =
67- static_cast<serial_data_type_t>(raw_type_octet[0]);
68- if (!ValidateTypeOctet(type)) {
69- // TODO(dennischeng): Proper error handling.
70- LOG_ERROR(LOG_TAG, "Error: Received invalid packet type.");
71- }
72- return type;
73-}
74-
75-bool PacketStream::SendEvent(const EventPacket& event, int fd) const {
76- LOG_INFO(LOG_TAG, "Sending event with event code: 0x%04X",
77- event.GetEventCode());
78- LOG_INFO(LOG_TAG, "Sending event with size: %zu octets",
79- event.GetPacketSize());
80-
81- if (!SendAll({static_cast<uint8_t>(event.GetType())}, 1, fd)) {
82- LOG_ERROR(LOG_TAG, "Error: Could not send event type.");
83- return false;
84- }
85-
86- if (!SendAll(event.GetHeader(), event.GetHeaderSize(), fd)) {
87- LOG_ERROR(LOG_TAG, "Error: Could not send event header.");
88- return false;
89- }
90-
91- if (!SendAll(event.GetPayload(), event.GetPayloadSize(), fd)) {
92- LOG_ERROR(LOG_TAG, "Error: Could not send event payload.");
93- return false;
94- }
95- return true;
96-}
97-
98-bool PacketStream::ValidateTypeOctet(serial_data_type_t type) const {
99- LOG_INFO(LOG_TAG, "Signal octet is 0x%02X.", type);
100- // The only types of packets that should be received from the HCI are command
101- // packets and data packets.
102- return (type >= DATA_TYPE_COMMAND) && (type <= DATA_TYPE_SCO);
103-}
104-
105-bool PacketStream::ReceiveAll(std::vector<uint8_t>& destination,
106- size_t num_octets_to_receive, int fd) const {
107- destination.resize(num_octets_to_receive);
108- size_t octets_remaining = num_octets_to_receive;
109- while (octets_remaining > 0) {
110- const int num_octets_received =
111- read(fd, &destination[num_octets_to_receive - octets_remaining],
112- octets_remaining);
113- if (num_octets_received < 0)
114- return false;
115- octets_remaining -= num_octets_received;
116- }
117- return true;
118-}
119-
120-bool PacketStream::SendAll(const std::vector<uint8_t>& source,
121- size_t num_octets_to_send, int fd) const {
122- CHECK(source.size() >= num_octets_to_send);
123- size_t octets_remaining = num_octets_to_send;
124- while (octets_remaining > 0) {
125- const int num_octets_sent = write(
126- fd, &source[num_octets_to_send - octets_remaining], octets_remaining);
127- if (num_octets_sent < 0)
128- return false;
129- octets_remaining -= num_octets_sent;
130- }
131- return true;
132-}
133-
134-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/src/test_channel_transport.cc
+++ /dev/null
@@ -1,138 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "test_channel_transport"
18-
19-#include "vendor_libs/test_vendor_lib/include/test_channel_transport.h"
20-
21-#include "base/logging.h"
22-
23-extern "C" {
24-#include "osi/include/log.h"
25-
26-#include <sys/socket.h>
27-#include <netinet/in.h>
28-} // extern "C"
29-
30-namespace test_vendor_lib {
31-
32-TestChannelTransport::TestChannelTransport(bool enabled, int port)
33- : enabled_(enabled), port_(port) {}
34-
35-bool TestChannelTransport::SetUp() {
36- CHECK(enabled_);
37-
38- struct sockaddr_in listen_address, test_channel_address;
39- int sockaddr_in_size = sizeof(struct sockaddr_in);
40- int listen_fd = -1;
41- int accept_fd = -1;
42- memset(&listen_address, 0, sockaddr_in_size);
43- memset(&test_channel_address, 0, sockaddr_in_size);
44-
45- if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
46- LOG_INFO(LOG_TAG, "Error creating socket for test channel.");
47- return false;
48- }
49-
50- LOG_INFO(LOG_TAG, "port: %d", port_);
51- listen_address.sin_family = AF_INET;
52- listen_address.sin_port = htons(port_);
53- listen_address.sin_addr.s_addr = htonl(INADDR_ANY);
54-
55- if (bind(listen_fd, reinterpret_cast<sockaddr*>(&listen_address),
56- sockaddr_in_size) < 0) {
57- LOG_INFO(LOG_TAG, "Error binding test channel listener socket to address.");
58- close(listen_fd);
59- return false;
60- }
61-
62- if (listen(listen_fd, 1) < 0) {
63- LOG_INFO(LOG_TAG, "Error listening for test channel.");
64- close(listen_fd);
65- return false;
66- }
67-
68- if ((accept_fd =
69- accept(listen_fd, reinterpret_cast<sockaddr*>(&test_channel_address),
70- &sockaddr_in_size)) < 0) {
71- LOG_INFO(LOG_TAG, "Error accepting test channel connection.");
72- close(listen_fd);
73- return false;
74- }
75-
76- fd_.reset(new base::ScopedFD(accept_fd));
77- return GetFd() >= 0;
78-}
79-
80-int TestChannelTransport::GetFd() {
81- return fd_->get();
82-}
83-
84-bool TestChannelTransport::IsEnabled() {
85- return enabled_;
86-}
87-
88-// base::MessageLoopForIO::Watcher overrides:
89-void TestChannelTransport::OnFileCanReadWithoutBlocking(int fd) {
90- CHECK(fd == GetFd());
91-
92- LOG_INFO(LOG_TAG, "Event ready in TestChannelTransport on fd: %d", fd);
93- uint8_t command_name_size = 0;
94- read(fd, &command_name_size, 1);
95- std::vector<uint8_t> command_name_raw;
96- command_name_raw.resize(command_name_size);
97- read(fd, &command_name_raw[0], command_name_size);
98- std::string command_name(command_name_raw.begin(), command_name_raw.end());
99- LOG_INFO(LOG_TAG, "Received command from test channel: %s",
100- command_name.data());
101-
102- if (command_name == "CLOSE_TEST_CHANNEL") {
103- fd_.reset(nullptr);
104- return;
105- }
106-
107- uint8_t num_args = 0;
108- read(fd, &num_args, 1);
109- LOG_INFO(LOG_TAG, "num_args: %d", num_args);
110- std::vector<std::string> args;
111- for (uint8_t i = 0; i < num_args; ++i) {
112- uint8_t arg_size = 0;
113- read(fd, &arg_size, 1);
114- std::vector<uint8_t> arg;
115- arg.resize(arg_size);
116- read(fd, &arg[0], arg_size);
117- args.push_back(std::string(arg.begin(), arg.end()));
118- }
119-
120- for (size_t i = 0; i < args.size(); ++i)
121- LOG_INFO(LOG_TAG, "Command argument %zu: %s", i, args[i].data());
122-
123- command_handler_(command_name, args);
124-}
125-
126-void TestChannelTransport::OnFileCanWriteWithoutBlocking(int fd) {}
127-
128-void TestChannelTransport::RegisterCommandHandler(
129- std::function<void(const std::string&, const std::vector<std::string>&)>
130- callback) {
131- command_handler_ = callback;
132-}
133-
134-void TestChannelTransport::Disable() {
135- enabled_ = false;
136-}
137-
138-} // namespace test_vendor_lib {
--- a/vendor_libs/test_vendor_lib/src/vendor_manager.cc
+++ /dev/null
@@ -1,149 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#define LOG_TAG "vendor_manager"
18-
19-#include "vendor_manager.h"
20-
21-#include "base/bind.h"
22-#include "base/logging.h"
23-
24-extern "C" {
25-#include "osi/include/log.h"
26-} // extern "C"
27-
28-namespace test_vendor_lib {
29-
30-VendorManager* g_manager = nullptr;
31-
32-// static
33-void VendorManager::CleanUp() {
34- delete g_manager;
35- g_manager = nullptr;
36-}
37-
38-// static
39-VendorManager* VendorManager::Get() {
40- // Initialize should have been called already.
41- CHECK(g_manager);
42- return g_manager;
43-}
44-
45-// static
46-void VendorManager::Initialize() {
47- CHECK(!g_manager);
48- g_manager = new VendorManager();
49-}
50-
51-VendorManager::VendorManager()
52- : running_(false),
53- test_channel_transport_(true, 6111),
54- thread_("TestVendorLibrary"),
55- weak_ptr_factory_(this) {}
56-
57-bool VendorManager::Run() {
58- CHECK(!running_);
59-
60- if (!transport_.SetUp()) {
61- LOG_ERROR(LOG_TAG, "Error setting up transport object.");
62- return false;
63- }
64-
65- if (test_channel_transport_.IsEnabled()) {
66- LOG_INFO(LOG_TAG, "Test channel is enabled.");
67-
68- if (test_channel_transport_.SetUp()) {
69- controller_.RegisterHandlersWithTestChannelTransport(
70- test_channel_transport_);
71- } else {
72- LOG_ERROR(LOG_TAG,
73- "Error setting up test channel object, continuing without it.");
74- test_channel_transport_.Disable();
75- }
76- } else {
77- LOG_INFO(LOG_TAG, "Test channel is disabled.");
78- }
79-
80- controller_.RegisterHandlersWithHciTransport(transport_);
81- // TODO(dennischeng): Register PostDelayedEventResponse instead.
82- controller_.RegisterDelayedEventChannel(
83- std::bind(&HciTransport::PostDelayedEventResponse, &transport_,
84- std::placeholders::_1, std::placeholders::_2));
85-
86- running_ = true;
87- if (!thread_.StartWithOptions(
88- base::Thread::Options(base::MessageLoop::TYPE_IO, 0))) {
89- LOG_ERROR(LOG_TAG, "Error starting TestVendorLibrary thread.");
90- running_ = false;
91- return false;
92- }
93-
94- if (!PostTask(base::Bind(&VendorManager::StartWatchingOnThread,
95- weak_ptr_factory_.GetWeakPtr()))) {
96- LOG_ERROR(LOG_TAG, "Error posting StartWatchingOnThread to task runner.");
97- running_ = false;
98- return false;
99- }
100-
101- return true;
102-}
103-
104-void VendorManager::StartWatchingOnThread() {
105- CHECK(running_);
106- CHECK(base::MessageLoopForIO::IsCurrent());
107-
108- if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
109- transport_.GetVendorFd(), true,
110- base::MessageLoopForIO::WATCH_READ_WRITE, &hci_watcher_,
111- &transport_)) {
112- LOG_ERROR(LOG_TAG, "Error watching vendor fd.");
113- return;
114- }
115-
116- if (test_channel_transport_.IsEnabled())
117- if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
118- test_channel_transport_.GetFd(), true,
119- base::MessageLoopForIO::WATCH_READ, &test_channel_watcher_,
120- &test_channel_transport_))
121- LOG_ERROR(LOG_TAG, "Error watching test channel fd.");
122-}
123-
124-bool VendorManager::PostTask(const base::Closure& task) {
125- return PostDelayedTask(task, base::TimeDelta::FromMilliseconds(0));
126-}
127-
128-bool VendorManager::PostDelayedTask(const base::Closure& task,
129- base::TimeDelta delay) {
130- return thread_.task_runner()->PostDelayedTask(FROM_HERE, task, delay);
131-}
132-
133-void VendorManager::SetVendorCallbacks(const bt_vendor_callbacks_t& callbacks) {
134- vendor_callbacks_ = callbacks;
135-}
136-
137-const bt_vendor_callbacks_t& VendorManager::GetVendorCallbacks() const {
138- return vendor_callbacks_;
139-}
140-
141-void VendorManager::CloseHciFd() {
142- transport_.CloseHciFd();
143-}
144-
145-int VendorManager::GetHciFd() const {
146- return transport_.GetHciFd();
147-}
148-
149-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/test/hci_transport_unittest.cc
+++ /dev/null
@@ -1,140 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#include "vendor_libs/test_vendor_lib/include/command_packet.h"
18-#include "vendor_libs/test_vendor_lib/include/hci_transport.h"
19-
20-#include "base/bind.h"
21-#include "base/message_loop/message_loop.h"
22-#include "base/threading/thread.h"
23-
24-#include <gtest/gtest.h>
25-#include <functional>
26-#include <mutex>
27-
28-extern "C" {
29-#include "stack/include/hcidefs.h"
30-} // extern "C"
31-
32-namespace {
33-const std::vector<uint8_t> stub_command({DATA_TYPE_COMMAND,
34- static_cast<uint8_t>(HCI_RESET),
35- static_cast<uint8_t>(HCI_RESET >> 8),
36- 0});
37-
38-const int kMultiIterations = 10000;
39-
40-void WriteStubCommand(int fd) {
41- write(fd, &stub_command[0], stub_command.size());
42-}
43-
44-} // namespace
45-
46-namespace test_vendor_lib {
47-
48-class HciTransportTest : public ::testing::Test {
49- public:
50- HciTransportTest()
51- : command_callback_count_(0),
52- thread_("HciTransportTest"),
53- weak_ptr_factory_(this) {
54- SetUpTransport();
55- StartThread();
56- PostStartWatchingOnThread();
57- }
58-
59- ~HciTransportTest() {
60- transport_.CloseHciFd();
61- }
62-
63- void CommandCallback(std::unique_ptr<CommandPacket> command) {
64- ++command_callback_count_;
65- // Ensure that the received packet matches the stub command.
66- EXPECT_EQ(DATA_TYPE_COMMAND, command->GetType());
67- EXPECT_EQ(HCI_RESET, command->GetOpcode());
68- EXPECT_EQ(0, command->GetPayloadSize());
69- transport_.CloseVendorFd();
70- }
71-
72- void MultiCommandCallback(std::unique_ptr<CommandPacket> command) {
73- ++command_callback_count_;
74- // Ensure that the received packet matches the stub command.
75- EXPECT_EQ(DATA_TYPE_COMMAND, command->GetType());
76- EXPECT_EQ(HCI_RESET, command->GetOpcode());
77- EXPECT_EQ(0, command->GetPayloadSize());
78- if (command_callback_count_ == kMultiIterations)
79- transport_.CloseVendorFd();
80- }
81-
82- protected:
83- // Tracks the number of commands received.
84- int command_callback_count_;
85- base::Thread thread_;
86- HciTransport transport_;
87- base::MessageLoopForIO::FileDescriptorWatcher watcher_;
88- base::WeakPtrFactory<HciTransportTest> weak_ptr_factory_;
89-
90- private:
91- // Workaround because ASSERT cannot be used directly in a constructor
92- void SetUpTransport() {
93- ASSERT_TRUE(transport_.SetUp());
94- }
95-
96- void StartThread() {
97- ASSERT_TRUE(thread_.StartWithOptions(
98- base::Thread::Options(base::MessageLoop::TYPE_IO, 0)));
99- }
100-
101- void PostStartWatchingOnThread() {
102- thread_.task_runner()->PostTask(
103- FROM_HERE, base::Bind(&HciTransportTest::StartWatchingOnThread,
104- weak_ptr_factory_.GetWeakPtr()));
105- }
106-
107- void StartWatchingOnThread() {
108- base::MessageLoopForIO* loop =
109- static_cast<base::MessageLoopForIO*>(thread_.message_loop());
110- ASSERT_TRUE(loop);
111- ASSERT_TRUE(loop->WatchFileDescriptor(
112- transport_.GetVendorFd(), true,
113- base::MessageLoopForIO::WATCH_READ_WRITE, &watcher_, &transport_));
114- }
115-};
116-
117-TEST_F(HciTransportTest, SingleCommandCallback) {
118- transport_.RegisterCommandHandler(std::bind(
119- &HciTransportTest::CommandCallback, this, std::placeholders::_1));
120- EXPECT_EQ(0, command_callback_count_);
121- WriteStubCommand(transport_.GetHciFd());
122- thread_.Stop(); // Wait for the command handler to finish.
123- EXPECT_EQ(1, command_callback_count_);
124-}
125-
126-TEST_F(HciTransportTest, MultiCommandCallback) {
127- transport_.RegisterCommandHandler(std::bind(
128- &HciTransportTest::MultiCommandCallback, this, std::placeholders::_1));
129- EXPECT_EQ(0, command_callback_count_);
130- WriteStubCommand(transport_.GetHciFd());
131- for (int i = 1; i < kMultiIterations; ++i)
132- WriteStubCommand(transport_.GetHciFd());
133- thread_.Stop(); // Wait for the command handler to finish.
134- EXPECT_EQ(kMultiIterations, command_callback_count_);
135-}
136-
137-// TODO(dennischeng): Add tests for PostEventResponse and
138-// PostDelayedEventResponse.
139-
140-} // namespace test_vendor_lib
--- a/vendor_libs/test_vendor_lib/test/packet_stream_unittest.cc
+++ /dev/null
@@ -1,151 +0,0 @@
1-//
2-// Copyright 2015 The Android Open Source Project
3-//
4-// Licensed under the Apache License, Version 2.0 (the "License");
5-// you may not use this file except in compliance with the License.
6-// You may obtain a copy of the License at
7-//
8-// http://www.apache.org/licenses/LICENSE-2.0
9-//
10-// Unless required by applicable law or agreed to in writing, software
11-// distributed under the License is distributed on an "AS IS" BASIS,
12-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-// See the License for the specific language governing permissions and
14-// limitations under the License.
15-//
16-
17-#include "vendor_libs/test_vendor_lib/include/packet_stream.h"
18-#include "vendor_libs/test_vendor_lib/include/command_packet.h"
19-#include "vendor_libs/test_vendor_lib/include/event_packet.h"
20-#include "vendor_libs/test_vendor_lib/include/packet.h"
21-
22-#include <gtest/gtest.h>
23-#include <cstdint>
24-#include <memory>
25-#include <vector>
26-
27-extern "C" {
28-#include "hci/include/hci_hal.h"
29-#include "stack/include/hcidefs.h"
30-
31-#include <sys/socket.h>
32-} // extern "C"
33-
34-namespace {
35-const char small_payload[] = "foo bar baz";
36-const char large_payload[] =
37- "Aristotle's principles will then be no more principles to him, than those "
38- "of Epicurus and the Stoics: let this diversity of opinions be propounded "
39- "to, and laid before him; he will himself choose, if he be able; if not, "
40- "he will remain in doubt.";
41-} // namespace
42-
43-namespace test_vendor_lib {
44-
45-class PacketStreamTest : public ::testing::Test {
46- public:
47- PacketStreamTest() {
48- socketpair(AF_LOCAL, SOCK_STREAM, 0, socketpair_fds_);
49- CheckSocketpairInit();
50- }
51-
52- ~PacketStreamTest() {
53- close(socketpair_fds_[0]);
54- close(socketpair_fds_[1]);
55- }
56-
57- void CheckedReceiveCommand(const char* payload, uint16_t opcode) {
58- uint8_t payload_size = strlen(payload);
59- std::vector<uint8_t> packet;
60-
61- packet.push_back(DATA_TYPE_COMMAND);
62- packet.push_back(opcode);
63- packet.push_back(opcode >> 8);
64- packet.push_back(payload_size);
65-
66- // Set the packet's payload.
67- for (int i = 0; i < payload_size; ++i)
68- packet.push_back(payload[i]);
69-
70- // Send the packet to |packet_stream_|.
71- write(socketpair_fds_[1], &packet[1], packet.size());
72-
73- // Read the command packet.
74- std::unique_ptr<CommandPacket> command =
75- packet_stream_.ReceiveCommand(socketpair_fds_[0]);
76-
77- const std::vector<uint8_t> received_payload = command->GetPayload();
78-
79- // Validate the packet by checking that it's the appropriate size and then
80- // checking each byte.
81- EXPECT_EQ(packet.size(), command->GetPacketSize());
82- EXPECT_EQ(DATA_TYPE_COMMAND, command->GetType());
83- EXPECT_EQ(opcode, command->GetOpcode());
84- EXPECT_EQ(payload_size, command->GetPayloadSize());
85- for (int i = 0; i < payload_size; ++i)
86- EXPECT_EQ(packet[4 + i], received_payload[i]);
87- }
88-
89- void CheckedSendEvent(std::unique_ptr<EventPacket> event) {
90- EXPECT_TRUE(packet_stream_.SendEvent(*(event.get()), socketpair_fds_[0]));
91-
92- // Read the packet sent by |packet_stream_|.
93- uint8_t event_header[3];
94- read(socketpair_fds_[1], event_header, 3);
95-
96- uint8_t return_parameters_size = event_header[2];
97- uint8_t return_parameters[return_parameters_size];
98- read(socketpair_fds_[1], return_parameters, sizeof(return_parameters));
99-
100- const std::vector<uint8_t> expected_payload = event->GetPayload();
101-
102- // Validate the packet by checking that it's the
103- // appropriate size and then checking each byte.
104- EXPECT_EQ(event->GetPacketSize(),
105- sizeof(event_header) + sizeof(return_parameters));
106- EXPECT_EQ(DATA_TYPE_EVENT, event_header[0]);
107- EXPECT_EQ(event->GetEventCode(), event_header[1]);
108- EXPECT_EQ(event->GetPayloadSize(), return_parameters_size);
109- for (int i = 0; i < return_parameters_size; ++i)
110- EXPECT_EQ(expected_payload[i], return_parameters[i]);
111- }
112-
113- protected:
114- PacketStream packet_stream_;
115-
116- int socketpair_fds_[2];
117-
118- private:
119- // Workaround because ASSERT cannot be used directly in a constructor
120- void CheckSocketpairInit() {
121- ASSERT_TRUE(socketpair_fds_[0] > 0);
122- ASSERT_TRUE(socketpair_fds_[1] > 0);
123- }
124-
125-};
126-
127-TEST_F(PacketStreamTest, ReceivePacketType) {
128- serial_data_type_t command_type = DATA_TYPE_COMMAND;
129- write(socketpair_fds_[1], &command_type, 1);
130- EXPECT_EQ(command_type, packet_stream_.ReceivePacketType(socketpair_fds_[0]));
131-}
132-
133-TEST_F(PacketStreamTest, ReceiveEmptyCommand) {
134- CheckedReceiveCommand("", HCI_RESET);
135-}
136-
137-TEST_F(PacketStreamTest, ReceiveSmallCommand) {
138- CheckedReceiveCommand(small_payload, HCI_RESET);
139-}
140-
141-TEST_F(PacketStreamTest, ReceiveLargeCommand) {
142- CheckedReceiveCommand(large_payload, HCI_RESET);
143-}
144-
145-TEST_F(PacketStreamTest, SendEvent) {
146- const std::vector<uint8_t> return_parameters = {0};
147- CheckedSendEvent(
148- EventPacket::CreateCommandCompleteEvent(1, HCI_RESET, return_parameters));
149-}
150-
151-} // namespace test_vendor_lib