1 /*
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>
25 #include <thread>
26 
27 namespace android::hardware::automotive::can::V1_0::implementation {
28 
29 /** Wrapper around SocketCAN socket. */
30 struct CanSocket {
31     using ReadCallback = std::function<void(const struct canfd_frame&, std::chrono::nanoseconds)>;
32     using ErrorCallback = std::function<void(int errnoVal)>;
33 
34     /**
35      * Open and bind SocketCAN socket.
36      *
37      * \param ifname SocketCAN network interface name (such as can0)
38      * \param rdcb Callback on received messages
39      * \param errcb Callback on socket failure
40      * \return Socket instance, or nullptr if it wasn't possible to open one
41      */
42     static std::unique_ptr<CanSocket> open(const std::string& ifname, ReadCallback rdcb,
43                                            ErrorCallback errcb);
44     virtual ~CanSocket();
45 
46     /**
47      * Send CAN frame.
48      *
49      * \param frame Frame to send
50      * \return true in case of success, false otherwise
51      */
52     bool send(const struct canfd_frame& frame);
53 
54   private:
55     CanSocket(base::unique_fd socket, ReadCallback rdcb, ErrorCallback errcb);
56     void readerThread();
57 
58     ReadCallback mReadCallback;
59     ErrorCallback mErrorCallback;
60 
61     const base::unique_fd mSocket;
62     std::thread mReaderThread;
63     std::atomic<bool> mStopReaderThread = false;
64     std::atomic<bool> mReaderThreadFinished = false;
65 
66     DISALLOW_COPY_AND_ASSIGN(CanSocket);
67 };
68 
69 }  // namespace android::hardware::automotive::can::V1_0::implementation
70