blob: c98330bfe09461e2f6ab8dff123d02d6349c534e [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>
25#include <thread>
26
27namespace android {
28namespace hardware {
29namespace automotive {
30namespace can {
31namespace V1_0 {
32namespace implementation {
33
chrisweircf36cea2019-11-08 16:41:02 -080034/** Wrapper around SocketCAN socket. */
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070035struct CanSocket {
36 using ReadCallback = std::function<void(const struct canfd_frame&, std::chrono::nanoseconds)>;
Tomasz Wasilczyka9061962019-11-04 12:53:09 -080037 using ErrorCallback = std::function<void(int errnoVal)>;
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070038
39 /**
40 * Open and bind SocketCAN socket.
41 *
42 * \param ifname SocketCAN network interface name (such as can0)
43 * \param rdcb Callback on received messages
44 * \param errcb Callback on socket failure
45 * \return Socket instance, or nullptr if it wasn't possible to open one
46 */
47 static std::unique_ptr<CanSocket> open(const std::string& ifname, ReadCallback rdcb,
48 ErrorCallback errcb);
49 virtual ~CanSocket();
50
51 /**
52 * Send CAN frame.
53 *
54 * \param frame Frame to send
55 * \return true in case of success, false otherwise
56 */
57 bool send(const struct canfd_frame& frame);
58
59 private:
60 CanSocket(base::unique_fd socket, ReadCallback rdcb, ErrorCallback errcb);
61 void readerThread();
62
63 ReadCallback mReadCallback;
64 ErrorCallback mErrorCallback;
65
66 const base::unique_fd mSocket;
67 std::thread mReaderThread;
68 std::atomic<bool> mStopReaderThread = false;
Tomasz Wasilczyka9061962019-11-04 12:53:09 -080069 std::atomic<bool> mReaderThreadFinished = false;
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070070
71 DISALLOW_COPY_AND_ASSIGN(CanSocket);
72};
73
74} // namespace implementation
75} // namespace V1_0
76} // namespace can
77} // namespace automotive
78} // namespace hardware
79} // namespace android