coap-zero 0.3.0

CoAP protocol implementation for no_std without alloc
Documentation
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
// Copyright Open Logistics Foundation
//
// Licensed under the Open Logistics Foundation License 1.3.
// For details on the licensing terms, see the LICENSE file.
// SPDX-License-Identifier: OLFL-1.3

//! The incoming communication path

use core::marker::PhantomData;

use embedded_nal::UdpClientStack;
use embedded_timers::clock::Clock;
use heapless::Vec;

use crate::message::{
    codes::ResponseCode, encoded_message::EncodedMessage, options::CoapOption, Message, Type,
};

use super::{
    error::Error, Connection, MessageBuffer, MessageIdentification, RetransmissionState,
    RetransmissionTimeout, TransmissionParameters,
};

/// The state in which the incoming communication path is currently
#[derive(Debug, Clone, Copy)]
pub enum IncomingState {
    /// New requests can be handled
    //
    // In this state, it depends on the contained [`LastResponse`] what the internal message
    // buffer contains. Since it should not be required, access to it is forbidden.
    Idle(LastResponse),
    /// A request was received and needs to be handled by the user. The contained `bool` determines
    /// if the request was confirmable (`true`) or non-confirmable (`false`).
    ///
    /// In any case, the response may be sent with [`IncomingCommunication::schedule_response`]
    /// immediately. For CON requests, this will result in a piggybacked response. For NON
    /// requests, a NON response will be sent which is considered the default case for NON requests
    /// (see RFC 7252 5.2.3 Non-confirmable: "If the request message is Non-confirmable, then the
    /// response SHOULD be returned in a Non-confirmable message as well.")
    ///
    /// Furthermore, [`IncomingCommunication::schedule_rst`] may be called in both cases which will
    /// transmit a RST message.
    ///
    /// If a different behavior is desired, the following different options exist:
    /// - In `Received(true)`, [`IncomingCommunication::schedule_empty_ack`] allows to send an
    /// empty ACK which will trigger a state transition via [`IncomingState::SendingAck`]
    /// into [`IncomingState::AwaitingResponse`] where separate responses may be sent.
    /// Additionally, [`IncomingCommunication::schedule_piggybacked_response`] may be called which
    /// is identical to [`IncomingCommunication::schedule_response`] in this case.
    /// - In `Received(false)`, [`IncomingCommunication::schedule_con_response`] and
    /// [`IncomingCommunication::schedule_non_response`] are available, the second being
    /// identical to [`IncomingCommunication::schedule_response`] in this case.
    ///
    /// In this state, the message buffer contains the request message. Thus, the request
    /// message may be obtained by calling [`IncomingCommunication::request`].
    Received(bool),
    /// An ACK is being sent. Afterwards, we will go into the [`IncomingState::AwaitingResponse`]
    /// state.
    //
    // In this state, the message buffer still contains the request message and may be obtained
    // with [`IncomingCommunication::request`].
    SendingAck,
    /// A RST message is being sent. Afterwards, we will go back to the `Idle` state.
    SendingRst,
    /// A piggybacked response is being sent. Afterwards, we will go into the `Idle` state.
    //
    // In this state, the message buffer contains the piggybacked response message.
    SendingPiggybacked,
    /// The request has been acknowledged, i.e. a separate response is expected. In this state,
    /// [`IncomingCommunication::schedule_con_response`] and
    /// [`IncomingCommunication::schedule_non_response`] are available and either of those
    /// _must_ be called by the user.
    ///
    /// In this state, the message buffer still contains the request message and may be obtained
    /// with [`IncomingCommunication::request`].
    AwaitingResponse,
    /// A separate CON response is being sent. We will stay in this state and try retransmissions
    /// until an ACK to this message is received or until the whole communication attempt (with
    /// retries) times out.
    //
    // In this state, the message buffer contains the separate CON response message.
    SendingCon(RetransmissionState),
    /// A separate NON response is being sent.
    //
    // In this state, the message buffer contains the separate NON response message.
    SendingNon,
}

/// Distinguishes different cases on how we can respond to a request
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LastResponse {
    /// We have not yet answered any request
    //
    // The internal message_buffer should be `None` in this case.
    NoResponse,
    /// The last request was answered with a RST message
    //
    // The internal message buffer contains the last request because it has not been overwritten
    // with an actual response. It should not be required anyways.
    RespRst,
    /// The last request was answered with a CON message
    ///
    /// The contained `bool` stores if the CON message was successfully acked. If `false`,
    /// transmitting the CON timed out.
    //
    // The internal message buffer contains the CON response that was sent out.
    RespCon(bool),
    /// The last request was answered with a separate NON response or a piggybacked response (in
    /// both cases, we do not know if the requester has received our response)
    //
    // The internal message buffer contains the response we have sent out before.
    RespNon,
}

/// What has happened in the [`IncomingCommunication`] path when calling
/// [`CoapEndpoint::process`](super::CoapEndpoint::process)
///
/// This type is annotated with `must_use` because some events require user interaction to avoid
/// getting stuck in specific states. See the documentation for the specific events for more
/// information.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IncomingEvent<'a> {
    /// No _real_ event happened. This pseudo-event is included as a variant here to allow concise
    /// event handling on the user side.
    Nothing,
    /// A new request was received. The user _must_ respond to this event. The event contains the
    /// `bool` flag if the request is confirmable (`true`) or non-confirmable (`false`) and the
    /// request message itself.
    ///
    /// In any case, the response may be sent with [`IncomingCommunication::schedule_response`]
    /// immediately. For CON requests, this will result in a piggybacked response. For NON
    /// requests, a NON response will be sent. For other options, see the
    /// [`IncomingState::Received`] state.
    ///
    /// The contained [`EncodedMessage`] keeps the borrow of the [`Endpoint`](super::CoapEndpoint)
    /// alive which might be undesirable in some situations. To resolve this, it may safely be `drop`ped, it can be accessed later via [`IncomingCommunication::request`].
    Request(bool, EncodedMessage<'a>),
    /// We have received the same request again. Depending on how we have already handled the
    /// request, appropriate action is taken automatically. For example, if the request has already
    /// been ACKed but a separate response is still missing, we send the ACK again. If we have sent
    /// a NON response before which may not have reached the other endpoint, we send it again.
    DuplicatedRequest,
    /// We have sent an ACK. With this event, a state transition into
    /// [`IncomingState::AwaitingResponse`] takes place in which more user interaction is
    /// _required_.
    SendAck,
    /// A separate CON response has been (re-)sent. NON and piggybacked responses directly result
    /// in a [`IncomingEvent::Success`] event.
    SendCon,
    /// We have successfully finished the communication (from our perspective). If our response was
    /// piggybacked or a separate NON message, we have no guarantee that the other endpoint has
    /// already received our response. If our response was a separate CON message, the
    /// corresponding ACK has been received and we know that the other endpoint has received our
    /// response.
    Success,
    /// We have sent a RST message. With this event, a state transition into
    /// [`IncomingState::Idle`] takes place.
    SendRst,
    /// Sending the separate CON response has timed out. Piggybacked or separate NON responses will
    /// not be ACKed so they can not time out.
    Timeout,
    /// We have received a RST when sending a separate CON response
    RecvRst,
}

/// Incoming communication path. This handles incoming requests and pings which will be
/// automatically answered with RST messages.
#[derive(Debug)]
pub struct IncomingCommunication<
    'a,
    UDP: UdpClientStack,
    CLOCK: Clock,
    const BUFFER_SIZE: usize = { crate::DEFAULT_COAP_MESSAGE_SIZE },
    const MAX_OPTION_COUNT: usize = { crate::DEFAULT_MAX_OPTION_COUNT },
    const MAX_OPTION_SIZE: usize = { crate::DEFAULT_MAX_OPTION_SIZE },
> {
    message_buffer: MessageBuffer<BUFFER_SIZE>,
    /// Depending on the state, contains the request we are currently handling or the last request
    /// we have handled (for de-duplication)
    last_request: Option<MessageIdentification>,
    state: IncomingState,
    clock: &'a CLOCK,
    transmission_parameters: TransmissionParameters,
    /// Next message ID to create/schedule a separate response. Since the endpoint is in charge of
    /// the message ID generation, the next message ID must be determined in advance.
    pub(super) next_message_id: Option<u16>,
    /// Random value between 0 and 1 to initialize the RetransmissionState required to schedule a
    /// CON message. Since the endpoint owns the RNG, the next random number must be determined in
    /// advance.
    pub(super) next_random: Option<f32>,
    _udp: PhantomData<UDP>,
}

impl<
        'a,
        UDP,
        CLOCK,
        const BUFFER_SIZE: usize,
        const MAX_OPTION_COUNT: usize,
        const MAX_OPTION_SIZE: usize,
    > IncomingCommunication<'a, UDP, CLOCK, BUFFER_SIZE, MAX_OPTION_COUNT, MAX_OPTION_SIZE>
where
    UDP: UdpClientStack,
    CLOCK: Clock,
{
    /// Initializes the incoming communication path in the [`IncomingState::Idle`] state so it is
    /// ready to handle incoming requests.
    pub fn new(clock: &'a CLOCK, transmission_parameters: TransmissionParameters) -> Self {
        Self {
            message_buffer: MessageBuffer::default(),
            last_request: None,
            state: IncomingState::Idle(LastResponse::NoResponse),
            clock,
            transmission_parameters,
            next_message_id: None,
            next_random: None,
            _udp: PhantomData,
        }
    }

    /// Returns the current state of the `IncomingCommunication`. Depending on the state, the user
    /// _must_ take action to drive the state forward, see the documentation to the states in
    /// [`IncomingState`].
    pub fn state(&self) -> IncomingState {
        self.state
    }

    /// Resets the internal state machine
    pub fn reset(&mut self) {
        *self = Self::new(self.clock, self.transmission_parameters);
    }

    /// Returns the current request message which is the same that was returned in the `Request`
    /// event before. Therefore, usage of this method is only required if the decision between
    /// ACK + separate response and a piggybacked response shall be postponed (the message from the
    /// `Request` event can probably not be stored due to lifetime requirements).
    ///
    /// This method is only available in [`IncomingState::Received`], [`IncomingState::SendingAck`]
    /// and [`IncomingState::AwaitingResponse`] and will return [`Error::Forbidden`] otherwise.
    pub fn request(&self) -> Result<EncodedMessage, Error<<UDP as UdpClientStack>::Error>> {
        use IncomingState::*;
        match self.state {
            Received(_) | SendingAck | AwaitingResponse => {
                Ok(self.message_buffer.message().unwrap())
            }
            _ => Err(Error::Forbidden),
        }
    }

    /// Schedules an immediate response to be sent.
    ///
    /// If a confirmable request was received, a piggy-backed response will be scheduled.
    /// In case of a non-confirmable request, the response will be send as non-confirmable as well.
    ///
    /// For more control, the user can check if the request was confirmable or non-confirmable
    /// themselves and call [`IncomingCommunication::schedule_empty_ack`],
    /// [`IncomingCommunication::schedule_piggybacked_response`],
    /// [`IncomingCommunication::schedule_con_response`] or
    /// [`IncomingCommunication::schedule_non_response`] accordingly.
    pub fn schedule_response(
        &mut self,
        code: ResponseCode,
        options: Vec<CoapOption<'_>, MAX_OPTION_COUNT>,
        payload: Option<&[u8]>,
    ) -> Result<(), Error<<UDP as UdpClientStack>::Error>> {
        match self.state {
            IncomingState::Received(true) => {
                self.schedule_piggybacked_response(code, options, payload)
            }
            IncomingState::Received(false) => self.schedule_non_response(code, options, payload),
            _ => Err(Error::Forbidden),
        }
    }

    /// Schedules an Acknowledgement to be sent.
    ///
    /// The ACK will fit the `message_id` for the last received request
    pub fn schedule_empty_ack(&mut self) -> Result<(), Error<<UDP as UdpClientStack>::Error>> {
        if !matches!(self.state, IncomingState::Received(true)) {
            return Err(Error::Forbidden);
        }
        self.state = IncomingState::SendingAck;
        Ok(())
    }

    /// Schedules a RST message to be sent.
    pub fn schedule_rst(&mut self) -> Result<(), Error<<UDP as UdpClientStack>::Error>> {
        if !matches!(self.state, IncomingState::Received(_)) {
            return Err(Error::Forbidden);
        }
        self.state = IncomingState::SendingRst;
        Ok(())
    }

    /// Schedules an Acknowledgement with piggy-backed response
    ///
    /// The ACK will fit the `message_id` for the last received request.
    /// The response is defined by the given details (`code`, `payload` and `additional_options`).
    pub fn schedule_piggybacked_response(
        &mut self,
        code: ResponseCode,
        options: Vec<CoapOption<'_>, MAX_OPTION_COUNT>,
        payload: Option<&[u8]>,
    ) -> Result<(), Error<<UDP as UdpClientStack>::Error>> {
        if !matches!(self.state, IncomingState::Received(true)) {
            return Err(Error::Busy);
        }

        let ident = self.last_request.as_ref().unwrap();

        let message: Message<MAX_OPTION_COUNT> = Message::new(
            Type::Acknowledgement,
            code.into(),
            ident.id,
            ident.token,
            options,
            payload,
        );
        self.message_buffer.encode(message)?;

        self.state = IncomingState::SendingPiggybacked;

        Ok(())
    }

    /// Schedules a message to be sent as a separate CON response
    pub fn schedule_con_response(
        &mut self,
        code: ResponseCode,
        options: Vec<CoapOption<'_>, MAX_OPTION_COUNT>,
        payload: Option<&[u8]>,
    ) -> Result<(), Error<<UDP as UdpClientStack>::Error>> {
        self.schedule_separate_response(Type::Confirmable, code, options, payload)?;
        let retransmission_state = RetransmissionState::new(
            self.transmission_parameters,
            self.next_random.take().unwrap(),
        );
        self.state = IncomingState::SendingCon(retransmission_state);
        Ok(())
    }

    /// Schedules a message to be sent as a separate NON response
    pub fn schedule_non_response(
        &mut self,
        code: ResponseCode,
        options: Vec<CoapOption<'_>, MAX_OPTION_COUNT>,
        payload: Option<&[u8]>,
    ) -> Result<(), Error<<UDP as UdpClientStack>::Error>> {
        self.schedule_separate_response(Type::NonConfirmable, code, options, payload)?;
        self.state = IncomingState::SendingNon;
        Ok(())
    }

    /// Schedules a message to be sent as a response for an incoming request.
    ///
    /// Internal method to handle CON and NON cases
    fn schedule_separate_response(
        &mut self,
        response_type: Type,
        code: ResponseCode,
        options: Vec<CoapOption<'_>, MAX_OPTION_COUNT>,
        payload: Option<&[u8]>,
    ) -> Result<(), Error<<UDP as UdpClientStack>::Error>> {
        if !matches!(self.state, IncomingState::AwaitingResponse)
            && !matches!(self.state, IncomingState::Received(false))
        {
            return Err(Error::Busy);
        }

        let message: Message<MAX_OPTION_COUNT> = Message::new(
            response_type,
            code.into(),
            self.next_message_id.unwrap(),
            self.last_request.unwrap().token,
            options,
            payload,
        );

        self.message_buffer.encode(message)?;

        self.next_message_id = None;

        Ok(())
    }

    /// Drives the internal state machine
    ///
    /// If we receive a new request in a non-Idle state, it is ignored here. This seems to be the
    /// right thing to do if we imagine a setup with NSTART>1 because then, an other
    /// [`IncomingCommunication`] could handle this request. Currently, this will result in
    /// unhandled messages in the endpoint which is responsible to react accordingly. It is advised
    /// to silently ignore the request to trigger a retransmission on the requester's side.
    pub(crate) fn process_incoming(
        &mut self,
        connection: &mut Connection<UDP>,
        received: &mut Option<EncodedMessage<'_>>,
    ) -> Result<IncomingEvent, Error<<UDP as UdpClientStack>::Error>> {
        use IncomingEvent::*;
        use IncomingState::*;
        use LastResponse::*;

        // We can generate events when we handle the received message or when an internal
        // retransmission timeout occurs. So whenever either of those happens, we should skip the
        // other because we can not return two events at the same time. Since we can only handle a
        // received message _now_, we start by handling messages and skip checking timeouts. If the
        // user calls the process method often enough, the timeout will trigger anyways in the next
        // iteration.
        //
        // Message de-duplication happens in nearly all states. To not duplicate the de-duplication
        // code in every state, we handle de-duplication in a first match and the other cases in a
        // second match.

        if let (Some(message), Some(last_message_ident)) = (&received, self.last_request) {
            if message.is_request().unwrap()
                && last_message_ident.id == message.message_id()
                && last_message_ident.token == message.token().unwrap()
            {
                match self.state {
                    Idle(NoResponse) => panic!(
                        "In the Idle(NoResponse) state, the internal message buffer should be None"
                    ),
                    Idle(RespRst) => {
                        // Previously, we have responded with an ACK. We should do so now, too.
                        connection.send(&EncodedMessage::rst(last_message_ident.id))?;
                    }
                    Idle(RespCon(true)) => {
                        // The requester has already received and acked our response. So this
                        // must be a request which has been sent before their ACK. We should
                        // ignore it.
                    }
                    Idle(RespCon(false)) => {
                        // Our CON response (with retries!) timed out. We have already tried a lot
                        // to respond but the connection just seems to be bad. Who knows how this
                        // request reached us again, let's just not handle it again.
                    }
                    Idle(RespNon) => {
                        // We have responded with a NON message which may have not have reached the
                        // other endpoint. Let's just try again.
                        connection.send(self.message_buffer.message().unwrap().data)?;
                    }
                    Received(_) => {
                        // We do not know the response yet so we can only ignore it
                    }
                    SendingAck | SendingRst | SendingPiggybacked | SendingNon => {
                        // We can ignore it because a message will be sent now anyways
                    }
                    AwaitingResponse => {
                        // We have already ACKed the request but we do not know the separate
                        // response yet. It looks like the ACK did not reach the other endpoint, so
                        // let's send it again.
                        connection.send(&EncodedMessage::ack(last_message_ident.id))?;
                    }
                    SendingCon(_) => {
                        // We are in the process of (re-)transmitting a CON response anyways so
                        // we do not need to ACK again
                    }
                }
                received.take();
                return Ok(DuplicatedRequest);
            }
        }

        match self.state {
            Idle(_) => {
                // When we get passed some received data,
                // we need to check if we just received a request.
                if let Some(message) = received {
                    if message.is_request().unwrap() {
                        // New request, we save all metadata and return the message
                        self.last_request = Some(MessageIdentification {
                            id: message.message_id(),
                            token: message.token().unwrap(),
                        });
                        let confirmable = message.message_type() == Type::Confirmable;
                        self.message_buffer.replace_with(received.take().unwrap())?;
                        self.state = Received(confirmable);
                        return Ok(Request(confirmable, self.message_buffer.message().unwrap()));
                    }
                }
            }
            Received(_) | AwaitingResponse => {
                // We actually don't have anything to do
                // since we are just waiting for the user to ACK.
                // In case we are already in state AwaitingResponse,
                // we wait for the user to send the separate response.
            }
            SendingAck => {
                let ident = self.last_request.as_ref().unwrap();
                connection.send(&EncodedMessage::ack(ident.id))?;
                self.state = AwaitingResponse;
                return Ok(SendAck);
            }
            SendingRst => {
                let ident = self.last_request.as_ref().unwrap();
                connection.send(&EncodedMessage::rst(ident.id))?;
                self.state = Idle(RespRst);
                return Ok(SendRst);
            }
            SendingPiggybacked | SendingNon => {
                connection.send(self.message_buffer.message().unwrap().data)?;
                self.state = Idle(RespNon);
                return Ok(Success);
            }
            SendingCon(ref mut retransmission_state) => {
                if let Some(message) = received {
                    if message.message_type() == Type::Acknowledgement
                        && message.message_id()
                            == self.message_buffer.message().unwrap().message_id()
                    {
                        received.take();
                        self.state = Idle(RespCon(true));
                        return Ok(Success);
                    } else if message.message_type() == Type::Reset
                        && message.message_id()
                            == self.message_buffer.message().unwrap().message_id()
                    {
                        received.take();
                        self.state = Idle(RespCon(false));
                        return Ok(RecvRst);
                    }
                }
                match retransmission_state.retransmit_required(self.clock.try_now().unwrap()) {
                    Ok(true) => {
                        connection.send(self.message_buffer.message().unwrap().data)?;
                        return Ok(SendCon);
                    }
                    Ok(false) => {}
                    Err(RetransmissionTimeout) => {
                        self.state = Idle(RespCon(false));
                        // Timeout is an Event not an Error because it is specified in the protocol
                        return Ok(Timeout);
                    }
                }
            }
        }

        Ok(Nothing)
    }
}

#[cfg(test)]
mod tests {
    use core::{cell::RefCell, time::Duration};

    use embedded_hal::prelude::_embedded_hal_blocking_rng_Read;
    use embedded_nal::{IpAddr, Ipv4Addr, SocketAddr, UdpClientStack};
    use heapless::Vec;
    use mockall::predicate::*;
    use mockall::*;

    use crate::{
        endpoint::incoming::{IncomingEvent, IncomingState},
        message::{
            codes::{RequestCode, SuccessCode},
            token::{Token, TokenLength},
            Message, Type,
        },
    };

    use super::{super::CoapEndpoint, TransmissionParameters};

    #[derive(Debug)]
    struct Random {
        value: u128,
    }

    impl embedded_hal::blocking::rng::Read for Random {
        type Error = std::io::Error;

        fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
            self.value += 1;

            let buf_len = buf.len();

            buf[..buf_len].copy_from_slice(&self.value.to_le_bytes()[..buf_len]);

            Ok(())
        }
    }

    #[derive(Debug)]
    struct StackError;

    struct Socket;

    mock! {
        Stack {}

        impl UdpClientStack for Stack {
            type UdpSocket = Socket;
            type Error = StackError;

            fn socket(&mut self) -> Result<Socket, StackError>;
            fn connect(
                &mut self,
                socket: &mut Socket,
                remote: SocketAddr
            ) -> Result<(), StackError>;
            fn send(
                &mut self,
                socket: &mut Socket,
                buffer: &[u8]
            ) -> Result<(), nb::Error<StackError>>;
            fn receive(
                &mut self,
                socket: &mut Socket,
                buffer: &mut [u8]
            ) -> Result<(usize, SocketAddr), nb::Error<StackError>>;
            fn close(&mut self, socket: Socket) -> Result<(), StackError>;
        }
    }

    #[derive(Debug)]
    struct MyClock {
        last_time: RefCell<Duration>,
        now: RefCell<Duration>,
    }

    impl embedded_timers::clock::Clock for MyClock {
        fn try_now(
            &self,
        ) -> Result<embedded_timers::clock::Instant, embedded_timers::clock::ClockError> {
            *self.last_time.borrow_mut() = *self.now.borrow();
            Ok(*self.now.borrow())
        }
    }

    impl MyClock {
        fn advance(&self, step: Duration) {
            *self.now.borrow_mut() = *self.last_time.borrow() + step;
        }
    }

    #[test]
    fn receive_con_get_piggybacked() {
        let mut stack = MockStack::default();

        let clock = MyClock {
            last_time: RefCell::new(Duration::from_secs(0)),
            now: RefCell::new(Duration::from_secs(1)),
        };

        let mut receive_buffer = [0_u8; crate::DEFAULT_COAP_MESSAGE_SIZE];

        let mut endpoint: CoapEndpoint<
            '_,
            MockStack,
            Random,
            MyClock,
            8,
            32,
            128,
            //{ coap_zero::DEFAULT_COAP_MESSAGE_SIZE },
        > = CoapEndpoint::try_new(
            TransmissionParameters::default(),
            Random { value: 0 },
            &clock,
            &mut receive_buffer,
        )
        .unwrap();

        stack.expect_socket().once().return_once(|| Ok(Socket));
        stack.expect_connect().once().return_once(|_, _| Ok(()));

        endpoint
            .connect_to_addr(&mut stack, "127.0.0.1:5683".parse().unwrap())
            .unwrap();

        stack
            .expect_receive()
            .once()
            .return_once(|_, _| Err(nb::Error::WouldBlock));

        let (incoming, _, _) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Nothing));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));

        let next_message_id = endpoint.message_id_counter.next();
        let mut token = Token::default();
        token.length = TokenLength::Eight;
        endpoint.rng.read(&mut token.bytes).unwrap();
        let request: Message<'_> = Message::new(
            Type::Confirmable,
            RequestCode::Get.into(),
            next_message_id,
            token,
            Vec::new(),
            Some(b"/hello"),
        );
        let response: Message<'_> = Message::new(
            Type::Acknowledgement,
            SuccessCode::Content.into(),
            next_message_id,
            token,
            Vec::new(),
            Some(b"world"),
        );
        let mut response_buf = [0_u8; 32];
        let response_length = response.encode(&mut response_buf).unwrap().message_length();

        stack.expect_receive().once().return_once(move |_, buffer| {
            let encoded_message = request.encode(buffer).unwrap();

            Ok((
                encoded_message.message_length(),
                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5683),
            ))
        });

        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Request(true, _)));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Received(true)
        ));
        // TODO Test Message

        endpoint
            .incoming()
            .schedule_piggybacked_response(SuccessCode::Content.into(), Vec::new(), Some(b"world"))
            .unwrap();

        stack
            .expect_receive()
            .once()
            .return_once(|_, _| Err(nb::Error::WouldBlock));
        stack.expect_send().once().return_once(move |_, buffer| {
            assert_eq!(buffer, &response_buf[..response_length]);

            Ok(())
        });

        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Success));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
    }

    #[test]
    fn receive_non_get_non() {
        let mut stack = MockStack::default();

        let clock = MyClock {
            last_time: RefCell::new(Duration::from_secs(0)),
            now: RefCell::new(Duration::from_secs(1)),
        };

        let mut receive_buffer = [0_u8; crate::DEFAULT_COAP_MESSAGE_SIZE];

        let mut endpoint: CoapEndpoint<
            '_,
            MockStack,
            Random,
            MyClock,
            8,
            32,
            128,
            //{ coap_zero::DEFAULT_COAP_MESSAGE_SIZE },
        > = CoapEndpoint::try_new(
            TransmissionParameters::default(),
            Random { value: 0 },
            &clock,
            &mut receive_buffer,
        )
        .unwrap();

        stack.expect_socket().once().return_once(|| Ok(Socket));
        stack.expect_connect().once().return_once(|_, _| Ok(()));

        endpoint
            .connect_to_addr(&mut stack, "127.0.0.1:5683".parse().unwrap())
            .unwrap();

        stack
            .expect_receive()
            .once()
            .return_once(|_, _| Err(nb::Error::WouldBlock));

        let (incoming, _, _) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Nothing));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));

        let next_message_id = endpoint.message_id_counter.next();
        let mut token = Token::default();
        token.length = TokenLength::Eight;
        endpoint.rng.read(&mut token.bytes).unwrap();
        let request: Message<'_> = Message::new(
            Type::NonConfirmable,
            RequestCode::Get.into(),
            next_message_id,
            token,
            Vec::new(),
            Some(b"/hello"),
        );
        let response: Message<'_> = Message::new(
            Type::NonConfirmable,
            SuccessCode::Content.into(),
            endpoint.incoming_communication.next_message_id.unwrap(),
            token,
            Vec::new(),
            Some(b"world"),
        );
        let mut response_buf = [0_u8; 32];
        let response_length = response.encode(&mut response_buf).unwrap().message_length();

        stack.expect_receive().once().return_once(move |_, buffer| {
            let encoded_message = request.encode(buffer).unwrap();

            Ok((
                encoded_message.message_length(),
                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5683),
            ))
        });

        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(
            incoming.unwrap(),
            IncomingEvent::Request(false, _)
        ));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Received(false)
        ));
        // TODO Test Message

        stack
            .expect_receive()
            .once()
            .return_once(|_, _| Err(nb::Error::WouldBlock));

        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Nothing));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Received(false)
        ));

        endpoint
            .incoming()
            .schedule_response(SuccessCode::Content.into(), Vec::new(), Some(b"world"))
            .unwrap();

        stack
            .expect_receive()
            .once()
            .return_once(|_, _| Err(nb::Error::WouldBlock));
        stack.expect_send().once().return_once(move |_, buffer| {
            assert_eq!(buffer, &response_buf[..response_length]);

            Ok(())
        });

        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Success));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
    }

    #[test]
    fn receive_non_get_con() {
        let mut stack = MockStack::default();

        let clock = MyClock {
            last_time: RefCell::new(Duration::from_secs(0)),
            now: RefCell::new(Duration::from_secs(1)),
        };

        let mut receive_buffer = [0_u8; crate::DEFAULT_COAP_MESSAGE_SIZE];

        let mut endpoint: CoapEndpoint<
            '_,
            MockStack,
            Random,
            MyClock,
            8,
            32,
            128,
            //{ coap_zero::DEFAULT_COAP_MESSAGE_SIZE },
        > = CoapEndpoint::try_new(
            TransmissionParameters::default(),
            Random { value: 0 },
            &clock,
            &mut receive_buffer,
        )
        .unwrap();

        let next_message_id = endpoint.message_id_counter.next();
        let mut token = Token::default();
        token.length = TokenLength::Eight;
        endpoint.rng.read(&mut token.bytes).unwrap();
        let request: Message<'_> = Message::new(
            Type::NonConfirmable,
            RequestCode::Get.into(),
            next_message_id,
            token,
            Vec::new(),
            Some(b"/hello"),
        );

        stack.expect_socket().once().return_once(|| Ok(Socket));
        stack.expect_connect().once().return_once(|_, _| Ok(()));

        endpoint
            .connect_to_addr(&mut stack, "127.0.0.1:5683".parse().unwrap())
            .unwrap();

        stack.expect_receive().once().return_once(move |_, buffer| {
            let encoded_message = request.encode(buffer).unwrap();

            Ok((
                encoded_message.message_length(),
                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5683),
            ))
        });

        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(
            incoming.unwrap(),
            IncomingEvent::Request(false, _)
        ));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Received(false)
        ));

        endpoint
            .incoming()
            .schedule_con_response(SuccessCode::Content.into(), Vec::new(), Some(b"world"))
            .unwrap();

        stack
            .expect_receive()
            .once()
            .return_once(|_, _| Err(nb::Error::WouldBlock));
        stack.expect_send().once().return_once(|_, _| Ok(()));

        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::SendingCon(_)
        ));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::SendCon));
        // TODO We have sent the message and waiting for the ack now. Staying in SendingCon feels a little unintuitive.
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::SendingCon(_)
        ));

        let ack_id = endpoint
            .incoming_communication
            .message_buffer
            .message()
            .unwrap()
            .message_id();
        let ack = Message::<0>::new_ack(ack_id);

        stack.expect_receive().once().return_once(move |_, buffer| {
            let encoded_ack = ack.encode(buffer).unwrap();
            Ok((
                encoded_ack.message_length(),
                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5683),
            ))
        });

        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Success));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
    }

    #[test]
    fn receive_non_get_con_timeout() {
        let mut stack = MockStack::default();

        let clock = MyClock {
            last_time: RefCell::new(Duration::from_secs(0)),
            now: RefCell::new(Duration::from_secs(1)),
        };

        let mut receive_buffer = [0_u8; crate::DEFAULT_COAP_MESSAGE_SIZE];

        let mut endpoint: CoapEndpoint<
            '_,
            MockStack,
            Random,
            MyClock,
            8,
            32,
            128,
            //{ coap_zero::DEFAULT_COAP_MESSAGE_SIZE },
        > = CoapEndpoint::try_new(
            TransmissionParameters::default(),
            Random { value: 0 },
            &clock,
            &mut receive_buffer,
        )
        .unwrap();

        let next_message_id = endpoint.message_id_counter.next();
        let mut token = Token::default();
        token.length = TokenLength::Eight;
        endpoint.rng.read(&mut token.bytes).unwrap();
        let request: Message<'_> = Message::new(
            Type::NonConfirmable,
            RequestCode::Get.into(),
            next_message_id,
            token,
            Vec::new(),
            Some(b"/hello"),
        );

        stack.expect_socket().once().return_once(|| Ok(Socket));
        stack.expect_connect().once().return_once(|_, _| Ok(()));

        endpoint
            .connect_to_addr(&mut stack, "127.0.0.1:5683".parse().unwrap())
            .unwrap();

        stack.expect_receive().once().return_once(move |_, buffer| {
            let encoded_message = request.encode(buffer).unwrap();

            Ok((
                encoded_message.message_length(),
                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5683),
            ))
        });

        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(
            incoming.unwrap(),
            IncomingEvent::Request(false, _)
        ));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Received(false)
        ));

        endpoint
            .incoming()
            .schedule_con_response(SuccessCode::Content.into(), Vec::new(), Some(b"world"))
            .unwrap();

        stack
            .expect_receive()
            .returning(move |_, _| Err(nb::Error::WouldBlock));
        stack.expect_send().returning(|_, _| Ok(()));

        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::SendCon));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::SendingCon(_)
        ));

        // 4 Retries
        clock.advance(Duration::from_secs(3));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::SendCon));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::SendingCon(_)
        ));

        clock.advance(Duration::from_secs(5));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::SendCon));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::SendingCon(_)
        ));

        clock.advance(Duration::from_secs(9));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::SendCon));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::SendingCon(_)
        ));

        clock.advance(Duration::from_secs(17));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::SendCon));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::SendingCon(_)
        ));

        // Timeout
        clock.advance(Duration::from_secs(33));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Timeout));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
    }

    #[test]
    fn receive_piggybacked_response() {
        let mut stack = MockStack::default();

        let clock = MyClock {
            last_time: RefCell::new(Duration::from_secs(0)),
            now: RefCell::new(Duration::from_secs(1)),
        };

        let mut receive_buffer = [0_u8; crate::DEFAULT_COAP_MESSAGE_SIZE];

        let mut endpoint: CoapEndpoint<
            '_,
            MockStack,
            Random,
            MyClock,
            8,
            32,
            128,
            //{ coap_zero::DEFAULT_COAP_MESSAGE_SIZE },
        > = CoapEndpoint::try_new(
            TransmissionParameters::default(),
            Random { value: 0 },
            &clock,
            &mut receive_buffer,
        )
        .unwrap();

        let message_id = endpoint.message_id_counter.next();
        let mut token = Token::default();
        token.length = TokenLength::Eight;
        endpoint.rng.read(&mut token.bytes).unwrap();
        let message: Message<'_> = Message::new(
            Type::Acknowledgement,
            SuccessCode::Content.into(),
            message_id,
            token,
            Vec::new(),
            Some(b"world"),
        );

        stack.expect_socket().once().return_once(|| Ok(Socket));
        stack.expect_connect().once().return_once(|_, _| Ok(()));

        endpoint
            .connect_to_addr(&mut stack, "127.0.0.1:5683".parse().unwrap())
            .unwrap();

        stack.expect_receive().once().return_once(move |_, buffer| {
            let encoded_message = message.encode(buffer).unwrap();

            Ok((
                encoded_message.message_length(),
                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5683),
            ))
        });
        // The Response should be handled by outgoing or be unhandled, so incoming should do nothing
        // at all.

        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Nothing));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
    }

    #[test]
    fn receive_ack() {
        let mut stack = MockStack::default();

        let clock = MyClock {
            last_time: RefCell::new(Duration::from_secs(0)),
            now: RefCell::new(Duration::from_secs(1)),
        };

        let mut receive_buffer = [0_u8; crate::DEFAULT_COAP_MESSAGE_SIZE];

        let mut endpoint: CoapEndpoint<
            '_,
            MockStack,
            Random,
            MyClock,
            8,
            32,
            128,
            //{ coap_zero::DEFAULT_COAP_MESSAGE_SIZE },
        > = CoapEndpoint::try_new(
            TransmissionParameters::default(),
            Random { value: 0 },
            &clock,
            &mut receive_buffer,
        )
        .unwrap();

        let message_id = endpoint.message_id_counter.next();

        stack.expect_socket().once().return_once(|| Ok(Socket));
        stack.expect_connect().once().return_once(|_, _| Ok(()));

        endpoint
            .connect_to_addr(&mut stack, "127.0.0.1:5683".parse().unwrap())
            .unwrap();

        stack.expect_receive().once().return_once(move |_, buffer| {
            let encoded_message = Message::<0>::new_ack(message_id).encode(buffer).unwrap();

            Ok((
                encoded_message.message_length(),
                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5683),
            ))
        });
        // The ACK is not handled at all because it is not expected anywhere, so incoming should do
        // nothing at all.

        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Nothing));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
    }

    #[test]
    fn receive_reset() {
        let mut stack = MockStack::default();

        let clock = MyClock {
            last_time: RefCell::new(Duration::from_secs(0)),
            now: RefCell::new(Duration::from_secs(1)),
        };

        let mut receive_buffer = [0_u8; crate::DEFAULT_COAP_MESSAGE_SIZE];

        let mut endpoint: CoapEndpoint<
            '_,
            MockStack,
            Random,
            MyClock,
            8,
            32,
            128,
            //{ coap_zero::DEFAULT_COAP_MESSAGE_SIZE },
        > = CoapEndpoint::try_new(
            TransmissionParameters::default(),
            Random { value: 0 },
            &clock,
            &mut receive_buffer,
        )
        .unwrap();

        let message_id = endpoint.message_id_counter.next();
        let message: Message<'_> = Message::new_rst(message_id);

        stack.expect_socket().once().return_once(|| Ok(Socket));
        stack.expect_connect().once().return_once(|_, _| Ok(()));

        endpoint
            .connect_to_addr(&mut stack, "127.0.0.1:5683".parse().unwrap())
            .unwrap();

        stack.expect_receive().once().return_once(move |_, buffer| {
            let encoded_message = message.encode(buffer).unwrap();

            Ok((
                encoded_message.message_length(),
                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 5683),
            ))
        });
        // The Response should be handled by outgoing, so incoming should do nothing at all.

        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
        let (incoming, _outgoing, _endpoint) = endpoint.process(&mut stack).unwrap();
        assert!(matches!(incoming.unwrap(), IncomingEvent::Nothing));
        assert!(matches!(
            endpoint.incoming_communication.state,
            IncomingState::Idle(_)
        ));
    }
}