RadioLib
Universal wireless communication library for Arduino
Loading...
Searching...
No Matches
LoRaWAN.h
1#if !defined(_RADIOLIB_LORAWAN_H) && !RADIOLIB_EXCLUDE_LORAWAN
2#define _RADIOLIB_LORAWAN_H
3
4#include "../../TypeDef.h"
5#include "../PhysicalLayer/PhysicalLayer.h"
6#include "../../utils/Cryptography.h"
7
8// activation mode
9#define RADIOLIB_LORAWAN_MODE_OTAA (0x07AA)
10#define RADIOLIB_LORAWAN_MODE_ABP (0x0AB9)
11#define RADIOLIB_LORAWAN_MODE_NONE (0x0000)
12
13// operation mode
14#define RADIOLIB_LORAWAN_CLASS_A (0x00)
15#define RADIOLIB_LORAWAN_CLASS_B (0x01)
16#define RADIOLIB_LORAWAN_CLASS_C (0x02)
17
18// preamble format
19#define RADIOLIB_LORAWAN_LORA_SYNC_WORD (0x34)
20#define RADIOLIB_LORAWAN_LORA_PREAMBLE_LEN (8)
21#define RADIOLIB_LORAWAN_GFSK_SYNC_WORD (0xC194C1)
22#define RADIOLIB_LORAWAN_GFSK_PREAMBLE_LEN (5)
23#define RADIOLIB_LORAWAN_LR_FHSS_SYNC_WORD (0x2C0F7995)
24
25// MAC header field encoding MSB LSB DESCRIPTION
26#define RADIOLIB_LORAWAN_MHDR_MTYPE_JOIN_REQUEST (0x00 << 5) // 7 5 message type: join request
27#define RADIOLIB_LORAWAN_MHDR_MTYPE_JOIN_ACCEPT (0x01 << 5) // 7 5 join accept
28#define RADIOLIB_LORAWAN_MHDR_MTYPE_UNCONF_DATA_UP (0x02 << 5) // 7 5 unconfirmed data up
29#define RADIOLIB_LORAWAN_MHDR_MTYPE_UNCONF_DATA_DOWN (0x03 << 5) // 7 5 unconfirmed data down
30#define RADIOLIB_LORAWAN_MHDR_MTYPE_CONF_DATA_UP (0x04 << 5) // 7 5 confirmed data up
31#define RADIOLIB_LORAWAN_MHDR_MTYPE_CONF_DATA_DOWN (0x05 << 5) // 7 5 confirmed data down
32#define RADIOLIB_LORAWAN_MHDR_MTYPE_PROPRIETARY (0x07 << 5) // 7 5 proprietary
33#define RADIOLIB_LORAWAN_MHDR_MTYPE_MASK (0x07 << 5) // 7 5 bitmask of all possible options
34#define RADIOLIB_LORAWAN_MHDR_MAJOR_R1 (0x00 << 0) // 1 0 major version: LoRaWAN R1
35
36// frame control field encoding
37#define RADIOLIB_LORAWAN_FCTRL_ADR_ENABLED (0x01 << 7) // 7 7 adaptive data rate: enabled
38#define RADIOLIB_LORAWAN_FCTRL_ADR_DISABLED (0x00 << 7) // 7 7 disabled
39#define RADIOLIB_LORAWAN_FCTRL_ADR_ACK_REQ (0x01 << 6) // 6 6 adaptive data rate ACK request
40#define RADIOLIB_LORAWAN_FCTRL_ACK (0x01 << 5) // 5 5 confirmed message acknowledge
41#define RADIOLIB_LORAWAN_FCTRL_FRAME_PENDING (0x01 << 4) // 4 4 downlink frame is pending
42
43// fPort field
44#define RADIOLIB_LORAWAN_FPORT_MAC_COMMAND (0x00 << 0) // 7 0 payload contains MAC commands only
45#define RADIOLIB_LORAWAN_FPORT_PAYLOAD_MIN (0x01 << 0) // 7 0 start of user-allowed fPort range
46#define RADIOLIB_LORAWAN_FPORT_PAYLOAD_MAX (0xDF << 0) // 7 0 end of user-allowed fPort range
47#define RADIOLIB_LORAWAN_FPORT_RESERVED (0xE0 << 0) // 7 0 fPort values equal to and larger than this are reserved
48
49// data rate encoding
50#define RADIOLIB_LORAWAN_DATA_RATE_MODEM (0x03 << 6) // 7 6 modem mask
51#define RADIOLIB_LORAWAN_DATA_RATE_LORA (0x00 << 6) // 7 6 use LoRa modem
52#define RADIOLIB_LORAWAN_DATA_RATE_FSK (0x01 << 6) // 7 6 use FSK modem
53#define RADIOLIB_LORAWAN_DATA_RATE_LR_FHSS (0x02 << 6) // 7 6 use LR-FHSS modem
54#define RADIOLIB_LORAWAN_DATA_RATE_SF (0x07 << 3) // 5 3 LoRa spreading factor mask
55#define RADIOLIB_LORAWAN_DATA_RATE_SF_12 (0x05 << 3) // 5 3 LoRa spreading factor: SF12
56#define RADIOLIB_LORAWAN_DATA_RATE_SF_11 (0x04 << 3) // 5 3 SF11
57#define RADIOLIB_LORAWAN_DATA_RATE_SF_10 (0x03 << 3) // 5 3 SF10
58#define RADIOLIB_LORAWAN_DATA_RATE_SF_9 (0x02 << 3) // 5 3 SF9
59#define RADIOLIB_LORAWAN_DATA_RATE_SF_8 (0x01 << 3) // 5 3 SF8
60#define RADIOLIB_LORAWAN_DATA_RATE_SF_7 (0x00 << 3) // 5 3 SF7
61#define RADIOLIB_LORAWAN_DATA_RATE_BW (0x03 << 1) // 2 1 bandwidth mask
62#define RADIOLIB_LORAWAN_DATA_RATE_BW_125_KHZ (0x00 << 1) // 2 1 125 kHz
63#define RADIOLIB_LORAWAN_DATA_RATE_BW_250_KHZ (0x01 << 1) // 2 1 250 kHz
64#define RADIOLIB_LORAWAN_DATA_RATE_BW_500_KHZ (0x02 << 1) // 2 1 LoRa bandwidth: 500 kHz
65#define RADIOLIB_LORAWAN_DATA_RATE_BW_137_KHZ (0x00 << 1) // 2 1 137 kHz
66#define RADIOLIB_LORAWAN_DATA_RATE_BW_336_KHZ (0x01 << 1) // 2 1 336 kHz
67#define RADIOLIB_LORAWAN_DATA_RATE_BW_1523_KHZ (0x02 << 1) // 2 1 LR-FHSS bandwidth: 1523 kHz
68#define RADIOLIB_LORAWAN_DATA_RATE_CR (0x01 << 0) // 0 0 coding rate mask
69#define RADIOLIB_LORAWAN_DATA_RATE_CR_1_3 (0x00 << 0) // 0 0 LR-FHSS coding rate: 1/3
70#define RADIOLIB_LORAWAN_DATA_RATE_CR_2_3 (0x01 << 0) // 0 0 2/3
71#define RADIOLIB_LORAWAN_DATA_RATE_UNUSED (0xFF << 0) // 7 0 unused data rate
72
73// channels and channel plans
74#define RADIOLIB_LORAWAN_UPLINK (0x00 << 0)
75#define RADIOLIB_LORAWAN_DOWNLINK (0x01 << 0)
76#define RADIOLIB_LORAWAN_RX1 (0x01 << 0)
77#define RADIOLIB_LORAWAN_RX2 (0x02 << 0)
78#define RADIOLIB_LORAWAN_RX_BC (0x03 << 0)
79#define RADIOLIB_LORAWAN_BAND_DYNAMIC (0)
80#define RADIOLIB_LORAWAN_BAND_FIXED (1)
81#define RADIOLIB_LORAWAN_CHANNEL_NUM_DATARATES (15)
82#define RADIOLIB_LORAWAN_CHANNEL_INDEX_NONE (0xFF >> 0)
83
84// recommended default settings
85#define RADIOLIB_LORAWAN_RECEIVE_DELAY_1_MS (1000)
86#define RADIOLIB_LORAWAN_RECEIVE_DELAY_2_MS ((RADIOLIB_LORAWAN_RECEIVE_DELAY_1_MS) + 1000)
87#define RADIOLIB_LORAWAN_RX1_DR_OFFSET (0)
88#define RADIOLIB_LORAWAN_JOIN_ACCEPT_DELAY_1_MS (5000)
89#define RADIOLIB_LORAWAN_JOIN_ACCEPT_DELAY_2_MS (6000)
90#define RADIOLIB_LORAWAN_ADR_ACK_LIMIT_EXP (0x06)
91#define RADIOLIB_LORAWAN_ADR_ACK_DELAY_EXP (0x05)
92#define RADIOLIB_LORAWAN_RETRANSMIT_TIMEOUT_MIN_MS (1000)
93#define RADIOLIB_LORAWAN_RETRANSMIT_TIMEOUT_MAX_MS (3000)
94#define RADIOLIB_LORAWAN_POWER_STEP_SIZE_DBM (-2)
95#define RADIOLIB_LORAWAN_REJOIN_MAX_COUNT_N (10) // send rejoin request 16384 uplinks
96#define RADIOLIB_LORAWAN_REJOIN_MAX_TIME_N (15) // once every year, not actually implemented
97
98// join request message layout
99#define RADIOLIB_LORAWAN_JOIN_REQUEST_LEN (23)
100#define RADIOLIB_LORAWAN_JOIN_REQUEST_JOIN_EUI_POS (1)
101#define RADIOLIB_LORAWAN_JOIN_REQUEST_DEV_EUI_POS (9)
102#define RADIOLIB_LORAWAN_JOIN_REQUEST_DEV_NONCE_POS (17)
103#define RADIOLIB_LORAWAN_JOIN_REQUEST_TYPE (0xFF)
104#define RADIOLIB_LORAWAN_JOIN_REQUEST_TYPE_0 (0x00)
105#define RADIOLIB_LORAWAN_JOIN_REQUEST_TYPE_1 (0x01)
106#define RADIOLIB_LORAWAN_JOIN_REQUEST_TYPE_2 (0x02)
107
108// join accept message layout
109#define RADIOLIB_LORAWAN_JOIN_ACCEPT_MAX_LEN (33)
110#define RADIOLIB_LORAWAN_JOIN_ACCEPT_JOIN_NONCE_POS (1)
111#define RADIOLIB_LORAWAN_JOIN_ACCEPT_HOME_NET_ID_POS (4)
112#define RADIOLIB_LORAWAN_JOIN_ACCEPT_DEV_ADDR_POS (7)
113#define RADIOLIB_LORAWAN_JOIN_ACCEPT_DL_SETTINGS_POS (11)
114#define RADIOLIB_LORAWAN_JOIN_ACCEPT_RX_DELAY_POS (12)
115#define RADIOLIB_LORAWAN_JOIN_ACCEPT_CFLIST_POS (13)
116#define RADIOLIB_LORAWAN_JOIN_ACCEPT_CFLIST_LEN (16)
117#define RADIOLIB_LORAWAN_JOIN_ACCEPT_CFLIST_TYPE_POS (RADIOLIB_LORAWAN_JOIN_ACCEPT_CFLIST_POS + RADIOLIB_LORAWAN_JOIN_ACCEPT_CFLIST_LEN - 1)
118
119// join accept key derivation layout
120#define RADIOLIB_LORAWAN_JOIN_ACCEPT_AES_JOIN_NONCE_POS (1) // regular keys
121#define RADIOLIB_LORAWAN_JOIN_ACCEPT_AES_JOIN_EUI_POS (4)
122#define RADIOLIB_LORAWAN_JOIN_ACCEPT_AES_DEV_NONCE_POS (12)
123#define RADIOLIB_LORAWAN_JOIN_ACCEPT_AES_DEV_ADDR_POS (1) // relay keys
124
125// join accept message variables
126#define RADIOLIB_LORAWAN_JOIN_ACCEPT_R_1_0 (0x00 << 7) // 7 7 LoRaWAN revision: 1.0
127#define RADIOLIB_LORAWAN_JOIN_ACCEPT_R_1_1 (0x01 << 7) // 7 7 1.1
128#define RADIOLIB_LORAWAN_JOIN_ACCEPT_F_NWK_S_INT_KEY (0x01)
129#define RADIOLIB_LORAWAN_JOIN_ACCEPT_APP_S_KEY (0x02)
130#define RADIOLIB_LORAWAN_JOIN_ACCEPT_S_NWK_S_INT_KEY (0x03)
131#define RADIOLIB_LORAWAN_JOIN_ACCEPT_NWK_S_ENC_KEY (0x04)
132#define RADIOLIB_LORAWAN_JOIN_ACCEPT_JS_ENC_KEY (0x05)
133#define RADIOLIB_LORAWAN_JOIN_ACCEPT_JS_INT_KEY (0x06)
134#define RADIOLIB_LORAWAN_JOIN_ACCEPT_ROOT_WOR_S_KEY (0x01)
135#define RADIOLIB_LORAWAN_JOIN_ACCEPT_WOR_S_INT_KEY (0x01)
136#define RADIOLIB_LORAWAN_JOIN_ACCEPT_WOR_S_ENC_KEY (0x02)
137
138// frame header layout
139#define RADIOLIB_LORAWAN_FHDR_LEN_START_OFFS (16)
140#define RADIOLIB_LORAWAN_FHDR_DEV_ADDR_POS (RADIOLIB_LORAWAN_FHDR_LEN_START_OFFS + 1)
141#define RADIOLIB_LORAWAN_FHDR_FCTRL_POS (RADIOLIB_LORAWAN_FHDR_LEN_START_OFFS + 5)
142#define RADIOLIB_LORAWAN_FHDR_FCNT_POS (RADIOLIB_LORAWAN_FHDR_LEN_START_OFFS + 6)
143#define RADIOLIB_LORAWAN_FHDR_FOPTS_POS (RADIOLIB_LORAWAN_FHDR_LEN_START_OFFS + 8)
144#define RADIOLIB_LORAWAN_FHDR_FOPTS_LEN_MASK (0x0F)
145#define RADIOLIB_LORAWAN_FHDR_FOPTS_MAX_LEN (15)
146#define RADIOLIB_LORAWAN_FHDR_FPORT_POS(FOPTS) (RADIOLIB_LORAWAN_FHDR_LEN_START_OFFS + 8 + (FOPTS))
147#define RADIOLIB_LORAWAN_FRAME_PAYLOAD_POS(FOPTS) (RADIOLIB_LORAWAN_FHDR_LEN_START_OFFS + 9 + (FOPTS))
148#define RADIOLIB_LORAWAN_FRAME_LEN(PAYLOAD, FOPTS) (16 + 13 + (PAYLOAD) + (FOPTS))
149
150// payload encryption/MIC blocks common layout
151#define RADIOLIB_LORAWAN_BLOCK_MAGIC_POS (0)
152#define RADIOLIB_LORAWAN_BLOCK_CONF_FCNT_POS (1)
153#define RADIOLIB_LORAWAN_BLOCK_DIR_POS (5)
154#define RADIOLIB_LORAWAN_BLOCK_DEV_ADDR_POS (6)
155#define RADIOLIB_LORAWAN_BLOCK_FCNT_POS (10)
156
157// payload encryption block layout
158#define RADIOLIB_LORAWAN_ENC_BLOCK_MAGIC (0x01)
159#define RADIOLIB_LORAWAN_ENC_BLOCK_COUNTER_ID_POS (4)
160#define RADIOLIB_LORAWAN_ENC_BLOCK_COUNTER_POS (15)
161
162// payload MIC blocks layout
163#define RADIOLIB_LORAWAN_MIC_BLOCK_MAGIC (0x49)
164#define RADIOLIB_LORAWAN_MIC_BLOCK_LEN_POS (15)
165#define RADIOLIB_LORAWAN_MIC_DATA_RATE_POS (3)
166#define RADIOLIB_LORAWAN_MIC_CH_INDEX_POS (4)
167
168// maximum allowed dwell time on bands that implement dwell time limitations
169#define RADIOLIB_LORAWAN_DWELL_TIME (400)
170
171// unused frame counter value
172#define RADIOLIB_LORAWAN_FCNT_NONE (0xFFFFFFFF)
173
174// TR013 CSMA recommended values
175#define RADIOLIB_LORAWAN_DIFS_DEFAULT (2)
176#define RADIOLIB_LORAWAN_BACKOFF_MAX_DEFAULT (6)
177#define RADIOLIB_LORAWAN_MAX_CHANGES_DEFAULT (4)
178
179// MAC commands
180#define RADIOLIB_LORAWAN_NUM_MAC_COMMANDS (24)
181
182#define RADIOLIB_LORAWAN_MAC_RESET (0x01)
183#define RADIOLIB_LORAWAN_MAC_LINK_CHECK (0x02)
184#define RADIOLIB_LORAWAN_MAC_LINK_ADR (0x03)
185#define RADIOLIB_LORAWAN_MAC_DUTY_CYCLE (0x04)
186#define RADIOLIB_LORAWAN_MAC_RX_PARAM_SETUP (0x05)
187#define RADIOLIB_LORAWAN_MAC_DEV_STATUS (0x06)
188#define RADIOLIB_LORAWAN_MAC_NEW_CHANNEL (0x07)
189#define RADIOLIB_LORAWAN_MAC_RX_TIMING_SETUP (0x08)
190#define RADIOLIB_LORAWAN_MAC_TX_PARAM_SETUP (0x09)
191#define RADIOLIB_LORAWAN_MAC_DL_CHANNEL (0x0A)
192#define RADIOLIB_LORAWAN_MAC_REKEY (0x0B)
193#define RADIOLIB_LORAWAN_MAC_ADR_PARAM_SETUP (0x0C)
194#define RADIOLIB_LORAWAN_MAC_DEVICE_TIME (0x0D)
195#define RADIOLIB_LORAWAN_MAC_FORCE_REJOIN (0x0E)
196#define RADIOLIB_LORAWAN_MAC_REJOIN_PARAM_SETUP (0x0F)
197#define RADIOLIB_LORAWAN_MAC_DEVICE_MODE (0x20)
198#define RADIOLIB_LORAWAN_MAC_PROPRIETARY (0x80)
199
200// number of supported LoRaWAN TS packages
201#define RADIOLIB_LORAWAN_NUM_SUPPORTED_PACKAGES (7)
202
203// Package ID numbering as per TS008 (TS011 ID is made up)
204#define RADIOLIB_LORAWAN_PACKAGE_TS007 (0)
205#define RADIOLIB_LORAWAN_PACKAGE_TS003 (1)
206#define RADIOLIB_LORAWAN_PACKAGE_TS005 (2)
207#define RADIOLIB_LORAWAN_PACKAGE_TS004 (3)
208#define RADIOLIB_LORAWAN_PACKAGE_TS006 (4)
209#define RADIOLIB_LORAWAN_PACKAGE_TS009 (5)
210#define RADIOLIB_LORAWAN_PACKAGE_TS011 (6)
211
212// Package FPort (specified or recommended)
213#define RADIOLIB_LORAWAN_FPORT_TS007 (225)
214#define RADIOLIB_LORAWAN_FPORT_TS003 (202)
215#define RADIOLIB_LORAWAN_FPORT_TS005 (200)
216#define RADIOLIB_LORAWAN_FPORT_TS004 (201)
217#define RADIOLIB_LORAWAN_FPORT_TS006 (203)
218#define RADIOLIB_LORAWAN_FPORT_TS009 (224)
219#define RADIOLIB_LORAWAN_FPORT_TS011 (226)
220
221// the length of internal MAC command queue - hopefully this is enough for most use cases
222#define RADIOLIB_LORAWAN_MAC_COMMAND_QUEUE_SIZE (9)
223
224// the maximum number of simultaneously available channels
225#define RADIOLIB_LORAWAN_NUM_AVAILABLE_CHANNELS (16)
226
227// maximum MAC command sizes
228#define RADIOLIB_LORAWAN_MAX_MAC_COMMAND_LEN_DOWN (5)
229#define RADIOLIB_LORAWAN_MAX_MAC_COMMAND_LEN_UP (2)
230#define RADIOLIB_LORAWAN_MAX_NUM_ADR_COMMANDS (8)
231
232#define RADIOLIB_LORAWAN_MAX_DOWNLINK_SIZE (250)
233
234// threshold at which sleeping via user callback enabled, in ms
235#define RADIOLIB_LORAWAN_DELAY_SLEEP_THRESHOLD (50)
236
243 const uint8_t cid;
244
246 const uint8_t lenDn;
247
249 const uint8_t lenUp;
250
252 const bool persist;
253
255 const bool user;
256};
257
258#define RADIOLIB_LORAWAN_MAC_COMMAND_NONE { .cid = 0, .lenDn = 0, .lenUp = 0, .persist = false, .user = false }
259
260constexpr LoRaWANMacCommand_t MacTable[RADIOLIB_LORAWAN_NUM_MAC_COMMANDS] = {
261 { RADIOLIB_LORAWAN_MAC_RESET, 1, 1, true, false },
262 { RADIOLIB_LORAWAN_MAC_LINK_CHECK, 2, 0, false, true },
263 { RADIOLIB_LORAWAN_MAC_LINK_ADR, 4, 1, false, false },
264 { RADIOLIB_LORAWAN_MAC_DUTY_CYCLE, 1, 0, false, false },
265 { RADIOLIB_LORAWAN_MAC_RX_PARAM_SETUP, 4, 1, true, false },
266 { RADIOLIB_LORAWAN_MAC_DEV_STATUS, 0, 2, false, false },
267 { RADIOLIB_LORAWAN_MAC_NEW_CHANNEL, 5, 1, false, false },
268 { RADIOLIB_LORAWAN_MAC_RX_TIMING_SETUP, 1, 0, true, false },
269 { RADIOLIB_LORAWAN_MAC_TX_PARAM_SETUP, 1, 0, true, false },
270 { RADIOLIB_LORAWAN_MAC_DL_CHANNEL, 4, 1, true, false },
271 { RADIOLIB_LORAWAN_MAC_REKEY, 1, 1, true, false },
272 { RADIOLIB_LORAWAN_MAC_ADR_PARAM_SETUP, 1, 0, false, false },
273 { RADIOLIB_LORAWAN_MAC_DEVICE_TIME, 5, 0, false, true },
274 { RADIOLIB_LORAWAN_MAC_FORCE_REJOIN, 2, 0, false, false },
275 { RADIOLIB_LORAWAN_MAC_REJOIN_PARAM_SETUP, 1, 1, false, false },
276 { RADIOLIB_LORAWAN_MAC_DEVICE_MODE, 1, 1, true, false },
277 { RADIOLIB_LORAWAN_MAC_PROPRIETARY, 5, 0, false, true },
278};
279
281typedef void (*PackageCb_t)(uint8_t* dataDown, size_t lenDown);
282
289 uint8_t packId;
290
292 uint8_t packFPort;
293
296
299
302
304 PackageCb_t callback;
305};
306
307constexpr LoRaWANPackage_t PackageTable[RADIOLIB_LORAWAN_NUM_SUPPORTED_PACKAGES] = {
308 { RADIOLIB_LORAWAN_PACKAGE_TS007, RADIOLIB_LORAWAN_FPORT_TS007, true, false, false, NULL },
309 { RADIOLIB_LORAWAN_PACKAGE_TS003, RADIOLIB_LORAWAN_FPORT_TS003, true, true, false, NULL },
310 { RADIOLIB_LORAWAN_PACKAGE_TS005, RADIOLIB_LORAWAN_FPORT_TS005, true, true, false, NULL },
311 { RADIOLIB_LORAWAN_PACKAGE_TS004, RADIOLIB_LORAWAN_FPORT_TS004, true, true, false, NULL },
312 { RADIOLIB_LORAWAN_PACKAGE_TS006, RADIOLIB_LORAWAN_FPORT_TS006, true, true, false, NULL },
313 { RADIOLIB_LORAWAN_PACKAGE_TS009, RADIOLIB_LORAWAN_FPORT_TS009, true, false, false, NULL },
314 { RADIOLIB_LORAWAN_PACKAGE_TS011, RADIOLIB_LORAWAN_FPORT_TS011, false, false, false, NULL }
315};
316
317#define RADIOLIB_LORAWAN_PACKAGE_NONE { .packId = 0, .packFPort = 0, .isAppPack = false, .fixedFPort = false, .enabled = false, .callback = NULL }
318
319#define RADIOLIB_LORAWAN_NONCES_VERSION_VAL (0x0002)
320
321enum LoRaWANSchemeBase_t {
322 RADIOLIB_LORAWAN_NONCES_START = 0x00,
323 RADIOLIB_LORAWAN_NONCES_VERSION = RADIOLIB_LORAWAN_NONCES_START, // 2 bytes
324 RADIOLIB_LORAWAN_NONCES_MODE = RADIOLIB_LORAWAN_NONCES_VERSION + sizeof(uint16_t), // 2 bytes
325 RADIOLIB_LORAWAN_NONCES_PLAN = RADIOLIB_LORAWAN_NONCES_MODE + sizeof(uint16_t), // 1 byte
326 RADIOLIB_LORAWAN_NONCES_CHECKSUM = RADIOLIB_LORAWAN_NONCES_PLAN + sizeof(uint8_t), // 2 bytes
327 RADIOLIB_LORAWAN_NONCES_DEV_NONCE = RADIOLIB_LORAWAN_NONCES_CHECKSUM + sizeof(uint16_t), // 2 bytes
328 RADIOLIB_LORAWAN_NONCES_JOIN_NONCE = RADIOLIB_LORAWAN_NONCES_DEV_NONCE + sizeof(uint16_t), // 3 bytes
329 RADIOLIB_LORAWAN_NONCES_ACTIVE = RADIOLIB_LORAWAN_NONCES_JOIN_NONCE + 3, // 1 byte
330 RADIOLIB_LORAWAN_NONCES_SIGNATURE = RADIOLIB_LORAWAN_NONCES_ACTIVE + sizeof(uint8_t), // 2 bytes
331 RADIOLIB_LORAWAN_NONCES_BUF_SIZE = RADIOLIB_LORAWAN_NONCES_SIGNATURE + sizeof(uint16_t) // Nonces buffer size
332};
333
334enum LoRaWANSchemeSession_t {
335 RADIOLIB_LORAWAN_SESSION_START = 0x00,
336 RADIOLIB_LORAWAN_SESSION_NWK_SENC_KEY = RADIOLIB_LORAWAN_SESSION_START, // 16 bytes
337 RADIOLIB_LORAWAN_SESSION_APP_SKEY = RADIOLIB_LORAWAN_SESSION_NWK_SENC_KEY + RADIOLIB_AES128_KEY_SIZE, // 16 bytes
338 RADIOLIB_LORAWAN_SESSION_FNWK_SINT_KEY = RADIOLIB_LORAWAN_SESSION_APP_SKEY + RADIOLIB_AES128_KEY_SIZE, // 16 bytes
339 RADIOLIB_LORAWAN_SESSION_SNWK_SINT_KEY = RADIOLIB_LORAWAN_SESSION_FNWK_SINT_KEY + RADIOLIB_AES128_KEY_SIZE, // 16 bytes
340 RADIOLIB_LORAWAN_SESSION_DEV_ADDR = RADIOLIB_LORAWAN_SESSION_SNWK_SINT_KEY + RADIOLIB_AES128_KEY_SIZE, // 4 bytes
341 RADIOLIB_LORAWAN_SESSION_NONCES_SIGNATURE = RADIOLIB_LORAWAN_SESSION_DEV_ADDR + sizeof(uint32_t), // 2 bytes
342 RADIOLIB_LORAWAN_SESSION_FCNT_UP = RADIOLIB_LORAWAN_SESSION_NONCES_SIGNATURE + sizeof(uint16_t), // 4 bytes
343 RADIOLIB_LORAWAN_SESSION_N_FCNT_DOWN = RADIOLIB_LORAWAN_SESSION_FCNT_UP + sizeof(uint32_t), // 4 bytes
344 RADIOLIB_LORAWAN_SESSION_A_FCNT_DOWN = RADIOLIB_LORAWAN_SESSION_N_FCNT_DOWN + sizeof(uint32_t), // 4 bytes
345 RADIOLIB_LORAWAN_SESSION_ADR_FCNT = RADIOLIB_LORAWAN_SESSION_A_FCNT_DOWN + sizeof(uint32_t), // 4 bytes
346 RADIOLIB_LORAWAN_SESSION_CONF_FCNT_UP = RADIOLIB_LORAWAN_SESSION_ADR_FCNT + sizeof(uint32_t), // 4 bytes
347 RADIOLIB_LORAWAN_SESSION_CONF_FCNT_DOWN = RADIOLIB_LORAWAN_SESSION_CONF_FCNT_UP + sizeof(uint32_t), // 4 bytes
348 RADIOLIB_LORAWAN_SESSION_RJ_COUNT0 = RADIOLIB_LORAWAN_SESSION_CONF_FCNT_DOWN + sizeof(uint32_t), // 2 bytes
349 RADIOLIB_LORAWAN_SESSION_RJ_COUNT1 = RADIOLIB_LORAWAN_SESSION_RJ_COUNT0 + sizeof(uint16_t), // 2 bytes
350 RADIOLIB_LORAWAN_SESSION_HOMENET_ID = RADIOLIB_LORAWAN_SESSION_RJ_COUNT1 + sizeof(uint16_t), // 4 bytes
351 RADIOLIB_LORAWAN_SESSION_VERSION = RADIOLIB_LORAWAN_SESSION_HOMENET_ID + sizeof(uint32_t), // 1 byte
352 RADIOLIB_LORAWAN_SESSION_CLASS = RADIOLIB_LORAWAN_SESSION_VERSION + 1, // 1 byte
353 RADIOLIB_LORAWAN_SESSION_LINK_ADR = RADIOLIB_LORAWAN_SESSION_CLASS + sizeof(uint8_t), // 14 bytes
354 RADIOLIB_LORAWAN_SESSION_DUTY_CYCLE = RADIOLIB_LORAWAN_SESSION_LINK_ADR + 14, // 1 byte
355 RADIOLIB_LORAWAN_SESSION_RX_PARAM_SETUP = RADIOLIB_LORAWAN_SESSION_DUTY_CYCLE + 1, // 4 bytes
356 RADIOLIB_LORAWAN_SESSION_RX_TIMING_SETUP = RADIOLIB_LORAWAN_SESSION_RX_PARAM_SETUP + 4, // 1 byte
357 RADIOLIB_LORAWAN_SESSION_TX_PARAM_SETUP = RADIOLIB_LORAWAN_SESSION_RX_TIMING_SETUP + 1, // 1 byte
358 RADIOLIB_LORAWAN_SESSION_ADR_PARAM_SETUP = RADIOLIB_LORAWAN_SESSION_TX_PARAM_SETUP + 1, // 1 byte
359 RADIOLIB_LORAWAN_SESSION_REJOIN_PARAM_SETUP = RADIOLIB_LORAWAN_SESSION_ADR_PARAM_SETUP + 1, // 1 byte
360 RADIOLIB_LORAWAN_SESSION_UL_CHANNELS = RADIOLIB_LORAWAN_SESSION_REJOIN_PARAM_SETUP + 1, // 16*5 bytes
361 RADIOLIB_LORAWAN_SESSION_DL_CHANNELS = RADIOLIB_LORAWAN_SESSION_UL_CHANNELS + RADIOLIB_LORAWAN_NUM_AVAILABLE_CHANNELS*5, // 16*4 bytes
362 RADIOLIB_LORAWAN_SESSION_AVAILABLE_CHANNELS = RADIOLIB_LORAWAN_SESSION_DL_CHANNELS + RADIOLIB_LORAWAN_NUM_AVAILABLE_CHANNELS*4, // 2 bytes
363 RADIOLIB_LORAWAN_SESSION_MAC_QUEUE = RADIOLIB_LORAWAN_SESSION_AVAILABLE_CHANNELS + sizeof(uint16_t), // 15 bytes
364 RADIOLIB_LORAWAN_SESSION_MAC_QUEUE_LEN = RADIOLIB_LORAWAN_SESSION_MAC_QUEUE + RADIOLIB_LORAWAN_FHDR_FOPTS_MAX_LEN, // 1 byte
365 RADIOLIB_LORAWAN_SESSION_SIGNATURE = RADIOLIB_LORAWAN_SESSION_MAC_QUEUE_LEN + sizeof(uint8_t), // 2 bytes
366 RADIOLIB_LORAWAN_SESSION_BUF_SIZE = RADIOLIB_LORAWAN_SESSION_SIGNATURE + sizeof(uint16_t) // Session buffer size
367};
368
377
379 uint8_t idx;
380
382 uint32_t freq;
383
385 uint8_t drMin;
386
388 uint8_t drMax;
389
391 uint8_t dr;
392
395};
396
397// alias for unused channel
398#define RADIOLIB_LORAWAN_CHANNEL_NONE { .enabled = false, .idx = RADIOLIB_LORAWAN_CHANNEL_INDEX_NONE, .freq = 0, \
399 .drMin = 0, .drMax = 0, .dr = RADIOLIB_LORAWAN_DATA_RATE_UNUSED, .available = false }
400
408 uint8_t numChannels;
409
411 uint32_t freqStart;
412
414 uint32_t freqStep;
415
417 uint8_t drMin;
418
420 uint8_t drMax;
421
424};
425
426// alias for unused channel span
427#define RADIOLIB_LORAWAN_CHANNEL_SPAN_NONE { .numChannels = 0, .freqStart = 0, .freqStep = 0, .drMin = 0, .drMax = 0, .drJoinRequest = RADIOLIB_LORAWAN_DATA_RATE_UNUSED }
428
435 uint8_t bandNum;
436
438 uint8_t bandType;
439
441 uint32_t freqMin;
442
444 uint32_t freqMax;
445
447 uint8_t payloadLenMax[RADIOLIB_LORAWAN_CHANNEL_NUM_DATARATES];
448
450 int8_t powerMax;
451
454
457
460
463
466
469
471 uint8_t numTxSpans;
472
475
478
479 uint8_t rx1DrTable[RADIOLIB_LORAWAN_CHANNEL_NUM_DATARATES][8];
480
483
486
489
491 uint8_t dataRates[RADIOLIB_LORAWAN_CHANNEL_NUM_DATARATES];
492};
493
494// supported bands
495extern const LoRaWANBand_t EU868;
496extern const LoRaWANBand_t US915;
497extern const LoRaWANBand_t EU433;
498extern const LoRaWANBand_t AU915;
499extern const LoRaWANBand_t CN470;
500extern const LoRaWANBand_t AS923;
501extern const LoRaWANBand_t AS923_2;
502extern const LoRaWANBand_t AS923_3;
503extern const LoRaWANBand_t AS923_4;
504extern const LoRaWANBand_t KR920;
505extern const LoRaWANBand_t IN865;
506
511enum LoRaWANBandNum_t {
512 BandEU868,
513 BandUS915,
514 BandEU433,
515 BandAU915,
516 BandCN470,
517 BandAS923,
518 BandAS923_2,
519 BandAS923_3,
520 BandAS923_4,
521 BandKR920,
522 BandIN865,
523 BandLast
524};
525
526// provide easy access to the number of currently supported bands
527#define RADIOLIB_LORAWAN_NUM_SUPPORTED_BANDS (BandLast - BandEU868)
528
529// array of currently supported bands
530extern const LoRaWANBand_t* LoRaWANBands[];
531
538 bool newSession = false;
539
541 uint16_t devNonce = 0;
542
544 uint32_t joinNonce = 0;
545};
546
553 uint8_t dir;
554
557
561
564
566 uint8_t datarate;
567
569 float freq;
570
572 int16_t power;
573
575 uint32_t fCnt;
576
578 uint8_t fPort;
579
581 uint8_t nbTrans;
582
585};
586
592 public:
593
600 LoRaWANNode(PhysicalLayer* phy, const LoRaWANBand_t* band, uint8_t subBand = 0);
601
606 uint8_t* getBufferNonces();
607
613 int16_t setBufferNonces(const uint8_t* persistentBuffer);
614
618 void clearSession();
619
624 uint8_t* getBufferSession();
625
631 int16_t setBufferSession(const uint8_t* persistentBuffer);
632
641 int16_t beginOTAA(uint64_t joinEUI, uint64_t devEUI, const uint8_t* nwkKey, const uint8_t* appKey);
642
653 int16_t beginABP(uint32_t addr, const uint8_t* fNwkSIntKey, const uint8_t* sNwkSIntKey, const uint8_t* nwkSEncKey, const uint8_t* appSKey);
654
661 virtual int16_t activateOTAA(uint8_t initialDr = RADIOLIB_LORAWAN_DATA_RATE_UNUSED, LoRaWANJoinEvent_t *joinEvent = NULL);
662
669 virtual int16_t activateABP(uint8_t initialDr = RADIOLIB_LORAWAN_DATA_RATE_UNUSED);
670
672 bool isActivated();
673
675 int16_t setClass(uint8_t cls);
676
689 int16_t startMulticastSession(uint8_t cls, uint32_t mcAddr, const uint8_t* mcAppSKey, const uint8_t* mcNwkSKey, uint32_t mcFCntMin = 0, uint32_t mcFCntMax = 0xFFFFFFFF, uint32_t mcFreq = 0, uint8_t mcDr = RADIOLIB_LORAWAN_DATA_RATE_UNUSED);
690
693
694 #if defined(RADIOLIB_BUILD_ARDUINO)
707 virtual int16_t sendReceive(const String& strUp, uint8_t fPort, String& strDown, bool isConfirmed = false, LoRaWANEvent_t* eventUp = NULL, LoRaWANEvent_t* eventDown = NULL);
708 #endif
709
721 virtual int16_t sendReceive(const char* strUp, uint8_t fPort, bool isConfirmed = false, LoRaWANEvent_t* eventUp = NULL, LoRaWANEvent_t* eventDown = NULL);
722
736 virtual int16_t sendReceive(const char* strUp, uint8_t fPort, uint8_t* dataDown, size_t* lenDown, bool isConfirmed = false, LoRaWANEvent_t* eventUp = NULL, LoRaWANEvent_t* eventDown = NULL);
737
750 virtual int16_t sendReceive(const uint8_t* dataUp, size_t lenUp, uint8_t fPort = 1, bool isConfirmed = false, LoRaWANEvent_t* eventUp = NULL, LoRaWANEvent_t* eventDown = NULL);
751
766 virtual int16_t sendReceive(const uint8_t* dataUp, size_t lenUp, uint8_t fPort, uint8_t* dataDown, size_t* lenDown, bool isConfirmed = false, LoRaWANEvent_t* eventUp = NULL, LoRaWANEvent_t* eventDown = NULL);
767
776 int16_t getDownlinkClassC(uint8_t* dataDown, size_t* lenDown, LoRaWANEvent_t* eventDown = NULL);
777
785 int16_t sendMacCommandReq(uint8_t cid);
786
795 int16_t getMacLinkCheckAns(uint8_t* margin, uint8_t* gwCnt);
796
806 int16_t getMacDeviceTimeAns(uint32_t* gpsEpoch, uint8_t* fraction, bool returnUnix = true);
807
813 int16_t setDatarate(uint8_t drUp);
814
820 int16_t setTxPower(int8_t txPower);
821
828 int16_t setRx2Dr(uint8_t dr);
829
834 void setADR(bool enable = true);
835
842 void setDutyCycle(bool enable = true, RadioLibTime_t msPerHour = 0);
843
850 void setDwellTime(bool enable, RadioLibTime_t msPerUplink = 0);
851
859 void setCSMA(bool csmaEnabled, uint8_t maxChanges = 4, uint8_t backoffMax = 0, uint8_t difsSlots = 2);
860
866 void setDeviceStatus(uint8_t battLevel);
867
876
881 uint32_t getFCntUp();
882
887 uint32_t getNFCntDown();
888
893 uint32_t getAFCntDown();
894
900 void resetFCntDown();
901
906 uint32_t getDevAddr();
907
913
922
925
930 uint8_t getMaxPayloadLen();
931
933 typedef void (*SleepCb_t)(RadioLibTime_t ms);
934
942 void setSleepFunction(SleepCb_t cb);
943
955 int16_t addAppPackage(uint8_t packageId, PackageCb_t callback);
956
969 int16_t addAppPackage(uint8_t packageId, PackageCb_t callback, uint8_t fPort);
970
974 void removePackage(uint8_t packageId);
975
989
990#if !RADIOLIB_GODMODE
991 protected:
992#endif
993 PhysicalLayer* phyLayer = NULL;
994 const LoRaWANBand_t* band = NULL;
995
996 // a buffer that holds all LW base parameters that should persist at all times!
997 uint8_t bufferNonces[RADIOLIB_LORAWAN_NONCES_BUF_SIZE] = { 0 };
998
999 // a buffer that holds all LW session parameters that preferably persist, but can be afforded to get lost
1000 uint8_t bufferSession[RADIOLIB_LORAWAN_SESSION_BUF_SIZE] = { 0 };
1001
1002 uint8_t fOptsUp[RADIOLIB_LORAWAN_FHDR_FOPTS_MAX_LEN] = { 0 };
1003 uint8_t fOptsDown[RADIOLIB_LORAWAN_FHDR_FOPTS_MAX_LEN] = { 0 };
1004 uint8_t fOptsUpLen = 0;
1005 uint8_t fOptsDownLen = 0;
1006
1007 uint16_t lwMode = RADIOLIB_LORAWAN_MODE_NONE;
1008 uint8_t lwClass = RADIOLIB_LORAWAN_CLASS_A;
1009 bool isActive = false;
1010
1011 uint64_t joinEUI = 0;
1012 uint64_t devEUI = 0;
1013 uint8_t nwkKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1014 uint8_t appKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1015
1016 // the following is either provided by the network server (OTAA)
1017 // or directly entered by the user (ABP)
1018 uint32_t devAddr = 0;
1019 uint8_t appSKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1020 uint8_t fNwkSIntKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1021 uint8_t sNwkSIntKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1022 uint8_t nwkSEncKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1023 uint8_t jSIntKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1024
1025 uint16_t keyCheckSum = 0;
1026
1027 // device-specific parameters, persistent through sessions
1028 uint16_t devNonce = 0;
1029 uint32_t joinNonce = 0;
1030
1031 // session-specific parameters
1032 uint32_t homeNetId = 0;
1033 uint8_t adrLimitExp = RADIOLIB_LORAWAN_ADR_ACK_LIMIT_EXP;
1034 uint8_t adrDelayExp = RADIOLIB_LORAWAN_ADR_ACK_DELAY_EXP;
1035 uint8_t nbTrans = 1; // Number of allowed frame retransmissions
1036 uint8_t txPowerSteps = 0;
1037 uint8_t txPowerMax = 0;
1038 uint32_t fCntUp = 0;
1039 uint32_t aFCntDown = 0;
1040 uint32_t nFCntDown = 0;
1041 uint32_t confFCntUp = RADIOLIB_LORAWAN_FCNT_NONE;
1042 uint32_t confFCntDown = RADIOLIB_LORAWAN_FCNT_NONE;
1043 uint32_t adrFCnt = 0;
1044
1045 // ADR is enabled by default
1046 bool adrEnabled = true;
1047
1048 // duty cycle is set upon initialization and activated in regions that impose this
1049 bool dutyCycleEnabled = false;
1050 uint32_t dutyCycle = 0;
1051
1052 // dwell time is set upon initialization and activated in regions that impose this
1053 uint16_t dwellTimeUp = 0;
1054 uint16_t dwellTimeDn = 0;
1055
1056 RadioLibTime_t tUplink = 0; // scheduled uplink transmission time (internal clock)
1057 RadioLibTime_t tDownlink = 0; // time at end of downlink reception
1058
1059 // multicast parameters
1060 uint8_t multicast = false;
1061 uint32_t mcAddr = 0;
1062 uint8_t mcAppSKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1063 uint8_t mcNwkSKey[RADIOLIB_AES128_KEY_SIZE] = { 0 };
1064 uint32_t mcAFCnt = 0;
1065 uint32_t mcAFCntMax = 0;
1066
1067 // enabled TS packages
1068 LoRaWANPackage_t packages[RADIOLIB_LORAWAN_NUM_SUPPORTED_PACKAGES];
1069
1070 // enable/disable CSMA for LoRaWAN
1071 bool csmaEnabled = false;
1072
1073 // maximum number of channel hops during CSMA
1074 uint8_t maxChanges = RADIOLIB_LORAWAN_MAX_CHANGES_DEFAULT;
1075
1076 // number of backoff slots to be checked after DIFS phase.
1077 // A random BO avoids collisions in the case where two or more nodes start the CSMA
1078 // process at the same time.
1079 uint8_t backoffMax = RADIOLIB_LORAWAN_BACKOFF_MAX_DEFAULT;
1080
1081 // number of CADs to estimate a clear channel
1082 uint8_t difsSlots = RADIOLIB_LORAWAN_DIFS_DEFAULT;
1083
1084 // available channel frequencies from list passed during OTA activation
1085 LoRaWANChannel_t channelPlan[2][RADIOLIB_LORAWAN_NUM_AVAILABLE_CHANNELS];
1086
1087 // currently configured channels for Tx, Rx1, Rx2, RxBC
1088 LoRaWANChannel_t channels[4] = { RADIOLIB_LORAWAN_CHANNEL_NONE, RADIOLIB_LORAWAN_CHANNEL_NONE,
1089 RADIOLIB_LORAWAN_CHANNEL_NONE, RADIOLIB_LORAWAN_CHANNEL_NONE };
1090
1091 // delays between the uplink and Rx1/2 windows
1092 // the first field is meaningless, but is used for offsetting for Rx windows 1 and 2
1093 RadioLibTime_t rxDelays[3] = { 0, RADIOLIB_LORAWAN_RECEIVE_DELAY_1_MS, RADIOLIB_LORAWAN_RECEIVE_DELAY_2_MS };
1094
1095 // offset between Tx and Rx1 (such that Rx1 has equal or lower DR)
1096 uint8_t rx1DrOffset = 0;
1097
1098 // LoRaWAN revision (1.0 vs 1.1)
1099 uint8_t rev = 0;
1100
1101 // Time on Air of last uplink
1102 RadioLibTime_t lastToA = 0;
1103
1104 // timestamp to measure the Rx1/2 delay (from uplink end)
1105 RadioLibTime_t rxDelayStart = 0;
1106
1107 // duration of SPI transaction for phyLayer->launchMode()
1108 RadioLibTime_t launchDuration = 0;
1109
1110 // device status - battery level
1111 uint8_t battLevel = 0xFF;
1112
1113 // indicates whether an uplink has MAC commands as payload
1114 bool isMACPayload = false;
1115
1116 // save the selected sub-band in case this must be restored in ADR control
1117 uint8_t subBand = 0;
1118
1119 // user-provided sleep callback
1120 SleepCb_t sleepCb = nullptr;
1121
1122 // this will reset the device credentials, so the device starts completely new
1123 void clearNonces();
1124
1125 // start a fresh session using default parameters
1126 void createSession(uint16_t lwMode, uint8_t initialDr);
1127
1128 // setup Join-Request payload
1129 void composeJoinRequest(uint8_t* joinRequestMsg);
1130
1131 // extract Join-Accept payload and start a new session
1132 int16_t processJoinAccept(LoRaWANJoinEvent_t *joinEvent);
1133
1134 // a join-accept can piggy-back a set of channels or channel masks
1135 void processCFList(const uint8_t* cfList);
1136
1137 // check whether payload length and fport are allowed
1138 int16_t isValidUplink(size_t len, uint8_t fPort);
1139
1140 // perform ADR backoff
1141 void adrBackoff();
1142
1143 // create an encrypted uplink buffer, composing metadata, user data and MAC data
1144 void composeUplink(const uint8_t* in, uint8_t lenIn, uint8_t* out, uint8_t fPort, bool isConfirmed);
1145
1146 // generate and set the MIC of an uplink buffer (depends on selected channels)
1147 void micUplink(uint8_t* inOut, size_t lenInOut);
1148
1149 // transmit uplink buffer on a specified channel
1150 int16_t transmitUplink(const LoRaWANChannel_t* chnl, uint8_t* in, uint8_t len, bool retrans = false);
1151
1152 // handle one of the Class A receive windows with a given channel and certain timestamps
1153 int16_t receiveClassA(uint8_t dir, const LoRaWANChannel_t* dlChannel, uint8_t window, const RadioLibTime_t dlDelay, RadioLibTime_t tReference);
1154
1155 // handle a Class C receive window with timeout (between Class A windows) or without (between uplinks)
1156 int16_t receiveClassC(RadioLibTime_t timeout = 0);
1157
1158 // open a series of Class A (and C) downlinks
1159 int16_t receiveDownlink();
1160
1161 // extract downlink payload and process MAC commands
1162 int16_t parseDownlink(uint8_t* data, size_t* len, uint8_t window, LoRaWANEvent_t* event = NULL);
1163
1164 // add a LoRaWAN package that runs through the network layer
1165 // (not available to users, they are only allowed to add application packages)
1166 int16_t addNwkPackage(uint8_t packageId, PackageCb_t callback);
1167
1168 // execute mac command, return the number of processed bytes for sequential processing
1169 bool execMacCommand(uint8_t cid, uint8_t* optIn, uint8_t lenIn);
1170 bool execMacCommand(uint8_t cid, uint8_t* optIn, uint8_t lenIn, uint8_t* optOut);
1171
1172 // possible override for additional MAC commands that are not in the base specification
1173 virtual bool derivedMacHandler(uint8_t cid, uint8_t* optIn, uint8_t lenIn, uint8_t* optOut);
1174
1175 // pre-process a (set of) LinkAdrReq commands into one super-channel-mask + Tx/Dr/NbTrans fields
1176 void preprocessMacLinkAdr(uint8_t* mPtr, uint8_t cLen, uint8_t* mAdrOpt);
1177
1178 // post-process a (set of) LinkAdrAns commands depending on LoRaWAN version
1179 void postprocessMacLinkAdr(uint8_t* ack, uint8_t cLen);
1180
1181 // get the properties of a MAC command given a certain command ID
1182 int16_t getMacCommand(uint8_t cid, LoRaWANMacCommand_t* cmd);
1183
1184 // possible override for additional MAC commands that are not in the base specification
1185 virtual int16_t derivedMacFinder(uint8_t cid, LoRaWANMacCommand_t* cmd);
1186
1187 // get the length of a certain MAC command in a specific direction (up/down)
1188 // if inclusive is true, add one for the CID byte
1189 // include payload in case the MAC command has a dynamic length
1190 virtual int16_t getMacLen(uint8_t cid, uint8_t* len, uint8_t dir, bool inclusive = false, uint8_t* payload = NULL);
1191
1192 // find out of a MAC command should persist destruction
1193 // in uplink direction, some commands must persist if no downlink is received
1194 // in downlink direction, the user-accessible MAC commands remain available for retrieval
1195 bool isPersistentMacCommand(uint8_t cid, uint8_t dir);
1196
1197 // push MAC command to queue, done by copy
1198 int16_t pushMacCommand(uint8_t cid, const uint8_t* cOcts, uint8_t* out, uint8_t* lenOut, uint8_t dir);
1199
1200 // retrieve the payload of a certain MAC command, if present in the buffer
1201 int16_t getMacPayload(uint8_t cid, const uint8_t* in, uint8_t lenIn, uint8_t* out, uint8_t dir);
1202
1203 // delete a specific MAC command from queue, indicated by the command ID
1204 int16_t deleteMacCommand(uint8_t cid, uint8_t* inOut, uint8_t* lenInOut, uint8_t dir);
1205
1206 // clear a MAC buffer, possible retaining persistent MAC commands
1207 void clearMacCommands(uint8_t* inOut, uint8_t* lenInOut, uint8_t dir);
1208
1209 // configure the common physical layer properties (frequency, sync word etc.)
1210 int16_t setPhyProperties(const LoRaWANChannel_t* chnl, uint8_t dir, int8_t pwr, size_t pre = 0);
1211
1212 // Performs CSMA as per LoRa Alliance Technical Recommendation 13 (TR-013).
1213 bool csmaChannelClear(uint8_t difs, uint8_t numBackoff);
1214
1215 // perform a single CAD operation for the under SF/CH combination. Returns either busy or otherwise.
1216 bool cadChannelClear();
1217
1218 // (dynamic bands:) get or (fixed bands:) create a complete 80-bit channel mask for current configuration
1219 void getChannelPlanMask(uint64_t* chMaskGrp0123, uint32_t* chMaskGrp45);
1220
1221 // setup uplink/downlink channel data rates and frequencies
1222 // for dynamic channels, there is a small set of predefined channels
1223 // in case of JoinRequest, add some optional extra frequencies
1224 void selectChannelPlanDyn();
1225
1226 // setup uplink/downlink channel data rates and frequencies
1227 // for fixed bands, we only allow one sub-band at a time to be selected
1228 void selectChannelPlanFix();
1229
1230 // get the number of available channels,
1231 // along with a 16-bit mask indicating which channels can be used next for uplink/downlink
1232 uint8_t getAvailableChannels(uint16_t* mask);
1233
1234 // (re)set/restore which channels can be used next for uplink/downlink
1235 void setAvailableChannels(uint16_t mask);
1236
1237 // select a set of random TX/RX channels for up- and downlink
1238 int16_t selectChannels();
1239
1240 // apply a 96-bit channel mask
1241 bool applyChannelMask(uint64_t chMaskGrp0123, uint32_t chMaskGrp45);
1242
1243#if RADIOLIB_DEBUG_PROTOCOL
1244 // print the available channels through debug
1245 void printChannels();
1246#endif
1247
1248 // method to generate message integrity code
1249 uint32_t generateMIC(const uint8_t* msg, size_t len, uint8_t* key);
1250
1251 // method to verify message integrity code
1252 // it assumes that the MIC is the last 4 bytes of the message
1253 bool verifyMIC(uint8_t* msg, size_t len, uint8_t* key);
1254
1255 // find the first usable data rate for the given band
1256 int16_t findDataRate(uint8_t dr, DataRate_t* dataRate);
1257
1258 // function to encrypt and decrypt payloads (regular uplink/downlink)
1259 void processAES(const uint8_t* in, size_t len, uint8_t* key, uint8_t* out, uint32_t addr, uint32_t fCnt, uint8_t dir, uint8_t ctrId, bool counter);
1260
1261 // function that allows sleeping via user-provided callback
1262 void sleepDelay(RadioLibTime_t ms);
1263
1264 // 16-bit checksum method that takes a uint8_t array of even length and calculates the checksum
1265 static uint16_t checkSum16(const uint8_t *key, uint16_t keyLen);
1266
1267 // check the integrity of a buffer using a 16-bit checksum located in the last two bytes of the buffer
1268 static int16_t checkBufferCommon(const uint8_t *buffer, uint16_t size);
1269
1270 // network-to-host conversion method - takes data from network packet and converts it to the host endians
1271 template<typename T>
1272 static T ntoh(const uint8_t* buff, size_t size = 0);
1273
1274 // host-to-network conversion method - takes data from host variable and and converts it to network packet endians
1275 template<typename T>
1276 static void hton(uint8_t* buff, T val, size_t size = 0);
1277};
1278
1279template<typename T>
1280T LoRaWANNode::ntoh(const uint8_t* buff, size_t size) {
1281 const uint8_t* buffPtr = buff;
1282 size_t targetSize = sizeof(T);
1283 if(size != 0) {
1284 targetSize = size;
1285 }
1286 T res = 0;
1287 for(size_t i = 0; i < targetSize; i++) {
1288 res |= (uint32_t)(*(buffPtr++)) << 8*i;
1289 }
1290 return(res);
1291}
1292
1293template<typename T>
1294void LoRaWANNode::hton(uint8_t* buff, T val, size_t size) {
1295 uint8_t* buffPtr = buff;
1296 size_t targetSize = sizeof(T);
1297 if(size != 0) {
1298 targetSize = size;
1299 }
1300 for(size_t i = 0; i < targetSize; i++) {
1301 *(buffPtr++) = val >> 8*i;
1302 }
1303}
1304
1305#endif
LoRaWAN-compatible node (class A device).
Definition LoRaWAN.h:591
void clearSession()
Clear an active session, so that the device will have to rejoin the network.
Definition LoRaWAN.cpp:306
virtual int16_t sendReceive(const char *strUp, uint8_t fPort, bool isConfirmed=false, LoRaWANEvent_t *eventUp=NULL, LoRaWANEvent_t *eventDown=NULL)
Send a message to the server and wait for a downlink during Rx1 and/or Rx2 window.
Definition LoRaWAN.cpp:47
void setSleepFunction(SleepCb_t cb)
Set custom delay/sleep function callback. If set, LoRaWAN node will call this function to wait for pe...
Definition LoRaWAN.cpp:3671
int16_t startMulticastSession(uint8_t cls, uint32_t mcAddr, const uint8_t *mcAppSKey, const uint8_t *mcNwkSKey, uint32_t mcFCntMin=0, uint32_t mcFCntMax=0xFFFFFFFF, uint32_t mcFreq=0, uint8_t mcDr=RADIOLIB_LORAWAN_DATA_RATE_UNUSED)
Start a Multicast session.
Definition LoRaWAN.cpp:1087
int16_t setDatarate(uint8_t drUp)
Set uplink datarate. This should not be used when ADR is enabled.
Definition LoRaWAN.cpp:2983
void scheduleTransmission(RadioLibTime_t tUplink)
Set the exact time a transmission should occur. Note: this is the internal clock time....
Definition LoRaWAN.cpp:3118
RadioLibTime_t scanGuard
Rx window padding in milliseconds according to the spec, the Rx window must be at least enough time t...
Definition LoRaWAN.h:988
void setCSMA(bool csmaEnabled, uint8_t maxChanges=4, uint8_t backoffMax=0, uint8_t difsSlots=2)
Configures CSMA for LoRaWAN as per TR013, LoRa Alliance.
Definition LoRaWAN.cpp:3100
void(* SleepCb_t)(RadioLibTime_t ms)
Callback to a user-provided sleep function.
Definition LoRaWAN.h:933
int16_t addAppPackage(uint8_t packageId, PackageCb_t callback)
Add a LoRaWAN Application Package as defined in one of the TSxxx documents. Any downlinks that occur ...
Definition LoRaWAN.cpp:3675
void setDutyCycle(bool enable=true, RadioLibTime_t msPerHour=0)
Toggle adherence to dutyCycle limits to on or off.
Definition LoRaWAN.cpp:3074
int16_t beginABP(uint32_t addr, const uint8_t *fNwkSIntKey, const uint8_t *sNwkSIntKey, const uint8_t *nwkSEncKey, const uint8_t *appSKey)
Set the device credentials and activation configuration.
Definition LoRaWAN.cpp:645
RadioLibTime_t timeUntilUplink()
Returns time in milliseconds until next uplink is available under dutyCycle limits.
Definition LoRaWAN.cpp:3623
int16_t getDownlinkClassC(uint8_t *dataDown, size_t *lenDown, LoRaWANEvent_t *eventDown=NULL)
Check if there is an RxC downlink and parse it if available.
Definition LoRaWAN.cpp:2149
void stopMulticastSession()
Stop an ongoing multicast session.
Definition LoRaWAN.cpp:1139
void setDeviceStatus(uint8_t battLevel)
Set device status.
Definition LoRaWAN.cpp:3114
RadioLibTime_t dutyCycleInterval(RadioLibTime_t msPerHour, RadioLibTime_t airtime)
Calculate the minimum interval to adhere to a certain dutyCycle. This interval is based on the ToA of...
Definition LoRaWAN.cpp:3613
void setDwellTime(bool enable, RadioLibTime_t msPerUplink=0)
Set or disable uplink dwell time limitation; enabled by default if mandatory.
Definition LoRaWAN.cpp:3087
uint32_t getAFCntDown()
Returns the last application downlink's frame counter; also 0 if no application downlink occured yet.
Definition LoRaWAN.cpp:3134
RadioLibTime_t getLastToA()
Get the Time-on-air of the last uplink message (in milliseconds).
Definition LoRaWAN.cpp:3147
virtual int16_t activateABP(uint8_t initialDr=RADIOLIB_LORAWAN_DATA_RATE_UNUSED)
Join network by restoring ABP session or performing over-the-air activation. In this procedure,...
Definition LoRaWAN.cpp:964
uint8_t * getBufferNonces()
Returns the pointer to the internal buffer that holds the LW base parameters.
Definition LoRaWAN.cpp:257
uint8_t * getBufferSession()
Returns the pointer to the internal buffer that holds the LW session parameters.
Definition LoRaWAN.cpp:459
bool isActivated()
Whether there is an ongoing session active.
Definition LoRaWAN.cpp:1054
int16_t setTxPower(int8_t txPower)
Configure TX power of the radio module.
Definition LoRaWAN.cpp:3016
int16_t getMacDeviceTimeAns(uint32_t *gpsEpoch, uint8_t *fraction, bool returnUnix=true)
Returns the network time after requesting a DeviceTime MAC command. Returns 'true' if a network respo...
Definition LoRaWAN.cpp:2829
uint32_t getNFCntDown()
Returns the last network downlink's frame counter; also 0 if no network downlink occured yet.
Definition LoRaWAN.cpp:3130
int16_t setClass(uint8_t cls)
Configure class (RADIOLIB_LORAWAN_CLASS_A or RADIOLIB_LORAWAN_CLASS_C)
Definition LoRaWAN.cpp:1058
int16_t beginOTAA(uint64_t joinEUI, uint64_t devEUI, const uint8_t *nwkKey, const uint8_t *appKey)
Set the device credentials and activation configuration.
Definition LoRaWAN.cpp:617
uint8_t getMaxPayloadLen()
Returns the maximum allowed uplink payload size given the current MAC state. Most importantly,...
Definition LoRaWAN.cpp:3632
virtual int16_t activateOTAA(uint8_t initialDr=RADIOLIB_LORAWAN_DATA_RATE_UNUSED, LoRaWANJoinEvent_t *joinEvent=NULL)
Join network by restoring OTAA session or performing over-the-air activation. By this procedure,...
Definition LoRaWAN.cpp:903
uint32_t getFCntUp()
Returns the last uplink's frame counter; also 0 if no uplink occured yet.
Definition LoRaWAN.cpp:3123
int16_t setBufferNonces(const uint8_t *persistentBuffer)
Fill the internal buffer that holds the LW base parameters with a supplied buffer.
Definition LoRaWAN.cpp:271
int16_t setRx2Dr(uint8_t dr)
Configure the Rx2 datarate for ABP mode. This should not be needed for LoRaWAN 1.1 as it is configure...
Definition LoRaWAN.cpp:3042
int16_t sendMacCommandReq(uint8_t cid)
Add a MAC command to the uplink queue. Only LinkCheck and DeviceTime are available to the user....
Definition LoRaWAN.cpp:2794
int16_t getMacLinkCheckAns(uint8_t *margin, uint8_t *gwCnt)
Returns the quality of connectivity after requesting a LinkCheck MAC command. Returns 'true' if a net...
Definition LoRaWAN.cpp:2818
void setADR(bool enable=true)
Toggle ADR to on or off.
Definition LoRaWAN.cpp:3070
int16_t setBufferSession(const uint8_t *persistentBuffer)
Fill the internal buffer that holds the LW session parameters with a supplied buffer.
Definition LoRaWAN.cpp:492
uint32_t getDevAddr()
Returns the DevAddr of the device, regardless of OTAA or ABP mode.
Definition LoRaWAN.cpp:3143
void resetFCntDown()
Reset the downlink frame counters (application and network) This is unsafe and can possibly allow rep...
Definition LoRaWAN.cpp:3138
void removePackage(uint8_t packageId)
Disable a package that was previously added.
Definition LoRaWAN.cpp:3718
Provides common interface for protocols that run on LoRa/FSK modules, such as RTTY or LoRaWAN....
Definition PhysicalLayer.h:216
unsigned long RadioLibTime_t
Type used for durations in RadioLib.
Definition TypeDef.h:642
Structure to save information about LoRaWAN band.
Definition LoRaWAN.h:433
int8_t powerMax
Maximum allowed output power in this band in dBm.
Definition LoRaWAN.h:450
bool txParamSupported
Whether this band implements the MAC command TxParamSetupReq.
Definition LoRaWAN.h:465
LoRaWANChannel_t txAck[2]
Relay channels for ACK downlink.
Definition LoRaWAN.h:488
RadioLibTime_t dutyCycle
Number of milliseconds per hour of allowed Time-on-Air.
Definition LoRaWAN.h:456
uint8_t dataRates[RADIOLIB_LORAWAN_CHANNEL_NUM_DATARATES]
The corresponding datarates, bandwidths and coding rates for DR index.
Definition LoRaWAN.h:491
RadioLibTime_t dwellTimeUp
Maximum dwell time per uplink message in milliseconds.
Definition LoRaWAN.h:459
LoRaWANChannel_t txWoR[2]
Relay channels for WoR uplink.
Definition LoRaWAN.h:485
uint32_t freqMin
Minimum allowed frequency (coded in 100 Hz steps)
Definition LoRaWAN.h:441
uint8_t payloadLenMax[RADIOLIB_LORAWAN_CHANNEL_NUM_DATARATES]
Array of allowed maximum application payload lengths for each data rate (N-value)
Definition LoRaWAN.h:447
LoRaWANChannel_t txFreqs[3]
A set of default uplink (TX) channels for dynamic bands.
Definition LoRaWAN.h:468
int8_t powerNumSteps
Number of power steps in this band.
Definition LoRaWAN.h:453
LoRaWANChannelSpan_t txSpans[2]
Default uplink (TX) channel spans for fixed bands, including Join-Request parameters.
Definition LoRaWAN.h:474
uint8_t bandNum
Identier for this band.
Definition LoRaWAN.h:435
uint32_t freqMax
Maximum allowed frequency (coded in 100 Hz steps)
Definition LoRaWAN.h:444
uint8_t bandType
Whether the channels are fixed per specification, or dynamically allocated through the network (plus ...
Definition LoRaWAN.h:438
LoRaWANChannel_t rx2
Backup channel for downlink (RX2) window.
Definition LoRaWAN.h:482
uint8_t numTxSpans
The number of TX channel spans for fixed bands.
Definition LoRaWAN.h:471
RadioLibTime_t dwellTimeDn
Maximum dwell time per downlink message in milliseconds.
Definition LoRaWAN.h:462
LoRaWANChannelSpan_t rx1Span
Default downlink (RX1) channel span for fixed bands.
Definition LoRaWAN.h:477
IDs of all currently supported bands.
Structure to save information about LoRaWAN channels. To save space, adjacent channels are saved in "...
Definition LoRaWAN.h:374
bool available
Whether this channel is available for channel selection.
Definition LoRaWAN.h:394
uint8_t dr
Datarate currently in use on this channel.
Definition LoRaWAN.h:391
uint32_t freq
The channel frequency (coded in 100 Hz steps)
Definition LoRaWAN.h:382
uint8_t idx
The channel number, as specified by defaults or the network.
Definition LoRaWAN.h:379
uint8_t drMin
Minimum allowed datarate for this channel.
Definition LoRaWAN.h:385
bool enabled
Whether this channel is enabled (can be used) or is disabled.
Definition LoRaWAN.h:376
uint8_t drMax
Maximum allowed datarate for this channel (inclusive)
Definition LoRaWAN.h:388
Structure to save information about LoRaWAN channels. To save space, adjacent channels are saved in "...
Definition LoRaWAN.h:406
uint8_t drJoinRequest
Allowed data rates for a join request message.
Definition LoRaWAN.h:423
uint32_t freqStart
Center frequency of the first channel in span (coded in 100 Hz steps)
Definition LoRaWAN.h:411
uint8_t numChannels
Total number of channels in the span.
Definition LoRaWAN.h:408
uint8_t drMax
Maximum allowed datarate for all channels in this span (inclusive)
Definition LoRaWAN.h:420
uint32_t freqStep
Frequency step between adjacent channels (coded in 100 Hz steps)
Definition LoRaWAN.h:414
uint8_t drMin
Minimum allowed datarate for all channels in this span.
Definition LoRaWAN.h:417
Structure to save extra information about uplink/downlink event.
Definition LoRaWAN.h:551
float freq
Frequency in MHz.
Definition LoRaWAN.h:569
bool confirmed
Whether the event is confirmed or not (e.g., confirmed uplink sent by user application)
Definition LoRaWAN.h:556
uint8_t fPort
Port number.
Definition LoRaWAN.h:578
int16_t power
Transmit power in dBm for uplink, or RSSI for downlink.
Definition LoRaWAN.h:572
bool confirming
Whether the event is confirming a previous request (e.g., server downlink reply to confirmed uplink s...
Definition LoRaWAN.h:560
uint8_t datarate
Datarate.
Definition LoRaWAN.h:566
uint8_t dir
Event direction, one of RADIOLIB_LORAWAN_CHANNEL_DIR_*.
Definition LoRaWAN.h:553
uint8_t nbTrans
Number of times this uplink was transmitted (ADR)
Definition LoRaWAN.h:581
uint32_t fCnt
The appropriate frame counter - for different events, different frame counters will be reported!
Definition LoRaWAN.h:575
bool multicast
Multicast or unicast.
Definition LoRaWAN.h:584
bool frmPending
Whether further downlink messages are pending on the server side.
Definition LoRaWAN.h:563
Structure to save extra information about activation event.
Definition LoRaWAN.h:536
bool newSession
Whether a new session was started.
Definition LoRaWAN.h:538
uint32_t joinNonce
The received Join-Request JoinNonce value.
Definition LoRaWAN.h:544
uint16_t devNonce
The transmitted Join-Request DevNonce value.
Definition LoRaWAN.h:541
MAC command specification structure.
Definition LoRaWAN.h:241
const uint8_t lenDn
Uplink message length.
Definition LoRaWAN.h:246
const bool user
Whether this MAC command can be issued by the user or not.
Definition LoRaWAN.h:255
const uint8_t cid
Command ID.
Definition LoRaWAN.h:243
const uint8_t lenUp
Downlink message length.
Definition LoRaWAN.h:249
const bool persist
Some commands must be resent until Class A downlink received.
Definition LoRaWAN.h:252
LoRaWAN Packages structure (for TSxxx documents).
Definition LoRaWAN.h:287
uint8_t packId
Package ID as per TS008.
Definition LoRaWAN.h:289
uint8_t packFPort
Package default FPort (specified or recommended)
Definition LoRaWAN.h:292
bool isAppPack
Whether the package runs through the Application layer.
Definition LoRaWAN.h:295
bool enabled
Whether the package is currently in use.
Definition LoRaWAN.h:301
PackageCb_t callback
User-provided callback for handling package downlinks.
Definition LoRaWAN.h:304
bool fixedFPort
Whether the FPort value is fixed or may be modified.
Definition LoRaWAN.h:298
Common data rate structure.
Definition PhysicalLayer.h:74