1 /*
2  * Copyright (c) 2024 A Labs GmbH
3  * Copyright (c) 2024 tado GmbH
4  * Copyright (c) 2022 Jiapeng Li
5  *
6  * Based on: https://github.com/JiapengLi/LoRaWANFragmentedDataBlockTransportAlgorithm
7  * Original algorithm: http://www.inference.org.uk/mackay/gallager/papers/ldpc.pdf
8  *
9  * SPDX-License-Identifier: Apache-2.0
10  */
11 
12 #ifndef FRAG_DEC_H_
13 #define FRAG_DEC_H_
14 
15 #include <stdint.h>
16 #include <stddef.h>
17 
18 #define FRAG_MAX_NB                                                                                \
19 	(CONFIG_LORAWAN_FRAG_TRANSPORT_IMAGE_SIZE / CONFIG_LORAWAN_FRAG_TRANSPORT_MIN_FRAG_SIZE +  \
20 	 1U)
21 #define FRAG_MAX_SIZE  (CONFIG_LORAWAN_FRAG_TRANSPORT_MAX_FRAG_SIZE)
22 #define FRAG_TOLERANCE (FRAG_MAX_NB * CONFIG_LORAWAN_FRAG_TRANSPORT_MAX_REDUNDANCY / 100U)
23 
24 #define FRAG_DEC_ONGOING                  (-1)
25 #define FRAG_DEC_ERR_INVALID_FRAME        (-2)
26 #define FRAG_DEC_ERR_TOO_MANY_FRAMES_LOST (-3)
27 #define FRAG_DEC_ERR                      (-4)
28 
29 enum frag_decoder_status {
30 	/** Processing uncoded fragments */
31 	FRAG_DEC_STA_UNCODED,
32 	/** Processing coded fragments and restoring data with the help of other fragments */
33 	FRAG_DEC_STA_CODED,
34 	/** All fragments received and/or restored */
35 	FRAG_DEC_STA_DONE,
36 };
37 
38 struct frag_decoder {
39 	/** Current decoder status */
40 	enum frag_decoder_status status;
41 
42 	/** Number of fragments */
43 	uint16_t nb_frag;
44 	/** Size of individual fragment */
45 	uint8_t frag_size;
46 
47 	/** Number of frames lost in this session */
48 	uint16_t lost_frame_count;
49 	/** Number of frames recovered in this session */
50 	uint16_t filled_lost_frame_count;
51 };
52 
53 void frag_dec_init(struct frag_decoder *decoder, size_t nb_frag, size_t frag_size);
54 int frag_dec(struct frag_decoder *decoder, uint16_t frag_counter, const uint8_t *buf, size_t len);
55 
56 #endif /* FRAG_DEC_H_ */
57