1 /*!
2 * \file main.c
3 *
4 * \brief Performs a periodic uplink
5 *
6 * \copyright Revised BSD License, see section \ref LICENSE.
7 *
8 * \code
9 * ______ _
10 * / _____) _ | |
11 * ( (____ _____ ____ _| |_ _____ ____| |__
12 * \____ \| ___ | (_ _) ___ |/ ___) _ \
13 * _____) ) ____| | | || |_| ____( (___| | | |
14 * (______/|_____)_|_|_| \__)_____)\____)_| |_|
15 * (C)2013-2018 Semtech
16 *
17 * \endcode
18 *
19 * \author Miguel Luis ( Semtech )
20 */
21
22 /*! \file periodic-uplink/SAMR34/main.c */
23
24 #include <stdio.h>
25 #include "../firmwareVersion.h"
26 #include "../../common/githubVersion.h"
27 #include "utilities.h"
28 #include "board.h"
29 #include "gpio.h"
30 #include "uart.h"
31 #include "RegionCommon.h"
32
33 #include "cli.h"
34 #include "Commissioning.h"
35 #include "LmHandler.h"
36 #include "LmhpCompliance.h"
37 #include "CayenneLpp.h"
38 #include "LmHandlerMsgDisplay.h"
39
40 #ifndef ACTIVE_REGION
41
42 #warning "No active region defined, LORAMAC_REGION_EU868 will be used as default."
43
44 #define ACTIVE_REGION LORAMAC_REGION_EU868
45
46 #endif
47
48 /*!
49 * LoRaWAN default end-device class
50 */
51 #ifndef LORAWAN_DEFAULT_CLASS
52 #define LORAWAN_DEFAULT_CLASS CLASS_A
53 #endif
54
55 /*!
56 * Defines the application data transmission duty cycle. 5s, value in [ms].
57 */
58 #define APP_TX_DUTYCYCLE 5000
59
60 /*!
61 * Defines a random delay for application data transmission duty cycle. 1s,
62 * value in [ms].
63 */
64 #define APP_TX_DUTYCYCLE_RND 1000
65
66 /*!
67 * LoRaWAN Adaptive Data Rate
68 *
69 * \remark Please note that when ADR is enabled the end-device should be static
70 */
71 #define LORAWAN_ADR_STATE LORAMAC_HANDLER_ADR_ON
72
73 /*!
74 * Default datarate
75 *
76 * \remark Please note that LORAWAN_DEFAULT_DATARATE is used only when ADR is disabled
77 */
78 #define LORAWAN_DEFAULT_DATARATE DR_0
79
80 /*!
81 * LoRaWAN confirmed messages
82 */
83 #define LORAWAN_DEFAULT_CONFIRMED_MSG_STATE LORAMAC_HANDLER_UNCONFIRMED_MSG
84
85 /*!
86 * User application data buffer size
87 */
88 #define LORAWAN_APP_DATA_BUFFER_MAX_SIZE 242
89
90 /*!
91 * LoRaWAN ETSI duty cycle control enable/disable
92 *
93 * \remark Please note that ETSI mandates duty cycled transmissions. Use only for test purposes
94 */
95 #define LORAWAN_DUTYCYCLE_ON true
96
97 /*!
98 * LoRaWAN application port
99 * @remark The allowed port range is from 1 up to 223. Other values are reserved.
100 */
101 #define LORAWAN_APP_PORT 2
102
103 /*!
104 *
105 */
106 typedef enum
107 {
108 LORAMAC_HANDLER_TX_ON_TIMER,
109 LORAMAC_HANDLER_TX_ON_EVENT,
110 }LmHandlerTxEvents_t;
111
112 /*!
113 * User application data
114 */
115 static uint8_t AppDataBuffer[LORAWAN_APP_DATA_BUFFER_MAX_SIZE];
116
117 /*!
118 * User application data structure
119 */
120 static LmHandlerAppData_t AppData =
121 {
122 .Buffer = AppDataBuffer,
123 .BufferSize = 0,
124 .Port = 0,
125 };
126
127 /*!
128 * Specifies the state of the application LED
129 */
130 static bool AppLedStateOn = false;
131
132 /*!
133 * Timer to handle the application data transmission duty cycle
134 */
135 static TimerEvent_t TxTimer;
136
137 /*!
138 * Timer to handle the state of LED1
139 */
140 static TimerEvent_t Led1Timer;
141
142 /*!
143 * Timer to handle the state of LED2
144 */
145 static TimerEvent_t Led2Timer;
146
147 /*!
148 * Timer to handle the state of LED beacon indicator
149 */
150 static TimerEvent_t LedBeaconTimer;
151
152 static void OnMacProcessNotify( void );
153 static void OnNvmDataChange( LmHandlerNvmContextStates_t state, uint16_t size );
154 static void OnNetworkParametersChange( CommissioningParams_t* params );
155 static void OnMacMcpsRequest( LoRaMacStatus_t status, McpsReq_t *mcpsReq, TimerTime_t nextTxIn );
156 static void OnMacMlmeRequest( LoRaMacStatus_t status, MlmeReq_t *mlmeReq, TimerTime_t nextTxIn );
157 static void OnJoinRequest( LmHandlerJoinParams_t* params );
158 static void OnTxData( LmHandlerTxParams_t* params );
159 static void OnRxData( LmHandlerAppData_t* appData, LmHandlerRxParams_t* params );
160 static void OnClassChange( DeviceClass_t deviceClass );
161 static void OnBeaconStatusChange( LoRaMacHandlerBeaconParams_t* params );
162 #if( LMH_SYS_TIME_UPDATE_NEW_API == 1 )
163 static void OnSysTimeUpdate( bool isSynchronized, int32_t timeCorrection );
164 #else
165 static void OnSysTimeUpdate( void );
166 #endif
167 static void PrepareTxFrame( void );
168 static void StartTxProcess( LmHandlerTxEvents_t txEvent );
169 static void UplinkProcess( void );
170
171 static void OnTxPeriodicityChanged( uint32_t periodicity );
172 static void OnTxFrameCtrlChanged( LmHandlerMsgTypes_t isTxConfirmed );
173 static void OnPingSlotPeriodicityChanged( uint8_t pingSlotPeriodicity );
174
175 /*!
176 * Function executed on TxTimer event
177 */
178 static void OnTxTimerEvent( void* context );
179
180 /*!
181 * Function executed on Led 1 Timeout event
182 */
183 static void OnLed1TimerEvent( void* context );
184
185 /*!
186 * Function executed on Led 2 Timeout event
187 */
188 static void OnLed2TimerEvent( void* context );
189
190 /*!
191 * \brief Function executed on Beacon timer Timeout event
192 */
193 static void OnLedBeaconTimerEvent( void* context );
194
195 static LmHandlerCallbacks_t LmHandlerCallbacks =
196 {
197 .GetBatteryLevel = BoardGetBatteryLevel,
198 .GetTemperature = NULL,
199 .GetRandomSeed = BoardGetRandomSeed,
200 .OnMacProcess = OnMacProcessNotify,
201 .OnNvmDataChange = OnNvmDataChange,
202 .OnNetworkParametersChange = OnNetworkParametersChange,
203 .OnMacMcpsRequest = OnMacMcpsRequest,
204 .OnMacMlmeRequest = OnMacMlmeRequest,
205 .OnJoinRequest = OnJoinRequest,
206 .OnTxData = OnTxData,
207 .OnRxData = OnRxData,
208 .OnClassChange= OnClassChange,
209 .OnBeaconStatusChange = OnBeaconStatusChange,
210 .OnSysTimeUpdate = OnSysTimeUpdate,
211 };
212
213 static LmHandlerParams_t LmHandlerParams =
214 {
215 .Region = ACTIVE_REGION,
216 .AdrEnable = LORAWAN_ADR_STATE,
217 .IsTxConfirmed = LORAWAN_DEFAULT_CONFIRMED_MSG_STATE,
218 .TxDatarate = LORAWAN_DEFAULT_DATARATE,
219 .PublicNetworkEnable = LORAWAN_PUBLIC_NETWORK,
220 .DutyCycleEnabled = LORAWAN_DUTYCYCLE_ON,
221 .DataBufferMaxSize = LORAWAN_APP_DATA_BUFFER_MAX_SIZE,
222 .DataBuffer = AppDataBuffer,
223 .PingSlotPeriodicity = REGION_COMMON_DEFAULT_PING_SLOT_PERIODICITY,
224 };
225
226 static LmhpComplianceParams_t LmhpComplianceParams =
227 {
228 .FwVersion.Value = FIRMWARE_VERSION,
229 .OnTxPeriodicityChanged = OnTxPeriodicityChanged,
230 .OnTxFrameCtrlChanged = OnTxFrameCtrlChanged,
231 .OnPingSlotPeriodicityChanged = OnPingSlotPeriodicityChanged,
232 };
233
234 /*!
235 * Indicates if LoRaMacProcess call is pending.
236 *
237 * \warning If variable is equal to 0 then the MCU can be set in low power mode
238 */
239 static volatile uint8_t IsMacProcessPending = 0;
240
241 static volatile uint8_t IsTxFramePending = 0;
242
243 static volatile uint32_t TxPeriodicity = 0;
244
245 /*!
246 * LED GPIO pins objects
247 */
248 extern Gpio_t Led1; // Tx
249
250 /*!
251 * UART object used for command line interface handling
252 */
253 extern Uart_t Uart1;
254
255 /*!
256 * Main application entry point.
257 */
main(void)258 int main( void )
259 {
260 BoardInitMcu( );
261 BoardInitPeriph( );
262
263 TimerInit( &Led1Timer, OnLed1TimerEvent );
264 TimerSetValue( &Led1Timer, 25 );
265
266 TimerInit( &Led2Timer, OnLed2TimerEvent );
267 TimerSetValue( &Led2Timer, 25 );
268
269 TimerInit( &LedBeaconTimer, OnLedBeaconTimerEvent );
270 TimerSetValue( &LedBeaconTimer, 5000 );
271
272 // Initialize transmission periodicity variable
273 TxPeriodicity = APP_TX_DUTYCYCLE + randr( -APP_TX_DUTYCYCLE_RND, APP_TX_DUTYCYCLE_RND );
274
275 const Version_t appVersion = { .Value = FIRMWARE_VERSION };
276 const Version_t gitHubVersion = { .Value = GITHUB_VERSION };
277 DisplayAppInfo( "periodic-uplink-lpp",
278 &appVersion,
279 &gitHubVersion );
280
281 if ( LmHandlerInit( &LmHandlerCallbacks, &LmHandlerParams ) != LORAMAC_HANDLER_SUCCESS )
282 {
283 printf( "LoRaMac wasn't properly initialized\n" );
284 // Fatal error, endless loop.
285 while ( 1 )
286 {
287 }
288 }
289
290 // Set system maximum tolerated rx error in milliseconds
291 LmHandlerSetSystemMaxRxError( 50 );
292
293 // The LoRa-Alliance Compliance protocol package should always be
294 // initialized and activated.
295 LmHandlerPackageRegister( PACKAGE_ID_COMPLIANCE, &LmhpComplianceParams );
296
297 LmHandlerJoin( );
298
299 StartTxProcess( LORAMAC_HANDLER_TX_ON_TIMER );
300
301 while( 1 )
302 {
303 // Tick the RTC to execute callback in context of the main loop (in stead of the IRQ)
304 TimerProcess( );
305
306 // Process characters sent over the command line interface
307 CliProcess( &Uart1 );
308
309 // Processes the LoRaMac events
310 LmHandlerProcess( );
311
312 // Process application uplinks management
313 UplinkProcess( );
314
315 CRITICAL_SECTION_BEGIN( );
316 if( IsMacProcessPending == 1 )
317 {
318 // Clear flag and prevent MCU to go into low power modes.
319 IsMacProcessPending = 0;
320 }
321 else
322 {
323 // The MCU wakes up through events
324 BoardLowPowerHandler( );
325 }
326 CRITICAL_SECTION_END( );
327 }
328 }
329
OnMacProcessNotify(void)330 static void OnMacProcessNotify( void )
331 {
332 IsMacProcessPending = 1;
333 }
334
OnNvmDataChange(LmHandlerNvmContextStates_t state,uint16_t size)335 static void OnNvmDataChange( LmHandlerNvmContextStates_t state, uint16_t size )
336 {
337 DisplayNvmDataChange( state, size );
338 }
339
OnNetworkParametersChange(CommissioningParams_t * params)340 static void OnNetworkParametersChange( CommissioningParams_t* params )
341 {
342 DisplayNetworkParametersUpdate( params );
343 }
344
OnMacMcpsRequest(LoRaMacStatus_t status,McpsReq_t * mcpsReq,TimerTime_t nextTxIn)345 static void OnMacMcpsRequest( LoRaMacStatus_t status, McpsReq_t *mcpsReq, TimerTime_t nextTxIn )
346 {
347 DisplayMacMcpsRequestUpdate( status, mcpsReq, nextTxIn );
348 }
349
OnMacMlmeRequest(LoRaMacStatus_t status,MlmeReq_t * mlmeReq,TimerTime_t nextTxIn)350 static void OnMacMlmeRequest( LoRaMacStatus_t status, MlmeReq_t *mlmeReq, TimerTime_t nextTxIn )
351 {
352 DisplayMacMlmeRequestUpdate( status, mlmeReq, nextTxIn );
353 }
354
OnJoinRequest(LmHandlerJoinParams_t * params)355 static void OnJoinRequest( LmHandlerJoinParams_t* params )
356 {
357 DisplayJoinRequestUpdate( params );
358 if( params->Status == LORAMAC_HANDLER_ERROR )
359 {
360 LmHandlerJoin( );
361 }
362 else
363 {
364 LmHandlerRequestClass( LORAWAN_DEFAULT_CLASS );
365 }
366 }
367
OnTxData(LmHandlerTxParams_t * params)368 static void OnTxData( LmHandlerTxParams_t* params )
369 {
370 DisplayTxUpdate( params );
371 }
372
OnRxData(LmHandlerAppData_t * appData,LmHandlerRxParams_t * params)373 static void OnRxData( LmHandlerAppData_t* appData, LmHandlerRxParams_t* params )
374 {
375 DisplayRxUpdate( appData, params );
376
377 switch( appData->Port )
378 {
379 case 1: // The application LED can be controlled on port 1 or 2
380 case LORAWAN_APP_PORT:
381 {
382 AppLedStateOn = appData->Buffer[0] & 0x01;
383 }
384 break;
385 default:
386 break;
387 }
388
389 // Switch LED 1 ON for each received downlink
390 GpioWrite( &Led1, 1 );
391 TimerStart( &Led2Timer );
392 }
393
OnClassChange(DeviceClass_t deviceClass)394 static void OnClassChange( DeviceClass_t deviceClass )
395 {
396 DisplayClassUpdate( deviceClass );
397
398 // Inform the server as soon as possible that the end-device has switched to ClassB
399 LmHandlerAppData_t appData =
400 {
401 .Buffer = NULL,
402 .BufferSize = 0,
403 .Port = 0,
404 };
405 LmHandlerSend( &appData, LORAMAC_HANDLER_UNCONFIRMED_MSG );
406 }
407
OnBeaconStatusChange(LoRaMacHandlerBeaconParams_t * params)408 static void OnBeaconStatusChange( LoRaMacHandlerBeaconParams_t* params )
409 {
410 switch( params->State )
411 {
412 case LORAMAC_HANDLER_BEACON_RX:
413 {
414 TimerStart( &LedBeaconTimer );
415 break;
416 }
417 case LORAMAC_HANDLER_BEACON_LOST:
418 case LORAMAC_HANDLER_BEACON_NRX:
419 {
420 TimerStop( &LedBeaconTimer );
421 break;
422 }
423 default:
424 {
425 break;
426 }
427 }
428
429 DisplayBeaconUpdate( params );
430 }
431
432 #if( LMH_SYS_TIME_UPDATE_NEW_API == 1 )
OnSysTimeUpdate(bool isSynchronized,int32_t timeCorrection)433 static void OnSysTimeUpdate( bool isSynchronized, int32_t timeCorrection )
434 {
435
436 }
437 #else
OnSysTimeUpdate(void)438 static void OnSysTimeUpdate( void )
439 {
440
441 }
442 #endif
443
444 /*!
445 * Prepares the payload of the frame and transmits it.
446 */
PrepareTxFrame(void)447 static void PrepareTxFrame( void )
448 {
449 if( LmHandlerIsBusy( ) == true )
450 {
451 return;
452 }
453
454 uint8_t channel = 0;
455
456 AppData.Port = LORAWAN_APP_PORT;
457
458 CayenneLppReset( );
459 CayenneLppAddDigitalInput( channel++, AppLedStateOn );
460 CayenneLppAddAnalogInput( channel++, BoardGetBatteryLevel( ) * 100 / 254 );
461
462 CayenneLppCopy( AppData.Buffer );
463 AppData.BufferSize = CayenneLppGetSize( );
464
465 if( LmHandlerSend( &AppData, LmHandlerParams.IsTxConfirmed ) == LORAMAC_HANDLER_SUCCESS )
466 {
467 // Switch LED 1 ON
468 GpioWrite( &Led1, 0 );
469 TimerStart( &Led1Timer );
470 }
471 }
472
StartTxProcess(LmHandlerTxEvents_t txEvent)473 static void StartTxProcess( LmHandlerTxEvents_t txEvent )
474 {
475 switch( txEvent )
476 {
477 default:
478 // Intentional fall through
479 case LORAMAC_HANDLER_TX_ON_TIMER:
480 {
481 // Schedule 1st packet transmission
482 TimerInit( &TxTimer, OnTxTimerEvent );
483 TimerSetValue( &TxTimer, TxPeriodicity );
484 OnTxTimerEvent( NULL );
485 }
486 break;
487 case LORAMAC_HANDLER_TX_ON_EVENT:
488 {
489 }
490 break;
491 }
492 }
493
UplinkProcess(void)494 static void UplinkProcess( void )
495 {
496 uint8_t isPending = 0;
497 CRITICAL_SECTION_BEGIN( );
498 isPending = IsTxFramePending;
499 IsTxFramePending = 0;
500 CRITICAL_SECTION_END( );
501 if( isPending == 1 )
502 {
503 PrepareTxFrame( );
504 }
505 }
506
OnTxPeriodicityChanged(uint32_t periodicity)507 static void OnTxPeriodicityChanged( uint32_t periodicity )
508 {
509 TxPeriodicity = periodicity;
510
511 if( TxPeriodicity == 0 )
512 { // Revert to application default periodicity
513 TxPeriodicity = APP_TX_DUTYCYCLE + randr( -APP_TX_DUTYCYCLE_RND, APP_TX_DUTYCYCLE_RND );
514 }
515
516 // Update timer periodicity
517 TimerStop( &TxTimer );
518 TimerSetValue( &TxTimer, TxPeriodicity );
519 TimerStart( &TxTimer );
520 }
521
OnTxFrameCtrlChanged(LmHandlerMsgTypes_t isTxConfirmed)522 static void OnTxFrameCtrlChanged( LmHandlerMsgTypes_t isTxConfirmed )
523 {
524 LmHandlerParams.IsTxConfirmed = isTxConfirmed;
525 }
526
OnPingSlotPeriodicityChanged(uint8_t pingSlotPeriodicity)527 static void OnPingSlotPeriodicityChanged( uint8_t pingSlotPeriodicity )
528 {
529 LmHandlerParams.PingSlotPeriodicity = pingSlotPeriodicity;
530 }
531
532 /*!
533 * Function executed on TxTimer event
534 */
OnTxTimerEvent(void * context)535 static void OnTxTimerEvent( void* context )
536 {
537 TimerStop( &TxTimer );
538
539 IsTxFramePending = 1;
540
541 // Schedule next transmission
542 TimerSetValue( &TxTimer, TxPeriodicity );
543 TimerStart( &TxTimer );
544 }
545
546 /*!
547 * Function executed on Led 1 Timeout event
548 */
OnLed1TimerEvent(void * context)549 static void OnLed1TimerEvent( void* context )
550 {
551 TimerStop( &Led1Timer );
552 // Switch LED 1 OFF
553 GpioWrite( &Led1, 0 );
554 }
555
556 /*!
557 * Function executed on Led 2 Timeout event
558 */
OnLed2TimerEvent(void * context)559 static void OnLed2TimerEvent( void* context )
560 {
561 TimerStop( &Led1Timer );
562 // Switch LED 1 OFF
563 GpioWrite( &Led1, 0 );
564 }
565
566 /*!
567 * \brief Function executed on Beacon timer Timeout event
568 */
OnLedBeaconTimerEvent(void * context)569 static void OnLedBeaconTimerEvent( void* context )
570 {
571 GpioWrite( &Led1, 1 );
572 TimerStart( &Led2Timer );
573
574 TimerStart( &LedBeaconTimer );
575 }
576