1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef SEC_MESSENGER_UTILS_H
17 #define SEC_MESSENGER_UTILS_H
18
19 #include <stdint.h>
20 #include <stdlib.h>
21 #include <sys/time.h>
22
23 #include "securec.h"
24 #include "utils_hexstring.h"
25
26 #include "messenger.h"
27
28 #ifdef __cplusplus
29 extern "C" {
30 #endif
31
32 #define MAX_TRY_TIMES 512
33
34 typedef struct QueueMsgData {
35 DeviceIdentify srcIdentity;
36 uint32_t msgLen;
37 uint8_t msgData[1];
38 } QueueMsgData;
39
MaskDeviceIdentity(const char * deviceId,uint32_t length)40 static inline uint32_t MaskDeviceIdentity(const char *deviceId, uint32_t length)
41 {
42 #define MASK_LEN 4U
43 #define SHIFT_LENGTH 8U
44 #define MASK_LOW 0x00ffU
45 #define MASK_HIGH 0xff00U
46 if (deviceId == NULL || length < MASK_LEN) {
47 return 0;
48 }
49
50 uint16_t maskId = 0;
51 DslmHexStringToByte(deviceId, MASK_LEN, (uint8_t *)&maskId, sizeof(maskId));
52 return ((maskId & MASK_HIGH) >> SHIFT_LENGTH) | ((maskId & MASK_LOW) << SHIFT_LENGTH);
53 }
54
MessengerSleep(uint32_t seconds)55 static inline void MessengerSleep(uint32_t seconds)
56 {
57 int ret;
58 struct timeval tmv = {
59 .tv_sec = seconds,
60 .tv_usec = 0,
61 };
62 do {
63 ret = select(0, NULL, NULL, NULL, &tmv);
64 } while ((ret == -1) && (errno == EINTR));
65 }
66
IsSameDevice(const DeviceIdentify * left,const DeviceIdentify * right)67 static inline bool IsSameDevice(const DeviceIdentify *left, const DeviceIdentify *right)
68 {
69 if ((left == NULL) || (right == NULL)) {
70 return false;
71 }
72
73 if (left->length != right->length) {
74 return false;
75 }
76
77 if (memcmp(left->identity, right->identity, left->length) != 0) {
78 return false;
79 }
80
81 return true;
82 }
83
84 QueueMsgData *CreateQueueMsgData(const DeviceIdentify *devId, const uint8_t *msg, uint32_t msgLen,
85 uint32_t *queueDataLen);
86
87 #ifdef __cplusplus
88 }
89 #endif
90
91 #endif // SEC_MESSENGER_UTILS_H
92