Merge "Add more HWC vs RenderEngine tests to composer vts"
diff --git a/OWNERS b/OWNERS
index 1d7a8e1..433bbb7 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,3 +1,6 @@
+per-file *.hal,*.aidl,OWNERS = set noparent
+per-file *.hal,*.aidl,OWNERS = elsk@google.com,malchev@google.com,smoreland@google.com
+
elsk@google.com
maco@google.com
malchev@google.com
diff --git a/automotive/can/1.0/Android.bp b/automotive/can/1.0/Android.bp
new file mode 100644
index 0000000..fe2a2be
--- /dev/null
+++ b/automotive/can/1.0/Android.bp
@@ -0,0 +1,20 @@
+// This file is autogenerated by hidl-gen -Landroidbp.
+
+hidl_interface {
+ name: "android.hardware.automotive.can@1.0",
+ root: "android.hardware",
+ vndk: {
+ enabled: true,
+ },
+ srcs: [
+ "types.hal",
+ "ICanBus.hal",
+ "ICanController.hal",
+ "ICanMessageListener.hal",
+ "ICloseHandle.hal",
+ ],
+ interfaces: [
+ "android.hidl.base@1.0",
+ ],
+ gen_java: true,
+}
diff --git a/automotive/can/1.0/ICanBus.hal b/automotive/can/1.0/ICanBus.hal
new file mode 100644
index 0000000..6ed89f3
--- /dev/null
+++ b/automotive/can/1.0/ICanBus.hal
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.hardware.automotive.can@1.0;
+
+import ICanMessageListener;
+import ICloseHandle;
+
+/**
+ * Represents a CAN bus interface that's up and configured.
+ *
+ * Configuration part is done in ICanController.
+ */
+interface ICanBus {
+ /**
+ * Send CAN message.
+ *
+ * @param message CAN message to send out
+ * @return result OK in the case of success
+ * PAYLOAD_TOO_LONG if the payload is too long
+ * INTERFACE_DOWN if the bus is down
+ * TRANSMISSION_FAILURE in case of transmission failure
+ */
+ send(CanMessage message) generates (Result result);
+
+ /**
+ * Requests HAL implementation to listen for specific CAN messages.
+ *
+ * HAL is responsible for maintaining listener set and sending out messages
+ * to each listener that matches given filter against received message.
+ *
+ * Empty filter list means no filtering. If two or more listeners requested
+ * different filters, HAL server must merge these to fulfill the superset of
+ * these filters. HAL must not send out a message to a listener which filter
+ * doesn't match given message id.
+ *
+ * If filtering is not supported at the hardware level (what's strongly
+ * recommended), it must be covered in the HAL.
+ *
+ * @param filter The set of requested filters
+ * @param listener The interface to receive the messages on
+ * @return result OK in the case of success
+ * INTERFACE_DOWN if the bus is down
+ * @return close A handle to call in order to remove the listener
+ */
+ listen(vec<CanMessageFilter> filter, ICanMessageListener listener)
+ generates (Result result, ICloseHandle close);
+};
diff --git a/automotive/can/1.0/ICanController.hal b/automotive/can/1.0/ICanController.hal
new file mode 100644
index 0000000..2c7494a
--- /dev/null
+++ b/automotive/can/1.0/ICanController.hal
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.hardware.automotive.can@1.0;
+
+/**
+ * Represents a CAN controller that's capable of configuring CAN bus interfaces.
+ *
+ * The goal of this service is to configure CAN interfaces and bring up HIDL
+ * server instances of ICanBus for each one that's up.
+ *
+ * Providing an ICanController interface to configure CAN buses is optional.
+ * A system can elect to publish only ICanBus if the hardware is hardcoded
+ * for a specific application.
+ */
+interface ICanController {
+ /**
+ * Type of an interface, a mean to express the domain of device address.
+ */
+ enum InterfaceType : uint8_t {
+ /**
+ * Virtual SocketCAN interface.
+ *
+ * The address is an interface name, such as vcan0. If the interface
+ * doesn't exist, HAL server must create it.
+ *
+ * Valid InterfaceIdentifier types:
+ * - address.
+ */
+ VIRTUAL,
+
+ /**
+ * Native SocketCAN interface.
+ *
+ * The address is an interface name, such as can0.
+ *
+ * Valid InterfaceIdentifier types:
+ * - address;
+ * - serialno.
+ */
+ SOCKETCAN,
+
+ /**
+ * Serial-based interface.
+ *
+ * The address is a patch to a device, such as /dev/ttyUSB0.
+ *
+ * Valid InterfaceIdentifier types:
+ * - address;
+ * - serialno.
+ */
+ SLCAN,
+
+ /**
+ * Proprietary interface, specific to the hardware system Android
+ * is running on. Instead of using address field, the interface is
+ * addressed with 0-based index.
+ *
+ * Valid InterfaceIdentifier types:
+ * - index
+ */
+ INDEXED
+ };
+
+ enum Result : uint8_t {
+ OK,
+
+ /**
+ * General error class, if others are not applicable.
+ */
+ UNKNOWN_ERROR,
+
+ /**
+ * Up request was called out of order (i.e. trying to up the
+ * interface twice).
+ */
+ INVALID_STATE,
+
+ /** Interface type is not supported. */
+ NOT_SUPPORTED,
+
+ /**
+ * Provided address (interface name, device path) doesn't exist or there
+ * is no device with a given serial no.
+ */
+ BAD_ADDRESS,
+
+ /** Provided baud rate is not supported by the hardware. */
+ BAD_BAUDRATE,
+ };
+
+ /**
+ * Configuration of the (physical or virtual) CAN bus.
+ *
+ * ISO TP and CAN FD are currently not supported.
+ */
+ struct BusConfiguration {
+ /**
+ * Name under which ICanBus HIDL service should be published.
+ *
+ * It must consist of only alphanumeric characters and underscore
+ * (a-z, A-Z, 0-9, '_'), at least 1 and at most 32 characters long.
+ */
+ string name;
+
+ /**
+ * Type of the hardware (or virtual) CAN interface.
+ */
+ InterfaceType iftype;
+
+ /**
+ * Identification of hardware interface to configure.
+ */
+ safe_union InterfaceIdentifier {
+ /**
+ * Interface name or other mean of identification of the specific
+ * interface port. Syntax depends on {@see iftype}, for details
+ * {@see InterfaceType}.
+ */
+ string address;
+
+ /**
+ * Numerical identifier of interface, used for InterfaceType#INDEXED.
+ */
+ uint8_t index;
+
+ /**
+ * Alternatively to providing {@see address}, one may provide a list
+ * of interface serial number suffixes. If there happens to be
+ * a device (like USB2CAN) with a matching serial number suffix,
+ * it gets selected.
+ *
+ * Client may utilize this in two ways: by matching against the
+ * entire serial number, or the last few characters (usually one).
+ * The former is better for small-scale test deployments (with just
+ * a handful of vehicles), the latter is good for larger scale
+ * (where a small suffix list may support large test fleet).
+ */
+ vec<string> serialno;
+ } interfaceId;
+
+ /**
+ * Baud rate for CAN communication.
+ *
+ * Typical baud rates are: 100000, 125000, 250000, 500000.
+ *
+ * For virtual interfaces this value is ignored.
+ */
+ uint32_t baudrate;
+ };
+
+ /**
+ * Fetches the list of interface types supported by this HAL server.
+ *
+ * @return iftypes The list of supported interface types
+ */
+ getSupportedInterfaceTypes() generates (vec<InterfaceType> iftypes);
+
+ /**
+ * Bring up the CAN interface and publish ICanBus server instance.
+ *
+ * @param config Configuration of the CAN interface
+ * @return result OK if the operation succeeded; error code otherwise.
+ */
+ upInterface(BusConfiguration config) generates (Result result);
+
+ /**
+ * Unpublish ICanBus server instance and bring down the CAN interface.
+ *
+ * In case of failure, at least the ICanBus server instance must be
+ * unpublished and resources freed on best-effort basis.
+ *
+ * @param name Name of the interface (@see BusConfiguration#name} to
+ * bring down
+ * @return success true in case of success, false otherwise
+ */
+ downInterface(string name) generates (bool success);
+};
diff --git a/automotive/can/1.0/ICanMessageListener.hal b/automotive/can/1.0/ICanMessageListener.hal
new file mode 100644
index 0000000..992d1c7
--- /dev/null
+++ b/automotive/can/1.0/ICanMessageListener.hal
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.hardware.automotive.can@1.0;
+
+/**
+ * CAN message listener.
+ */
+interface ICanMessageListener {
+ /**
+ * Called on received CAN message.
+ *
+ * The timestamp field of message struct is set to time when the message
+ * was received by the hardware. If it's not possible to fetch exact
+ * hardware time, this field should be set as early as possible to decrease
+ * potential time delta.
+ *
+ * @param message Received CAN message
+ */
+ onReceive(CanMessage message);
+
+ /**
+ * Called on error event.
+ *
+ * @param error Error type
+ */
+ onError(ErrorEvent error);
+};
diff --git a/automotive/can/1.0/ICloseHandle.hal b/automotive/can/1.0/ICloseHandle.hal
new file mode 100644
index 0000000..924c58b
--- /dev/null
+++ b/automotive/can/1.0/ICloseHandle.hal
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.hardware.automotive.can@1.0;
+
+/**
+ * Represents a generic close handle to remove a callback that doesn't need
+ * active interface.
+ *
+ * When close() is called OR when the interface is released, the underlying
+ * resources must be freed.
+ */
+interface ICloseHandle {
+ /**
+ * Closes the handle.
+ *
+ * The call must not fail and must be issued by the client at most once.
+ * Otherwise, the server must ignore subsequent calls.
+ */
+ close();
+};
diff --git a/automotive/can/1.0/default/Android.bp b/automotive/can/1.0/default/Android.bp
new file mode 100644
index 0000000..0a4afd6
--- /dev/null
+++ b/automotive/can/1.0/default/Android.bp
@@ -0,0 +1,55 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_defaults {
+ name: "android.hardware.automotive.can@defaults",
+ cpp_std: "experimental",
+ cflags: [
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+ "-DANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION=1",
+ ],
+ shared_libs: [
+ "libbase",
+ "libutils",
+ ],
+}
+
+cc_binary {
+ name: "android.hardware.automotive.can@1.0-service",
+ init_rc: ["android.hardware.automotive.can@1.0-service.rc"],
+ defaults: ["android.hardware.automotive.can@defaults"],
+ vendor: true,
+ relative_install_path: "hw",
+ srcs: [
+ "CanBus.cpp",
+ "CanBusNative.cpp",
+ "CanBusVirtual.cpp",
+ "CanController.cpp",
+ "CanSocket.cpp",
+ "CloseHandle.cpp",
+ "service.cpp",
+ ],
+ shared_libs: [
+ "android.hardware.automotive.can@1.0",
+ "libhidlbase",
+ "libhidltransport",
+ ],
+ static_libs: [
+ "android.hardware.automotive.can@libnetdevice",
+ ],
+}
diff --git a/automotive/can/1.0/default/CanBus.cpp b/automotive/can/1.0/default/CanBus.cpp
new file mode 100644
index 0000000..65da291
--- /dev/null
+++ b/automotive/can/1.0/default/CanBus.cpp
@@ -0,0 +1,249 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "CanBus.h"
+
+#include "CloseHandle.h"
+
+#include <android-base/logging.h>
+#include <libnetdevice/can.h>
+#include <libnetdevice/libnetdevice.h>
+#include <linux/can.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+/**
+ * Whether to log sent/received packets.
+ */
+static constexpr bool kSuperVerbose = false;
+
+Return<Result> CanBus::send(const CanMessage& message) {
+ std::lock_guard<std::mutex> lck(mIsUpGuard);
+ if (!mIsUp) return Result::INTERFACE_DOWN;
+
+ if (UNLIKELY(kSuperVerbose)) {
+ LOG(VERBOSE) << "Sending " << toString(message);
+ }
+
+ if (message.payload.size() > CAN_MAX_DLEN) return Result::PAYLOAD_TOO_LONG;
+
+ struct canfd_frame frame = {};
+ frame.can_id = message.id;
+ frame.len = message.payload.size();
+ memcpy(frame.data, message.payload.data(), message.payload.size());
+
+ if (!mSocket->send(frame)) return Result::TRANSMISSION_FAILURE;
+
+ return Result::OK;
+}
+
+Return<void> CanBus::listen(const hidl_vec<CanMessageFilter>& filter,
+ const sp<ICanMessageListener>& listenerCb, listen_cb _hidl_cb) {
+ std::lock_guard<std::mutex> lck(mIsUpGuard);
+
+ if (listenerCb == nullptr) {
+ _hidl_cb(Result::INVALID_ARGUMENTS, nullptr);
+ return {};
+ }
+ if (!mIsUp) {
+ _hidl_cb(Result::INTERFACE_DOWN, nullptr);
+ return {};
+ }
+
+ std::lock_guard<std::mutex> lckListeners(mListenersGuard);
+
+ sp<CloseHandle> closeHandle = new CloseHandle([this, listenerCb]() {
+ std::lock_guard<std::mutex> lck(mListenersGuard);
+ std::erase_if(mListeners, [&](const auto& e) { return e.callback == listenerCb; });
+ });
+ mListeners.emplace_back(CanMessageListener{listenerCb, filter, closeHandle});
+ auto& listener = mListeners.back();
+
+ // fix message IDs to have all zeros on bits not covered by mask
+ std::for_each(listener.filter.begin(), listener.filter.end(),
+ [](auto& rule) { rule.id &= rule.mask; });
+
+ _hidl_cb(Result::OK, closeHandle);
+ return {};
+}
+
+CanBus::CanBus(const std::string& ifname) : mIfname(ifname) {}
+
+CanBus::~CanBus() {
+ std::lock_guard<std::mutex> lck(mIsUpGuard);
+ CHECK(!mIsUp) << "Interface is still up while being destroyed";
+
+ std::lock_guard<std::mutex> lckListeners(mListenersGuard);
+ CHECK(mListeners.empty()) << "Listeners list is not empty while interface is being destroyed";
+}
+
+ICanController::Result CanBus::preUp() {
+ return ICanController::Result::OK;
+}
+
+bool CanBus::postDown() {
+ return true;
+}
+
+ICanController::Result CanBus::up() {
+ std::lock_guard<std::mutex> lck(mIsUpGuard);
+
+ if (mIsUp) {
+ LOG(WARNING) << "Interface is already up";
+ return ICanController::Result::INVALID_STATE;
+ }
+
+ const auto preResult = preUp();
+ if (preResult != ICanController::Result::OK) return preResult;
+
+ const auto isUp = netdevice::isUp(mIfname);
+ if (!isUp.has_value()) {
+ // preUp() should prepare the interface (either create or make sure it's there)
+ LOG(ERROR) << "Interface " << mIfname << " didn't get prepared";
+ return ICanController::Result::BAD_ADDRESS;
+ }
+ mWasUpInitially = *isUp;
+
+ if (!mWasUpInitially && !netdevice::up(mIfname)) {
+ LOG(ERROR) << "Can't bring " << mIfname << " up";
+ return ICanController::Result::UNKNOWN_ERROR;
+ }
+
+ using namespace std::placeholders;
+ CanSocket::ReadCallback rdcb = std::bind(&CanBus::onRead, this, _1, _2);
+ CanSocket::ErrorCallback errcb = std::bind(&CanBus::onError, this);
+ mSocket = CanSocket::open(mIfname, rdcb, errcb);
+ if (!mSocket) {
+ if (!mWasUpInitially) netdevice::down(mIfname);
+ return ICanController::Result::UNKNOWN_ERROR;
+ }
+
+ mIsUp = true;
+ return ICanController::Result::OK;
+}
+
+void CanBus::clearListeners() {
+ std::vector<wp<ICloseHandle>> listenersToClose;
+ {
+ std::lock_guard<std::mutex> lck(mListenersGuard);
+ std::transform(mListeners.begin(), mListeners.end(), std::back_inserter(listenersToClose),
+ [](const auto& e) { return e.closeHandle; });
+ }
+
+ for (auto& weakListener : listenersToClose) {
+ /* Between populating listenersToClose and calling close method here, some listeners might
+ * have been already removed from the original mListeners list (resulting in a dangling weak
+ * pointer here). It's fine - we just want to clean them up. */
+ auto listener = weakListener.promote();
+ if (listener != nullptr) listener->close();
+ }
+
+ std::lock_guard<std::mutex> lck(mListenersGuard);
+ CHECK(mListeners.empty()) << "Listeners list wasn't emptied";
+}
+
+bool CanBus::down() {
+ std::lock_guard<std::mutex> lck(mIsUpGuard);
+
+ if (!mIsUp) {
+ LOG(WARNING) << "Interface is already down";
+ return false;
+ }
+ mIsUp = false;
+
+ clearListeners();
+ mSocket.reset();
+
+ bool success = true;
+
+ if (!mWasUpInitially && !netdevice::down(mIfname)) {
+ LOG(ERROR) << "Can't bring " << mIfname << " down";
+ // don't return yet, let's try to do best-effort cleanup
+ success = false;
+ }
+
+ if (!postDown()) success = false;
+
+ return success;
+}
+
+/**
+ * Match the filter set against message id.
+ *
+ * For details on the filters syntax, please see CanMessageFilter at
+ * the HAL definition (types.hal).
+ *
+ * \param filter Filter to match against
+ * \param id Message id to filter
+ * \return true if the message id matches the filter, false otherwise
+ */
+static bool match(const hidl_vec<CanMessageFilter>& filter, CanMessageId id) {
+ if (filter.size() == 0) return true;
+
+ bool anyNonInvertedPresent = false;
+ bool anyNonInvertedSatisfied = false;
+ for (auto& rule : filter) {
+ const bool satisfied = ((id & rule.mask) == rule.id) == !rule.inverted;
+ if (rule.inverted) {
+ // Any inverted (blacklist) rule not being satisfied invalidates the whole filter set.
+ if (!satisfied) return false;
+ } else {
+ anyNonInvertedPresent = true;
+ if (satisfied) anyNonInvertedSatisfied = true;
+ }
+ }
+ return !anyNonInvertedPresent || anyNonInvertedSatisfied;
+}
+
+void CanBus::onRead(const struct canfd_frame& frame, std::chrono::nanoseconds timestamp) {
+ CanMessage message = {};
+ message.id = frame.can_id;
+ message.payload = hidl_vec<uint8_t>(frame.data, frame.data + frame.len);
+ message.timestamp = timestamp.count();
+
+ if (UNLIKELY(kSuperVerbose)) {
+ LOG(VERBOSE) << "Got message " << toString(message);
+ }
+
+ std::lock_guard<std::mutex> lck(mListenersGuard);
+ for (auto& listener : mListeners) {
+ if (!match(listener.filter, message.id)) continue;
+ if (!listener.callback->onReceive(message).isOk()) {
+ LOG(WARNING) << "Failed to notify listener about message";
+ }
+ }
+}
+
+void CanBus::onError() {
+ std::lock_guard<std::mutex> lck(mListenersGuard);
+ for (auto& listener : mListeners) {
+ if (!listener.callback->onError(ErrorEvent::HARDWARE_ERROR).isOk()) {
+ LOG(WARNING) << "Failed to notify listener about error";
+ }
+ }
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanBus.h b/automotive/can/1.0/default/CanBus.h
new file mode 100644
index 0000000..81a83c8
--- /dev/null
+++ b/automotive/can/1.0/default/CanBus.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "CanSocket.h"
+
+#include <android-base/unique_fd.h>
+#include <android/hardware/automotive/can/1.0/ICanBus.h>
+#include <android/hardware/automotive/can/1.0/ICanController.h>
+#include <utils/Mutex.h>
+
+#include <atomic>
+#include <thread>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+struct CanBus : public ICanBus {
+ virtual ~CanBus();
+
+ Return<Result> send(const CanMessage& message) override;
+ Return<void> listen(const hidl_vec<CanMessageFilter>& filter,
+ const sp<ICanMessageListener>& listener, listen_cb _hidl_cb) override;
+
+ ICanController::Result up();
+ bool down();
+
+ protected:
+ CanBus(const std::string& ifname);
+
+ /**
+ * Prepare the SocketCAN interface.
+ *
+ * After calling this method, mIfname network interface is available and ready to be brought up.
+ */
+ virtual ICanController::Result preUp();
+
+ /**
+ * Cleanup after bringing the interface down.
+ *
+ * This is a counterpart to preUp().
+ */
+ virtual bool postDown();
+
+ /** Network interface name. */
+ const std::string mIfname;
+
+ private:
+ struct CanMessageListener {
+ sp<ICanMessageListener> callback;
+ hidl_vec<CanMessageFilter> filter;
+ wp<ICloseHandle> closeHandle;
+ };
+ void clearListeners();
+
+ void onRead(const struct canfd_frame& frame, std::chrono::nanoseconds timestamp);
+ void onError();
+
+ std::mutex mListenersGuard;
+ std::vector<CanMessageListener> mListeners GUARDED_BY(mListenersGuard);
+
+ std::unique_ptr<CanSocket> mSocket;
+ bool mWasUpInitially;
+
+ /**
+ * Guard for up flag is required to be held for entire time when the interface is being used
+ * (i.e. message being sent), because we don't want the interface to be torn down while
+ * executing that operation.
+ */
+ std::mutex mIsUpGuard;
+ bool mIsUp GUARDED_BY(mIsUpGuard) = false;
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanBusNative.cpp b/automotive/can/1.0/default/CanBusNative.cpp
new file mode 100644
index 0000000..365b749
--- /dev/null
+++ b/automotive/can/1.0/default/CanBusNative.cpp
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "CanBusNative.h"
+
+#include <android-base/logging.h>
+#include <libnetdevice/can.h>
+#include <libnetdevice/libnetdevice.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+CanBusNative::CanBusNative(const std::string& ifname, uint32_t baudrate)
+ : CanBus(ifname), mBaudrate(baudrate) {}
+
+ICanController::Result CanBusNative::preUp() {
+ if (!netdevice::exists(mIfname)) {
+ LOG(ERROR) << "Interface " << mIfname << " doesn't exist";
+ return ICanController::Result::BAD_ADDRESS;
+ }
+
+ if (!netdevice::down(mIfname)) {
+ LOG(ERROR) << "Can't bring " << mIfname << " down (to configure it)";
+ return ICanController::Result::UNKNOWN_ERROR;
+ }
+
+ if (!netdevice::can::setBitrate(mIfname, mBaudrate)) {
+ LOG(ERROR) << "Can't set bitrate " << mBaudrate << " for " << mIfname;
+ return ICanController::Result::BAD_BAUDRATE;
+ }
+
+ return ICanController::Result::OK;
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanBusNative.h b/automotive/can/1.0/default/CanBusNative.h
new file mode 100644
index 0000000..126f1cb
--- /dev/null
+++ b/automotive/can/1.0/default/CanBusNative.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "CanBus.h"
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+struct CanBusNative : public CanBus {
+ CanBusNative(const std::string& ifname, uint32_t baudrate);
+
+ protected:
+ virtual ICanController::Result preUp() override;
+
+ private:
+ const uint32_t mBaudrate;
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanBusVirtual.cpp b/automotive/can/1.0/default/CanBusVirtual.cpp
new file mode 100644
index 0000000..cc59fa9
--- /dev/null
+++ b/automotive/can/1.0/default/CanBusVirtual.cpp
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "CanBusVirtual.h"
+
+#include <android-base/logging.h>
+#include <libnetdevice/libnetdevice.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+CanBusVirtual::CanBusVirtual(const std::string& ifname) : CanBus(ifname) {}
+
+ICanController::Result CanBusVirtual::preUp() {
+ if (netdevice::exists(mIfname)) return ICanController::Result::OK;
+
+ LOG(DEBUG) << "Virtual interface " << mIfname << " doesn't exist, creating...";
+ mWasCreated = true;
+ if (!netdevice::add(mIfname, "vcan")) {
+ LOG(ERROR) << "Can't create vcan interface " << mIfname;
+ return ICanController::Result::UNKNOWN_ERROR;
+ }
+
+ return ICanController::Result::OK;
+}
+
+bool CanBusVirtual::postDown() {
+ if (mWasCreated) {
+ mWasCreated = false;
+ if (!netdevice::del(mIfname)) {
+ LOG(ERROR) << "Couldn't remove vcan interface " << mIfname;
+ return false;
+ }
+ }
+ return true;
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanBusVirtual.h b/automotive/can/1.0/default/CanBusVirtual.h
new file mode 100644
index 0000000..c2d5794
--- /dev/null
+++ b/automotive/can/1.0/default/CanBusVirtual.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "CanBus.h"
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+struct CanBusVirtual : public CanBus {
+ CanBusVirtual(const std::string& ifname);
+
+ protected:
+ virtual ICanController::Result preUp() override;
+ virtual bool postDown() override;
+
+ private:
+ bool mWasCreated = false;
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanController.cpp b/automotive/can/1.0/default/CanController.cpp
new file mode 100644
index 0000000..20adbe1
--- /dev/null
+++ b/automotive/can/1.0/default/CanController.cpp
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "CanController.h"
+
+#include "CanBusNative.h"
+#include "CanBusVirtual.h"
+
+#include <android-base/logging.h>
+#include <android/hidl/manager/1.2/IServiceManager.h>
+
+#include <regex>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+using IfaceIdDisc = ICanController::BusConfiguration::InterfaceIdentifier::hidl_discriminator;
+
+Return<void> CanController::getSupportedInterfaceTypes(getSupportedInterfaceTypes_cb _hidl_cb) {
+ _hidl_cb({
+ ICanController::InterfaceType::VIRTUAL,
+ ICanController::InterfaceType::SOCKETCAN,
+ });
+ return {};
+}
+
+static bool isValidName(const std::string& name) {
+ static const std::regex nameRE("^[a-zA-Z0-9_]{1,32}$");
+ return std::regex_match(name, nameRE);
+}
+
+Return<ICanController::Result> CanController::upInterface(
+ const ICanController::BusConfiguration& config) {
+ LOG(VERBOSE) << "Attempting to bring interface up: " << toString(config);
+
+ std::lock_guard<std::mutex> lck(mCanBusesGuard);
+
+ if (!isValidName(config.name)) {
+ LOG(ERROR) << "Bus name " << config.name << " is invalid";
+ return ICanController::Result::UNKNOWN_ERROR;
+ }
+
+ if (mCanBuses.find(config.name) != mCanBuses.end()) {
+ LOG(ERROR) << "Bus " << config.name << " is already up";
+ return ICanController::Result::INVALID_STATE;
+ }
+
+ sp<CanBus> busService;
+
+ if (config.iftype == ICanController::InterfaceType::SOCKETCAN) {
+ // TODO(b/135918744): support serialno
+ if (config.interfaceId.getDiscriminator() == IfaceIdDisc::address) {
+ busService = new CanBusNative(config.interfaceId.address(), config.baudrate);
+ } else {
+ return ICanController::Result::BAD_ADDRESS;
+ }
+ } else if (config.iftype == ICanController::InterfaceType::VIRTUAL) {
+ if (config.interfaceId.getDiscriminator() == IfaceIdDisc::address) {
+ busService = new CanBusVirtual(config.interfaceId.address());
+ } else {
+ return ICanController::Result::BAD_ADDRESS;
+ }
+ } else {
+ return ICanController::Result::NOT_SUPPORTED;
+ }
+
+ const auto result = busService->up();
+ if (result != ICanController::Result::OK) return result;
+
+ if (busService->registerAsService(config.name) != OK) {
+ LOG(ERROR) << "Failed to register ICanBus/" << config.name;
+ if (!busService->down()) {
+ LOG(WARNING) << "Failed to bring down CAN bus that failed to register";
+ }
+ return ICanController::Result::UNKNOWN_ERROR;
+ }
+
+ mCanBuses[config.name] = busService;
+
+ return ICanController::Result::OK;
+}
+
+Return<bool> CanController::downInterface(const hidl_string& name) {
+ LOG(VERBOSE) << "Attempting to bring interface down: " << name;
+
+ std::lock_guard<std::mutex> lck(mCanBusesGuard);
+
+ auto busEntry = mCanBuses.extract(name);
+ if (!busEntry) {
+ LOG(WARNING) << "Interface " << name << " is not up";
+ return false;
+ }
+
+ auto success = true;
+
+ auto manager = hidl::manager::V1_2::IServiceManager::getService();
+ if (!manager || !manager->tryUnregister(ICanBus::descriptor, name, busEntry.mapped())) {
+ LOG(ERROR) << "Couldn't unregister " << name;
+ // don't return yet, let's try to do best-effort cleanup
+ success = false;
+ }
+
+ if (!busEntry.mapped()->down()) {
+ LOG(ERROR) << "Couldn't bring " << name << " down";
+ success = false;
+ }
+
+ return success;
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanController.h b/automotive/can/1.0/default/CanController.h
new file mode 100644
index 0000000..0674d0e
--- /dev/null
+++ b/automotive/can/1.0/default/CanController.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "CanBus.h"
+
+#include <android/hardware/automotive/can/1.0/ICanController.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+struct CanController : public ICanController {
+ Return<void> getSupportedInterfaceTypes(getSupportedInterfaceTypes_cb _hidl_cb) override;
+
+ Return<ICanController::Result> upInterface(
+ const ICanController::BusConfiguration& config) override;
+ Return<bool> downInterface(const hidl_string& name) override;
+
+ private:
+ std::mutex mCanBusesGuard;
+ std::map<std::string, sp<CanBus>> mCanBuses GUARDED_BY(mCanBusesGuard);
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanSocket.cpp b/automotive/can/1.0/default/CanSocket.cpp
new file mode 100644
index 0000000..4d86de6
--- /dev/null
+++ b/automotive/can/1.0/default/CanSocket.cpp
@@ -0,0 +1,150 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "CanSocket.h"
+
+#include <android-base/logging.h>
+#include <libnetdevice/can.h>
+#include <libnetdevice/libnetdevice.h>
+#include <linux/can.h>
+#include <utils/SystemClock.h>
+
+#include <chrono>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+using namespace std::chrono_literals;
+
+/**
+ * How frequently the read thread checks whether the interface was asked to be down.
+ *
+ * Note: This does *not* affect read timing or bandwidth, just CPU load vs time to
+ * down the interface.
+ */
+static constexpr auto kReadPooling = 100ms;
+
+std::unique_ptr<CanSocket> CanSocket::open(const std::string& ifname, ReadCallback rdcb,
+ ErrorCallback errcb) {
+ auto sock = netdevice::can::socket(ifname);
+ if (!sock.ok()) {
+ LOG(ERROR) << "Can't open CAN socket on " << ifname;
+ return nullptr;
+ }
+
+ // Can't use std::make_unique due to private CanSocket constructor.
+ return std::unique_ptr<CanSocket>(new CanSocket(std::move(sock), rdcb, errcb));
+}
+
+CanSocket::CanSocket(base::unique_fd socket, ReadCallback rdcb, ErrorCallback errcb)
+ : mReadCallback(rdcb),
+ mErrorCallback(errcb),
+ mSocket(std::move(socket)),
+ mReaderThread(&CanSocket::readerThread, this) {}
+
+CanSocket::~CanSocket() {
+ mStopReaderThread = true;
+ mReaderThread.join();
+}
+
+bool CanSocket::send(const struct canfd_frame& frame) {
+ const auto res = write(mSocket.get(), &frame, CAN_MTU);
+ if (res < 0) {
+ LOG(DEBUG) << "CanSocket send failed: " << errno;
+ return false;
+ }
+ if (res != CAN_MTU) {
+ LOG(DEBUG) << "CanSocket sent wrong number of bytes: " << res;
+ return false;
+ }
+ return true;
+}
+
+static struct timeval toTimeval(std::chrono::microseconds t) {
+ struct timeval tv;
+ tv.tv_sec = t / 1s;
+ tv.tv_usec = (t % 1s) / 1us;
+ return tv;
+}
+
+static int selectRead(const base::unique_fd& fd, std::chrono::microseconds timeout) {
+ auto timeouttv = toTimeval(timeout);
+ fd_set readfds;
+ FD_ZERO(&readfds);
+ FD_SET(fd.get(), &readfds);
+ return select(fd.get() + 1, &readfds, nullptr, nullptr, &timeouttv);
+}
+
+void CanSocket::readerThread() {
+ LOG(VERBOSE) << "Reader thread started";
+
+ while (!mStopReaderThread) {
+ /* The ideal would be to have a blocking read(3) call and interrupt it with shutdown(3).
+ * This is unfortunately not supported for SocketCAN, so we need to rely on select(3).
+ */
+ const auto sel = selectRead(mSocket, kReadPooling);
+ if (sel == 0) continue; // timeout
+ if (sel == -1) {
+ LOG(ERROR) << "Select failed: " << errno;
+ break;
+ }
+
+ struct canfd_frame frame;
+ const auto nbytes = read(mSocket.get(), &frame, CAN_MTU);
+
+ /* We could use SIOCGSTAMP to get a precise UNIX timestamp for a given packet, but what
+ * we really need is a time since boot. There is no direct way to convert between these
+ * clocks. We could implement a class to calculate the difference between the clocks
+ * (querying both several times and picking the smallest difference); apply the difference
+ * to a SIOCGSTAMP returned value; re-synchronize if the elapsed time is too much in the
+ * past (indicating the UNIX timestamp might have been adjusted).
+ *
+ * Apart from the added complexity, it's possible the added calculations and system calls
+ * would add so much time to the processing pipeline so the precision of the reported time
+ * was buried under the subsystem latency. Let's just use a local time since boot here and
+ * leave precise hardware timestamps for custom proprietary implementations (if needed).
+ */
+ const std::chrono::nanoseconds ts(elapsedRealtimeNano());
+
+ if (nbytes != CAN_MTU) {
+ if (nbytes >= 0) {
+ LOG(ERROR) << "Failed to read CAN packet, got " << nbytes << " bytes";
+ break;
+ }
+ if (errno == EAGAIN) continue;
+
+ LOG(ERROR) << "Failed to read CAN packet: " << errno;
+ break;
+ }
+
+ mReadCallback(frame, ts);
+ }
+
+ if (!mStopReaderThread) mErrorCallback();
+
+ LOG(VERBOSE) << "Reader thread stopped";
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CanSocket.h b/automotive/can/1.0/default/CanSocket.h
new file mode 100644
index 0000000..cd7162d
--- /dev/null
+++ b/automotive/can/1.0/default/CanSocket.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android-base/macros.h>
+#include <android-base/unique_fd.h>
+#include <linux/can.h>
+
+#include <atomic>
+#include <chrono>
+#include <thread>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+/**
+ * Wrapper around SocketCAN socket.
+ */
+struct CanSocket {
+ using ReadCallback = std::function<void(const struct canfd_frame&, std::chrono::nanoseconds)>;
+ using ErrorCallback = std::function<void()>;
+
+ /**
+ * Open and bind SocketCAN socket.
+ *
+ * \param ifname SocketCAN network interface name (such as can0)
+ * \param rdcb Callback on received messages
+ * \param errcb Callback on socket failure
+ * \return Socket instance, or nullptr if it wasn't possible to open one
+ */
+ static std::unique_ptr<CanSocket> open(const std::string& ifname, ReadCallback rdcb,
+ ErrorCallback errcb);
+ virtual ~CanSocket();
+
+ /**
+ * Send CAN frame.
+ *
+ * \param frame Frame to send
+ * \return true in case of success, false otherwise
+ */
+ bool send(const struct canfd_frame& frame);
+
+ private:
+ CanSocket(base::unique_fd socket, ReadCallback rdcb, ErrorCallback errcb);
+ void readerThread();
+
+ ReadCallback mReadCallback;
+ ErrorCallback mErrorCallback;
+
+ const base::unique_fd mSocket;
+ std::thread mReaderThread;
+ std::atomic<bool> mStopReaderThread = false;
+
+ DISALLOW_COPY_AND_ASSIGN(CanSocket);
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CloseHandle.cpp b/automotive/can/1.0/default/CloseHandle.cpp
new file mode 100644
index 0000000..13693d2
--- /dev/null
+++ b/automotive/can/1.0/default/CloseHandle.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "CloseHandle.h"
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+CloseHandle::CloseHandle(Callback callback) : mCallback(callback) {}
+
+CloseHandle::~CloseHandle() {
+ close();
+}
+
+Return<void> CloseHandle::close() {
+ const auto wasClosed = mIsClosed.exchange(true);
+ if (wasClosed) return {};
+
+ mCallback();
+ return {};
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/CloseHandle.h b/automotive/can/1.0/default/CloseHandle.h
new file mode 100644
index 0000000..94972e0
--- /dev/null
+++ b/automotive/can/1.0/default/CloseHandle.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android-base/macros.h>
+#include <android/hardware/automotive/can/1.0/ICloseHandle.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+/**
+ * Generic ICloseHandle implementation ignoring double-close events.
+ */
+struct CloseHandle : public ICloseHandle {
+ using Callback = std::function<void()>;
+
+ /**
+ * Create a handle with a callback.
+ *
+ * The callback is guaranteed to be called exactly once.
+ *
+ * \param callback Called on the first close() call, or on destruction of the handle
+ */
+ CloseHandle(Callback callback);
+ virtual ~CloseHandle();
+
+ Return<void> close() override;
+
+ private:
+ Callback mCallback;
+ std::atomic<bool> mIsClosed = false;
+
+ DISALLOW_COPY_AND_ASSIGN(CloseHandle);
+};
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/default/android.hardware.automotive.can@1.0-service.rc b/automotive/can/1.0/default/android.hardware.automotive.can@1.0-service.rc
new file mode 100644
index 0000000..a629bda
--- /dev/null
+++ b/automotive/can/1.0/default/android.hardware.automotive.can@1.0-service.rc
@@ -0,0 +1,5 @@
+service can-hal-1.0-service /vendor/bin/hw/android.hardware.automotive.can@1.0-service
+ class hal
+ capabilities NET_ADMIN
+ user vehicle_network
+ group system inet
diff --git a/automotive/can/1.0/default/libnetdevice/Android.bp b/automotive/can/1.0/default/libnetdevice/Android.bp
new file mode 100644
index 0000000..31e5ad0
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/Android.bp
@@ -0,0 +1,30 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_library_static {
+ name: "android.hardware.automotive.can@libnetdevice",
+ defaults: ["android.hardware.automotive.can@defaults"],
+ vendor_available: true,
+ relative_install_path: "hw",
+ srcs: [
+ "NetlinkRequest.cpp",
+ "NetlinkSocket.cpp",
+ "can.cpp",
+ "common.cpp",
+ "libnetdevice.cpp",
+ ],
+ export_include_dirs: ["include"],
+}
diff --git a/automotive/can/1.0/default/libnetdevice/NetlinkRequest.cpp b/automotive/can/1.0/default/libnetdevice/NetlinkRequest.cpp
new file mode 100644
index 0000000..9845bc7
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/NetlinkRequest.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "NetlinkRequest.h"
+
+#include <android-base/logging.h>
+
+namespace android {
+namespace netdevice {
+namespace impl {
+
+static struct rtattr* nlmsg_tail(struct nlmsghdr* n) {
+ return reinterpret_cast<struct rtattr*>( //
+ reinterpret_cast<uintptr_t>(n) + NLMSG_ALIGN(n->nlmsg_len));
+}
+
+struct rtattr* addattr_l(struct nlmsghdr* n, size_t maxLen, rtattrtype_t type, const void* data,
+ size_t dataLen) {
+ size_t newLen = NLMSG_ALIGN(n->nlmsg_len) + RTA_SPACE(dataLen);
+ if (newLen > maxLen) {
+ LOG(ERROR) << "addattr_l failed - exceeded maxLen: " << newLen << " > " << maxLen;
+ return nullptr;
+ }
+
+ auto attr = nlmsg_tail(n);
+ attr->rta_len = RTA_SPACE(dataLen);
+ attr->rta_type = type;
+ if (dataLen > 0) memcpy(RTA_DATA(attr), data, dataLen);
+
+ n->nlmsg_len = newLen;
+ return attr;
+}
+
+struct rtattr* addattr_nest(struct nlmsghdr* n, size_t maxLen, rtattrtype_t type) {
+ return addattr_l(n, maxLen, type, nullptr, 0);
+}
+
+void addattr_nest_end(struct nlmsghdr* n, struct rtattr* nest) {
+ size_t nestLen = reinterpret_cast<uintptr_t>(nlmsg_tail(n)) - reinterpret_cast<uintptr_t>(nest);
+ nest->rta_len = nestLen;
+}
+
+} // namespace impl
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/NetlinkRequest.h b/automotive/can/1.0/default/libnetdevice/NetlinkRequest.h
new file mode 100644
index 0000000..21202e3
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/NetlinkRequest.h
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android-base/macros.h>
+#include <linux/rtnetlink.h>
+
+#include <string>
+
+namespace android {
+namespace netdevice {
+
+typedef unsigned short rtattrtype_t; // as in rtnetlink.h
+typedef __u16 nlmsgtype_t; // as in netlink.h
+
+/**
+ * Implementation details, do not use outside NetlinkRequest template.
+ */
+namespace impl {
+
+struct rtattr* addattr_l(struct nlmsghdr* n, size_t maxLen, rtattrtype_t type, const void* data,
+ size_t dataLen);
+struct rtattr* addattr_nest(struct nlmsghdr* n, size_t maxLen, rtattrtype_t type);
+void addattr_nest_end(struct nlmsghdr* n, struct rtattr* nest);
+
+} // namespace impl
+
+/**
+ * Wrapper around NETLINK_ROUTE messages, to build them in C++ style.
+ *
+ * \param T specific message header (such as struct ifinfomsg)
+ * \param BUFSIZE how much space to reserve for payload (not counting the header size)
+ */
+template <class T, unsigned int BUFSIZE = 128>
+struct NetlinkRequest {
+ /**
+ * Create empty message.
+ *
+ * \param type Message type (such as RTM_NEWLINK)
+ * \param flags Message flags (such as NLM_F_REQUEST)
+ */
+ NetlinkRequest(nlmsgtype_t type, uint16_t flags) {
+ mRequest.nlmsg.nlmsg_len = NLMSG_LENGTH(sizeof(mRequest.data));
+ mRequest.nlmsg.nlmsg_type = type;
+ mRequest.nlmsg.nlmsg_flags = flags;
+ }
+
+ /** Returns pointer to raw netlink message header. */
+ struct nlmsghdr* header() {
+ return &mRequest.nlmsg;
+ }
+ /** Reference to message-specific header. */
+ T& data() { return mRequest.data; }
+
+ /**
+ * Adds an attribute of a simple type.
+ *
+ * If this method fails (i.e. due to insufficient space), the message will be marked
+ * as bad (\see isGood).
+ *
+ * \param type attribute type (such as IFLA_IFNAME)
+ * \param attr attribute data
+ */
+ template <class A>
+ void addattr(rtattrtype_t type, const A& attr) {
+ if (!mIsGood) return;
+ auto ap = impl::addattr_l(&mRequest.nlmsg, sizeof(mRequest), type, &attr, sizeof(attr));
+ if (ap == nullptr) mIsGood = false;
+ }
+
+ template <>
+ void addattr(rtattrtype_t type, const std::string& s) {
+ if (!mIsGood) return;
+ auto ap = impl::addattr_l(&mRequest.nlmsg, sizeof(mRequest), type, s.c_str(), s.size() + 1);
+ if (ap == nullptr) mIsGood = false;
+ }
+
+ /**
+ * Guard class to frame nested attributes. See nest(int).
+ */
+ struct Nest {
+ Nest(NetlinkRequest& req, rtattrtype_t type) : mReq(req), mAttr(req.nestStart(type)) {}
+ ~Nest() { mReq.nestEnd(mAttr); }
+
+ private:
+ NetlinkRequest& mReq;
+ struct rtattr* mAttr;
+
+ DISALLOW_COPY_AND_ASSIGN(Nest);
+ };
+
+ /**
+ * Add nested attribute.
+ *
+ * The returned object is a guard for auto-nesting children inside the argument attribute.
+ * When the Nest object goes out of scope, the nesting attribute is closed.
+ *
+ * Example usage nesting IFLA_CAN_BITTIMING inside IFLA_INFO_DATA, which is nested
+ * inside IFLA_LINKINFO:
+ * NetlinkRequest<struct ifinfomsg> req(RTM_NEWLINK, NLM_F_REQUEST);
+ * {
+ * auto linkinfo = req.nest(IFLA_LINKINFO);
+ * req.addattr(IFLA_INFO_KIND, "can");
+ * {
+ * auto infodata = req.nest(IFLA_INFO_DATA);
+ * req.addattr(IFLA_CAN_BITTIMING, bitTimingStruct);
+ * }
+ * }
+ * // use req
+ *
+ * \param type attribute type (such as IFLA_LINKINFO)
+ */
+ Nest nest(int type) { return Nest(*this, type); }
+
+ /**
+ * Indicates, whether the message is in a good state.
+ *
+ * The bad state is usually a result of payload buffer being too small.
+ * You can modify BUFSIZE template parameter to fix this.
+ */
+ bool isGood() const { return mIsGood; }
+
+ private:
+ bool mIsGood = true;
+
+ struct {
+ struct nlmsghdr nlmsg;
+ T data;
+ char buf[BUFSIZE];
+ } mRequest = {};
+
+ struct rtattr* nestStart(rtattrtype_t type) {
+ if (!mIsGood) return nullptr;
+ auto attr = impl::addattr_nest(&mRequest.nlmsg, sizeof(mRequest), type);
+ if (attr == nullptr) mIsGood = false;
+ return attr;
+ }
+
+ void nestEnd(struct rtattr* nest) {
+ if (mIsGood && nest != nullptr) impl::addattr_nest_end(&mRequest.nlmsg, nest);
+ }
+};
+
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/NetlinkSocket.cpp b/automotive/can/1.0/default/libnetdevice/NetlinkSocket.cpp
new file mode 100644
index 0000000..0514764
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/NetlinkSocket.cpp
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "NetlinkSocket.h"
+
+#include <android-base/logging.h>
+
+namespace android {
+namespace netdevice {
+
+NetlinkSocket::NetlinkSocket(int protocol) {
+ mFd.reset(socket(AF_NETLINK, SOCK_RAW, protocol));
+ if (!mFd.ok()) {
+ LOG(ERROR) << "Can't open Netlink socket: " << errno;
+ mFailed = true;
+ return;
+ }
+
+ struct sockaddr_nl sa = {};
+ sa.nl_family = AF_NETLINK;
+
+ if (bind(mFd.get(), reinterpret_cast<struct sockaddr*>(&sa), sizeof(sa)) < 0) {
+ LOG(ERROR) << "Can't bind Netlink socket: " << errno;
+ mFd.reset();
+ mFailed = true;
+ }
+}
+
+bool NetlinkSocket::send(struct nlmsghdr* nlmsg) {
+ if (mFailed) return false;
+
+ nlmsg->nlmsg_pid = 0; // kernel
+ nlmsg->nlmsg_seq = mSeq++;
+ nlmsg->nlmsg_flags |= NLM_F_ACK;
+
+ struct iovec iov = {nlmsg, nlmsg->nlmsg_len};
+
+ struct sockaddr_nl sa = {};
+ sa.nl_family = AF_NETLINK;
+
+ struct msghdr msg = {};
+ msg.msg_name = &sa;
+ msg.msg_namelen = sizeof(sa);
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+
+ if (sendmsg(mFd.get(), &msg, 0) < 0) {
+ LOG(ERROR) << "Can't send Netlink message: " << errno;
+ return false;
+ }
+ return true;
+}
+
+bool NetlinkSocket::receiveAck() {
+ if (mFailed) return false;
+
+ char buf[8192];
+
+ struct sockaddr_nl sa;
+ struct iovec iov = {buf, sizeof(buf)};
+
+ struct msghdr msg = {};
+ msg.msg_name = &sa;
+ msg.msg_namelen = sizeof(sa);
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+
+ const ssize_t status = recvmsg(mFd.get(), &msg, 0);
+ if (status < 0) {
+ LOG(ERROR) << "Failed to receive Netlink message: " << errno;
+ return false;
+ }
+ size_t remainingLen = status;
+
+ if (msg.msg_flags & MSG_TRUNC) {
+ LOG(ERROR) << "Failed to receive Netlink message: truncated";
+ return false;
+ }
+
+ for (auto nlmsg = reinterpret_cast<struct nlmsghdr*>(buf); NLMSG_OK(nlmsg, remainingLen);
+ nlmsg = NLMSG_NEXT(nlmsg, remainingLen)) {
+ // We're looking for error/ack message only, ignoring others.
+ if (nlmsg->nlmsg_type != NLMSG_ERROR) {
+ LOG(WARNING) << "Received unexpected Netlink message (ignored): " << nlmsg->nlmsg_type;
+ continue;
+ }
+
+ // Found error/ack message, return status.
+ auto nlerr = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(nlmsg));
+ if (nlerr->error != 0) {
+ LOG(ERROR) << "Received Netlink error message: " << nlerr->error;
+ return false;
+ }
+ return true;
+ }
+ // Couldn't find any error/ack messages.
+ return false;
+}
+
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/NetlinkSocket.h b/automotive/can/1.0/default/libnetdevice/NetlinkSocket.h
new file mode 100644
index 0000000..81d6224
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/NetlinkSocket.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "NetlinkRequest.h"
+
+#include <android-base/macros.h>
+#include <android-base/unique_fd.h>
+
+#include <linux/netlink.h>
+
+namespace android {
+namespace netdevice {
+
+/**
+ * A wrapper around AF_NETLINK sockets.
+ *
+ * This class is not thread safe to use a single instance between multiple threads, but it's fine to
+ * use multiple instances over multiple threads.
+ */
+struct NetlinkSocket {
+ NetlinkSocket(int protocol);
+
+ /**
+ * Send Netlink message to Kernel.
+ *
+ * @param msg Message to send, nlmsg_seq will be set to next sequence number
+ * @return true, if succeeded
+ */
+ template <class T, unsigned int BUFSIZE>
+ bool send(NetlinkRequest<T, BUFSIZE>& req) {
+ if (!req.isGood()) return false;
+ return send(req.header());
+ }
+
+ /**
+ * Receive Netlink ACK message from Kernel.
+ *
+ * @return true if received ACK message, false in case of error
+ */
+ bool receiveAck();
+
+ private:
+ uint32_t mSeq = 0;
+ base::unique_fd mFd;
+ bool mFailed = false;
+
+ bool send(struct nlmsghdr* msg);
+
+ DISALLOW_COPY_AND_ASSIGN(NetlinkSocket);
+};
+
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/can.cpp b/automotive/can/1.0/default/libnetdevice/can.cpp
new file mode 100644
index 0000000..87617dd
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/can.cpp
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <libnetdevice/libnetdevice.h>
+
+#include "NetlinkRequest.h"
+#include "NetlinkSocket.h"
+#include "common.h"
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+#include <linux/can.h>
+#include <linux/can/netlink.h>
+
+namespace android {
+namespace netdevice {
+namespace can {
+
+base::unique_fd socket(const std::string& ifname) {
+ struct sockaddr_can addr = {};
+ addr.can_family = AF_CAN;
+ addr.can_ifindex = nametoindex(ifname);
+ if (addr.can_ifindex == 0) {
+ LOG(ERROR) << "Interface " << ifname << " doesn't exists";
+ return {};
+ }
+
+ base::unique_fd sock(::socket(PF_CAN, SOCK_RAW, CAN_RAW));
+ if (!sock.ok()) {
+ LOG(ERROR) << "Failed to create CAN socket";
+ return {};
+ }
+
+ if (0 != fcntl(sock.get(), F_SETFL, O_RDWR | O_NONBLOCK)) {
+ LOG(ERROR) << "Couldn't put CAN socket in non-blocking mode";
+ return {};
+ }
+
+ if (0 != bind(sock.get(), reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr))) {
+ LOG(ERROR) << "Can't bind to CAN interface " << ifname;
+ return {};
+ }
+
+ return sock;
+}
+
+bool setBitrate(std::string ifname, uint32_t bitrate) {
+ struct can_bittiming bt = {};
+ bt.bitrate = bitrate;
+
+ NetlinkRequest<struct ifinfomsg> req(RTM_NEWLINK, NLM_F_REQUEST);
+
+ const auto ifidx = nametoindex(ifname);
+ if (ifidx == 0) {
+ LOG(ERROR) << "Can't find interface " << ifname;
+ return false;
+ }
+ req.data().ifi_index = ifidx;
+
+ {
+ auto linkinfo = req.nest(IFLA_LINKINFO);
+ req.addattr(IFLA_INFO_KIND, "can");
+ {
+ auto infodata = req.nest(IFLA_INFO_DATA);
+ /* For CAN FD, it would require to add IFLA_CAN_DATA_BITTIMING
+ * and IFLA_CAN_CTRLMODE as well. */
+ req.addattr(IFLA_CAN_BITTIMING, bt);
+ }
+ }
+
+ NetlinkSocket sock(NETLINK_ROUTE);
+ return sock.send(req) && sock.receiveAck();
+}
+
+} // namespace can
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/common.cpp b/automotive/can/1.0/default/libnetdevice/common.cpp
new file mode 100644
index 0000000..3deac3e
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/common.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "common.h"
+
+#include <android-base/logging.h>
+
+#include <net/if.h>
+
+namespace android {
+namespace netdevice {
+
+unsigned int nametoindex(const std::string& ifname) {
+ const auto ifidx = if_nametoindex(ifname.c_str());
+ if (ifidx != 0) return ifidx;
+
+ const auto err = errno;
+ if (err != ENODEV) {
+ LOG(ERROR) << "if_nametoindex(" << ifname << ") failed: " << err;
+ }
+ return 0;
+}
+
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/common.h b/automotive/can/1.0/default/libnetdevice/common.h
new file mode 100644
index 0000000..9bdff4d
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/common.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <string>
+
+namespace android {
+namespace netdevice {
+
+/**
+ * Returns the index of a given network interface.
+ *
+ * If the syscall to check the index fails with other error than ENODEV, it gets logged and the
+ * return value indicates the interface doesn't exists.
+ *
+ * \param ifname Interface to check
+ * \return Interface index, or 0 if the interface doesn't exist
+ */
+unsigned int nametoindex(const std::string& ifname);
+
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/include/libnetdevice/can.h b/automotive/can/1.0/default/libnetdevice/include/libnetdevice/can.h
new file mode 100644
index 0000000..ec3f962
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/include/libnetdevice/can.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android-base/unique_fd.h>
+
+#include <string>
+
+namespace android {
+namespace netdevice {
+namespace can {
+
+/**
+ * Opens and binds SocketCAN socket.
+ *
+ * @param ifname Interface to open a socket against
+ * @return Socket's FD or -1 in case of failure
+ */
+base::unique_fd socket(const std::string& ifname);
+
+/**
+ * Sets CAN interface bitrate.
+ */
+bool setBitrate(std::string ifname, uint32_t bitrate);
+
+} // namespace can
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/include/libnetdevice/libnetdevice.h b/automotive/can/1.0/default/libnetdevice/include/libnetdevice/libnetdevice.h
new file mode 100644
index 0000000..33d5de5
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/include/libnetdevice/libnetdevice.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <optional>
+#include <string>
+
+namespace android {
+namespace netdevice {
+
+/**
+ * Checks, if the network interface exists.
+ *
+ * @param ifname Interface to check
+ * @return true if it exists, false otherwise
+ */
+bool exists(std::string ifname);
+
+/**
+ * Checks if network interface is up.
+ *
+ * @param ifname Interface to check
+ * @return true/false if the check succeeded, nullopt otherwise
+ */
+std::optional<bool> isUp(std::string ifname);
+
+/**
+ * Brings network interface up.
+ *
+ * @param ifname Interface to bring up
+ * @return true in case of success, false otherwise
+ */
+bool up(std::string ifname);
+
+/**
+ * Brings network interface down.
+ *
+ * @param ifname Interface to bring down
+ * @return true in case of success, false otherwise
+ */
+bool down(std::string ifname);
+
+/**
+ * Adds virtual link.
+ *
+ * @param dev the name of the new virtual device
+ * @param type the type of the new device
+ * @return true in case of success, false otherwise
+ */
+bool add(std::string dev, std::string type);
+
+/**
+ * Deletes virtual link.
+ *
+ * @param dev the name of the device to remove
+ * @return true in case of success, false otherwise
+ */
+bool del(std::string dev);
+
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp b/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp
new file mode 100644
index 0000000..fc2b193
--- /dev/null
+++ b/automotive/can/1.0/default/libnetdevice/libnetdevice.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <libnetdevice/libnetdevice.h>
+
+#include "NetlinkRequest.h"
+#include "NetlinkSocket.h"
+#include "common.h"
+
+#include <android-base/logging.h>
+
+#include <linux/can.h>
+#include <net/if.h>
+
+namespace android {
+namespace netdevice {
+
+bool exists(std::string ifname) {
+ return nametoindex(ifname) != 0;
+}
+
+static bool sendIfreq(unsigned long request, struct ifreq& ifr) {
+ /* For general interfaces it would be socket(AF_INET, SOCK_DGRAM, 0),
+ * but SEPolicy forces us to limit our flexibility here. */
+ base::unique_fd sock(socket(PF_CAN, SOCK_RAW, CAN_RAW));
+ if (!sock.ok()) {
+ LOG(ERROR) << "Can't create socket";
+ return false;
+ }
+
+ if (ioctl(sock.get(), request, &ifr) < 0) {
+ LOG(ERROR) << "ioctl(" << std::hex << request << std::dec << ") failed: " << errno;
+ return false;
+ }
+
+ return true;
+}
+
+static struct ifreq ifreqFromName(const std::string& ifname) {
+ struct ifreq ifr = {};
+ strlcpy(ifr.ifr_name, ifname.c_str(), IF_NAMESIZE);
+ return ifr;
+}
+
+std::optional<bool> isUp(std::string ifname) {
+ struct ifreq ifr = ifreqFromName(ifname);
+ if (!sendIfreq(SIOCGIFFLAGS, ifr)) return std::nullopt;
+ return ifr.ifr_flags & IFF_UP;
+}
+
+bool up(std::string ifname) {
+ struct ifreq ifr = ifreqFromName(ifname);
+ if (!sendIfreq(SIOCGIFFLAGS, ifr)) return false;
+ ifr.ifr_flags |= IFF_UP;
+ return sendIfreq(SIOCSIFFLAGS, ifr);
+}
+
+bool down(std::string ifname) {
+ struct ifreq ifr = ifreqFromName(ifname);
+ if (!sendIfreq(SIOCGIFFLAGS, ifr)) return false;
+ ifr.ifr_flags &= ~IFF_UP;
+ return sendIfreq(SIOCSIFFLAGS, ifr);
+}
+
+bool add(std::string dev, std::string type) {
+ NetlinkRequest<struct ifinfomsg> req(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
+ req.addattr(IFLA_IFNAME, dev);
+
+ {
+ auto linkinfo = req.nest(IFLA_LINKINFO);
+ req.addattr(IFLA_INFO_KIND, type);
+ }
+
+ NetlinkSocket sock(NETLINK_ROUTE);
+ return sock.send(req) && sock.receiveAck();
+}
+
+bool del(std::string dev) {
+ NetlinkRequest<struct ifinfomsg> req(RTM_DELLINK, NLM_F_REQUEST);
+ req.addattr(IFLA_IFNAME, dev);
+
+ NetlinkSocket sock(NETLINK_ROUTE);
+ return sock.send(req) && sock.receiveAck();
+}
+
+} // namespace netdevice
+} // namespace android
diff --git a/automotive/can/1.0/default/service.cpp b/automotive/can/1.0/default/service.cpp
new file mode 100644
index 0000000..7ef44fc
--- /dev/null
+++ b/automotive/can/1.0/default/service.cpp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "CanController.h"
+
+#include <android-base/logging.h>
+#include <hidl/HidlTransportSupport.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace implementation {
+
+static void canControllerService() {
+ base::SetDefaultTag("CanController");
+ base::SetMinimumLogSeverity(android::base::VERBOSE);
+ configureRpcThreadpool(16, true);
+ LOG(DEBUG) << "CAN controller service starting...";
+
+ CanController canController;
+ if (canController.registerAsService("socketcan") != OK) {
+ LOG(FATAL) << "Failed to register CAN controller";
+ return;
+ }
+
+ LOG(INFO) << "CAN controller service ready";
+ joinRpcThreadpool();
+}
+
+} // namespace implementation
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
+
+int main() {
+ ::android::hardware::automotive::can::V1_0::implementation::canControllerService();
+ return 1; // canBusService (joinRpcThreadpool) shouldn't exit
+}
diff --git a/automotive/can/1.0/hidl-utils/Android.bp b/automotive/can/1.0/hidl-utils/Android.bp
new file mode 100644
index 0000000..bc8ff13
--- /dev/null
+++ b/automotive/can/1.0/hidl-utils/Android.bp
@@ -0,0 +1,20 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_library_headers {
+ name: "android.hardware.automotive.can@hidl-utils-lib",
+ export_include_dirs: ["include"],
+}
diff --git a/automotive/can/1.0/hidl-utils/include/hidl-utils/hidl-utils.h b/automotive/can/1.0/hidl-utils/include/hidl-utils/hidl-utils.h
new file mode 100644
index 0000000..039f971
--- /dev/null
+++ b/automotive/can/1.0/hidl-utils/include/hidl-utils/hidl-utils.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace hidl_utils {
+
+/**
+ * Helper functor to fetch results from multi-return HIDL calls.
+ * It's meant to be used in place of _hidl_cb callbacks.
+ *
+ * Please note extracting these return variables outside of the callback scope requires making
+ * a copy of each return variable. This may be costly for frequently called HIDL methods with
+ * non-negligible return object size. Please be cautious about performance when using this.
+ *
+ * Example usage:
+ * Result result;
+ * sp<ISomeInterface> iface;
+ * hidlObject->someMethod(arg1, arg2, hidl_utils::fill(&result, &iface)).assertOk();
+ * // use result and iface
+ */
+template <typename... T>
+struct fill : public std::function<void(const T&...)> {
+ /**
+ * Create _hidl_cb functor that copies the call arguments to specified pointers.
+ *
+ * \param args... Targets to copy the call arguments to
+ */
+ fill(T*... args) : mTargets(args...) {}
+
+ void operator()(const T&... args) { copy<0, T...>(args...); }
+
+ private:
+ std::tuple<T*...> mTargets;
+
+ template <int Pos, typename First>
+ inline void copy(const First& first) {
+ *std::get<Pos>(mTargets) = first;
+ }
+
+ template <int Pos, typename First, typename... Rest>
+ inline void copy(const First& first, const Rest&... rest) {
+ *std::get<Pos>(mTargets) = first;
+ copy<Pos + 1, Rest...>(rest...);
+ }
+};
+
+} // namespace hidl_utils
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/tools/Android.bp b/automotive/can/1.0/tools/Android.bp
new file mode 100644
index 0000000..8c26985
--- /dev/null
+++ b/automotive/can/1.0/tools/Android.bp
@@ -0,0 +1,60 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_binary {
+ name: "canhalctrl",
+ defaults: ["android.hardware.automotive.can@defaults"],
+ srcs: [
+ "canhalctrl.cpp",
+ ],
+ shared_libs: [
+ "android.hardware.automotive.can@1.0",
+ "libhidlbase",
+ "libhidltransport",
+ ],
+ header_libs: [
+ "android.hardware.automotive.can@hidl-utils-lib",
+ ],
+}
+
+cc_binary {
+ name: "canhaldump",
+ defaults: ["android.hardware.automotive.can@defaults"],
+ srcs: [
+ "canhaldump.cpp",
+ ],
+ shared_libs: [
+ "android.hardware.automotive.can@1.0",
+ "libhidlbase",
+ "libhidltransport",
+ ],
+ header_libs: [
+ "android.hardware.automotive.can@hidl-utils-lib",
+ ],
+}
+
+cc_binary {
+ name: "canhalsend",
+ defaults: ["android.hardware.automotive.can@defaults"],
+ srcs: [
+ "canhalsend.cpp",
+ ],
+ shared_libs: [
+ "android.hardware.automotive.can@1.0",
+ "libhidlbase",
+ "libhidltransport",
+ ],
+}
diff --git a/automotive/can/1.0/tools/canhalctrl.cpp b/automotive/can/1.0/tools/canhalctrl.cpp
new file mode 100644
index 0000000..fa1048d
--- /dev/null
+++ b/automotive/can/1.0/tools/canhalctrl.cpp
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android-base/logging.h>
+#include <android/hardware/automotive/can/1.0/ICanController.h>
+#include <android/hidl/manager/1.2/IServiceManager.h>
+#include <hidl-utils/hidl-utils.h>
+
+#include <iostream>
+#include <string>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+
+using ICanController = V1_0::ICanController;
+
+static void usage() {
+ std::cerr << "CAN bus HAL Control tool" << std::endl;
+ std::cerr << std::endl << "usage:" << std::endl << std::endl;
+ std::cerr << "canhalctrl up <bus name> <type> <interface> [baudrate]" << std::endl;
+ std::cerr << "where:" << std::endl;
+ std::cerr << " bus name - name under which ICanBus will be published" << std::endl;
+ std::cerr << " type - one of: virtual, socketcan, slcan, indexed" << std::endl;
+ std::cerr << " interface - hardware identifier (like can0, vcan0, /dev/ttyUSB0)" << std::endl;
+ std::cerr << " baudrate - such as 100000, 125000, 250000, 500000" << std::endl;
+ std::cerr << std::endl;
+ std::cerr << "canhalctrl down <bus name>" << std::endl;
+ std::cerr << "where:" << std::endl;
+ std::cerr << " bus name - name under which ICanBus will be published" << std::endl;
+}
+
+static hidl_vec<hidl_string> getControlServices() {
+ auto manager = hidl::manager::V1_2::IServiceManager::getService();
+ hidl_vec<hidl_string> services;
+ manager->listManifestByInterface(ICanController::descriptor, hidl_utils::fill(&services));
+ if (services.size() == 0) {
+ std::cerr << "No ICanController services registered (missing privileges?)" << std::endl;
+ exit(-1);
+ }
+ return services;
+}
+
+static bool isSupported(sp<ICanController> ctrl, ICanController::InterfaceType iftype) {
+ hidl_vec<ICanController::InterfaceType> supported;
+ if (!ctrl->getSupportedInterfaceTypes(hidl_utils::fill(&supported)).isOk()) return false;
+ return supported.contains(iftype);
+}
+
+static int up(const std::string& busName, ICanController::InterfaceType type,
+ const std::string& interface, uint32_t baudrate) {
+ bool anySupported = false;
+ for (auto&& service : getControlServices()) {
+ auto ctrl = ICanController::getService(service);
+ if (ctrl == nullptr) {
+ std::cerr << "Couldn't open ICanController/" << service;
+ continue;
+ }
+
+ if (!isSupported(ctrl, type)) continue;
+ anySupported = true;
+
+ ICanController::BusConfiguration config = {};
+ config.name = busName;
+ config.iftype = type;
+ config.baudrate = baudrate;
+
+ if (type == ICanController::InterfaceType::INDEXED) {
+ config.interfaceId.index(std::stol(interface));
+ } else {
+ config.interfaceId.address(interface);
+ }
+
+ const auto upresult = ctrl->upInterface(config);
+ if (upresult == ICanController::Result::OK) return 0;
+ std::cerr << "Failed to bring interface up: " << toString(upresult) << std::endl;
+ // Let's continue the loop to try other controllers.
+ }
+
+ if (!anySupported) {
+ std::cerr << "No controller supports " << toString(type) << std::endl;
+ }
+ return -1;
+}
+
+static int down(const std::string& busName) {
+ for (auto&& service : getControlServices()) {
+ auto ctrl = ICanController::getService(service);
+ if (ctrl == nullptr) continue;
+
+ if (ctrl->downInterface(busName)) return 0;
+ }
+
+ std::cerr << "Failed to bring interface " << busName << " down (maybe it's down already?)"
+ << std::endl;
+ return -1;
+}
+
+static std::optional<ICanController::InterfaceType> parseInterfaceType(const std::string& str) {
+ if (str == "virtual") return ICanController::InterfaceType::VIRTUAL;
+ if (str == "socketcan") return ICanController::InterfaceType::SOCKETCAN;
+ if (str == "slcan") return ICanController::InterfaceType::SLCAN;
+ if (str == "indexed") return ICanController::InterfaceType::INDEXED;
+ return std::nullopt;
+}
+
+static int main(int argc, char* argv[]) {
+ base::SetDefaultTag("CanHalControl");
+ base::SetMinimumLogSeverity(android::base::VERBOSE);
+
+ if (argc == 0) {
+ usage();
+ return 0;
+ }
+
+ std::string cmd(argv[0]);
+ argv++;
+ argc--;
+
+ if (cmd == "up") {
+ if (argc < 3 || argc > 4) {
+ std::cerr << "Invalid number of arguments to up command: " << argc << std::endl;
+ usage();
+ return -1;
+ }
+
+ const std::string busName(argv[0]);
+ const std::string typeStr(argv[1]);
+ const std::string interface(argv[2]);
+
+ const auto type = parseInterfaceType(typeStr);
+ if (!type) {
+ std::cerr << "Invalid interface type: " << typeStr << std::endl;
+ usage();
+ return -1;
+ }
+
+ long long baudrate = 0;
+ if (argc == 4) {
+ baudrate = std::stoll(argv[3]);
+ }
+
+ return up(busName, *type, interface, baudrate);
+ } else if (cmd == "down") {
+ if (argc != 1) {
+ std::cerr << "Invalid number of arguments to down command: " << argc << std::endl;
+ usage();
+ return -1;
+ }
+
+ return down(argv[0]);
+ } else {
+ std::cerr << "Invalid command: " << cmd << std::endl;
+ usage();
+ return -1;
+ }
+}
+
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
+
+int main(int argc, char* argv[]) {
+ if (argc < 1) return -1;
+ return ::android::hardware::automotive::can::main(--argc, ++argv);
+}
diff --git a/automotive/can/1.0/tools/canhaldump.cpp b/automotive/can/1.0/tools/canhaldump.cpp
new file mode 100644
index 0000000..5713d17
--- /dev/null
+++ b/automotive/can/1.0/tools/canhaldump.cpp
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android-base/logging.h>
+#include <android/hardware/automotive/can/1.0/ICanBus.h>
+#include <android/hardware/automotive/can/1.0/ICanMessageListener.h>
+#include <android/hidl/manager/1.2/IServiceManager.h>
+#include <hidl-utils/hidl-utils.h>
+
+#include <chrono>
+#include <iomanip>
+#include <iostream>
+#include <string>
+#include <thread>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+
+using namespace std::chrono_literals;
+
+using ICanBus = V1_0::ICanBus;
+using Result = V1_0::Result;
+
+struct CanMessageListener : public V1_0::ICanMessageListener {
+ const std::string name;
+
+ CanMessageListener(std::string name) : name(name) {}
+
+ virtual Return<void> onReceive(const V1_0::CanMessage& message) {
+ std::cout << " " << name << " " << std::hex << std::uppercase << std::setw(3)
+ << std::setfill('0') << message.id << std::setw(0);
+ if (message.remoteTransmissionRequest) {
+ std::cout << " RTR";
+ } else {
+ std::cout << " [" << message.payload.size() << "] ";
+ for (const auto byte : message.payload) {
+ std::cout << " " << unsigned(byte);
+ }
+ }
+ std::cout << std::nouppercase << std::dec << std::endl;
+ return {};
+ }
+
+ virtual Return<void> onError(V1_0::ErrorEvent error) {
+ std::cout << " " << name << " " << toString(error) << std::endl;
+ return {};
+ }
+};
+
+static void usage() {
+ std::cerr << "canhaldump - dump CAN bus traffic" << std::endl;
+ std::cerr << std::endl << "usage:" << std::endl << std::endl;
+ std::cerr << "canhaldump <bus name>" << std::endl;
+ std::cerr << "where:" << std::endl;
+ std::cerr << " bus name - name under which ICanBus is be published" << std::endl;
+}
+
+// TODO(b/135918744): extract to a new library
+static sp<ICanBus> tryOpen(const std::string& busname) {
+ auto bus = ICanBus::tryGetService(busname);
+ if (bus != nullptr) return bus;
+
+ /* Fallback for interfaces not registered in manifest. For testing purposes only,
+ * one should not depend on this in production deployment. */
+ auto manager = hidl::manager::V1_2::IServiceManager::getService();
+ auto ret = manager->get(ICanBus::descriptor, busname).withDefault(nullptr);
+ if (ret == nullptr) return nullptr;
+
+ std::cerr << "WARNING: bus " << busname << " is not registered in device manifest, "
+ << "trying to fetch it directly..." << std::endl;
+
+ return ICanBus::castFrom(ret);
+}
+
+static int candump(const std::string& busname) {
+ auto bus = tryOpen(busname);
+ if (bus == nullptr) {
+ std::cerr << "Bus " << busname << " is not available" << std::endl;
+ return -1;
+ }
+
+ Result result;
+ sp<V1_0::ICloseHandle> chnd;
+ // TODO(b/135918744): extract to library
+ bus->listen({}, new CanMessageListener(busname), hidl_utils::fill(&result, &chnd)).assertOk();
+
+ if (result != Result::OK) {
+ std::cerr << "Listen call failed: " << toString(result) << std::endl;
+ return -1;
+ }
+
+ while (true) std::this_thread::sleep_for(1h);
+}
+
+static int main(int argc, char* argv[]) {
+ base::SetDefaultTag("CanHalDump");
+ base::SetMinimumLogSeverity(android::base::VERBOSE);
+
+ if (argc == 0) {
+ usage();
+ return 0;
+ }
+
+ if (argc != 1) {
+ std::cerr << "Invalid number of arguments" << std::endl;
+ usage();
+ return -1;
+ }
+
+ return candump(argv[0]);
+}
+
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
+
+int main(int argc, char* argv[]) {
+ if (argc < 1) return -1;
+ return ::android::hardware::automotive::can::main(--argc, ++argv);
+}
diff --git a/automotive/can/1.0/tools/canhalsend.cpp b/automotive/can/1.0/tools/canhalsend.cpp
new file mode 100644
index 0000000..29330c9
--- /dev/null
+++ b/automotive/can/1.0/tools/canhalsend.cpp
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android-base/logging.h>
+#include <android/hardware/automotive/can/1.0/ICanBus.h>
+#include <android/hidl/manager/1.2/IServiceManager.h>
+
+#include <iostream>
+#include <string>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+
+using ICanBus = V1_0::ICanBus;
+using Result = V1_0::Result;
+
+static void usage() {
+ std::cerr << "cansend - simple command line tool to send raw CAN frames" << std::endl;
+ std::cerr << std::endl << "usage:" << std::endl << std::endl;
+ std::cerr << "canhalsend <bus name> <can id>#<data>" << std::endl;
+ std::cerr << "where:" << std::endl;
+ std::cerr << " bus name - name under which ICanBus is be published" << std::endl;
+ std::cerr << " can id - such as 1a5" << std::endl;
+ std::cerr << " data - such as deadbeef or 010203" << std::endl;
+}
+
+// TODO(b/135918744): extract to a new library
+static sp<ICanBus> tryOpen(const std::string& busname) {
+ auto bus = ICanBus::tryGetService(busname);
+ if (bus != nullptr) return bus;
+
+ /* Fallback for interfaces not registered in manifest. For testing purposes only,
+ * one should not depend on this in production deployment. */
+ auto manager = hidl::manager::V1_2::IServiceManager::getService();
+ auto ret = manager->get(ICanBus::descriptor, busname).withDefault(nullptr);
+ if (ret == nullptr) return nullptr;
+
+ std::cerr << "WARNING: bus " << busname << " is not registered in device manifest, "
+ << "trying to fetch it directly..." << std::endl;
+
+ return ICanBus::castFrom(ret);
+}
+
+static int cansend(const std::string& busname, V1_0::CanMessageId msgid,
+ std::vector<uint8_t> payload) {
+ auto bus = tryOpen(busname);
+ if (bus == nullptr) {
+ std::cerr << "Bus " << busname << " is not available" << std::endl;
+ return -1;
+ }
+
+ V1_0::CanMessage msg = {};
+ msg.id = msgid;
+ msg.payload = payload;
+
+ const auto result = bus->send(msg);
+ if (result != Result::OK) {
+ std::cerr << "Send call failed: " << toString(result) << std::endl;
+ return -1;
+ }
+ return 0;
+}
+
+static std::optional<std::tuple<V1_0::CanMessageId, std::vector<uint8_t>>> parseCanMessage(
+ const std::string& msg) {
+ const auto hashpos = msg.find("#");
+ if (hashpos == std::string::npos) return std::nullopt;
+
+ const std::string msgidStr = msg.substr(0, hashpos);
+ const std::string payloadStr = msg.substr(hashpos + 1);
+
+ size_t idx = 0;
+ V1_0::CanMessageId msgid = std::stoi(msgidStr, &idx, 16);
+ if (msgidStr[idx] != '\0') return std::nullopt;
+
+ std::vector<uint8_t> payload;
+ if (payloadStr.size() % 2 != 0) return std::nullopt;
+ for (size_t i = 0; i < payloadStr.size(); i += 2) {
+ std::string byteStr(payloadStr, i, 2);
+ payload.emplace_back(std::stoi(byteStr, &idx, 16));
+ if (byteStr[idx] != '\0') return std::nullopt;
+ }
+
+ return {{msgid, payload}};
+}
+
+static int main(int argc, char* argv[]) {
+ base::SetDefaultTag("CanHalSend");
+ base::SetMinimumLogSeverity(android::base::VERBOSE);
+
+ if (argc == 0) {
+ usage();
+ return 0;
+ }
+
+ if (argc != 2) {
+ std::cerr << "Invalid number of arguments" << std::endl;
+ usage();
+ return -1;
+ }
+
+ std::string busname(argv[0]);
+ const auto canmsg = parseCanMessage(argv[1]);
+ if (!canmsg) {
+ std::cerr << "Failed to parse CAN message argument" << std::endl;
+ return -1;
+ }
+ const auto [msgid, payload] = *canmsg;
+
+ return cansend(busname, msgid, payload);
+}
+
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
+
+int main(int argc, char* argv[]) {
+ if (argc < 1) return -1;
+ return ::android::hardware::automotive::can::main(--argc, ++argv);
+}
diff --git a/automotive/can/1.0/types.hal b/automotive/can/1.0/types.hal
new file mode 100644
index 0000000..37877c6
--- /dev/null
+++ b/automotive/can/1.0/types.hal
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.hardware.automotive.can@1.0;
+
+/**
+ * CAN message ID.
+ *
+ * Does not include any flags like RTR nor ERR, only a plain 11-bit
+ * or 29-bit identifier, as defined in CAN 1.x/2.0x.
+ *
+ * Unused bits must be set to zero.
+ */
+typedef uint32_t CanMessageId;
+
+/**
+ * CAN message being sent or received.
+ */
+struct CanMessage {
+ CanMessageId id;
+
+ /**
+ * CAN message payload, as defined in CAN 1.x and CAN 2.x standards.
+ *
+ * The length of the payload vector directly translates to the length
+ * of the data frame (i.e. includes any padding bytes), so it may be in
+ * a range of:
+ * - 0-8 bytes for standard CAN;
+ * - up to 64 bytes for CAN FD.
+ * ISO TP is not supported directly for now.
+ */
+ vec<uint8_t> payload;
+
+ /**
+ * Time in nanoseconds since boot.
+ *
+ * Ignored for outgoing messages.
+ */
+ uint64_t timestamp;
+
+ /**
+ * A request to proactively pull certain data from other ECU in CAN network.
+ *
+ * For details please refer to CAN standard.
+ *
+ * If this flag is set, payload must be empty.
+ */
+ bool remoteTransmissionRequest;
+};
+
+/**
+ * Single filter rule for CAN messages.
+ *
+ * A filter is satisfied if:
+ * ((receivedId & mask) == (id & mask)) == !inverted
+ *
+ * In order for set of filters to match, at least one non-inverted filters must match (if there is
+ * one) and all inverted filters must match. In other words:
+ * - a single matching non-inverted filter makes the whole set matching;
+ * - a single non-matching inverted filter makes the whole set non-matching.
+ */
+struct CanMessageFilter {
+ CanMessageId id;
+ uint32_t mask;
+ bool inverted;
+};
+
+enum Result : uint8_t {
+ OK,
+ UNKNOWN_ERROR,
+ PAYLOAD_TOO_LONG,
+ INTERFACE_DOWN,
+ TRANSMISSION_FAILURE,
+ INVALID_ARGUMENTS,
+};
+
+/**
+ * @see ICanMessageListener#onError
+ */
+enum ErrorEvent : uint8_t {
+ UNKNOWN_ERROR,
+
+ /** A problem with CAN interface HW. */
+ HARDWARE_ERROR,
+
+ /** TX buffer overflow: client is sending too many packets. */
+ TX_OVERFLOW,
+
+ /** RX buffer overflow: client is not reading packets fast enough. */
+ RX_OVERFLOW,
+
+ /** Received malformed input. */
+ MALFORMED_INPUT,
+
+ /** Bus overload: there is too much traffic on the bus. */
+ BUS_OVERLOAD,
+
+ /** Bus error: shorted Hi/Lo line, bus off etc. */
+ BUS_ERROR,
+};
diff --git a/automotive/can/1.0/vts/functional/Android.bp b/automotive/can/1.0/vts/functional/Android.bp
new file mode 100644
index 0000000..b4d9132
--- /dev/null
+++ b/automotive/can/1.0/vts/functional/Android.bp
@@ -0,0 +1,47 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_defaults {
+ name: "android.hardware.automotive.can@vts-defaults",
+ defaults: ["VtsHalTargetTestDefaults", "android.hardware.automotive.can@defaults"],
+ header_libs: [
+ "android.hardware.automotive.can@hidl-utils-lib",
+ "android.hardware.automotive.can@vts-utils-lib",
+ ],
+ static_libs: [
+ "android.hardware.automotive.can@1.0",
+ "libgmock",
+ ],
+ test_suites: ["general-tests"],
+}
+
+cc_test {
+ name: "VtsHalCanControllerV1_0TargetTest",
+ defaults: ["android.hardware.automotive.can@vts-defaults"],
+ srcs: ["VtsHalCanControllerV1_0TargetTest.cpp"],
+}
+
+cc_test {
+ name: "VtsHalCanBusV1_0TargetTest",
+ defaults: ["android.hardware.automotive.can@vts-defaults"],
+ srcs: ["VtsHalCanBusV1_0TargetTest.cpp"],
+}
+
+cc_test {
+ name: "VtsHalCanBusVirtualV1_0TargetTest",
+ defaults: ["android.hardware.automotive.can@vts-defaults"],
+ srcs: ["VtsHalCanBusVirtualV1_0TargetTest.cpp"],
+}
diff --git a/automotive/can/1.0/vts/functional/VtsHalCanBusV1_0TargetTest.cpp b/automotive/can/1.0/vts/functional/VtsHalCanBusV1_0TargetTest.cpp
new file mode 100644
index 0000000..215328e
--- /dev/null
+++ b/automotive/can/1.0/vts/functional/VtsHalCanBusV1_0TargetTest.cpp
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <VtsHalHidlTargetTestBase.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <android/hardware/automotive/can/1.0/ICanBus.h>
+#include <android/hardware/automotive/can/1.0/types.h>
+#include <can-vts-utils/can-hal-printers.h>
+#include <can-vts-utils/environment-utils.h>
+#include <gmock/gmock.h>
+#include <hidl-utils/hidl-utils.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace vts {
+
+using hardware::hidl_vec;
+
+static utils::SimpleHidlEnvironment<ICanBus>* gEnv = nullptr;
+
+struct CanMessageListener : public can::V1_0::ICanMessageListener {
+ virtual Return<void> onReceive(const can::V1_0::CanMessage&) { return {}; }
+ virtual Return<void> onError(can::V1_0::ErrorEvent) { return {}; }
+};
+
+class CanBusHalTest : public ::testing::VtsHalHidlTargetTestBase {
+ protected:
+ virtual void SetUp() override;
+ virtual void TearDown() override;
+
+ std::tuple<Result, sp<ICloseHandle>> listen(const hidl_vec<CanMessageFilter>& filter,
+ const sp<ICanMessageListener>& listener);
+
+ sp<ICanBus> mCanBus;
+};
+
+void CanBusHalTest::SetUp() {
+ const auto serviceName = gEnv->getServiceName<ICanBus>();
+ mCanBus = getService<ICanBus>(serviceName);
+ ASSERT_TRUE(mCanBus) << "Couldn't open CAN Bus: " << serviceName;
+}
+
+void CanBusHalTest::TearDown() {
+ mCanBus.clear();
+}
+
+std::tuple<Result, sp<ICloseHandle>> CanBusHalTest::listen(
+ const hidl_vec<CanMessageFilter>& filter, const sp<ICanMessageListener>& listener) {
+ Result halResult;
+ sp<ICloseHandle> closeHandle;
+ mCanBus->listen(filter, listener, hidl_utils::fill(&halResult, &closeHandle)).assertOk();
+
+ return {halResult, closeHandle};
+}
+
+TEST_F(CanBusHalTest, SendNoPayload) {
+ CanMessage msg = {};
+ msg.id = 0x123;
+
+ const auto result = mCanBus->send(msg);
+ ASSERT_EQ(Result::OK, result);
+}
+
+TEST_F(CanBusHalTest, Send8B) {
+ CanMessage msg = {};
+ msg.id = 0x234;
+ msg.payload = {1, 2, 3, 4, 5, 6, 7, 8};
+
+ const auto result = mCanBus->send(msg);
+ ASSERT_EQ(Result::OK, result);
+}
+
+TEST_F(CanBusHalTest, SendZeroId) {
+ CanMessage msg = {};
+ msg.payload = {1, 2, 3};
+
+ const auto result = mCanBus->send(msg);
+ ASSERT_EQ(Result::OK, result);
+}
+
+TEST_F(CanBusHalTest, SendTooLong) {
+ CanMessage msg = {};
+ msg.id = 0x123;
+ msg.payload = hidl_vec<uint8_t>(102400); // 100kiB
+
+ const auto result = mCanBus->send(msg);
+ ASSERT_EQ(Result::PAYLOAD_TOO_LONG, result);
+}
+
+TEST_F(CanBusHalTest, ListenNoFilter) {
+ const auto [result, closeHandle] = listen({}, new CanMessageListener());
+ ASSERT_EQ(Result::OK, result);
+
+ closeHandle->close().assertOk();
+}
+
+TEST_F(CanBusHalTest, ListenSomeFilter) {
+ hidl_vec<CanMessageFilter> filters = {
+ {0x123, 0x1FF, false},
+ {0x001, 0x00F, true},
+ {0x200, 0x100, false},
+ };
+
+ const auto [result, closeHandle] = listen(filters, new CanMessageListener());
+ ASSERT_EQ(Result::OK, result);
+
+ closeHandle->close().assertOk();
+}
+
+TEST_F(CanBusHalTest, ListenNull) {
+ const auto [result, closeHandle] = listen({}, nullptr);
+ ASSERT_EQ(Result::INVALID_ARGUMENTS, result);
+}
+
+TEST_F(CanBusHalTest, DoubleCloseListen) {
+ const auto [result, closeHandle] = listen({}, new CanMessageListener());
+ ASSERT_EQ(Result::OK, result);
+
+ closeHandle->close().assertOk();
+ closeHandle->close().assertOk();
+}
+
+TEST_F(CanBusHalTest, DontCloseListen) {
+ const auto [result, closeHandle] = listen({}, new CanMessageListener());
+ ASSERT_EQ(Result::OK, result);
+}
+
+} // namespace vts
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
+
+/**
+ * Example manual invocation:
+ * adb shell /data/nativetest64/VtsHalCanBusV1_0TargetTest/VtsHalCanBusV1_0TargetTest \
+ * --hal_service_instance=android.hardware.automotive.can@1.0::ICanBus/test
+ */
+int main(int argc, char** argv) {
+ using android::hardware::automotive::can::V1_0::ICanBus;
+ using android::hardware::automotive::can::V1_0::vts::gEnv;
+ using android::hardware::automotive::can::V1_0::vts::utils::SimpleHidlEnvironment;
+ android::base::SetDefaultTag("CanBusVts");
+ android::base::SetMinimumLogSeverity(android::base::VERBOSE);
+ gEnv = new SimpleHidlEnvironment<ICanBus>;
+ ::testing::AddGlobalTestEnvironment(gEnv);
+ ::testing::InitGoogleTest(&argc, argv);
+ gEnv->init(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/automotive/can/1.0/vts/functional/VtsHalCanBusVirtualV1_0TargetTest.cpp b/automotive/can/1.0/vts/functional/VtsHalCanBusVirtualV1_0TargetTest.cpp
new file mode 100644
index 0000000..699c138
--- /dev/null
+++ b/automotive/can/1.0/vts/functional/VtsHalCanBusVirtualV1_0TargetTest.cpp
@@ -0,0 +1,322 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <VtsHalHidlTargetTestBase.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <android/hardware/automotive/can/1.0/ICanBus.h>
+#include <android/hardware/automotive/can/1.0/ICanController.h>
+#include <android/hardware/automotive/can/1.0/types.h>
+#include <android/hidl/manager/1.2/IServiceManager.h>
+#include <can-vts-utils/can-hal-printers.h>
+#include <can-vts-utils/environment-utils.h>
+#include <gmock/gmock.h>
+#include <hidl-utils/hidl-utils.h>
+#include <utils/Mutex.h>
+#include <utils/SystemClock.h>
+
+#include <chrono>
+#include <thread>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace vts {
+
+using namespace std::chrono_literals;
+
+using hardware::hidl_vec;
+using InterfaceType = ICanController::InterfaceType;
+
+static utils::SimpleHidlEnvironment<ICanController>* gEnv = nullptr;
+
+struct CanMessageListener : public can::V1_0::ICanMessageListener {
+ DISALLOW_COPY_AND_ASSIGN(CanMessageListener);
+
+ CanMessageListener() {}
+
+ virtual Return<void> onReceive(const can::V1_0::CanMessage& msg) {
+ std::unique_lock<std::mutex> lk(mMessagesGuard);
+ mMessages.push_back(msg);
+ mMessagesUpdated.notify_one();
+ return {};
+ }
+
+ virtual Return<void> onError(can::V1_0::ErrorEvent event) {
+ EXPECT_TRUE(false) << "Got error: " << event;
+ return {};
+ }
+
+ virtual ~CanMessageListener() { mCloseHandle->close(); }
+
+ void assignCloseHandle(sp<ICloseHandle> closeHandle) {
+ EXPECT_TRUE(closeHandle);
+ EXPECT_FALSE(mCloseHandle);
+ mCloseHandle = closeHandle;
+ }
+
+ std::vector<can::V1_0::CanMessage> fetchMessages(std::chrono::milliseconds timeout,
+ unsigned atLeast = 1) {
+ std::unique_lock<std::mutex> lk(mMessagesGuard);
+ mMessagesUpdated.wait_for(lk, timeout, [&] { return mMessages.size() >= atLeast; });
+ const auto messages = mMessages;
+ mMessages.clear();
+ return messages;
+ }
+
+ private:
+ sp<ICloseHandle> mCloseHandle;
+
+ std::mutex mMessagesGuard;
+ std::condition_variable mMessagesUpdated GUARDED_BY(mMessagesGuard);
+ std::vector<can::V1_0::CanMessage> mMessages GUARDED_BY(mMessagesGuard);
+};
+
+struct Bus {
+ DISALLOW_COPY_AND_ASSIGN(Bus);
+
+ Bus(sp<ICanController> controller, const ICanController::BusConfiguration& config)
+ : mIfname(config.name), mController(controller) {
+ const auto result = controller->upInterface(config);
+ EXPECT_EQ(ICanController::Result::OK, result);
+
+ /* Not using ICanBus::getService here, since it ignores interfaces not in the manifest
+ * file -- this is a test, so we don't want to add dummy services to a device manifest.
+ */
+ auto manager = hidl::manager::V1_2::IServiceManager::getService();
+ auto service = manager->get(ICanBus::descriptor, config.name);
+ mBus = ICanBus::castFrom(service);
+ EXPECT_TRUE(mBus) << "ICanBus/" << config.name << " failed to register";
+ }
+
+ virtual ~Bus() { reset(); }
+
+ void reset() {
+ mBus.clear();
+ if (mController) {
+ const auto res = mController->downInterface(mIfname);
+ EXPECT_TRUE(res);
+ mController.clear();
+ }
+ }
+
+ ICanBus* operator->() const { return mBus.get(); }
+ sp<ICanBus> get() { return mBus; }
+
+ sp<CanMessageListener> listen(const hidl_vec<CanMessageFilter>& filter) {
+ sp<CanMessageListener> listener = new CanMessageListener();
+
+ Result result;
+ sp<ICloseHandle> closeHandle;
+ mBus->listen(filter, listener, hidl_utils::fill(&result, &closeHandle)).assertOk();
+ EXPECT_EQ(Result::OK, result);
+ listener->assignCloseHandle(closeHandle);
+
+ return listener;
+ }
+
+ void send(const CanMessage& msg) {
+ const auto result = mBus->send(msg);
+ EXPECT_EQ(Result::OK, result);
+ }
+
+ private:
+ const std::string mIfname;
+ sp<ICanController> mController;
+ sp<ICanBus> mBus;
+};
+
+class CanBusVirtualHalTest : public ::testing::VtsHalHidlTargetTestBase {
+ protected:
+ virtual void SetUp() override;
+
+ static void SetUpTestCase();
+ static void TearDownTestCase();
+
+ Bus makeBus();
+
+ private:
+ unsigned mLastIface = 0;
+ static sp<ICanController> mCanController;
+ static bool mVirtualSupported;
+};
+
+sp<ICanController> CanBusVirtualHalTest::mCanController = nullptr;
+bool CanBusVirtualHalTest::mVirtualSupported;
+
+static CanMessage makeMessage(CanMessageId id) {
+ CanMessage msg = {};
+ msg.id = id;
+ return msg;
+}
+
+static void clearTimestamps(std::vector<CanMessage>& messages) {
+ std::for_each(messages.begin(), messages.end(), [](auto& msg) { msg.timestamp = 0; });
+}
+
+void CanBusVirtualHalTest::SetUp() {
+ if (!mVirtualSupported) GTEST_SKIP();
+}
+
+void CanBusVirtualHalTest::SetUpTestCase() {
+ const auto serviceName = gEnv->getServiceName<ICanController>();
+ mCanController = getService<ICanController>(serviceName);
+ ASSERT_TRUE(mCanController) << "Couldn't open CAN Controller: " << serviceName;
+
+ hidl_vec<InterfaceType> supported;
+ mCanController->getSupportedInterfaceTypes(hidl_utils::fill(&supported)).assertOk();
+ mVirtualSupported = supported.contains(InterfaceType::VIRTUAL);
+}
+
+void CanBusVirtualHalTest::TearDownTestCase() {
+ mCanController.clear();
+}
+
+Bus CanBusVirtualHalTest::makeBus() {
+ const auto idx = ++mLastIface;
+
+ ICanController::BusConfiguration config = {};
+ config.name = "test" + std::to_string(idx);
+ config.iftype = InterfaceType::VIRTUAL;
+ config.interfaceId.address("vcan50");
+
+ return Bus(mCanController, config);
+}
+
+TEST_F(CanBusVirtualHalTest, Send) {
+ auto bus = makeBus();
+
+ CanMessage msg = {};
+ msg.id = 0x123;
+ msg.payload = {1, 2, 3};
+
+ bus.send(msg);
+}
+
+TEST_F(CanBusVirtualHalTest, SendAfterClose) {
+ auto bus = makeBus();
+ auto zombie = bus.get();
+ bus.reset();
+
+ const auto result = zombie->send({});
+ ASSERT_EQ(Result::INTERFACE_DOWN, result);
+}
+
+TEST_F(CanBusVirtualHalTest, SendAndRecv) {
+ auto bus1 = makeBus();
+ auto bus2 = makeBus();
+
+ auto listener = bus2.listen({});
+
+ CanMessage msg = {};
+ msg.id = 0x123;
+ msg.payload = {1, 2, 3};
+ bus1.send(msg);
+
+ auto messages = listener->fetchMessages(100ms);
+ ASSERT_EQ(1u, messages.size());
+ ASSERT_NEAR(uint64_t(elapsedRealtimeNano()), messages[0].timestamp,
+ std::chrono::nanoseconds(100ms).count());
+ clearTimestamps(messages);
+ ASSERT_EQ(msg, messages[0]);
+}
+
+TEST_F(CanBusVirtualHalTest, DownOneOfTwo) {
+ auto bus1 = makeBus();
+ auto bus2 = makeBus();
+
+ bus2.reset();
+
+ bus1.send({});
+}
+
+TEST_F(CanBusVirtualHalTest, Filter) {
+ auto bus1 = makeBus();
+ auto bus2 = makeBus();
+
+ hidl_vec<CanMessageFilter> filterPositive = {
+ {0x101, 0x100, false},
+ {0x010, 0x0F0, false},
+ };
+ auto listenerPositive = bus2.listen(filterPositive);
+
+ hidl_vec<CanMessageFilter> filterNegative = {
+ {0x123, 0x0FF, true},
+ {0x004, 0x00F, true},
+ };
+ auto listenerNegative = bus2.listen(filterNegative);
+
+ bus1.send(makeMessage(0));
+ bus1.send(makeMessage(0x1A0));
+ bus1.send(makeMessage(0x1A1));
+ bus1.send(makeMessage(0x2A0));
+ bus1.send(makeMessage(0x3A0));
+ bus1.send(makeMessage(0x010));
+ bus1.send(makeMessage(0x123));
+ bus1.send(makeMessage(0x023));
+ bus1.send(makeMessage(0x124));
+
+ std::vector<can::V1_0::CanMessage> expectedPositive{
+ makeMessage(0x1A0), //
+ makeMessage(0x1A1), //
+ makeMessage(0x3A0), //
+ makeMessage(0x010), //
+ makeMessage(0x123), //
+ makeMessage(0x124), //
+ };
+ std::vector<can::V1_0::CanMessage> expectedNegative{
+ makeMessage(0), //
+ makeMessage(0x1A0), //
+ makeMessage(0x1A1), //
+ makeMessage(0x2A0), //
+ makeMessage(0x3A0), //
+ makeMessage(0x010), //
+ };
+
+ auto messagesNegative = listenerNegative->fetchMessages(100ms, expectedNegative.size());
+ auto messagesPositive = listenerPositive->fetchMessages(100ms, expectedPositive.size());
+ clearTimestamps(messagesNegative);
+ clearTimestamps(messagesPositive);
+ ASSERT_EQ(expectedNegative, messagesNegative);
+ ASSERT_EQ(expectedPositive, messagesPositive);
+}
+
+} // namespace vts
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
+
+/**
+ * Example manual invocation:
+ * adb shell /data/nativetest64/VtsHalCanBusVirtualV1_0TargetTest/VtsHalCanBusVirtualV1_0TargetTest\
+ * --hal_service_instance=android.hardware.automotive.can@1.0::ICanController/socketcan
+ */
+int main(int argc, char** argv) {
+ using android::hardware::automotive::can::V1_0::ICanController;
+ using android::hardware::automotive::can::V1_0::vts::gEnv;
+ using android::hardware::automotive::can::V1_0::vts::utils::SimpleHidlEnvironment;
+ android::base::SetDefaultTag("CanBusVirtualVts");
+ android::base::SetMinimumLogSeverity(android::base::VERBOSE);
+ gEnv = new SimpleHidlEnvironment<ICanController>;
+ ::testing::AddGlobalTestEnvironment(gEnv);
+ ::testing::InitGoogleTest(&argc, argv);
+ gEnv->init(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/automotive/can/1.0/vts/functional/VtsHalCanControllerV1_0TargetTest.cpp b/automotive/can/1.0/vts/functional/VtsHalCanControllerV1_0TargetTest.cpp
new file mode 100644
index 0000000..70f9fe4
--- /dev/null
+++ b/automotive/can/1.0/vts/functional/VtsHalCanControllerV1_0TargetTest.cpp
@@ -0,0 +1,260 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <VtsHalHidlTargetTestBase.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <android/hardware/automotive/can/1.0/ICanBus.h>
+#include <android/hardware/automotive/can/1.0/ICanController.h>
+#include <android/hardware/automotive/can/1.0/types.h>
+#include <android/hidl/manager/1.2/IServiceManager.h>
+#include <can-vts-utils/can-hal-printers.h>
+#include <can-vts-utils/environment-utils.h>
+#include <gmock/gmock.h>
+#include <hidl-utils/hidl-utils.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace vts {
+
+using hardware::hidl_vec;
+using InterfaceType = ICanController::InterfaceType;
+
+static utils::SimpleHidlEnvironment<ICanController>* gEnv = nullptr;
+
+class CanControllerHalTest : public ::testing::VtsHalHidlTargetTestBase {
+ protected:
+ virtual void SetUp() override;
+ virtual void TearDown() override;
+
+ hidl_vec<InterfaceType> getSupportedInterfaceTypes();
+ bool isSupported(InterfaceType iftype);
+
+ bool up(InterfaceType iftype, const std::string srvname, std::string ifname,
+ ICanController::Result expected);
+ void assertRegistered(const std::string srvname, bool expectRegistered);
+
+ sp<ICanController> mCanController;
+};
+
+void CanControllerHalTest::SetUp() {
+ const auto serviceName = gEnv->getServiceName<ICanController>();
+ mCanController = getService<ICanController>(serviceName);
+ ASSERT_TRUE(mCanController) << "Couldn't open CAN Controller: " << serviceName;
+}
+
+void CanControllerHalTest::TearDown() {
+ mCanController.clear();
+}
+
+hidl_vec<InterfaceType> CanControllerHalTest::getSupportedInterfaceTypes() {
+ hidl_vec<InterfaceType> iftypesResult;
+ mCanController->getSupportedInterfaceTypes(hidl_utils::fill(&iftypesResult)).assertOk();
+ return iftypesResult;
+}
+
+bool CanControllerHalTest::isSupported(InterfaceType iftype) {
+ const auto supported = getSupportedInterfaceTypes();
+ return std::find(supported.begin(), supported.end(), iftype) != supported.end();
+}
+
+bool CanControllerHalTest::up(InterfaceType iftype, std::string srvname, std::string ifname,
+ ICanController::Result expected) {
+ ICanController::BusConfiguration config = {};
+ config.name = srvname;
+ config.iftype = iftype;
+ config.interfaceId.address(ifname);
+
+ const auto upresult = mCanController->upInterface(config);
+
+ if (!isSupported(iftype)) {
+ LOG(INFO) << iftype << " interfaces not supported";
+ EXPECT_EQ(ICanController::Result::NOT_SUPPORTED, upresult);
+ return false;
+ }
+
+ EXPECT_EQ(expected, upresult);
+ return true;
+}
+
+void CanControllerHalTest::assertRegistered(std::string srvname, bool expectRegistered) {
+ /* Not using ICanBus::tryGetService here, since it ignores interfaces not in the manifest
+ * file -- this is a test, so we don't want to add dummy services to a device manifest.
+ */
+ auto manager = hidl::manager::V1_2::IServiceManager::getService();
+ auto busService = manager->get(ICanBus::descriptor, srvname);
+ ASSERT_EQ(expectRegistered, busService.withDefault(nullptr) != nullptr)
+ << "ICanBus/" << srvname << (expectRegistered ? " is not " : " is ") << "registered"
+ << " (should be otherwise)";
+}
+
+TEST_F(CanControllerHalTest, SupportsSomething) {
+ const auto supported = getSupportedInterfaceTypes();
+ ASSERT_GT(supported.size(), 0u);
+}
+
+TEST_F(CanControllerHalTest, BringUpDown) {
+ const std::string name = "dummy";
+
+ assertRegistered(name, false);
+ if (!up(InterfaceType::VIRTUAL, name, "vcan57", ICanController::Result::OK)) GTEST_SKIP();
+ assertRegistered(name, true);
+
+ const auto dnresult = mCanController->downInterface(name);
+ ASSERT_TRUE(dnresult);
+
+ assertRegistered(name, false);
+}
+
+TEST_F(CanControllerHalTest, DownDummy) {
+ const auto result = mCanController->downInterface("imnotup");
+ ASSERT_FALSE(result);
+}
+
+TEST_F(CanControllerHalTest, UpTwice) {
+ const std::string name = "dummy";
+
+ assertRegistered(name, false);
+ if (!up(InterfaceType::VIRTUAL, name, "vcan72", ICanController::Result::OK)) GTEST_SKIP();
+ assertRegistered(name, true);
+ if (!up(InterfaceType::VIRTUAL, name, "vcan73", ICanController::Result::INVALID_STATE)) {
+ GTEST_SKIP();
+ }
+ assertRegistered(name, true);
+
+ const auto result = mCanController->downInterface(name);
+ ASSERT_TRUE(result);
+ assertRegistered(name, false);
+}
+
+TEST_F(CanControllerHalTest, IdentifierCompatibility) {
+ using IdDisc = ICanController::BusConfiguration::InterfaceIdentifier::hidl_discriminator;
+ static const std::map<InterfaceType, std::vector<IdDisc>> compatMatrix = {
+ {InterfaceType::VIRTUAL, {IdDisc::address}},
+ {InterfaceType::SOCKETCAN, {IdDisc::address, IdDisc::serialno}},
+ {InterfaceType::SLCAN, {IdDisc::address, IdDisc::serialno}},
+ {InterfaceType::INDEXED, {IdDisc::index}},
+ };
+ static const std::vector<IdDisc> allDisc = {IdDisc::address, IdDisc::index, IdDisc::serialno};
+
+ for (const auto [iftype, supported] : compatMatrix) {
+ for (const auto iddisc : allDisc) {
+ LOG(INFO) << "Compatibility testing: " << iftype << " / " << iddisc;
+
+ ICanController::BusConfiguration config = {};
+ config.name = "compattestsrv";
+ config.iftype = iftype;
+ config.baudrate = 125000;
+
+ // using random-ish addresses, which may not be valid - we can't test the success case
+ if (iddisc == IdDisc::address) {
+ config.interfaceId.address("can0");
+ } else if (iddisc == IdDisc::index) {
+ config.interfaceId.index(0);
+ } else if (iddisc == IdDisc::serialno) {
+ config.interfaceId.serialno({"dummy", "dummier"});
+ }
+
+ const auto upresult = mCanController->upInterface(config);
+
+ if (!isSupported(iftype)) {
+ ASSERT_EQ(ICanController::Result::NOT_SUPPORTED, upresult);
+ continue;
+ }
+ ASSERT_NE(ICanController::Result::NOT_SUPPORTED, upresult);
+
+ bool isSupportedDisc =
+ std::find(supported.begin(), supported.end(), iddisc) != supported.end();
+ if (!isSupportedDisc) {
+ ASSERT_EQ(ICanController::Result::BAD_ADDRESS, upresult);
+ continue;
+ }
+
+ if (upresult == ICanController::Result::OK) {
+ const auto dnresult = mCanController->downInterface(config.name);
+ ASSERT_TRUE(dnresult);
+ continue;
+ }
+ }
+ }
+}
+
+TEST_F(CanControllerHalTest, FailEmptyName) {
+ const std::string name = "";
+
+ assertRegistered(name, false);
+ if (!up(InterfaceType::VIRTUAL, name, "vcan57", ICanController::Result::UNKNOWN_ERROR)) {
+ GTEST_SKIP();
+ }
+ assertRegistered(name, false);
+}
+
+TEST_F(CanControllerHalTest, FailBadName) {
+ // 33 characters (name can be at most 32 characters long)
+ const std::string name = "ab012345678901234567890123456789c";
+
+ assertRegistered(name, false);
+ if (!up(InterfaceType::VIRTUAL, name, "vcan57", ICanController::Result::UNKNOWN_ERROR)) {
+ GTEST_SKIP();
+ }
+ assertRegistered(name, false);
+}
+
+TEST_F(CanControllerHalTest, FailBadVirtualAddress) {
+ const std::string name = "dummy";
+
+ assertRegistered(name, false);
+ if (!up(InterfaceType::VIRTUAL, name, "", ICanController::Result::BAD_ADDRESS)) GTEST_SKIP();
+ assertRegistered(name, false);
+}
+
+TEST_F(CanControllerHalTest, FailBadSocketcanAddress) {
+ const std::string name = "dummy";
+
+ assertRegistered(name, false);
+ if (!up(InterfaceType::SOCKETCAN, name, "can87", ICanController::Result::BAD_ADDRESS)) {
+ GTEST_SKIP();
+ }
+ assertRegistered(name, false);
+}
+
+} // namespace vts
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
+
+/**
+ * Example manual invocation:
+ * adb shell /data/nativetest64/VtsHalCanControllerV1_0TargetTest/VtsHalCanControllerV1_0TargetTest\
+ * --hal_service_instance=android.hardware.automotive.can@1.0::ICanController/socketcan
+ */
+int main(int argc, char** argv) {
+ using android::hardware::automotive::can::V1_0::ICanController;
+ using android::hardware::automotive::can::V1_0::vts::gEnv;
+ using android::hardware::automotive::can::V1_0::vts::utils::SimpleHidlEnvironment;
+ android::base::SetDefaultTag("CanControllerVts");
+ android::base::SetMinimumLogSeverity(android::base::VERBOSE);
+ gEnv = new SimpleHidlEnvironment<ICanController>;
+ ::testing::AddGlobalTestEnvironment(gEnv);
+ ::testing::InitGoogleTest(&argc, argv);
+ gEnv->init(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/automotive/can/1.0/vts/utils/Android.bp b/automotive/can/1.0/vts/utils/Android.bp
new file mode 100644
index 0000000..e925c8f
--- /dev/null
+++ b/automotive/can/1.0/vts/utils/Android.bp
@@ -0,0 +1,20 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_library_headers {
+ name: "android.hardware.automotive.can@vts-utils-lib",
+ export_include_dirs: ["include"],
+}
diff --git a/automotive/can/1.0/vts/utils/include/can-vts-utils/can-hal-printers.h b/automotive/can/1.0/vts/utils/include/can-vts-utils/can-hal-printers.h
new file mode 100644
index 0000000..0923998
--- /dev/null
+++ b/automotive/can/1.0/vts/utils/include/can-vts-utils/can-hal-printers.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android/hardware/automotive/can/1.0/ICanController.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+
+/**
+ * Define gTest printer for a given HIDL type, but skip definition for Return<T>.
+ */
+#define DEFINE_CAN_HAL_PRINTER_SIMPLE(T, converter) \
+ std::ostream& operator<<(std::ostream& os, const T& v) { return os << converter(v); }
+
+/**
+ * Define gTest printer for a given HIDL type.
+ */
+#define DEFINE_CAN_HAL_PRINTER(T, converter) \
+ DEFINE_CAN_HAL_PRINTER_SIMPLE(T, converter) \
+ std::ostream& operator<<(std::ostream& os, const Return<T>& v) { return os << converter(v); }
+
+DEFINE_CAN_HAL_PRINTER(CanMessage, toString)
+DEFINE_CAN_HAL_PRINTER(ErrorEvent, toString)
+DEFINE_CAN_HAL_PRINTER_SIMPLE(
+ ICanController::BusConfiguration::InterfaceIdentifier::hidl_discriminator, int)
+DEFINE_CAN_HAL_PRINTER(ICanController::InterfaceType, toString)
+DEFINE_CAN_HAL_PRINTER(ICanController::Result, toString)
+DEFINE_CAN_HAL_PRINTER(Result, toString)
+
+#undef DEFINE_CAN_HAL_PRINTER
+#undef DEFINE_CAN_HAL_PRINTER_SIMPLE
+
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/can/1.0/vts/utils/include/can-vts-utils/environment-utils.h b/automotive/can/1.0/vts/utils/include/can-vts-utils/environment-utils.h
new file mode 100644
index 0000000..a722dd0
--- /dev/null
+++ b/automotive/can/1.0/vts/utils/include/can-vts-utils/environment-utils.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <VtsHalHidlTargetTestEnvBase.h>
+
+namespace android {
+namespace hardware {
+namespace automotive {
+namespace can {
+namespace V1_0 {
+namespace vts {
+namespace utils {
+
+/**
+ * Simple test environment.
+ *
+ * This is a helper class to instantiate a test environment without boilerplate code for cases where
+ * there is no need to pass more parameters than just HIDL service instance name.
+ *
+ * The class implements registerTestServices() by calling registerTestService() on every HIDL
+ * interface provided as parameter to this template.
+ *
+ * Example usage:
+ * static utils::SimpleHidlEnvironment<IMyService>* gEnv = nullptr;
+ *
+ * void CanBusHalTest::SetUp() {
+ * const auto serviceName = gEnv->getServiceName<IMyService>();
+ * (...)
+ * }
+ *
+ * int main(int argc, char** argv) {
+ * gEnv = new SimpleHidlEnvironment<IMyService>;
+ * ::testing::AddGlobalTestEnvironment(gEnv);
+ * ::testing::InitGoogleTest(&argc, argv);
+ * gEnv->init(&argc, argv);
+ * return RUN_ALL_TESTS();
+ * }
+ *
+ * \param T... HIDL interface names to register for a test service
+ */
+template <typename... T>
+class SimpleHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
+ public:
+ virtual void registerTestServices() override {
+ // Call registerTestService() for every HIDL interface using this template.
+ using expander = int[];
+ (void)expander{0, (registerTestService<T>(), 0)...};
+ }
+};
+
+} // namespace utils
+} // namespace vts
+} // namespace V1_0
+} // namespace can
+} // namespace automotive
+} // namespace hardware
+} // namespace android
diff --git a/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultConfig.h b/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultConfig.h
index 8a008d3..5452cfa 100644
--- a/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultConfig.h
+++ b/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultConfig.h
@@ -85,6 +85,12 @@
0x0666 | VehiclePropertyGroup::VENDOR | VehicleArea::GLOBAL | VehiclePropertyType::MIXED;
/**
+ * This property is used for test purpose. End to end tests use this property to test set and get
+ * method for MIXED type properties.
+ */
+const int32_t kMixedTypePropertyForTest =
+ 0x1111 | VehiclePropertyGroup::VENDOR | VehicleArea::GLOBAL | VehiclePropertyType::MIXED;
+/**
* FakeDataCommand enum defines the supported command type for kGenerateFakeDataControllingProperty.
* All those commands can be send independently with each other. And each will override the one sent
* previously.
@@ -625,6 +631,14 @@
},
},
+ {.config = {.prop = kMixedTypePropertyForTest,
+ .access = VehiclePropertyAccess::READ_WRITE,
+ .changeMode = VehiclePropertyChangeMode::ON_CHANGE,
+ .configArray = {1, 1, 0, 2, 0, 0, 1, 0, 0}},
+ .initialValue = {.stringValue = "MIXED property",
+ .int32Values = {1 /* indicate TRUE boolean value */, 2, 3},
+ .floatValues = {4.5f}}},
+
{.config = {.prop = toInt(VehicleProperty::DOOR_LOCK),
.access = VehiclePropertyAccess::READ_WRITE,
.changeMode = VehiclePropertyChangeMode::ON_CHANGE,
diff --git a/automotive/vehicle/2.0/types.hal b/automotive/vehicle/2.0/types.hal
index 955283e..8c84c0a 100644
--- a/automotive/vehicle/2.0/types.hal
+++ b/automotive/vehicle/2.0/types.hal
@@ -35,6 +35,21 @@
/**
* Any combination of scalar or vector types. The exact format must be
* provided in the description of the property.
+ *
+ * For vendor MIXED type properties, configArray needs to be formatted in this
+ * structure.
+ * configArray[0], 1 indicates the property has a String value
+ * configArray[1], 1 indicates the property has a Boolean value .
+ * configArray[2], 1 indicates the property has an Integer value.
+ * configArray[3], the number indicates the size of Integer[] in the property.
+ * configArray[4], 1 indicates the property has a Long value.
+ * configArray[5], the number indicates the size of Long[] in the property.
+ * configArray[6], 1 indicates the property has a Float value.
+ * configArray[7], the number indicates the size of Float[] in the property.
+ * configArray[8], the number indicates the size of byte[] in the property.
+ * For example:
+ * {@code configArray = {1, 1, 1, 3, 0, 0, 0, 0, 0}} indicates the property has
+ * a String value, a Boolean value, an Integer value and an array with 3 integers.
*/
MIXED = 0x00e00000,
diff --git a/current.txt b/current.txt
index eb1b1ca..fbb9752 100644
--- a/current.txt
+++ b/current.txt
@@ -576,3 +576,4 @@
ad431c8de51c07934a068e3043d8dd0537ac4d3158627706628b123f42df48dc android.hardware.neuralnetworks@1.0::IPreparedModel
aafcc10cf04ab247e86d4582586c71c6b4c2b8c479241ffa7fe37deb659fc942 android.hardware.neuralnetworks@1.2::IPreparedModel
1a6e2bd289f22931c526b21916910f1d4c436b7acb9556e4243de4ce8e6cc2e4 android.hardware.soundtrigger@2.0::ISoundTriggerHwCallback
+fd65298e1e09e0e3c781ab18305920d757dbe55a3b459ce17814ec5cf6dfee99 android.hardware.wifi@1.0::IWifiP2pIface
diff --git a/sensors/2.0/multihal/Android.bp b/sensors/2.0/multihal/Android.bp
new file mode 100644
index 0000000..f0b33e4
--- /dev/null
+++ b/sensors/2.0/multihal/Android.bp
@@ -0,0 +1,47 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+cc_binary {
+ name: "android.hardware.sensors@2.0-service.multihal",
+ defaults: ["hidl_defaults"],
+ vendor: true,
+ relative_install_path: "hw",
+ srcs: [
+ "service.cpp",
+ "HalProxy.cpp",
+ ],
+ init_rc: ["android.hardware.sensors@2.0-service-multihal.rc"],
+ header_libs: [
+ "android.hardware.sensors@2.0-subhal.header",
+ ],
+ shared_libs: [
+ "android.hardware.sensors@1.0",
+ "android.hardware.sensors@2.0",
+ "libcutils",
+ "libfmq",
+ "libhidlbase",
+ "libhidltransport",
+ "liblog",
+ "libpower",
+ "libutils",
+ ],
+ vintf_fragments: ["android.hardware.sensors@2.0-multihal.xml"],
+}
+
+cc_library_headers {
+ name: "android.hardware.sensors@2.0-subhal.header",
+ vendor: true,
+ export_include_dirs: ["include"],
+}
\ No newline at end of file
diff --git a/sensors/2.0/multihal/HalProxy.cpp b/sensors/2.0/multihal/HalProxy.cpp
new file mode 100644
index 0000000..31f8a18
--- /dev/null
+++ b/sensors/2.0/multihal/HalProxy.cpp
@@ -0,0 +1,182 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "HalProxy.h"
+
+#include <android/hardware/sensors/2.0/types.h>
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V2_0 {
+namespace implementation {
+
+// TODO: Use this wake lock name as the prefix to all sensors HAL wake locks acquired.
+// constexpr const char* kWakeLockName = "SensorsHAL_WAKEUP";
+
+// TODO: Use the following class as a starting point for implementing the full HalProxyCallback
+// along with being inspiration for how to implement the ScopedWakelock class.
+/**
+ * Callback class used to provide the HalProxy with the index of which subHal is invoking
+ */
+class SensorsCallbackProxy : public ISensorsCallback {
+ public:
+ SensorsCallbackProxy(wp<HalProxy>& halProxy, int32_t subHalIndex)
+ : mHalProxy(halProxy), mSubHalIndex(subHalIndex) {}
+
+ Return<void> onDynamicSensorsConnected(
+ const hidl_vec<SensorInfo>& dynamicSensorsAdded) override {
+ sp<HalProxy> halProxy(mHalProxy.promote());
+ if (halProxy != nullptr) {
+ return halProxy->onDynamicSensorsConnected(dynamicSensorsAdded, mSubHalIndex);
+ }
+ return Return<void>();
+ }
+
+ Return<void> onDynamicSensorsDisconnected(
+ const hidl_vec<int32_t>& dynamicSensorHandlesRemoved) override {
+ sp<HalProxy> halProxy(mHalProxy.promote());
+ if (halProxy != nullptr) {
+ return halProxy->onDynamicSensorsDisconnected(dynamicSensorHandlesRemoved,
+ mSubHalIndex);
+ }
+ return Return<void>();
+ }
+
+ private:
+ wp<HalProxy>& mHalProxy;
+ int32_t mSubHalIndex;
+};
+
+HalProxy::HalProxy() {
+ // TODO: Initialize all sub-HALs and discover sensors.
+}
+
+HalProxy::~HalProxy() {
+ // TODO: Join any running threads and clean up FMQs and any other allocated
+ // state.
+}
+
+Return<void> HalProxy::getSensorsList(getSensorsList_cb /* _hidl_cb */) {
+ // TODO: Output sensors list created as part of HalProxy().
+ return Void();
+}
+
+Return<Result> HalProxy::setOperationMode(OperationMode /* mode */) {
+ // TODO: Proxy API call to all sub-HALs and return appropriate result.
+ return Result::INVALID_OPERATION;
+}
+
+Return<Result> HalProxy::activate(int32_t /* sensorHandle */, bool /* enabled */) {
+ // TODO: Proxy API call to appropriate sub-HAL.
+ return Result::INVALID_OPERATION;
+}
+
+Return<Result> HalProxy::initialize(
+ const ::android::hardware::MQDescriptorSync<Event>& eventQueueDescriptor,
+ const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
+ const sp<ISensorsCallback>& sensorsCallback) {
+ Result result = Result::OK;
+
+ // TODO: clean up sensor requests, if not already done elsewhere through a death recipient, and
+ // clean up any other resources that exist (FMQs, flags, threads, etc.)
+
+ mDynamicSensorsCallback = sensorsCallback;
+
+ // Create the Event FMQ from the eventQueueDescriptor. Reset the read/write positions.
+ mEventQueue =
+ std::make_unique<EventMessageQueue>(eventQueueDescriptor, true /* resetPointers */);
+
+ // Create the EventFlag that is used to signal to the framework that sensor events have been
+ // written to the Event FMQ
+ if (EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag) != OK) {
+ result = Result::BAD_VALUE;
+ }
+
+ // Create the Wake Lock FMQ that is used by the framework to communicate whenever WAKE_UP
+ // events have been successfully read and handled by the framework.
+ mWakeLockQueue =
+ std::make_unique<WakeLockMessageQueue>(wakeLockDescriptor, true /* resetPointers */);
+
+ if (!mDynamicSensorsCallback || !mEventQueue || !mWakeLockQueue || mEventQueueFlag == nullptr) {
+ result = Result::BAD_VALUE;
+ }
+
+ // TODO: start threads to read wake locks and process events from sub HALs.
+
+ return result;
+}
+
+Return<Result> HalProxy::batch(int32_t /* sensorHandle */, int64_t /* samplingPeriodNs */,
+ int64_t /* maxReportLatencyNs */) {
+ // TODO: Proxy API call to appropriate sub-HAL.
+ return Result::INVALID_OPERATION;
+}
+
+Return<Result> HalProxy::flush(int32_t /* sensorHandle */) {
+ // TODO: Proxy API call to appropriate sub-HAL.
+ return Result::INVALID_OPERATION;
+}
+
+Return<Result> HalProxy::injectSensorData(const Event& /* event */) {
+ // TODO: Proxy API call to appropriate sub-HAL.
+ return Result::INVALID_OPERATION;
+}
+
+Return<void> HalProxy::registerDirectChannel(const SharedMemInfo& /* mem */,
+ registerDirectChannel_cb _hidl_cb) {
+ // TODO: During init, discover the first sub-HAL in the config that has sensors with direct
+ // channel support, if any, and proxy the API call there.
+ _hidl_cb(Result::INVALID_OPERATION, -1 /* channelHandle */);
+ return Return<void>();
+}
+
+Return<Result> HalProxy::unregisterDirectChannel(int32_t /* channelHandle */) {
+ // TODO: During init, discover the first sub-HAL in the config that has sensors with direct
+ // channel support, if any, and proxy the API call there.
+ return Result::INVALID_OPERATION;
+}
+
+Return<void> HalProxy::configDirectReport(int32_t /* sensorHandle */, int32_t /* channelHandle */,
+ RateLevel /* rate */, configDirectReport_cb _hidl_cb) {
+ // TODO: During init, discover the first sub-HAL in the config that has sensors with direct
+ // channel support, if any, and proxy the API call there.
+ _hidl_cb(Result::INVALID_OPERATION, 0 /* reportToken */);
+ return Return<void>();
+}
+
+Return<void> HalProxy::debug(const hidl_handle& /* fd */, const hidl_vec<hidl_string>& /* args */) {
+ // TODO: output debug information
+ return Return<void>();
+}
+
+Return<void> HalProxy::onDynamicSensorsConnected(
+ const hidl_vec<SensorInfo>& /* dynamicSensorsAdded */, int32_t /* subHalIndex */) {
+ // TODO: Map the SensorInfo to the global list and then invoke the framework's callback.
+ return Return<void>();
+}
+
+Return<void> HalProxy::onDynamicSensorsDisconnected(
+ const hidl_vec<int32_t>& /* dynamicSensorHandlesRemoved */, int32_t /* subHalIndex */) {
+ // TODO: Unmap the SensorInfo from the global list and then invoke the framework's callback.
+ return Return<void>();
+}
+
+} // namespace implementation
+} // namespace V2_0
+} // namespace sensors
+} // namespace hardware
+} // namespace android
diff --git a/sensors/2.0/multihal/HalProxy.h b/sensors/2.0/multihal/HalProxy.h
new file mode 100644
index 0000000..b9855a6
--- /dev/null
+++ b/sensors/2.0/multihal/HalProxy.h
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "SubHal.h"
+
+#include <android/hardware/sensors/2.0/ISensors.h>
+#include <fmq/MessageQueue.h>
+#include <hardware_legacy/power.h>
+#include <hidl/MQDescriptor.h>
+#include <hidl/Status.h>
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::sp;
+using ::android::hardware::EventFlag;
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::MessageQueue;
+using ::android::hardware::MQDescriptor;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+
+struct HalProxy : public ISensors {
+ using Event = ::android::hardware::sensors::V1_0::Event;
+ using OperationMode = ::android::hardware::sensors::V1_0::OperationMode;
+ using RateLevel = ::android::hardware::sensors::V1_0::RateLevel;
+ using Result = ::android::hardware::sensors::V1_0::Result;
+ using SharedMemInfo = ::android::hardware::sensors::V1_0::SharedMemInfo;
+
+ HalProxy();
+ ~HalProxy();
+
+ // Methods from ::android::hardware::sensors::V2_0::ISensors follow.
+ Return<void> getSensorsList(getSensorsList_cb _hidl_cb) override;
+
+ Return<Result> setOperationMode(OperationMode mode) override;
+
+ Return<Result> activate(int32_t sensorHandle, bool enabled) override;
+
+ Return<Result> initialize(
+ const ::android::hardware::MQDescriptorSync<Event>& eventQueueDescriptor,
+ const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
+ const sp<ISensorsCallback>& sensorsCallback) override;
+
+ Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
+ int64_t maxReportLatencyNs) override;
+
+ Return<Result> flush(int32_t sensorHandle) override;
+
+ Return<Result> injectSensorData(const Event& event) override;
+
+ Return<void> registerDirectChannel(const SharedMemInfo& mem,
+ registerDirectChannel_cb _hidl_cb) override;
+
+ Return<Result> unregisterDirectChannel(int32_t channelHandle) override;
+
+ Return<void> configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
+ configDirectReport_cb _hidl_cb) override;
+
+ Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override;
+
+ // Below methods from ::android::hardware::sensors::V2_0::ISensorsCaback with a minor change
+ // to pass in the sub-HAL index. While the above methods are invoked from the sensors framework
+ // via the binder, these methods are invoked from a callback provided to sub-HALs inside the
+ // same process as the HalProxy, but potentially running on different threads.
+ Return<void> onDynamicSensorsConnected(const hidl_vec<SensorInfo>& dynamicSensorsAdded,
+ int32_t subHalIndex);
+
+ Return<void> onDynamicSensorsDisconnected(const hidl_vec<int32_t>& dynamicSensorHandlesRemoved,
+ int32_t subHalIndex);
+
+ private:
+ using EventMessageQueue = MessageQueue<Event, kSynchronizedReadWrite>;
+ using WakeLockMessageQueue = MessageQueue<uint32_t, kSynchronizedReadWrite>;
+
+ /**
+ * The Event FMQ where sensor events are written
+ */
+ std::unique_ptr<EventMessageQueue> mEventQueue;
+
+ /**
+ * The Wake Lock FMQ that is read to determine when the framework has handled WAKE_UP events
+ */
+ std::unique_ptr<WakeLockMessageQueue> mWakeLockQueue;
+
+ /**
+ * Event Flag to signal to the framework when sensor events are available to be read
+ */
+ EventFlag* mEventQueueFlag;
+
+ /**
+ * Callback to the sensors framework to inform it that new sensors have been added or removed.
+ */
+ sp<ISensorsCallback> mDynamicSensorsCallback;
+};
+
+} // namespace implementation
+} // namespace V2_0
+} // namespace sensors
+} // namespace hardware
+} // namespace android
diff --git a/sensors/2.0/multihal/OWNERS b/sensors/2.0/multihal/OWNERS
new file mode 100644
index 0000000..e955670
--- /dev/null
+++ b/sensors/2.0/multihal/OWNERS
@@ -0,0 +1,3 @@
+arthuri@google.com
+bduddie@google.com
+stange@google.com
\ No newline at end of file
diff --git a/sensors/2.0/multihal/android.hardware.sensors@2.0-multihal.xml b/sensors/2.0/multihal/android.hardware.sensors@2.0-multihal.xml
new file mode 100644
index 0000000..a771100
--- /dev/null
+++ b/sensors/2.0/multihal/android.hardware.sensors@2.0-multihal.xml
@@ -0,0 +1,11 @@
+<manifest version="1.0" type="device">
+ <hal format="hidl">
+ <name>android.hardware.sensors</name>
+ <transport>hwbinder</transport>
+ <version>2.0</version>
+ <interface>
+ <name>ISensors</name>
+ <instance>multihal</instance>
+ </interface>
+ </hal>
+</manifest>
diff --git a/sensors/2.0/multihal/android.hardware.sensors@2.0-service-multihal.rc b/sensors/2.0/multihal/android.hardware.sensors@2.0-service-multihal.rc
new file mode 100644
index 0000000..1671689
--- /dev/null
+++ b/sensors/2.0/multihal/android.hardware.sensors@2.0-service-multihal.rc
@@ -0,0 +1,6 @@
+service vendor.sensors-hal-2-0-multihal /vendor/bin/hw/android.hardware.sensors@2.0-service.multihal
+ class hal
+ user system
+ group system
+ capabilities BLOCK_SUSPEND
+ rlimit rtprio 10 10
diff --git a/sensors/2.0/multihal/include/SubHal.h b/sensors/2.0/multihal/include/SubHal.h
new file mode 100644
index 0000000..75e93a1
--- /dev/null
+++ b/sensors/2.0/multihal/include/SubHal.h
@@ -0,0 +1,202 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android/hardware/sensors/1.0/types.h>
+#include <android/hardware/sensors/2.0/ISensors.h>
+
+#include <vector>
+
+using ::android::hardware::sensors::V1_0::Event;
+using ::android::hardware::sensors::V1_0::Result;
+using ::android::hardware::sensors::V1_0::SensorInfo;
+
+// Indicates the current version of the multiHAL interface formatted as (HAL major version) << 24 |
+// (HAL minor version) << 16 | (multiHAL version)
+#define SUB_HAL_2_0_VERSION 0x02000000
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V2_0 {
+namespace implementation {
+
+/**
+ * Wrapper around wake lock acquisition functions (acquire/release_wake_lock) that provides a
+ * RAII-style mechanism for keeping a wake lock held for the duration of a scoped block.
+ * When a ScopedWakelock is created, it increments the reference count stored in the HalProxy
+ * for the sub-HALs specific wake lock, acquiring the wake lock if necessary. When the object goes
+ * out of scope, the ref count is decremented, potentially releasing the wake lock if no other
+ * references to the wake lock exist.
+ *
+ * This class is allocated through the createScopedWakelock callback inside the IHalProxyCallback
+ * provided to sub-HALs during initialization and should be used for all wake lock acquisition
+ * inside of the sub-HAL to ensure wake locks are not held indefinitely.
+ *
+ * The most prevalent use case for this class will be for posting events to the framework through
+ * the postEvents HalProxy callback. The expectation is that sub-HALs will create this
+ * ScopedWakelock through the createScopedWakelock upon receiving a sensor events. The lock boolean
+ * provided to createScopedWakelock will be set the according to whether the sensor events are
+ * from wakeup sensors. Then, the sub-HAL will perform any processing necessary before invoking the
+ * postEvents callback passing in the previously created ScopedWakelock. At this point, ownership
+ * of the object will be passed to the HalProxy that will then be responsible for ensuring any
+ * wake locks continue to be held, if necessary.
+ */
+class ScopedWakelock {
+ public:
+ ScopedWakelock(ScopedWakelock&&) = default;
+ ScopedWakelock& operator=(ScopedWakelock&&) = default;
+ virtual ~ScopedWakelock() { mLocked = false; };
+
+ bool isLocked() const { return mLocked; }
+
+ protected:
+ bool mLocked;
+
+ private:
+ // TODO: Mark HalProxy's subclass of ScopedWakelock as a friend so that it can be initialized.
+ ScopedWakelock();
+ ScopedWakelock(const ScopedWakelock&) = delete;
+ ScopedWakelock& operator=(const ScopedWakelock&) = delete;
+};
+
+/**
+ * Interface that contains several callbacks into the HalProxy class to communicate dynamic sensor
+ * changes and sensor events to the framework and acquire wake locks. The HalProxy will ensure
+ * callbacks occurring at the same time from multiple sub-HALs are synchronized in a safe, efficient
+ * manner.
+ */
+class IHalProxyCallback : public ISensorsCallback {
+ public:
+ /**
+ * Thread-safe callback used to post events to the HalProxy. Sub-HALs should invoke this
+ * whenever new sensor events need to be delivered to the sensors framework. Once invoked, the
+ * HalProxy will attempt to send events to the sensors framework using a blocking write with a
+ * 5 second timeout. This write may be done asynchronously if the queue used to communicate
+ * with the framework is full to avoid blocking sub-HALs for the length of the timeout. If the
+ * write fails, the events will be dropped and any wake locks held will be released.
+ *
+ * The provided ScopedWakelock must be locked if the events are from wakeup sensors. If it's
+ * not locked accordingly, the HalProxy will crash as this indicates the sub-HAL isn't compliant
+ * with the sensors HAL 2.0 specification. Additionally, since ScopedWakelock isn't copyable,
+ * the HalProxy will take ownership of the wake lock given when this method is invoked. Once the
+ * method returns, the HalProxy will handle holding the wake lock, if necessary, until the
+ * framework has successfully processed any wakeup events.
+ *
+ * No return type is used for this callback to avoid sub-HALs trying to resend events when
+ * writes fail. Writes should only fail when the framework is under inordinate stress which will
+ * likely result in a framework restart so retrying will likely only result in overloading the
+ * HalProxy. Sub-HALs should always assume that the write was a success and perform any
+ * necessary cleanup. Additionally, the HalProxy will ensure it logs any errors (through ADB and
+ * bug reports) it encounters during delivery to ensure it's obvious that a failure occurred.
+ *
+ * @param events the events that should be sent to the sensors framework
+ * @param wakelock ScopedWakelock that should be locked to send events from wake sensors and
+ * unlocked otherwise.
+ */
+ virtual void postEvents(const std::vector<Event>& events, ScopedWakelock wakelock) = 0;
+
+ /**
+ * Initializes a ScopedWakelock on the stack that, when locked, will increment the reference
+ * count for the sub-HAL's wake lock managed inside the HalProxy. See the ScopedWakelock class
+ * definition for how it should be used.
+ *
+ * @param lock whether the ScopedWakelock should be locked before it's returned.
+ * @return the created ScopedWakelock
+ */
+ virtual ScopedWakelock createScopedWakelock(bool lock) = 0;
+};
+
+/**
+ * ISensorsSubHal is an interface that sub-HALs must implement in order to be compliant with
+ * multihal 2.0 and in order for the HalProxy to successfully load and communicate with the sub-HAL.
+ *
+ * Any vendor wishing to implement this interface and support multihal 2.0 will need to create a
+ * dynamic library that exposes sensorsHalGetSubHal (defined below). This library will be loaded by
+ * the HalProxy when the sensors HAL is initialized and then the HalProxy will retrieve the vendor's
+ * implementation of sensorsHalGetSubHal.
+ *
+ * With the exception of the initialize method, ISensorsSubHal will implement the ISensors.hal spec.
+ * Any sensor handles given to the HalProxy, either through getSensorsList() or the
+ * onDynamicSensors(Dis)Connected callbacks, will be translated to avoid clashing with other sub-HAL
+ * handles. To achieve this, the HalProxy will use the upper byte to store the sub-HAL index and
+ * sub-HALs can continue to use the lower 3 bytes of the handle.
+ */
+class ISensorsSubHal : public ISensors {
+ // The ISensors version of initialize isn't used for multihal. Instead, sub-HALs must implement
+ // the version below to allow communciation logic to centralized in the HalProxy
+ Return<Result> initialize(
+ const ::android::hardware::MQDescriptorSync<Event>& /* eventQueueDescriptor */,
+ const ::android::hardware::MQDescriptorSync<uint32_t>& /* wakeLockDescriptor */,
+ const sp<ISensorsCallback>& /* sensorsCallback */) final {
+ return Result::INVALID_OPERATION;
+ }
+
+ /**
+ * Method defined in ::android::hidl::base::V1_0::IBase.
+ *
+ * This method should write debug information to hidl_handle that is useful for debugging
+ * issues. Suggestions include:
+ * - Sensor info including handle values and any other state available in the SensorInfo class
+ * - List of active sensors and their current sampling period and reporting latency
+ * - Information about pending flush requests
+ * - Current operating mode
+ * - Currently registered direct channel info
+ * - A history of any of the above
+ */
+ virtual Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) = 0;
+
+ /**
+ * @return A human-readable name for use in wake locks and logging.
+ */
+ virtual const std::string getName() = 0;
+
+ /**
+ * First method invoked on the sub-HAL after it's allocated through sensorsHalGetSubHal() by the
+ * HalProxy. Sub-HALs should use this to initialize any state and retain the callback given in
+ * order to communicate with the HalProxy.
+ *
+ * @param halProxyCallback callback used to inform the HalProxy when a dynamic sensor's state
+ * changes, new sensor events should be sent to the framework, and when a new ScopedWakelock
+ * should be created.
+ * @return result OK on success
+ */
+ virtual Return<Result> initialize(const sp<IHalProxyCallback>& halProxyCallback) = 0;
+};
+
+} // namespace implementation
+} // namespace V2_0
+} // namespace sensors
+} // namespace hardware
+} // namespace android
+
+using ::android::hardware::sensors::V2_0::implementation::ISensorsSubHal;
+
+/**
+ * Function that must be exported so the HalProxy class can invoke it on the sub-HAL dynamic
+ * library. This function will only be invoked once at initialization time.
+ *
+ * NOTE: The supported sensors HAL version must match SUB_HAL_2_0_VERSION exactly or the HalProxy
+ * will fail to initialize.
+ *
+ * @param uint32_t when this function returns, this parameter must contain the HAL version that
+ * this sub-HAL supports. To support this version of multi-HAL, this must be set to
+ * SUB_HAL_2_0_VERSION.
+ * @return A statically allocated, valid ISensorsSubHal implementation.
+ */
+__attribute__((visibility("default"))) extern "C" ISensorsSubHal* sensorsHalGetSubHal(
+ uint32_t* version);
diff --git a/sensors/2.0/multihal/service.cpp b/sensors/2.0/multihal/service.cpp
new file mode 100644
index 0000000..995cf3c
--- /dev/null
+++ b/sensors/2.0/multihal/service.cpp
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "android.hardware.sensors@2.0-service"
+
+#include <android/hardware/sensors/2.0/ISensors.h>
+#include <hidl/HidlTransportSupport.h>
+#include <log/log.h>
+#include <utils/StrongPointer.h>
+#include "HalProxy.h"
+
+using android::hardware::configureRpcThreadpool;
+using android::hardware::joinRpcThreadpool;
+using android::hardware::sensors::V2_0::ISensors;
+using android::hardware::sensors::V2_0::implementation::HalProxy;
+
+int main(int /* argc */, char** /* argv */) {
+ configureRpcThreadpool(1, true);
+
+ android::sp<ISensors> halProxy = new HalProxy();
+ if (halProxy->registerAsService() != ::android::OK) {
+ ALOGE("Failed to register Sensors HAL instance");
+ return -1;
+ }
+
+ joinRpcThreadpool();
+ return 1; // joinRpcThreadpool shouldn't exit
+}
diff --git a/sensors/2.0/multihal/testing/Android.bp b/sensors/2.0/multihal/testing/Android.bp
new file mode 100644
index 0000000..3dedbd6
--- /dev/null
+++ b/sensors/2.0/multihal/testing/Android.bp
@@ -0,0 +1,55 @@
+//
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+cc_defaults {
+ name: "android.hardware.sensors@2.0-fakesubhal-defaults",
+ vendor: true,
+ srcs: [
+ "Sensor.cpp",
+ "SensorsSubHal.cpp",
+ ],
+ header_libs: [
+ "android.hardware.sensors@2.0-subhal.header",
+ ],
+ shared_libs: [
+ "android.hardware.sensors@1.0",
+ "android.hardware.sensors@2.0",
+ "libcutils",
+ "libfmq",
+ "libhidlbase",
+ "libhidltransport",
+ "liblog",
+ "libpower",
+ "libutils",
+ ],
+}
+
+cc_library {
+ name: "android.hardware.sensors@2.0-fakesubhal-config1",
+ defaults: ["android.hardware.sensors@2.0-fakesubhal-defaults"],
+ cflags: [
+ "-DSUPPORT_CONTINUOUS_SENSORS",
+ "-DSUB_HAL_NAME=\"FakeSubHal-Continuous\"",
+ ],
+}
+
+cc_library {
+ name: "android.hardware.sensors@2.0-fakesubhal-config2",
+ defaults: ["android.hardware.sensors@2.0-fakesubhal-defaults"],
+ cflags: [
+ "-DSUPPORT_ON_CHANGE_SENSORS",
+ "-DSUB_HAL_NAME=\"FakeSubHal-OnChange\"",
+ ],
+}
\ No newline at end of file
diff --git a/sensors/2.0/multihal/testing/README b/sensors/2.0/multihal/testing/README
new file mode 100644
index 0000000..ddcc584
--- /dev/null
+++ b/sensors/2.0/multihal/testing/README
@@ -0,0 +1,19 @@
+This directory contains a modified version of the default implementation
+provided for sensors HAL 2.0 to support multi-HAL 2.0. It should be used as a
+means to verify the multi-HAL 2.0 implementation can successfully load and
+interact with sub-HALs.
+
+This sub-HAL implementation has two macros that can be used to configure support
+for different sets of sensors. One "SUPPORT_CONTINUOUS_SENSORS", enables
+support for continuous sensors like accel, and gyro whereas the other
+"SUPPORT_ON_CHANGE_SENSORS" enables support for on change sensors like the
+light and proximity sensor. A build target is defined for each of these macros,
+but more targets could be added to support both in one sub-HAL or none at all,
+if necessary.
+
+When built, the library will be written to
+out/target/product/<device>/vendor/lib64/android.hardware.sensors@2.0-fakesubhal.so
+
+Take this .so and place it where the multi-HAL config will cause the HalProxy to
+look and then restart the system server with adb shell stop / adb shell start
+to cause the multi-HAL to restart and attempt to load in the sub-HAL.
diff --git a/sensors/2.0/multihal/testing/Sensor.cpp b/sensors/2.0/multihal/testing/Sensor.cpp
new file mode 100644
index 0000000..e095efe
--- /dev/null
+++ b/sensors/2.0/multihal/testing/Sensor.cpp
@@ -0,0 +1,372 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "Sensor.h"
+
+#include <utils/SystemClock.h>
+
+#include <cmath>
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V2_0 {
+namespace subhal {
+namespace implementation {
+
+using ::android::hardware::sensors::V1_0::MetaDataEventType;
+using ::android::hardware::sensors::V1_0::SensorFlagBits;
+using ::android::hardware::sensors::V1_0::SensorStatus;
+
+static constexpr float kDefaultMaxDelayUs = 10 * 1000 * 1000;
+
+Sensor::Sensor(ISensorsEventCallback* callback)
+ : mIsEnabled(false),
+ mSamplingPeriodNs(0),
+ mLastSampleTimeNs(0),
+ mCallback(callback),
+ mMode(OperationMode::NORMAL) {
+ mRunThread = std::thread(startThread, this);
+}
+
+Sensor::~Sensor() {
+ std::unique_lock<std::mutex> lock(mRunMutex);
+ mStopThread = true;
+ mIsEnabled = false;
+ mWaitCV.notify_all();
+ lock.release();
+ mRunThread.join();
+}
+
+const SensorInfo& Sensor::getSensorInfo() const {
+ return mSensorInfo;
+}
+
+void Sensor::batch(int32_t samplingPeriodNs) {
+ samplingPeriodNs =
+ std::clamp(samplingPeriodNs, mSensorInfo.minDelay * 1000, mSensorInfo.maxDelay * 1000);
+
+ if (mSamplingPeriodNs != samplingPeriodNs) {
+ mSamplingPeriodNs = samplingPeriodNs;
+ // Wake up the 'run' thread to check if a new event should be generated now
+ mWaitCV.notify_all();
+ }
+}
+
+void Sensor::activate(bool enable) {
+ if (mIsEnabled != enable) {
+ std::unique_lock<std::mutex> lock(mRunMutex);
+ mIsEnabled = enable;
+ mWaitCV.notify_all();
+ }
+}
+
+Result Sensor::flush() {
+ // Only generate a flush complete event if the sensor is enabled and if the sensor is not a
+ // one-shot sensor.
+ if (!mIsEnabled || (mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::ONE_SHOT_MODE))) {
+ return Result::BAD_VALUE;
+ }
+
+ // Note: If a sensor supports batching, write all of the currently batched events for the sensor
+ // to the Event FMQ prior to writing the flush complete event.
+ Event ev;
+ ev.sensorHandle = mSensorInfo.sensorHandle;
+ ev.sensorType = SensorType::META_DATA;
+ ev.u.meta.what = MetaDataEventType::META_DATA_FLUSH_COMPLETE;
+ std::vector<Event> evs{ev};
+ mCallback->postEvents(evs, isWakeUpSensor());
+
+ return Result::OK;
+}
+
+void Sensor::startThread(Sensor* sensor) {
+ sensor->run();
+}
+
+void Sensor::run() {
+ std::unique_lock<std::mutex> runLock(mRunMutex);
+ constexpr int64_t kNanosecondsInSeconds = 1000 * 1000 * 1000;
+
+ while (!mStopThread) {
+ if (!mIsEnabled || mMode == OperationMode::DATA_INJECTION) {
+ mWaitCV.wait(runLock, [&] {
+ return ((mIsEnabled && mMode == OperationMode::NORMAL) || mStopThread);
+ });
+ } else {
+ timespec curTime;
+ clock_gettime(CLOCK_REALTIME, &curTime);
+ int64_t now = (curTime.tv_sec * kNanosecondsInSeconds) + curTime.tv_nsec;
+ int64_t nextSampleTime = mLastSampleTimeNs + mSamplingPeriodNs;
+
+ if (now >= nextSampleTime) {
+ mLastSampleTimeNs = now;
+ nextSampleTime = mLastSampleTimeNs + mSamplingPeriodNs;
+ mCallback->postEvents(readEvents(), isWakeUpSensor());
+ }
+
+ mWaitCV.wait_for(runLock, std::chrono::nanoseconds(nextSampleTime - now));
+ }
+ }
+}
+
+bool Sensor::isWakeUpSensor() {
+ return mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::WAKE_UP);
+}
+
+std::vector<Event> Sensor::readEvents() {
+ std::vector<Event> events;
+ Event event;
+ event.sensorHandle = mSensorInfo.sensorHandle;
+ event.sensorType = mSensorInfo.type;
+ event.timestamp = ::android::elapsedRealtimeNano();
+ event.u.vec3.x = 0;
+ event.u.vec3.y = 0;
+ event.u.vec3.z = 0;
+ event.u.vec3.status = SensorStatus::ACCURACY_HIGH;
+ events.push_back(event);
+ return events;
+}
+
+void Sensor::setOperationMode(OperationMode mode) {
+ if (mMode != mode) {
+ std::unique_lock<std::mutex> lock(mRunMutex);
+ mMode = mode;
+ mWaitCV.notify_all();
+ }
+}
+
+bool Sensor::supportsDataInjection() const {
+ return mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::DATA_INJECTION);
+}
+
+Result Sensor::injectEvent(const Event& event) {
+ Result result = Result::OK;
+ if (event.sensorType == SensorType::ADDITIONAL_INFO) {
+ // When in OperationMode::NORMAL, SensorType::ADDITIONAL_INFO is used to push operation
+ // environment data into the device.
+ } else if (!supportsDataInjection()) {
+ result = Result::INVALID_OPERATION;
+ } else if (mMode == OperationMode::DATA_INJECTION) {
+ mCallback->postEvents(std::vector<Event>{event}, isWakeUpSensor());
+ } else {
+ result = Result::BAD_VALUE;
+ }
+ return result;
+}
+
+OnChangeSensor::OnChangeSensor(ISensorsEventCallback* callback)
+ : Sensor(callback), mPreviousEventSet(false) {}
+
+void OnChangeSensor::activate(bool enable) {
+ Sensor::activate(enable);
+ if (!enable) {
+ mPreviousEventSet = false;
+ }
+}
+
+std::vector<Event> OnChangeSensor::readEvents() {
+ std::vector<Event> events = Sensor::readEvents();
+ std::vector<Event> outputEvents;
+
+ for (auto iter = events.begin(); iter != events.end(); ++iter) {
+ Event ev = *iter;
+ if (ev.u.vec3 != mPreviousEvent.u.vec3 || !mPreviousEventSet) {
+ outputEvents.push_back(ev);
+ mPreviousEvent = ev;
+ mPreviousEventSet = true;
+ }
+ }
+ return outputEvents;
+}
+
+AccelSensor::AccelSensor(int32_t sensorHandle, ISensorsEventCallback* callback) : Sensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Accel Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::ACCELEROMETER;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 78.4f; // +/- 8g
+ mSensorInfo.resolution = 1.52e-5;
+ mSensorInfo.power = 0.001f; // mA
+ mSensorInfo.minDelay = 20 * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::DATA_INJECTION);
+};
+
+PressureSensor::PressureSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
+ : Sensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Pressure Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::PRESSURE;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 1100.0f; // hPa
+ mSensorInfo.resolution = 0.005f; // hPa
+ mSensorInfo.power = 0.001f; // mA
+ mSensorInfo.minDelay = 100 * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags = 0;
+};
+
+MagnetometerSensor::MagnetometerSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
+ : Sensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Magnetic Field Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::MAGNETIC_FIELD;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 1300.0f;
+ mSensorInfo.resolution = 0.01f;
+ mSensorInfo.power = 0.001f; // mA
+ mSensorInfo.minDelay = 20 * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags = 0;
+};
+
+LightSensor::LightSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
+ : OnChangeSensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Light Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::LIGHT;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 43000.0f;
+ mSensorInfo.resolution = 10.0f;
+ mSensorInfo.power = 0.001f; // mA
+ mSensorInfo.minDelay = 200 * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE);
+};
+
+ProximitySensor::ProximitySensor(int32_t sensorHandle, ISensorsEventCallback* callback)
+ : OnChangeSensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Proximity Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::PROXIMITY;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 5.0f;
+ mSensorInfo.resolution = 1.0f;
+ mSensorInfo.power = 0.012f; // mA
+ mSensorInfo.minDelay = 200 * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags =
+ static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE | SensorFlagBits::WAKE_UP);
+};
+
+GyroSensor::GyroSensor(int32_t sensorHandle, ISensorsEventCallback* callback) : Sensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Gyro Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::GYROSCOPE;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 1000.0f * M_PI / 180.0f;
+ mSensorInfo.resolution = 1000.0f * M_PI / (180.0f * 32768.0f);
+ mSensorInfo.power = 0.001f;
+ mSensorInfo.minDelay = 2.5f * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags = 0;
+};
+
+AmbientTempSensor::AmbientTempSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
+ : OnChangeSensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Ambient Temp Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::AMBIENT_TEMPERATURE;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 80.0f;
+ mSensorInfo.resolution = 0.01f;
+ mSensorInfo.power = 0.001f;
+ mSensorInfo.minDelay = 40 * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE);
+};
+
+DeviceTempSensor::DeviceTempSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
+ : OnChangeSensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Device Temp Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::TEMPERATURE;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 80.0f;
+ mSensorInfo.resolution = 0.01f;
+ mSensorInfo.power = 0.001f;
+ mSensorInfo.minDelay = 40 * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE);
+}
+
+RelativeHumiditySensor::RelativeHumiditySensor(int32_t sensorHandle,
+ ISensorsEventCallback* callback)
+ : OnChangeSensor(callback) {
+ mSensorInfo.sensorHandle = sensorHandle;
+ mSensorInfo.name = "Relative Humidity Sensor";
+ mSensorInfo.vendor = "Vendor String";
+ mSensorInfo.version = 1;
+ mSensorInfo.type = SensorType::RELATIVE_HUMIDITY;
+ mSensorInfo.typeAsString = "";
+ mSensorInfo.maxRange = 100.0f;
+ mSensorInfo.resolution = 0.1f;
+ mSensorInfo.power = 0.001f;
+ mSensorInfo.minDelay = 40 * 1000; // microseconds
+ mSensorInfo.maxDelay = kDefaultMaxDelayUs;
+ mSensorInfo.fifoReservedEventCount = 0;
+ mSensorInfo.fifoMaxEventCount = 0;
+ mSensorInfo.requiredPermission = "";
+ mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE);
+}
+
+} // namespace implementation
+} // namespace subhal
+} // namespace V2_0
+} // namespace sensors
+} // namespace hardware
+} // namespace android
diff --git a/sensors/2.0/multihal/testing/Sensor.h b/sensors/2.0/multihal/testing/Sensor.h
new file mode 100644
index 0000000..980ea54
--- /dev/null
+++ b/sensors/2.0/multihal/testing/Sensor.h
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android/hardware/sensors/1.0/types.h>
+
+#include <condition_variable>
+#include <memory>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+using ::android::hardware::sensors::V1_0::Event;
+using ::android::hardware::sensors::V1_0::OperationMode;
+using ::android::hardware::sensors::V1_0::Result;
+using ::android::hardware::sensors::V1_0::SensorInfo;
+using ::android::hardware::sensors::V1_0::SensorType;
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V2_0 {
+namespace subhal {
+namespace implementation {
+
+class ISensorsEventCallback {
+ public:
+ virtual ~ISensorsEventCallback(){};
+ virtual void postEvents(const std::vector<Event>& events, bool wakeup) = 0;
+};
+
+class Sensor {
+ public:
+ Sensor(ISensorsEventCallback* callback);
+ virtual ~Sensor();
+
+ const SensorInfo& getSensorInfo() const;
+ void batch(int32_t samplingPeriodNs);
+ virtual void activate(bool enable);
+ Result flush();
+
+ void setOperationMode(OperationMode mode);
+ bool supportsDataInjection() const;
+ Result injectEvent(const Event& event);
+
+ protected:
+ void run();
+ virtual std::vector<Event> readEvents();
+ static void startThread(Sensor* sensor);
+
+ bool isWakeUpSensor();
+
+ bool mIsEnabled;
+ int64_t mSamplingPeriodNs;
+ int64_t mLastSampleTimeNs;
+ SensorInfo mSensorInfo;
+
+ std::atomic_bool mStopThread;
+ std::condition_variable mWaitCV;
+ std::mutex mRunMutex;
+ std::thread mRunThread;
+
+ ISensorsEventCallback* mCallback;
+
+ OperationMode mMode;
+};
+
+class OnChangeSensor : public Sensor {
+ public:
+ OnChangeSensor(ISensorsEventCallback* callback);
+
+ virtual void activate(bool enable) override;
+
+ protected:
+ virtual std::vector<Event> readEvents() override;
+
+ protected:
+ Event mPreviousEvent;
+ bool mPreviousEventSet;
+};
+
+class AccelSensor : public Sensor {
+ public:
+ AccelSensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+class GyroSensor : public Sensor {
+ public:
+ GyroSensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+class AmbientTempSensor : public OnChangeSensor {
+ public:
+ AmbientTempSensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+class DeviceTempSensor : public OnChangeSensor {
+ public:
+ DeviceTempSensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+class PressureSensor : public Sensor {
+ public:
+ PressureSensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+class MagnetometerSensor : public Sensor {
+ public:
+ MagnetometerSensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+class LightSensor : public OnChangeSensor {
+ public:
+ LightSensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+class ProximitySensor : public OnChangeSensor {
+ public:
+ ProximitySensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+class RelativeHumiditySensor : public OnChangeSensor {
+ public:
+ RelativeHumiditySensor(int32_t sensorHandle, ISensorsEventCallback* callback);
+};
+
+} // namespace implementation
+} // namespace subhal
+} // namespace V2_0
+} // namespace sensors
+} // namespace hardware
+} // namespace android
diff --git a/sensors/2.0/multihal/testing/SensorsSubHal.cpp b/sensors/2.0/multihal/testing/SensorsSubHal.cpp
new file mode 100644
index 0000000..8d45982
--- /dev/null
+++ b/sensors/2.0/multihal/testing/SensorsSubHal.cpp
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "SensorsSubHal.h"
+
+#include <android/hardware/sensors/2.0/types.h>
+#include <log/log.h>
+
+ISensorsSubHal* sensorsHalGetSubHal(uint32_t* version) {
+ static ::android::hardware::sensors::V2_0::subhal::implementation::SensorsSubHal subHal;
+ *version = SUB_HAL_2_0_VERSION;
+ return &subHal;
+}
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V2_0 {
+namespace subhal {
+namespace implementation {
+
+using ::android::hardware::Void;
+using ::android::hardware::sensors::V1_0::Event;
+using ::android::hardware::sensors::V1_0::OperationMode;
+using ::android::hardware::sensors::V1_0::RateLevel;
+using ::android::hardware::sensors::V1_0::Result;
+using ::android::hardware::sensors::V1_0::SharedMemInfo;
+using ::android::hardware::sensors::V2_0::SensorTimeout;
+using ::android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
+using ::android::hardware::sensors::V2_0::implementation::ScopedWakelock;
+
+SensorsSubHal::SensorsSubHal() : mCallback(nullptr), mNextHandle(1) {
+#ifdef SUPPORT_CONTINUOUS_SENSORS
+ AddSensor<AccelSensor>();
+ AddSensor<GyroSensor>();
+ AddSensor<MagnetometerSensor>();
+ AddSensor<PressureSensor>();
+#endif // SUPPORT_CONTINUOUS_SENSORS
+
+#ifdef SUPPORT_ON_CHANGE_SENSORS
+ AddSensor<AmbientTempSensor>();
+ AddSensor<DeviceTempSensor>();
+ AddSensor<LightSensor>();
+ AddSensor<ProximitySensor>();
+ AddSensor<RelativeHumiditySensor>();
+#endif // SUPPORT_ON_CHANGE_SENSORS
+}
+
+// Methods from ::android::hardware::sensors::V2_0::ISensors follow.
+Return<void> SensorsSubHal::getSensorsList(getSensorsList_cb _hidl_cb) {
+ std::vector<SensorInfo> sensors;
+ for (const auto& sensor : mSensors) {
+ sensors.push_back(sensor.second->getSensorInfo());
+ }
+
+ _hidl_cb(sensors);
+ return Void();
+}
+
+Return<Result> SensorsSubHal::setOperationMode(OperationMode mode) {
+ for (auto sensor : mSensors) {
+ sensor.second->setOperationMode(mode);
+ }
+ return Result::OK;
+}
+
+Return<Result> SensorsSubHal::activate(int32_t sensorHandle, bool enabled) {
+ auto sensor = mSensors.find(sensorHandle);
+ if (sensor != mSensors.end()) {
+ sensor->second->activate(enabled);
+ return Result::OK;
+ }
+ return Result::BAD_VALUE;
+}
+
+Return<Result> SensorsSubHal::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
+ int64_t /* maxReportLatencyNs */) {
+ auto sensor = mSensors.find(sensorHandle);
+ if (sensor != mSensors.end()) {
+ sensor->second->batch(samplingPeriodNs);
+ return Result::OK;
+ }
+ return Result::BAD_VALUE;
+}
+
+Return<Result> SensorsSubHal::flush(int32_t sensorHandle) {
+ auto sensor = mSensors.find(sensorHandle);
+ if (sensor != mSensors.end()) {
+ return sensor->second->flush();
+ }
+ return Result::BAD_VALUE;
+}
+
+Return<Result> SensorsSubHal::injectSensorData(const Event& event) {
+ auto sensor = mSensors.find(event.sensorHandle);
+ if (sensor != mSensors.end()) {
+ return sensor->second->injectEvent(event);
+ }
+
+ return Result::BAD_VALUE;
+}
+
+Return<void> SensorsSubHal::registerDirectChannel(const SharedMemInfo& /* mem */,
+ registerDirectChannel_cb _hidl_cb) {
+ _hidl_cb(Result::INVALID_OPERATION, -1 /* channelHandle */);
+ return Return<void>();
+}
+
+Return<Result> SensorsSubHal::unregisterDirectChannel(int32_t /* channelHandle */) {
+ return Result::INVALID_OPERATION;
+}
+
+Return<void> SensorsSubHal::configDirectReport(int32_t /* sensorHandle */,
+ int32_t /* channelHandle */, RateLevel /* rate */,
+ configDirectReport_cb _hidl_cb) {
+ _hidl_cb(Result::INVALID_OPERATION, 0 /* reportToken */);
+ return Return<void>();
+}
+
+Return<void> SensorsSubHal::debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) {
+ if (fd.getNativeHandle() == nullptr || fd->numFds < 1) {
+ ALOGE("%s: missing fd for writing", __FUNCTION__);
+ return Void();
+ }
+
+ FILE* out = fdopen(dup(fd->data[0]), "w");
+
+ if (args.size() != 0) {
+ fprintf(out,
+ "Note: sub-HAL %s currently does not support args. Input arguments are "
+ "ignored.\n",
+ getName().c_str());
+ }
+
+ std::ostringstream stream;
+ stream << "Available sensors:" << std::endl;
+ for (auto sensor : mSensors) {
+ SensorInfo info = sensor.second->getSensorInfo();
+ stream << "Name: " << info.name << std::endl;
+ stream << "Min delay: " << info.minDelay << std::endl;
+ stream << "Flags: " << info.flags << std::endl;
+ }
+ stream << std::endl;
+
+ fprintf(out, "%s", stream.str().c_str());
+
+ fclose(out);
+ return Return<void>();
+}
+
+Return<Result> SensorsSubHal::initialize(const sp<IHalProxyCallback>& halProxyCallback) {
+ mCallback = halProxyCallback;
+ return Result::OK;
+}
+
+void SensorsSubHal::postEvents(const std::vector<Event>& events, bool wakeup) {
+ ScopedWakelock wakelock = mCallback->createScopedWakelock(wakeup);
+ mCallback->postEvents(events, std::move(wakelock));
+}
+
+} // namespace implementation
+} // namespace subhal
+} // namespace V2_0
+} // namespace sensors
+} // namespace hardware
+} // namespace android
diff --git a/sensors/2.0/multihal/testing/SensorsSubHal.h b/sensors/2.0/multihal/testing/SensorsSubHal.h
new file mode 100644
index 0000000..93009d5
--- /dev/null
+++ b/sensors/2.0/multihal/testing/SensorsSubHal.h
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "SubHal.h"
+
+#include "Sensor.h"
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace V2_0 {
+namespace subhal {
+namespace implementation {
+
+using ::android::hardware::sensors::V2_0::implementation::IHalProxyCallback;
+
+/**
+ * Implementation of a ISensorsSubHal that can be used to test the implementation of multihal 2.0.
+ * See the README file for more details on how this class can be used for testing.
+ */
+class SensorsSubHal : public ISensorsSubHal, public ISensorsEventCallback {
+ using Event = ::android::hardware::sensors::V1_0::Event;
+ using OperationMode = ::android::hardware::sensors::V1_0::OperationMode;
+ using RateLevel = ::android::hardware::sensors::V1_0::RateLevel;
+ using Result = ::android::hardware::sensors::V1_0::Result;
+ using SharedMemInfo = ::android::hardware::sensors::V1_0::SharedMemInfo;
+
+ public:
+ SensorsSubHal();
+
+ // Methods from ::android::hardware::sensors::V2_0::ISensors follow.
+ Return<void> getSensorsList(getSensorsList_cb _hidl_cb) override;
+
+ Return<Result> setOperationMode(OperationMode mode) override;
+
+ Return<Result> activate(int32_t sensorHandle, bool enabled) override;
+
+ Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
+ int64_t maxReportLatencyNs) override;
+
+ Return<Result> flush(int32_t sensorHandle) override;
+
+ Return<Result> injectSensorData(const Event& event) override;
+
+ Return<void> registerDirectChannel(const SharedMemInfo& mem,
+ registerDirectChannel_cb _hidl_cb) override;
+
+ Return<Result> unregisterDirectChannel(int32_t channelHandle) override;
+
+ Return<void> configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
+ configDirectReport_cb _hidl_cb) override;
+
+ Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override;
+
+ // Methods from ::android::hardware::sensors::V2_0::implementation::ISensorsSubHal follow.
+ const std::string getName() override {
+#ifdef SUB_HAL_NAME
+ return SUB_HAL_NAME;
+#else // SUB_HAL_NAME
+ return "FakeSubHal";
+#endif // SUB_HAL_NAME
+ }
+
+ Return<Result> initialize(const sp<IHalProxyCallback>& halProxyCallback) override;
+
+ // Method from ISensorsEventCallback.
+ void postEvents(const std::vector<Event>& events, bool wakeup) override;
+
+ private:
+ template <class SensorType>
+ void AddSensor() {
+ std::shared_ptr<SensorType> sensor =
+ std::make_shared<SensorType>(mNextHandle++ /* sensorHandle */, this /* callback */);
+ mSensors[sensor->getSensorInfo().sensorHandle] = sensor;
+ }
+
+ /**
+ * Callback used to communicate to the HalProxy when dynamic sensors are connected /
+ * disconnected, sensor events need to be sent to the framework, and when a wakelock should be
+ * acquired.
+ */
+ sp<IHalProxyCallback> mCallback;
+
+ /**
+ * A map of the available sensors
+ */
+ std::map<int32_t, std::shared_ptr<Sensor>> mSensors;
+
+ /**
+ * The next available sensor handle
+ */
+ int32_t mNextHandle;
+};
+
+} // namespace implementation
+} // namespace subhal
+} // namespace V2_0
+} // namespace sensors
+} // namespace hardware
+} // namespace android
diff --git a/wifi/1.0/IWifiP2pIface.hal b/wifi/1.0/IWifiP2pIface.hal
index b908591..025f7ab 100644
--- a/wifi/1.0/IWifiP2pIface.hal
+++ b/wifi/1.0/IWifiP2pIface.hal
@@ -19,6 +19,6 @@
import IWifiIface;
/**
- * Interface used to represent a single NAN iface.
+ * Interface used to represent a single P2P iface.
*/
interface IWifiP2pIface extends IWifiIface {};