blob: f3e8e6065f7bb4f184c528cdea3e5fa75b4fa035 [file] [log] [blame]
Tomasz Wasilczyk87329672019-07-12 11:43:00 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <android-base/macros.h>
20#include <android-base/unique_fd.h>
21#include <linux/can.h>
22
23#include <atomic>
24#include <chrono>
Tomasz Wasilczykb87cdae2024-01-09 11:56:43 -080025#include <functional>
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070026#include <thread>
27
Tomasz Wasilczyk55f21932019-12-20 09:20:24 -080028namespace android::hardware::automotive::can::V1_0::implementation {
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070029
chrisweircf36cea2019-11-08 16:41:02 -080030/** Wrapper around SocketCAN socket. */
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070031struct CanSocket {
32 using ReadCallback = std::function<void(const struct canfd_frame&, std::chrono::nanoseconds)>;
Tomasz Wasilczyka9061962019-11-04 12:53:09 -080033 using ErrorCallback = std::function<void(int errnoVal)>;
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070034
35 /**
36 * Open and bind SocketCAN socket.
37 *
38 * \param ifname SocketCAN network interface name (such as can0)
39 * \param rdcb Callback on received messages
40 * \param errcb Callback on socket failure
41 * \return Socket instance, or nullptr if it wasn't possible to open one
42 */
43 static std::unique_ptr<CanSocket> open(const std::string& ifname, ReadCallback rdcb,
44 ErrorCallback errcb);
45 virtual ~CanSocket();
46
47 /**
48 * Send CAN frame.
49 *
50 * \param frame Frame to send
51 * \return true in case of success, false otherwise
52 */
53 bool send(const struct canfd_frame& frame);
54
55 private:
56 CanSocket(base::unique_fd socket, ReadCallback rdcb, ErrorCallback errcb);
57 void readerThread();
58
59 ReadCallback mReadCallback;
60 ErrorCallback mErrorCallback;
61
62 const base::unique_fd mSocket;
63 std::thread mReaderThread;
64 std::atomic<bool> mStopReaderThread = false;
Tomasz Wasilczyka9061962019-11-04 12:53:09 -080065 std::atomic<bool> mReaderThreadFinished = false;
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070066
67 DISALLOW_COPY_AND_ASSIGN(CanSocket);
68};
69
Tomasz Wasilczyk55f21932019-12-20 09:20:24 -080070} // namespace android::hardware::automotive::can::V1_0::implementation