blob: 4d86de6a282e6f6918ab078d1777ec0381c11ef1 [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#include "CanSocket.h"
18
19#include <android-base/logging.h>
20#include <libnetdevice/can.h>
21#include <libnetdevice/libnetdevice.h>
22#include <linux/can.h>
23#include <utils/SystemClock.h>
24
25#include <chrono>
26
27namespace android {
28namespace hardware {
29namespace automotive {
30namespace can {
31namespace V1_0 {
32namespace implementation {
33
34using namespace std::chrono_literals;
35
36/**
37 * How frequently the read thread checks whether the interface was asked to be down.
38 *
39 * Note: This does *not* affect read timing or bandwidth, just CPU load vs time to
40 * down the interface.
41 */
42static constexpr auto kReadPooling = 100ms;
43
44std::unique_ptr<CanSocket> CanSocket::open(const std::string& ifname, ReadCallback rdcb,
45 ErrorCallback errcb) {
46 auto sock = netdevice::can::socket(ifname);
47 if (!sock.ok()) {
48 LOG(ERROR) << "Can't open CAN socket on " << ifname;
49 return nullptr;
50 }
51
52 // Can't use std::make_unique due to private CanSocket constructor.
53 return std::unique_ptr<CanSocket>(new CanSocket(std::move(sock), rdcb, errcb));
54}
55
56CanSocket::CanSocket(base::unique_fd socket, ReadCallback rdcb, ErrorCallback errcb)
57 : mReadCallback(rdcb),
58 mErrorCallback(errcb),
59 mSocket(std::move(socket)),
60 mReaderThread(&CanSocket::readerThread, this) {}
61
62CanSocket::~CanSocket() {
63 mStopReaderThread = true;
64 mReaderThread.join();
65}
66
67bool CanSocket::send(const struct canfd_frame& frame) {
68 const auto res = write(mSocket.get(), &frame, CAN_MTU);
69 if (res < 0) {
70 LOG(DEBUG) << "CanSocket send failed: " << errno;
71 return false;
72 }
73 if (res != CAN_MTU) {
74 LOG(DEBUG) << "CanSocket sent wrong number of bytes: " << res;
75 return false;
76 }
77 return true;
78}
79
80static struct timeval toTimeval(std::chrono::microseconds t) {
81 struct timeval tv;
82 tv.tv_sec = t / 1s;
83 tv.tv_usec = (t % 1s) / 1us;
84 return tv;
85}
86
87static int selectRead(const base::unique_fd& fd, std::chrono::microseconds timeout) {
88 auto timeouttv = toTimeval(timeout);
89 fd_set readfds;
90 FD_ZERO(&readfds);
91 FD_SET(fd.get(), &readfds);
92 return select(fd.get() + 1, &readfds, nullptr, nullptr, &timeouttv);
93}
94
95void CanSocket::readerThread() {
96 LOG(VERBOSE) << "Reader thread started";
97
98 while (!mStopReaderThread) {
99 /* The ideal would be to have a blocking read(3) call and interrupt it with shutdown(3).
100 * This is unfortunately not supported for SocketCAN, so we need to rely on select(3).
101 */
102 const auto sel = selectRead(mSocket, kReadPooling);
103 if (sel == 0) continue; // timeout
104 if (sel == -1) {
105 LOG(ERROR) << "Select failed: " << errno;
106 break;
107 }
108
109 struct canfd_frame frame;
110 const auto nbytes = read(mSocket.get(), &frame, CAN_MTU);
111
112 /* We could use SIOCGSTAMP to get a precise UNIX timestamp for a given packet, but what
113 * we really need is a time since boot. There is no direct way to convert between these
114 * clocks. We could implement a class to calculate the difference between the clocks
115 * (querying both several times and picking the smallest difference); apply the difference
116 * to a SIOCGSTAMP returned value; re-synchronize if the elapsed time is too much in the
117 * past (indicating the UNIX timestamp might have been adjusted).
118 *
119 * Apart from the added complexity, it's possible the added calculations and system calls
120 * would add so much time to the processing pipeline so the precision of the reported time
121 * was buried under the subsystem latency. Let's just use a local time since boot here and
122 * leave precise hardware timestamps for custom proprietary implementations (if needed).
123 */
124 const std::chrono::nanoseconds ts(elapsedRealtimeNano());
125
126 if (nbytes != CAN_MTU) {
127 if (nbytes >= 0) {
128 LOG(ERROR) << "Failed to read CAN packet, got " << nbytes << " bytes";
129 break;
130 }
131 if (errno == EAGAIN) continue;
132
133 LOG(ERROR) << "Failed to read CAN packet: " << errno;
134 break;
135 }
136
137 mReadCallback(frame, ts);
138 }
139
140 if (!mStopReaderThread) mErrorCallback();
141
142 LOG(VERBOSE) << "Reader thread stopped";
143}
144
145} // namespace implementation
146} // namespace V1_0
147} // namespace can
148} // namespace automotive
149} // namespace hardware
150} // namespace android