1 /*
2  * Copyright (c) 2022 Martin Jäger <martin@libre.solar>
3  * Copyright (c) 2022 tado GmbH
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include "lorawan_services.h"
9 
10 #include <zephyr/init.h>
11 #include <zephyr/kernel.h>
12 #include <zephyr/logging/log.h>
13 
14 LOG_MODULE_REGISTER(lorawan_services, CONFIG_LORAWAN_SERVICES_LOG_LEVEL);
15 
16 struct service_uplink_msg {
17 	sys_snode_t node;
18 	/* absolute ticks when this message should be scheduled */
19 	int64_t ticks;
20 	/* sufficient space for up to 3 answers (max 6 bytes each) */
21 	uint8_t data[18];
22 	uint8_t len;
23 	uint8_t port;
24 	bool used;
25 };
26 
27 K_THREAD_STACK_DEFINE(thread_stack_area, CONFIG_LORAWAN_SERVICES_THREAD_STACK_SIZE);
28 
29 /*
30  * The services need a dedicated work queue, as the LoRaWAN stack uses the system
31  * work queue and gets blocked if other LoRaWAN messages are sent and processed from
32  * the system work queue in parallel.
33  */
34 static struct k_work_q services_workq;
35 
36 static struct k_work_delayable uplink_work;
37 
38 /* Number of active class C sessions and mutex to protect access to session info */
39 static uint8_t active_class_c_sessions;
40 static struct k_mutex session_mutex;
41 
42 /* single-linked list (with pointers) and array for implementation of priority queue */
43 static struct service_uplink_msg messages[10];
44 static sys_slist_t msg_list;
45 static struct k_sem msg_sem;
46 
uplink_handler(struct k_work * work)47 static void uplink_handler(struct k_work *work)
48 {
49 	struct service_uplink_msg msg_copy;
50 	struct service_uplink_msg *first;
51 	sys_snode_t *node;
52 	int err;
53 
54 	ARG_UNUSED(work);
55 
56 	/* take semaphore and create a copy of the next message */
57 	k_sem_take(&msg_sem, K_FOREVER);
58 
59 	node = sys_slist_get(&msg_list);
60 	if (node == NULL) {
61 		goto out;
62 	}
63 
64 	first = CONTAINER_OF(node, struct service_uplink_msg, node);
65 	msg_copy = *first;
66 	first->used = false;
67 	sys_slist_remove(&msg_list, NULL, &first->node);
68 
69 	/* semaphore must be given back before calling lorawan_send */
70 	k_sem_give(&msg_sem);
71 
72 	err = lorawan_send(msg_copy.port, msg_copy.data, msg_copy.len, LORAWAN_MSG_UNCONFIRMED);
73 	if (!err) {
74 		LOG_DBG("Message sent to port %d", msg_copy.port);
75 	} else {
76 		LOG_ERR("Sending message to port %d failed: %d",
77 			msg_copy.port, err);
78 	}
79 
80 	/* take the semaphore again to schedule next uplink */
81 	k_sem_take(&msg_sem, K_FOREVER);
82 
83 	node = sys_slist_peek_head(&msg_list);
84 	if (node == NULL) {
85 		goto out;
86 	}
87 	first = CONTAINER_OF(node, struct service_uplink_msg, node);
88 	k_work_reschedule_for_queue(&services_workq, &uplink_work,
89 		K_TIMEOUT_ABS_TICKS(first->ticks));
90 
91 out:
92 	k_sem_give(&msg_sem);
93 }
94 
insert_uplink(struct service_uplink_msg * msg_new)95 static inline void insert_uplink(struct service_uplink_msg *msg_new)
96 {
97 	struct service_uplink_msg *msg_prev;
98 
99 	if (sys_slist_is_empty(&msg_list)) {
100 		sys_slist_append(&msg_list, &msg_new->node);
101 	} else {
102 		int count = 0;
103 
104 		SYS_SLIST_FOR_EACH_CONTAINER(&msg_list, msg_prev, node) {
105 			count++;
106 			if (msg_prev->ticks <= msg_new->ticks) {
107 				break;
108 			}
109 		}
110 		if (msg_prev != NULL) {
111 			sys_slist_insert(&msg_list, &msg_prev->node, &msg_new->node);
112 		} else {
113 			sys_slist_append(&msg_list, &msg_new->node);
114 		}
115 	}
116 }
117 
lorawan_services_schedule_uplink(uint8_t port,uint8_t * data,uint8_t len,uint32_t timeout)118 int lorawan_services_schedule_uplink(uint8_t port, uint8_t *data, uint8_t len, uint32_t timeout)
119 {
120 	struct service_uplink_msg *next;
121 	int64_t timeout_abs_ticks;
122 
123 	if (len > sizeof(messages[0].data)) {
124 		LOG_ERR("Uplink payload for port %u too long: %u bytes", port, len);
125 		LOG_HEXDUMP_ERR(data, len, "Payload: ");
126 		return -EFBIG;
127 	}
128 
129 	timeout_abs_ticks = k_uptime_ticks() + k_ms_to_ticks_ceil64(timeout);
130 
131 	k_sem_take(&msg_sem, K_FOREVER);
132 
133 	for (int i = 0; i < ARRAY_SIZE(messages); i++) {
134 		if (!messages[i].used) {
135 			memcpy(messages[i].data, data, len);
136 			messages[i].port = port;
137 			messages[i].len = len;
138 			messages[i].ticks = timeout_abs_ticks;
139 			messages[i].used = true;
140 
141 			insert_uplink(&messages[i]);
142 
143 			next = SYS_SLIST_PEEK_HEAD_CONTAINER(&msg_list, next, node);
144 			if (next != NULL) {
145 				k_work_reschedule_for_queue(&services_workq, &uplink_work,
146 					K_TIMEOUT_ABS_TICKS(next->ticks));
147 			}
148 
149 			k_sem_give(&msg_sem);
150 
151 			return 0;
152 		}
153 	}
154 
155 	k_sem_give(&msg_sem);
156 
157 	LOG_WRN("Message queue full, message for port %u dropped.", port);
158 
159 	return -ENOSPC;
160 }
161 
lorawan_services_reschedule_work(struct k_work_delayable * dwork,k_timeout_t delay)162 int lorawan_services_reschedule_work(struct k_work_delayable *dwork, k_timeout_t delay)
163 {
164 	return k_work_reschedule_for_queue(&services_workq, dwork, delay);
165 }
166 
lorawan_services_class_c_start(void)167 int lorawan_services_class_c_start(void)
168 {
169 	int ret;
170 
171 	k_mutex_lock(&session_mutex, K_FOREVER);
172 
173 	if (active_class_c_sessions == 0) {
174 		ret = lorawan_set_class(LORAWAN_CLASS_C);
175 		if (ret == 0) {
176 			LOG_DBG("Switched to class C");
177 			active_class_c_sessions++;
178 			ret = active_class_c_sessions;
179 		}
180 	} else {
181 		active_class_c_sessions++;
182 		ret = active_class_c_sessions;
183 	}
184 
185 	k_mutex_unlock(&session_mutex);
186 
187 	return ret;
188 }
189 
lorawan_services_class_c_stop(void)190 int lorawan_services_class_c_stop(void)
191 {
192 	int ret = 0;
193 
194 	k_mutex_lock(&session_mutex, K_FOREVER);
195 
196 	if (active_class_c_sessions == 1) {
197 		ret = lorawan_set_class(LORAWAN_CLASS_A);
198 		if (ret == 0) {
199 			LOG_DBG("Reverted to class A");
200 			active_class_c_sessions--;
201 		}
202 	} else if (active_class_c_sessions > 1) {
203 		active_class_c_sessions--;
204 		ret = active_class_c_sessions;
205 	}
206 
207 	k_mutex_unlock(&session_mutex);
208 
209 	return ret;
210 }
211 
lorawan_services_class_c_active(void)212 int lorawan_services_class_c_active(void)
213 {
214 	return active_class_c_sessions;
215 }
216 
lorawan_services_init(void)217 static int lorawan_services_init(void)
218 {
219 
220 	sys_slist_init(&msg_list);
221 	k_sem_init(&msg_sem, 1, 1);
222 
223 	k_work_queue_init(&services_workq);
224 	k_work_queue_start(&services_workq,
225 			   thread_stack_area, K_THREAD_STACK_SIZEOF(thread_stack_area),
226 			   CONFIG_LORAWAN_SERVICES_THREAD_PRIORITY, NULL);
227 
228 	k_work_init_delayable(&uplink_work, uplink_handler);
229 
230 	k_mutex_init(&session_mutex);
231 
232 	k_thread_name_set(&services_workq.thread, "lorawan_services");
233 
234 	return 0;
235 }
236 
237 SYS_INIT(lorawan_services_init, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
238