1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
use crate::{
    error::Error, ffi::get_last_error, ip::NrfSockAddr, lte_link::LteLink, CancellationToken,
};
use core::{
    cell::RefCell,
    ops::{BitOr, BitOrAssign, Deref, Neg},
    sync::atomic::{AtomicU8, Ordering},
    task::{Poll, Waker},
};
use critical_section::Mutex;
use no_std_net::SocketAddr;
use num_enum::{IntoPrimitive, TryFromPrimitive};

// use 16 slots for wakers instead of 8, which is the max number of sockets allowed, so they
// are not overwritten when split into their rx/tx counterparts and run in separate tasks.
const WAKER_SLOTS: usize = (nrfxlib_sys::NRF_MODEM_MAX_SOCKET_COUNT * 2) as usize;
const WAKER_INIT: Option<(Waker, i32, SocketDirection)> = None;
#[allow(clippy::type_complexity)]
static SOCKET_WAKERS: Mutex<RefCell<[Option<(Waker, i32, SocketDirection)>; WAKER_SLOTS]>> =
    Mutex::new(RefCell::new([WAKER_INIT; WAKER_SLOTS]));

fn wake_sockets(socket_fd: i32, socket_dir: SocketDirection) {
    critical_section::with(|cs| {
        SOCKET_WAKERS
            .borrow_ref_mut(cs)
            .iter_mut()
            .filter(|slot| {
                if let Some((_, fd, dir)) = slot {
                    *fd == socket_fd && dir.same_direction(socket_dir)
                } else {
                    false
                }
            })
            .for_each(|slot| {
                let (waker, _, _) = slot.take().unwrap();
                waker.wake();
            });
    });
}

fn register_socket_waker(waker: Waker, socket_fd: i32, socket_dir: SocketDirection) {
    critical_section::with(|cs| {
        // Get the wakers
        let mut wakers = SOCKET_WAKERS.borrow_ref_mut(cs);

        // Search for an empty spot or a spot that already stores the waker for the socket
        let empty_waker = wakers.iter_mut().find(|waker| {
            waker.is_none()
                || waker.as_ref().map(|(_, fd, dir)| (*fd, *dir)) == Some((socket_fd, socket_dir))
        });

        if let Some(empty_waker) = empty_waker {
            // In principle we should always have an empty spot and run this code
            *empty_waker = Some((waker, socket_fd, socket_dir));
        } else {
            // It shouldn't ever happen, but if there's no empty spot, we just evict the first socket
            // That socket will just reregister itself
            wakers
                .first_mut()
                .unwrap()
                .replace((waker, socket_fd, socket_dir))
                .unwrap()
                .0
                .wake();
        }
    });
}

unsafe extern "C" fn socket_poll_callback(pollfd: *mut nrfxlib_sys::nrf_pollfd) {
    let pollfd = *pollfd;

    let mut direction = SocketDirection::Neither;

    if pollfd.revents as u32 & nrfxlib_sys::NRF_POLLIN != 0 {
        direction |= SocketDirection::In;
    }

    if pollfd.revents as u32 & nrfxlib_sys::NRF_POLLOUT != 0 {
        direction |= SocketDirection::Out;
    }

    if pollfd.revents as u32
        & (nrfxlib_sys::NRF_POLLERR | nrfxlib_sys::NRF_POLLHUP | nrfxlib_sys::NRF_POLLNVAL)
        != 0
    {
        direction |= SocketDirection::Either;
    }

    #[cfg(feature = "defmt")]
    defmt::trace!(
        "Socket poll callback. fd: {}, revents: {:X}, direction: {}",
        pollfd.fd,
        pollfd.revents,
        direction
    );

    wake_sockets(pollfd.fd, direction);
}

/// Used as a identifier for wakers when a socket is split into RX/TX halves
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
enum SocketDirection {
    /// Neither option
    Neither,
    /// RX
    In,
    /// TX
    Out,
    /// RX and/or TX
    Either,
}

impl BitOrAssign for SocketDirection {
    fn bitor_assign(&mut self, rhs: Self) {
        *self = *self | rhs;
    }
}

impl BitOr for SocketDirection {
    type Output = SocketDirection;

    fn bitor(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (SocketDirection::Neither, rhs) => rhs,
            (lhs, SocketDirection::Neither) => lhs,
            (SocketDirection::In, SocketDirection::In) => SocketDirection::In,
            (SocketDirection::Out, SocketDirection::Out) => SocketDirection::Out,
            (SocketDirection::In, SocketDirection::Out) => SocketDirection::Either,
            (SocketDirection::Out, SocketDirection::In) => SocketDirection::Either,
            (SocketDirection::Either, _) => SocketDirection::Either,
            (_, SocketDirection::Either) => SocketDirection::Either,
        }
    }
}

impl SocketDirection {
    fn same_direction(&self, other: Self) -> bool {
        match (self, other) {
            (SocketDirection::Neither, _) => false,
            (_, SocketDirection::Neither) => false,
            (SocketDirection::In, SocketDirection::In) => true,
            (SocketDirection::Out, SocketDirection::Out) => true,
            (SocketDirection::In, SocketDirection::Out) => false,
            (SocketDirection::Out, SocketDirection::In) => false,
            (_, SocketDirection::Either) => true,
            (SocketDirection::Either, _) => true,
        }
    }
}

/// Internal socket implementation
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Socket {
    /// The file descriptor given by the modem lib
    fd: i32,
    /// The socket family (required to know when we need to decipher an incoming IP address)
    family: SocketFamily,
    /// The link this socket holds to keep the LTE alive.
    /// This is an option because when deactivating we need to take ownership of it.
    link: Option<LteLink>,
    /// Gets set to true when the socket has been split. This is relevant for the drop functions
    split: bool,
}

impl Socket {
    /// Create a new socket with the given parameters
    pub async fn create(
        family: SocketFamily,
        s_type: SocketType,
        protocol: SocketProtocol,
    ) -> Result<Self, Error> {
        #[cfg(feature = "defmt")]
        defmt::debug!(
            "Creating socket with family: {}, type: {}, protocol: {}",
            family as u32 as i32,
            s_type as u32 as i32,
            protocol as u32 as i32
        );

        if unsafe { !nrfxlib_sys::nrf_modem_is_initialized() } {
            return Err(Error::ModemNotInitialized);
        }

        // Let's activate the modem
        let link = LteLink::new().await?;

        // Create the socket in the nrf-modem lib
        let fd = unsafe {
            nrfxlib_sys::nrf_socket(
                family as u32 as i32,
                s_type as u32 as i32,
                protocol as u32 as i32,
            )
        };

        // If the fd is -1, then there is an error in `errno`
        if fd == -1 {
            return Err(Error::NrfError(get_last_error()));
        }

        // Set the socket to non-blocking
        unsafe {
            let result = nrfxlib_sys::nrf_fcntl(
                fd,
                nrfxlib_sys::NRF_F_SETFL as _,
                nrfxlib_sys::NRF_O_NONBLOCK as _,
            );

            if result == -1 {
                return Err(Error::NrfError(get_last_error()));
            }
        }

        // Register the callback of the socket. This will be used to wake up the socket waker
        let poll_callback = nrfxlib_sys::nrf_modem_pollcb {
            callback: Some(socket_poll_callback),
            events: (nrfxlib_sys::NRF_POLLIN | nrfxlib_sys::NRF_POLLOUT) as _, // All events
            oneshot: false,
        };

        unsafe {
            let result = nrfxlib_sys::nrf_setsockopt(
                fd,
                nrfxlib_sys::NRF_SOL_SOCKET as _,
                nrfxlib_sys::NRF_SO_POLLCB as _,
                (&poll_callback as *const nrfxlib_sys::nrf_modem_pollcb).cast(),
                core::mem::size_of::<nrfxlib_sys::nrf_modem_pollcb>() as u32,
            );

            if result == -1 {
                return Err(Error::NrfError(get_last_error()));
            }
        }

        Ok(Socket {
            fd,
            family,
            link: Some(link),
            split: false,
        })
    }

    /// Get the nrf-modem file descriptor so the user can opt out of using this high level wrapper for things
    pub fn as_raw_fd(&self) -> i32 {
        self.fd
    }

    pub async fn split(mut self) -> Result<(SplitSocketHandle, SplitSocketHandle), Error> {
        let index = SplitSocketHandle::get_new_spot();
        self.split = true;

        Ok((
            SplitSocketHandle {
                inner: Some(Socket {
                    fd: self.fd,
                    family: self.family,
                    link: Some(LteLink::new().await?),
                    split: true,
                }),
                index,
            },
            SplitSocketHandle {
                inner: Some(self),
                index,
            },
        ))
    }

    /// Connect to the given socket address.
    ///
    /// This calls the `nrf_connect` function and can be used for tcp streams, udp connections and dtls connections.
    ///
    /// ## Safety
    ///
    /// If the connect is cancelled, the socket may be in a weird state and should be dropped.
    pub async unsafe fn connect(
        &self,
        address: SocketAddr,
        token: &CancellationToken,
    ) -> Result<(), Error> {
        #[cfg(feature = "defmt")]
        defmt::debug!(
            "Connecting socket {} to {:?}",
            self.fd,
            defmt::Debug2Format(&address)
        );

        token.bind_to_current_task().await;

        // Before we can connect, we need to make sure we have a working link.
        // It is possible this will never resolve, but it is up to the user to manage the timeouts.
        self.link
            .as_ref()
            .unwrap()
            .wait_for_link_with_cancellation(token)
            .await?;

        core::future::poll_fn(|cx| {
            #[cfg(feature = "defmt")]
            defmt::trace!("Connecting socket {}", self.fd);

            if token.is_cancelled() {
                return Poll::Ready(Err(Error::OperationCancelled));
            }

            // Cast the address to something the nrf-modem understands
            let address = NrfSockAddr::from(address);

            register_socket_waker(cx.waker().clone(), self.fd, SocketDirection::Either);

            // Do the connect call, this is non-blocking due to the socket setup
            let mut connect_result = unsafe {
                nrfxlib_sys::nrf_connect(self.fd, address.as_ptr(), address.size() as u32)
            } as isize;

            const NRF_EINPROGRESS: isize = nrfxlib_sys::NRF_EINPROGRESS as isize;
            const NRF_EALREADY: isize = nrfxlib_sys::NRF_EALREADY as isize;
            const NRF_EISCONN: isize = nrfxlib_sys::NRF_EISCONN as isize;

            if connect_result == -1 {
                connect_result = get_last_error();
            }

            #[cfg(feature = "defmt")]
            defmt::trace!("Connect result {}", connect_result);

            match connect_result {
                // 0 when we have succesfully connected
                0 => Poll::Ready(Ok(())),
                // The socket was already connected
                NRF_EISCONN => Poll::Ready(Ok(())),
                // The socket is not yet connected
                NRF_EINPROGRESS | NRF_EALREADY => Poll::Pending,
                // Something else, this is likely an error
                error => Poll::Ready(Err(Error::NrfError(error))),
            }
        })
        .await?;

        Ok(())
    }

    /// Bind the socket to a given address.
    ///
    /// This calls the `nrf_bind` function and can be used for udp sockets
    ///
    /// ## Safety
    ///
    /// If the bind is cancelled, the socket may be in a weird state and should be dropped.
    pub async unsafe fn bind(
        &self,
        address: SocketAddr,
        token: &CancellationToken,
    ) -> Result<(), Error> {
        #[cfg(feature = "defmt")]
        defmt::debug!(
            "Binding socket {} to {:?}",
            self.fd,
            defmt::Debug2Format(&address)
        );

        token.bind_to_current_task().await;

        // Before we can connect, we need to make sure we have a working link.
        // It is possible this will never resolve, but it is up to the user to manage the timeouts.
        self.link
            .as_ref()
            .unwrap()
            .wait_for_link_with_cancellation(token)
            .await?;

        core::future::poll_fn(|cx| {
            #[cfg(feature = "defmt")]
            defmt::trace!("Binding socket {}", self.fd);

            if token.is_cancelled() {
                return Poll::Ready(Err(Error::OperationCancelled));
            }

            // Cast the address to something the nrf-modem understands
            let address = NrfSockAddr::from(address);

            register_socket_waker(cx.waker().clone(), self.fd, SocketDirection::Either);

            // Do the bind call, this is non-blocking due to the socket setup
            let mut bind_result =
                unsafe { nrfxlib_sys::nrf_bind(self.fd, address.as_ptr(), address.size() as u32) }
                    as isize;

            const NRF_EINPROGRESS: isize = nrfxlib_sys::NRF_EINPROGRESS as isize;
            const NRF_EALREADY: isize = nrfxlib_sys::NRF_EALREADY as isize;
            const NRF_EISCONN: isize = nrfxlib_sys::NRF_EISCONN as isize;

            if bind_result == -1 {
                bind_result = get_last_error();
            }

            #[cfg(feature = "defmt")]
            defmt::trace!("Bind result {}", bind_result);

            match bind_result {
                // 0 when we have succesfully connected
                0 => Poll::Ready(Ok(())),
                // The socket was already connected
                NRF_EISCONN => Poll::Ready(Ok(())),
                // The socket is not yet connected
                NRF_EINPROGRESS | NRF_EALREADY => Poll::Pending,
                // Something else, this is likely an error
                error => Poll::Ready(Err(Error::NrfError(error))),
            }
        })
        .await?;

        Ok(())
    }

    /// Call the [nrfxlib_sys::nrf_send] in an async fashion
    pub async fn write(&self, buffer: &[u8], token: &CancellationToken) -> Result<usize, Error> {
        token.bind_to_current_task().await;

        core::future::poll_fn(|cx| {
            #[cfg(feature = "defmt")]
            defmt::trace!("Sending with socket {}", self.fd);

            if token.is_cancelled() {
                return Poll::Ready(Err(Error::OperationCancelled));
            }

            register_socket_waker(cx.waker().clone(), self.fd, SocketDirection::Out);

            let mut send_result = unsafe {
                nrfxlib_sys::nrf_send(self.fd, buffer.as_ptr() as *const _, buffer.len(), 0)
            };

            if send_result == -1 {
                send_result = get_last_error().abs().neg();
            }

            #[cfg(feature = "defmt")]
            defmt::trace!("Send result {}", send_result);

            const NRF_EWOULDBLOCK: isize = -(nrfxlib_sys::NRF_EWOULDBLOCK as isize);
            const NRF_ENOTCONN: isize = -(nrfxlib_sys::NRF_ENOTCONN as isize);

            match send_result {
                0 if !buffer.is_empty() => Poll::Ready(Err(Error::Disconnected)),
                NRF_ENOTCONN => Poll::Ready(Err(Error::Disconnected)),
                bytes_sent @ 0.. => Poll::Ready(Ok(bytes_sent as usize)),
                NRF_EWOULDBLOCK => Poll::Pending,
                error => Poll::Ready(Err(Error::NrfError(error))),
            }
        })
        .await
    }

    /// Call the [nrfxlib_sys::nrf_recv] in an async fashion
    pub async fn receive(
        &self,
        buffer: &mut [u8],
        token: &CancellationToken,
    ) -> Result<usize, Error> {
        token.bind_to_current_task().await;

        core::future::poll_fn(|cx| {
            #[cfg(feature = "defmt")]
            defmt::trace!("Receiving with socket {}", self.fd);

            if token.is_cancelled() {
                return Poll::Ready(Err(Error::OperationCancelled));
            }

            register_socket_waker(cx.waker().clone(), self.fd, SocketDirection::In);

            let mut receive_result = unsafe {
                nrfxlib_sys::nrf_recv(self.fd, buffer.as_mut_ptr() as *mut _, buffer.len(), 0)
            };

            if receive_result == -1 {
                receive_result = get_last_error().abs().neg();
            }

            #[cfg(feature = "defmt")]
            defmt::trace!("Receive result {}", receive_result);

            const NRF_EWOULDBLOCK: isize = -(nrfxlib_sys::NRF_EWOULDBLOCK as isize);
            const NRF_ENOTCONN: isize = -(nrfxlib_sys::NRF_ENOTCONN as isize);

            match receive_result {
                0 if !buffer.is_empty() => Poll::Ready(Err(Error::Disconnected)),
                NRF_ENOTCONN => Poll::Ready(Err(Error::Disconnected)),
                bytes_received @ 0.. => Poll::Ready(Ok(bytes_received as usize)),
                NRF_EWOULDBLOCK => Poll::Pending,
                error => Poll::Ready(Err(Error::NrfError(error))),
            }
        })
        .await
    }

    /// Call the [nrfxlib_sys::nrf_recvfrom] in an async fashion
    pub async fn receive_from(
        &self,
        buffer: &mut [u8],
        token: &CancellationToken,
    ) -> Result<(usize, SocketAddr), Error> {
        token.bind_to_current_task().await;

        core::future::poll_fn(|cx| {
            #[cfg(feature = "defmt")]
            defmt::trace!("Receiving with socket {}", self.fd);

            if token.is_cancelled() {
                return Poll::Ready(Err(Error::OperationCancelled));
            }

            // Big enough to store both ipv4 and ipv6
            let mut socket_addr_store =
                [0u8; core::mem::size_of::<nrfxlib_sys::nrf_sockaddr_in6>()];
            let socket_addr_ptr = socket_addr_store.as_mut_ptr() as *mut nrfxlib_sys::nrf_sockaddr;
            let mut socket_addr_len = 0u32;

            register_socket_waker(cx.waker().clone(), self.fd, SocketDirection::In);

            let mut receive_result = unsafe {
                nrfxlib_sys::nrf_recvfrom(
                    self.fd,
                    buffer.as_mut_ptr() as *mut _,
                    buffer.len(),
                    0,
                    socket_addr_ptr,
                    &mut socket_addr_len as *mut u32,
                )
            };

            if receive_result == -1 {
                receive_result = get_last_error().abs().neg();
            }

            #[cfg(feature = "defmt")]
            defmt::trace!("Receive result {}", receive_result);

            const NRF_EWOULDBLOCK: isize = -(nrfxlib_sys::NRF_EWOULDBLOCK as isize);
            const NRF_ENOTCONN: isize = -(nrfxlib_sys::NRF_ENOTCONN as isize);

            match receive_result {
                0 if !buffer.is_empty() => Poll::Ready(Err(Error::Disconnected)),
                NRF_ENOTCONN => Poll::Ready(Err(Error::Disconnected)),
                bytes_received @ 0.. => Poll::Ready(Ok((bytes_received as usize, {
                    unsafe { (*socket_addr_ptr).sa_family = self.family as u32 as i32 }
                    NrfSockAddr::from(socket_addr_ptr as *const _).into()
                }))),
                NRF_EWOULDBLOCK => Poll::Pending,
                error => Poll::Ready(Err(Error::NrfError(error))),
            }
        })
        .await
    }

    /// Call the [nrfxlib_sys::nrf_sendto] in an async fashion
    pub async fn send_to(
        &self,
        buffer: &[u8],
        address: SocketAddr,
        token: &CancellationToken,
    ) -> Result<usize, Error> {
        token.bind_to_current_task().await;

        core::future::poll_fn(|cx| {
            #[cfg(feature = "defmt")]
            defmt::trace!("Sending with socket {}", self.fd);

            if token.is_cancelled() {
                return Poll::Ready(Err(Error::OperationCancelled));
            }

            let addr = NrfSockAddr::from(address);

            register_socket_waker(cx.waker().clone(), self.fd, SocketDirection::Out);

            let mut send_result = unsafe {
                nrfxlib_sys::nrf_sendto(
                    self.fd,
                    buffer.as_ptr() as *mut _,
                    buffer.len(),
                    0,
                    addr.as_ptr(),
                    addr.size() as u32,
                )
            };

            if send_result == -1 {
                send_result = get_last_error().abs().neg();
            }

            #[cfg(feature = "defmt")]
            defmt::trace!("Sending result {}", send_result);

            const NRF_EWOULDBLOCK: isize = -(nrfxlib_sys::NRF_EWOULDBLOCK as isize);
            const NRF_ENOTCONN: isize = -(nrfxlib_sys::NRF_ENOTCONN as isize);

            match send_result {
                0 if !buffer.is_empty() => Poll::Ready(Err(Error::Disconnected)),
                NRF_ENOTCONN => Poll::Ready(Err(Error::Disconnected)),
                bytes_received @ 0.. => Poll::Ready(Ok(bytes_received as usize)),
                NRF_EWOULDBLOCK => Poll::Pending,
                error => Poll::Ready(Err(Error::NrfError(error))),
            }
        })
        .await
    }

    pub fn set_option<'a>(&'a self, option: SocketOption<'a>) -> Result<(), SocketOptionError> {
        let length = option.get_length();

        let result = unsafe {
            nrfxlib_sys::nrf_setsockopt(
                self.fd,
                nrfxlib_sys::NRF_SOL_SECURE.try_into().unwrap(),
                option.get_name(),
                option.get_value(),
                length,
            )
        };

        if result < 0 {
            Err(result.into())
        } else {
            Ok(())
        }
    }

    /// Deactivates the socket and the LTE link.
    /// A normal drop will do the same thing, but blocking.
    pub async fn deactivate(mut self) -> Result<(), Error> {
        self.link.take().unwrap().deactivate().await?;
        Ok(())
    }
}

impl Drop for Socket {
    fn drop(&mut self) {
        if !self.split {
            let e = unsafe { nrfxlib_sys::nrf_close(self.fd) };

            if e == -1 {
                panic!("{:?}", Error::NrfError(get_last_error()));
            }
        }
    }
}

impl PartialEq for Socket {
    fn eq(&self, other: &Self) -> bool {
        self.fd == other.fd
    }
}
impl Eq for Socket {}

#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SocketFamily {
    Unspecified = nrfxlib_sys::NRF_AF_UNSPEC,
    Ipv4 = nrfxlib_sys::NRF_AF_INET,
    Ipv6 = nrfxlib_sys::NRF_AF_INET6,
    Raw = nrfxlib_sys::NRF_AF_PACKET,
}

#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SocketType {
    Stream = nrfxlib_sys::NRF_SOCK_STREAM,
    Datagram = nrfxlib_sys::NRF_SOCK_DGRAM,
    Raw = nrfxlib_sys::NRF_SOCK_RAW,
}

#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SocketProtocol {
    IP = nrfxlib_sys::NRF_IPPROTO_IP,
    Tcp = nrfxlib_sys::NRF_IPPROTO_TCP,
    Udp = nrfxlib_sys::NRF_IPPROTO_UDP,
    Ipv6 = nrfxlib_sys::NRF_IPPROTO_IPV6,
    Raw = nrfxlib_sys::NRF_IPPROTO_RAW,
    All = nrfxlib_sys::NRF_IPPROTO_ALL,
    Tls1v2 = nrfxlib_sys::NRF_SPROTO_TLS1v2,
    DTls1v2 = nrfxlib_sys::NRF_SPROTO_DTLS1v2,
}

#[allow(clippy::enum_variant_names)]
#[derive(Debug)]
pub enum SocketOption<'a> {
    TlsHostName(&'a str),
    TlsPeerVerify(nrfxlib_sys::nrf_sec_peer_verify_t),
    TlsSessionCache(nrfxlib_sys::nrf_sec_session_cache_t),
    TlsTagList(&'a [nrfxlib_sys::nrf_sec_tag_t]),
}
impl<'a> SocketOption<'a> {
    pub(crate) fn get_name(&self) -> i32 {
        match self {
            SocketOption::TlsHostName(_) => nrfxlib_sys::NRF_SO_SEC_HOSTNAME as i32,
            SocketOption::TlsPeerVerify(_) => nrfxlib_sys::NRF_SO_SEC_PEER_VERIFY as i32,
            SocketOption::TlsSessionCache(_) => nrfxlib_sys::NRF_SO_SEC_SESSION_CACHE as i32,
            SocketOption::TlsTagList(_) => nrfxlib_sys::NRF_SO_SEC_TAG_LIST as i32,
        }
    }

    pub(crate) fn get_value(&self) -> *const core::ffi::c_void {
        match self {
            SocketOption::TlsHostName(s) => s.as_ptr() as *const core::ffi::c_void,
            SocketOption::TlsPeerVerify(x) => x as *const _ as *const core::ffi::c_void,
            SocketOption::TlsSessionCache(x) => x as *const _ as *const core::ffi::c_void,
            SocketOption::TlsTagList(x) => x.as_ptr() as *const core::ffi::c_void,
        }
    }

    pub(crate) fn get_length(&self) -> u32 {
        match self {
            SocketOption::TlsHostName(s) => s.len() as u32,
            SocketOption::TlsPeerVerify(x) => core::mem::size_of_val(x) as u32,
            SocketOption::TlsSessionCache(x) => core::mem::size_of_val(x) as u32,
            SocketOption::TlsTagList(x) => core::mem::size_of_val(*x) as u32,
        }
    }
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SocketOptionError {
    // The socket argument is not a valid file descriptor.
    InvalidFileDescriptor,
    // The send and receive timeout values are too big to fit into the timeout fields in the socket structure.
    TimeoutTooBig,
    // The specified option is invalid at the specified socket level or the socket has been shut down.
    InvalidOption,
    // The socket is already connected, and a specified option cannot be set while the socket is connected.
    AlreadyConnected,
    // The option is not supported by the protocol.
    UnsupportedOption,
    // The socket argument does not refer to a socket.
    NotASocket,
    // There was insufficient memory available for the operation to complete.
    OutOfMemory,
    // Insufficient resources are available in the system to complete the call.
    OutOfResources,
}

impl From<i32> for SocketOptionError {
    fn from(errno: i32) -> Self {
        match errno.unsigned_abs() {
            nrfxlib_sys::NRF_EBADF => SocketOptionError::InvalidFileDescriptor,
            nrfxlib_sys::NRF_EINVAL => SocketOptionError::InvalidOption,
            nrfxlib_sys::NRF_EISCONN => SocketOptionError::AlreadyConnected,
            nrfxlib_sys::NRF_ENOPROTOOPT => SocketOptionError::UnsupportedOption,
            nrfxlib_sys::NRF_ENOTSOCK => SocketOptionError::NotASocket,
            nrfxlib_sys::NRF_ENOMEM => SocketOptionError::OutOfMemory,
            nrfxlib_sys::NRF_ENOBUFS => SocketOptionError::OutOfResources,
            _ => panic!("Unknown error code: {}", errno),
        }
    }
}

#[allow(clippy::declare_interior_mutable_const)]
const ATOMIC_U8_INIT: AtomicU8 = AtomicU8::new(0);
static ACTIVE_SPLIT_SOCKETS: [AtomicU8; nrfxlib_sys::NRF_MODEM_MAX_SOCKET_COUNT as usize] =
    [ATOMIC_U8_INIT; nrfxlib_sys::NRF_MODEM_MAX_SOCKET_COUNT as usize];

pub struct SplitSocketHandle {
    inner: Option<Socket>,
    index: usize,
}

impl SplitSocketHandle {
    pub async fn deactivate(mut self) -> Result<(), Error> {
        let mut inner = self.inner.take().unwrap();

        if ACTIVE_SPLIT_SOCKETS[self.index].fetch_sub(1, Ordering::SeqCst) == 1 {
            // We were the last handle to drop so the inner socket isn't split anymore
            inner.split = false;
        }

        inner.deactivate().await?;

        Ok(())
    }

    fn get_new_spot() -> usize {
        for (index, count) in ACTIVE_SPLIT_SOCKETS.iter().enumerate() {
            if count
                .compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst)
                .is_ok()
            {
                return index;
            }
        }

        unreachable!("It should not be possible to have more splits than the maximum socket count");
    }
}

impl Deref for SplitSocketHandle {
    type Target = Socket;

    fn deref(&self) -> &Self::Target {
        self.inner.as_ref().unwrap()
    }
}

impl Drop for SplitSocketHandle {
    fn drop(&mut self) {
        if let Some(inner) = self.inner.as_mut() {
            if ACTIVE_SPLIT_SOCKETS[self.index].fetch_sub(1, Ordering::SeqCst) == 1 {
                // We were the last handle to drop so the inner socket isn't split anymore
                inner.split = false;
            }
        }
    }
}