blob: 7d4fb04339916e4497a49d17729899d83aaffb7c [file] [log] [blame]
Yuchen He3cbf5f32021-08-30 22:20:30 +00001/*
2 * Copyright (C) 2021 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#include "DeviceFileReader.h"
17
18namespace android {
19namespace hardware {
20namespace gnss {
21namespace common {
22
23void DeviceFileReader::getDataFromDeviceFile(const std::string& command, int mMinIntervalMs) {
24 char inputBuffer[INPUT_BUFFER_SIZE];
25 int mGnssFd = open(ReplayUtils::getGnssPath().c_str(),
26 O_RDWR | O_NONBLOCK);
27
28 if (mGnssFd == -1) {
29 return;
30 }
31
32 int bytes_write = write(mGnssFd, command.c_str(), command.size());
33 if (bytes_write <= 0) {
34 close(mGnssFd);
35 return;
36 }
37
38 struct epoll_event ev, events[1];
39 ev.data.fd = mGnssFd;
40 ev.events = EPOLLIN;
41 int epoll_fd = epoll_create1(0);
42 epoll_ctl(epoll_fd, EPOLL_CTL_ADD, mGnssFd, &ev);
43 int bytes_read = -1;
44 std::string inputStr = "";
45 int epoll_ret = epoll_wait(epoll_fd, events, 1, mMinIntervalMs);
46
47 if (epoll_ret == -1) {
48 close(mGnssFd);
49 return;
50 }
51 while (true) {
52 memset(inputBuffer, 0, INPUT_BUFFER_SIZE);
53 bytes_read = read(mGnssFd, &inputBuffer, INPUT_BUFFER_SIZE);
54 if (bytes_read <= 0) {
55 break;
56 }
57 s_buffer_ += std::string(inputBuffer, bytes_read);
58 }
59 close(mGnssFd);
60
61 // Trim end of file mark(\n\n\n\n).
62 auto pos = s_buffer_.find("\n\n\n\n");
63 if (pos != std::string::npos) {
64 inputStr = s_buffer_.substr(0, pos);
65 s_buffer_ = s_buffer_.substr(pos + 4);
66 } else {
67 return;
68 }
69
70 // Cache the injected data.
71 if (ReplayUtils::isGnssRawMeasurement(inputStr)) {
72 data_[CMD_GET_RAWMEASUREMENT] = inputStr;
73 } else if (ReplayUtils::isNMEA(inputStr)) {
74 data_[CMD_GET_LOCATION] = inputStr;
75 }
76}
77
78std::string DeviceFileReader::getLocationData() {
79 std::unique_lock<std::mutex> lock(mMutex);
80 getDataFromDeviceFile(CMD_GET_LOCATION, 20);
81 return data_[CMD_GET_LOCATION];
82}
83
84std::string DeviceFileReader::getGnssRawMeasurementData() {
85 std::unique_lock<std::mutex> lock(mMutex);
86 getDataFromDeviceFile(CMD_GET_RAWMEASUREMENT, 20);
87 return data_[CMD_GET_RAWMEASUREMENT];
88}
89
90DeviceFileReader::DeviceFileReader() {}
91
92DeviceFileReader::~DeviceFileReader() {}
93
94} // namespace common
95} // namespace gnss
96} // namespace hardware
97} // namespace android