1 /*
2  * Copyright (c) 2018 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /** @file mqtt_os.h
8  *
9  * @brief MQTT Client depends on certain OS specific functionality. The needed
10  *        methods are mapped here and should be implemented based on OS in use.
11  *
12  * @details Memory management, mutex, logging and wall clock are the needed
13  *          functionality for MQTT module. The needed interfaces are defined
14  *          in the OS. OS specific port of the interface shall be provided.
15  *
16  */
17 
18 #ifndef MQTT_OS_H_
19 #define MQTT_OS_H_
20 
21 #include <stddef.h>
22 #include <zephyr/kernel.h>
23 #include <zephyr/sys/mutex.h>
24 
25 #include <zephyr/net/net_core.h>
26 
27 #include "mqtt_internal.h"
28 
29 #ifdef __cplusplus
30 extern "C" {
31 #endif
32 
33 /**@brief Initialize the mutex for the module, if any.
34  *
35  * @details This method is called during module initialization @ref mqtt_init.
36  */
mqtt_mutex_init(struct mqtt_client * client)37 static inline void mqtt_mutex_init(struct mqtt_client *client)
38 {
39 	sys_mutex_init(&client->internal.mutex);
40 }
41 
42 /**@brief Acquire lock on the module specific mutex, if any.
43  *
44  * @details This is assumed to be a blocking method until the acquisition
45  *          of the mutex succeeds.
46  */
mqtt_mutex_lock(struct mqtt_client * client)47 static inline void mqtt_mutex_lock(struct mqtt_client *client)
48 {
49 	int ret = sys_mutex_lock(&client->internal.mutex, K_FOREVER);
50 
51 	__ASSERT(ret == 0, "sys_mutex_lock failed with %d", ret);
52 	(void)ret;
53 }
54 
55 /**@brief Release the lock on the module specific mutex, if any.
56  */
mqtt_mutex_unlock(struct mqtt_client * client)57 static inline void mqtt_mutex_unlock(struct mqtt_client *client)
58 {
59 	int ret = sys_mutex_unlock(&client->internal.mutex);
60 
61 	__ASSERT(ret == 0, "sys_mutex_unlock failed with %d", ret);
62 	(void)ret;
63 }
64 
65 /**@brief Method to get the sys tick or a wall clock in millisecond resolution.
66  *
67  * @retval Current wall clock or sys tick value in milliseconds.
68  */
mqtt_sys_tick_in_ms_get(void)69 static inline uint32_t mqtt_sys_tick_in_ms_get(void)
70 {
71 	return k_uptime_get_32();
72 }
73 
74 /**@brief Method to get elapsed time in milliseconds since the last activity.
75  *
76  * @param[in] last_activity The value since elapsed time is requested.
77  *
78  * @retval Time elapsed since last_activity time.
79  */
mqtt_elapsed_time_in_ms_get(uint32_t last_activity)80 static inline uint32_t mqtt_elapsed_time_in_ms_get(uint32_t last_activity)
81 {
82 	int32_t diff = k_uptime_get_32() - last_activity;
83 
84 	if (diff < 0) {
85 		return 0;
86 	}
87 
88 	return diff;
89 }
90 
91 #ifdef __cplusplus
92 }
93 #endif
94 
95 #endif /* MQTT_OS_H_ */
96