xref: /aosp_15_r20/system/chre/host/common/time_syncer.cc (revision 84e339476a462649f82315436d70fd732297a399)
1 /*
2  * Copyright (C) 2022 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 "chre_host/time_syncer.h"
18 #include <chre_host/host_protocol_host.h>
19 #include "chre_host/log.h"
20 
21 namespace android::chre {
22 // TODO(b/247124878): Can we add a static assert to make sure these functions
23 //  are not called when connection->isTimeSyncNeeded() returns false?
sendTimeSync(ChreConnection * connection)24 bool TimeSyncer::sendTimeSync(ChreConnection *connection) {
25   if (!connection->isTimeSyncNeeded()) {
26     LOGW("Platform doesn't require time sync. Ignore the request.");
27     return true;
28   }
29   int64_t timeOffsetUs = 0;
30   if (!connection->getTimeOffset(&timeOffsetUs)) {
31     LOGE("Failed to get time offset.");
32     return false;
33   }
34   flatbuffers::FlatBufferBuilder builder(64);
35   // clientId doesn't matter for time sync request so the default id is used.
36   HostProtocolHost::encodeTimeSyncMessage(builder, timeOffsetUs);
37   return connection->sendMessage(builder.GetBufferPointer(), builder.GetSize());
38 }
39 
sendTimeSyncWithRetry(ChreConnection * connection,size_t numOfRetries,useconds_t retryDelayUs)40 bool TimeSyncer::sendTimeSyncWithRetry(ChreConnection *connection,
41                                        size_t numOfRetries,
42                                        useconds_t retryDelayUs) {
43   if (!connection->isTimeSyncNeeded()) {
44     LOGW("Platform doesn't require time sync. Ignore the request.");
45     return true;
46   }
47   bool success = false;
48   while (!success && (numOfRetries-- > 0)) {
49     success = sendTimeSync(connection);
50     if (!success) {
51       usleep(retryDelayUs);
52     }
53   }
54   return success;
55 }
56 }  // namespace android::chre