1 /* 2 * Copyright (C) 2020 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 "chpp/services/timesync.h" 18 19 #include <stdbool.h> 20 #include <stddef.h> 21 #include <stdint.h> 22 23 #include "chpp/app.h" 24 #include "chpp/common/timesync.h" 25 #include "chpp/log.h" 26 #include "chpp/macros.h" 27 #include "chpp/services.h" 28 #include "chpp/time.h" 29 #include "chpp/transport.h" 30 31 /** 32 * Processes the GetTime (0x0001) request and responds with the time as on the 33 * service. This should be the same clock used to timestamp any data samples 34 * provided to CHPP. 35 * 36 * @param context Maintains status for each app layer instance. 37 * @param buf Input data. Cannot be null. 38 * @param len Length of input data in bytes. 39 */ 40 static void chppTimesyncGetTime(struct ChppAppState *context, 41 const uint8_t *buf, size_t len) { 42 UNUSED_VAR(len); 43 const struct ChppAppHeader *requestHeader = (const struct ChppAppHeader *)buf; 44 45 struct ChppTimesyncResponse *response = 46 chppAllocServiceResponseFixed(requestHeader, struct ChppTimesyncResponse); 47 size_t responseLen = sizeof(*response); 48 49 if (response == NULL) { 50 CHPP_LOG_OOM(); 51 CHPP_DEBUG_ASSERT(false); 52 53 } else { 54 response->timeNs = chppGetCurrentTimeNs(); 55 CHPP_LOGD("chppTimesyncGetTime returning %" PRIuSIZE 56 " bytes at time=%" PRIu64, 57 responseLen, response->timeNs / CHPP_NSEC_PER_MSEC); 58 59 chppEnqueueTxDatagramOrFail(context->transportContext, response, 60 responseLen); 61 } 62 } 63 64 /************************************************ 65 * Public Functions 66 ***********************************************/ 67 68 bool chppDispatchTimesyncClientRequest(struct ChppAppState *context, 69 const uint8_t *buf, size_t len) { 70 UNUSED_VAR(len); 71 const struct ChppAppHeader *rxHeader = (const struct ChppAppHeader *)buf; 72 bool success = true; 73 74 switch (rxHeader->command) { 75 case CHPP_TIMESYNC_COMMAND_GETTIME: { 76 chppTimesyncGetTime(context, buf, len); 77 break; 78 } 79 default: { 80 success = false; 81 } 82 } 83 return success; 84 } 85