1 /*
2  * Copyright (c) 2024 Trackunit Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/modem/pipelink.h>
8 
try_callback(struct modem_pipelink * link,enum modem_pipelink_event event)9 static void try_callback(struct modem_pipelink *link, enum modem_pipelink_event event)
10 {
11 	if (link->callback == NULL) {
12 		return;
13 	}
14 
15 	link->callback(link, event, link->user_data);
16 }
17 
modem_pipelink_attach(struct modem_pipelink * link,modem_pipelink_callback callback,void * user_data)18 void modem_pipelink_attach(struct modem_pipelink *link,
19 			   modem_pipelink_callback callback,
20 			   void *user_data)
21 {
22 	K_SPINLOCK(&link->spinlock) {
23 		link->callback = callback;
24 		link->user_data = user_data;
25 	}
26 }
27 
modem_pipelink_is_connected(struct modem_pipelink * link)28 bool modem_pipelink_is_connected(struct modem_pipelink *link)
29 {
30 	bool connected;
31 
32 	K_SPINLOCK(&link->spinlock) {
33 		connected = link->connected;
34 	}
35 
36 	return connected;
37 }
38 
modem_pipelink_get_pipe(struct modem_pipelink * link)39 struct modem_pipe *modem_pipelink_get_pipe(struct modem_pipelink *link)
40 {
41 	return link->pipe;
42 }
43 
modem_pipelink_release(struct modem_pipelink * link)44 void modem_pipelink_release(struct modem_pipelink *link)
45 {
46 	K_SPINLOCK(&link->spinlock) {
47 		link->callback = NULL;
48 		link->user_data = NULL;
49 	}
50 }
51 
modem_pipelink_init(struct modem_pipelink * link,struct modem_pipe * pipe)52 void modem_pipelink_init(struct modem_pipelink *link, struct modem_pipe *pipe)
53 {
54 	link->pipe = pipe;
55 	link->callback = NULL;
56 	link->user_data = NULL;
57 	link->connected = false;
58 }
59 
modem_pipelink_notify_connected(struct modem_pipelink * link)60 void modem_pipelink_notify_connected(struct modem_pipelink *link)
61 {
62 	K_SPINLOCK(&link->spinlock) {
63 		if (link->connected) {
64 			K_SPINLOCK_BREAK;
65 		}
66 
67 		link->connected = true;
68 		try_callback(link, MODEM_PIPELINK_EVENT_CONNECTED);
69 	}
70 }
71 
modem_pipelink_notify_disconnected(struct modem_pipelink * link)72 void modem_pipelink_notify_disconnected(struct modem_pipelink *link)
73 {
74 	K_SPINLOCK(&link->spinlock) {
75 		if (!link->connected) {
76 			K_SPINLOCK_BREAK;
77 		}
78 
79 		link->connected = false;
80 		try_callback(link, MODEM_PIPELINK_EVENT_DISCONNECTED);
81 	}
82 }
83