-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.c
More file actions
1317 lines (1066 loc) · 40.7 KB
/
Copy pathmain.c
File metadata and controls
1317 lines (1066 loc) · 40.7 KB
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
/*
* FreeRTOS V1.4.7
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*
* Debug setup instructions:
* 1) Open the debug configuration dialog.
* 2) Go to the Debugger tab.
* 3) If the 'Mode Setup' options are not visible, click the 'Show Generator' button.
* 4) In the Mode Setup|Reset Mode drop down ensure that
* 'Software System Reset' is selected.
*/
#include "main.h"
#include "stdint.h"
#include "stdarg.h"
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Demo includes */
#include "iot_system_init.h"
#include "iot_logging_task.h"
#include "iot_wifi.h"
#include "aws_clientcredential.h"
#include "aws_dev_mode_key_provisioning.h"
#include "iot_uart.h"
#include "trcRecorder.h"
#include "dfm.h"
#include "dfmCrashCatcher.h"
#include "dfmStoragePort.h"
/* WiFi driver includes. */
#include "es_wifi.h"
/* The SPI driver polls at a high priority. The logging task's priority must also
* be high to be not be starved of CPU time. */
#define mainLOGGING_TASK_PRIORITY ( configMAX_PRIORITIES - 1 )
#define mainLOGGING_TASK_STACK_SIZE ( 2000 )
#define mainLOGGING_MESSAGE_QUEUE_LENGTH ( 15 )
/* Minimum required WiFi firmware version. */
#define mainREQUIRED_WIFI_FIRMWARE_WICED_MAJOR_VERSION ( 3 )
#define mainREQUIRED_WIFI_FIRMWARE_WICED_MINOR_VERSION ( 5 )
#define mainREQUIRED_WIFI_FIRMWARE_WICED_PATCH_VERSION ( 2 )
#define mainREQUIRED_WIFI_FIRMWARE_INVENTEK_VERSION ( 5 )
#define mainREQUIRED_WIFI_FIRMWARE_DESCRIPTOR_STRING ( "STM" )
/*-----------------------------------------------------------*/
// Move this to a DFM file?
int vDfmSetGCCBuildID(char* dest, int size);
void vApplicationDaemonTaskStartupHook( void );
/* Defined in es_wifi_io.c. */
extern void SPI_WIFI_ISR( void );
extern SPI_HandleTypeDef hspi;
#ifdef USE_OFFLOAD_SSL
#if (DEMO_CFG_SERIAL_UPLOAD_ONLY != 1)
/* Defined in iot_wifi.c. */
extern WIFIReturnCode_t WIFI_GetFirmwareVersion( uint8_t * pucBuffer );
#endif
#endif /* USE_OFFLOAD_SSL */
/**********************
* Global Variables
**********************/
RTC_HandleTypeDef xHrtc;
RNG_HandleTypeDef xHrng;
IotUARTHandle_t xConsoleUart;
/* Private function prototypes -----------------------------------------------*/
static void SystemClock_Config( void );
static void Console_UART_Init( void );
static void RTC_Init( void );
#if (DEMO_CFG_SERIAL_UPLOAD_ONLY != 1)
static void prvWifiConnect( void );
#endif
/**
* @brief Initializes the STM32L475 IoT node board.
*
* Initialization of clock, LEDs, RNG, RTC, and WIFI module.
*/
static void prvMiscInitialization( void );
/**
* @brief Initializes the FreeRTOS heap.
*
* Heap_5 is being used because the RAM is not contiguous, therefore the heap
* needs to be initialized. See http://www.freertos.org/a00111.html
*/
static void prvInitializeHeap( void );
unsigned int getHardwareRand(void);
DfmResult_t myGetUniqueSessionID(char cBuffer[], uint32_t ulSize, uint32_t* pulBytesWritten);
DfmResult_t myGetDeviceName(char cBuffer[], uint32_t ulSize, uint32_t* pulBytesWritten);
#ifdef USE_OFFLOAD_SSL
/**
* @brief Checks whether the Inventek module's firmware version needs to be
* updated.
*
* Prints a message to inform the user to update the WiFi firmware.
*/
#if (DEMO_CFG_SERIAL_UPLOAD_ONLY != 1)
static void prvCheckWiFiFirmwareVersion( void );
#endif
#endif /* USE_OFFLOAD_SSL */
/*-----------------------------------------------------------*/
void ButtonTask(void* argument);
char* stackoverflowpadding = NULL;
typedef struct task_arg {
uint32_t type;
const char* message;
} task_arg_t;
// Provokes a hard fault exception
static int MakeFaultExceptionByIllegalRead(void)
{
int r;
volatile unsigned int* p;
p = (unsigned int*)0x00100000; // 0x00100000-0x07FFFFFF is reserved on STM32F4
r = *p;
return r;
}
// This is just to make the call stack a bit longer and more interesting...
int dosomething(int n)
{
if (n != -42)
{
return MakeFaultExceptionByIllegalRead();
}
return 0;
}
#define MAX_MESSAGE_SIZE 12
void getNetworkMessage(char* data)
{
sprintf(data, "Incoming data");
}
void processNetworkMessage(char* data)
{
configPRINT_STRING(" Simulated network message: \"");
configPRINT_STRING(data);
configPRINT_STRING("\"\n");
}
void prvCheckForNetworkMessages(void)
{
char message[MAX_MESSAGE_SIZE];
getNetworkMessage(message);
processNetworkMessage(message);
}
// This will cause a buffer overrun. See the error handler __stack_chk_fail in dfmCrashCatcher.c
void testBufferOverrun(void)
{
prvCheckForNetworkMessages();
}
void testAssertFailed(char* str)
{
configASSERT( str != NULL );
configPRINTF(("Input: %s", str));
}
/**
* Button checker
*/
TaskHandle_t xBhjHandle = NULL;
char* ptr = NULL;
void ButtonTask(void* argument)
{
configPRINT_STRING( "\n\nDemo ready - Press blue button to trigger an error that is captured by DevAlert.\n\n" );
for(;;)
{
ulTaskNotifyTake( pdTRUE, portMAX_DELAY ); /* Block indefinitely. */
switch(getHardwareRand() % 4)
{
case 0:
configPRINTF(( "Test case: Assert failed\n"));
vTaskDelay(1000);
testAssertFailed(ptr);
break;
case 1:
configPRINTF(( "Test case: Malloc failed\n"));
vTaskDelay(1000);
pvPortMalloc(1000000); // This much heap memory isn't available, should fail
break;
case 2:
configPRINTF(( "Test case: Hardware fault exception\n"));
vTaskDelay(1000);
dosomething(3);
break;
case 3:
configPRINTF(( "Test case: Buffer overrun\n"));
vTaskDelay(1000);
testBufferOverrun();
break;
/*
case 4:
configPRINTF(( "Test case: Stack overflow\n"));
vTaskDelay(1000);
{
char data[4000];
memset(data, 0, 4000);
}
break; */
}
}
}
#define nMSG 5
#define nSTATE 3
const char * messages[nMSG] = { "SetMode A",
"SetOptionsFlags X,Y",
"Certificate checksum 123456789ABCDEF",
"SetRemoteIP 127.0.0.1",
"SetRemotePort 8888"};
const char * states[nSTATE] = { "State A",
"State B",
"State C"};
void prvRXTask(void* argument)
{
int delay;
volatile int dummy;
int counter = 0;
int state = 0;
int len = 0;
TraceStringHandle_t command_chn;
TraceStateMachineHandle_t myfsm;
TraceStateMachineStateHandle_t myfsm_state[5];
xTraceStringRegister("Command Log", &command_chn);
/* Trace a state machine (states can span between tasks) */
xTraceStateMachineCreate("RX State", &myfsm);
for (int i = 0; i < nSTATE; i++)
{
// Register each state name, one for each message
xTraceStateMachineStateCreate(myfsm, states[i], &myfsm_state[i]);
}
for(;;)
{
len = strlen(messages[counter]);
xTracePrintF(command_chn, messages[counter]);
// Just cycle through these...
counter = (counter+1) % nMSG;
state = (state+1) % nSTATE;
// Make the task run longer...
for (dummy = 0; dummy < 3000; dummy++);
// Log a state transition
xTraceStateMachineSetState(myfsm, myfsm_state[state]);
// Make the task run longer...
for (dummy = 0; dummy < (1000 * len); dummy++);
// Simulate timing of incoming messages
delay = 5 + getHardwareRand() % 85;
vTaskDelay(delay);
}
}
char gcc_build_id[48];
/**
* @brief Application runtime entry point.
*/
int main( void )
{
char tmp[48];
uint32_t bytesWritten = 0;
/* Perform any hardware initialization that does not require the RTOS to be
* running. */
prvMiscInitialization();
if (myGetDeviceName(tmp, sizeof(tmp), &bytesWritten) == DFM_SUCCESS)
{
configPRINT_STRING(("DeviceName: "));
configPRINT_STRING((tmp));
configPRINT_STRING(("\n"));
}
else
{
configPRINT_STRING(("DeviceName: FAIL\n"));
}
if (myGetUniqueSessionID(tmp, sizeof(tmp), &bytesWritten) == DFM_SUCCESS)
{
configPRINT_STRING(("SessionID: "));
configPRINT_STRING((tmp));
configPRINT_STRING(("\n"));
}
else
{
configPRINT_STRING(("SessionID: FAIL\n"));
}
BSP_LED_Off( LED_GREEN );
if( xTaskCreate( prvRXTask, "RX", 1000, NULL, 6, NULL ) != pdPASS )
{
configPRINT_STRING(("Failed creating task."));
}
/* Create tasks that are not dependent on the WiFi being initialized. */
xLoggingTaskInitialize( mainLOGGING_TASK_STACK_SIZE,
mainLOGGING_TASK_PRIORITY,
mainLOGGING_MESSAGE_QUEUE_LENGTH );
/* Start the scheduler. Initialization that requires the OS to be running,
* including the WiFi initialization, is performed in the RTOS daemon task
* startup hook. */
vTaskStartScheduler();
return 0;
}
/*-----------------------------------------------------------*/
/* For STM32, tested on STM32L475 */
unsigned int getHardwareRand(void)
{
uint32_t rand;
HAL_RNG_GenerateRandomNumber(&xHrng, &rand);
return rand;
}
typedef struct {
uint32_t namesz;
uint32_t descsz;
uint32_t type;
uint8_t data[];
} ElfNoteSection_t;
extern const ElfNoteSection_t build_id_elf_note;
/******************************************************************************
* vDfmSetGCCBuildID - Writes the GCC Build ID to dest.
* Parameter size is the maximum length (at least 42)
*
* * For this to work:
* - Add .gnu_build_id section in linker script (see .ld file in root folder)
* - Add -Wl,--build-id in linker flags
*
* Can be read from elf file by "arm-none-eabi-readelf -n aws_demos.elf"
* to archive the elf file for automated lookup using the Build ID.
*****************************************************************************/
int vDfmSetGCCBuildID(char* dest, int size)
{
if (size < 42) return DFM_FAIL;
const uint8_t *build_id_data = &build_id_elf_note.data[build_id_elf_note.namesz];
// The GNU Build ID is 20 bytes.
for (int i = 0; i < 20; i++)
{
char byte_str[4] = "";
sprintf(byte_str, "%02x", build_id_data[i]);
strncat(dest, byte_str, 2);
}
return DFM_SUCCESS;
}
void vApplicationDaemonTaskStartupHook( void )
{
configPRINTF( ( "\n\n\n\n--- Percepio DevAlert Demonstration ---\n" ) );
// Can be read from elf file by "arm-none-eabi-readelf -n aws_demos.elf"
configPRINTF(("Revision: %s\n", DFM_CFG_FIRMWARE_VERSION));
#if (DEMO_CFG_SERIAL_UPLOAD_ONLY == 1)
configPRINTF(("Upload method: Serial (upload via host computer)\n"));
#else
configPRINTF(("Upload method: AWS_MQTT (direct upload to cloud)\n"));
#endif
/* For testing the serial port upload, Wifi/AWS connectivity not needed */
#if (DEMO_CFG_SERIAL_UPLOAD_ONLY != 1)
WIFIReturnCode_t xWifiStatus;
/* Turn on the WiFi before key provisioning. This is needed because
* if we want to use offload SSL, device certificate and key is stored
* on the WiFi module during key provisioning which requires the WiFi
* module to be initialized. */
xWifiStatus = WIFI_On();
if( xWifiStatus == eWiFiSuccess )
{
configPRINTF( ( "WiFi module initialized.\r\n" ) );
/* A simple example to demonstrate key and certificate provisioning in
* microcontroller flash using PKCS#11 interface. This should be replaced
* by production ready key provisioning mechanism. */
if( SYSTEM_Init() == pdPASS )
{
// Must be after SYSTEM_Init
vDevModeKeyProvisioning();
/* Connect to the WiFi before running the demos */
prvWifiConnect();
srand(getHardwareRand());
// When using AWS MQTT upload, DFM is initialized after the connection is established.
if (xDfmInitialize(myGetUniqueSessionID, myGetDeviceName) == DFM_FAIL)
{
configPRINTF(("Failed to initialize DFM\r\n"));
}
#ifdef USE_OFFLOAD_SSL
/* Check if WiFi firmware needs to be updated. */
prvCheckWiFiFirmwareVersion();
#endif /* USE_OFFLOAD_SSL */
configPRINTF(("DFM: Sending any stored alerts.\n"));
/* Try sending any stored alerts from a prior crash */
xDfmAlertSendAll();
/* Reset and delete any alerts from storage - this is specific for the STM32 FLASH storage port. */
xDfmStoragePortReset();
xTaskCreate(ButtonTask, /* Function that implements the task. */
"DemoTask1", /* Text name for the task. */
1024, /* Stack size in words, not bytes. */
NULL, /* Parameter passed into the task. */
tskIDLE_PRIORITY,/* Priority at which the task is created. */
&xBhjHandle ); /* Used to pass out the created task's handle. */
BSP_LED_On( LED_GREEN );
}
}
else
{
configPRINTF( ( "WiFi module failed to initialize.\r\n" ) );
/* Stop here if we fail to initialize WiFi. */
configASSERT( xWifiStatus == eWiFiSuccess );
}
#else
#if (0)
{
static DfmAlertHandle_t xAlertHandle = 0;
char* payloadString = "Example Payload from DFM";
if (xDfmAlertBegin(DFM_TYPE_ASSERT_FAILED, "Demo alert", &xAlertHandle) == DFM_SUCCESS)
{
xDfmAlertAddSymptom(xAlertHandle, DFM_SYMPTOM_LINE, __LINE__);
xDfmAlertAddPayload(xAlertHandle, payloadString, strlen(payloadString), "demo_payload.txt");
xDfmAlertEnd(xAlertHandle);
}
for(;;);
}
#else
/* Basic demo initialization for serial port upload */
xTaskCreate(ButtonTask, /* Function that implements the task. */
"DemoTask1", /* Text name for the task. */
1024, /* Stack size in words, not bytes. */
NULL, /* Parameter passed into the task. */
tskIDLE_PRIORITY,/* Priority at which the task is created. */
&xBhjHandle ); /* Used to pass out the created task's handle. */
/* Test - Getting a crashes in FreeRTOS functions when testing the Stack Overflow issue, but this didn't help.
* The crashes occur BEFORE the stack overflow test, but the behavior changes if I modify the "data" stack allocation in the switch statement above.
* This is weird. Might be that I'm getting stack overflows at an earlier point?
* Needs further digging. NOTE: RECORDER DISABLED (that wasn't the problem)*/
stackoverflowpadding = pvPortMalloc(4096);
#endif
#if (0)
/* Try sending any stored alerts from a prior crash */
/* Not needed when using serial output, as no data is stored on the device */
{
int dfmResult = DFM_SUCCESS;
dfmResult = xDfmAlertSendAll();
if ((dfmResult == DFM_FAIL) || (dfmResult == DFM_NO_ALERTS))
{
configPRINTF(("DFM: No stored alerts.\n\n"));
}
else if (dfmResult == DFM_SUCCESS)
{
configPRINTF(("DFM: Found and uploaded alerts.\n\n"));
/* Erase stored alerts to avoid they are sent repeatedly */
xDfmStoragePortReset();
}
else
{
configPRINTF(("DFM: Unexpected return code (%d)!\n\n", dfmResult));
}
// Needed?
xDfmSessionSetStorageStrategy(DFM_STORAGE_STRATEGY_OVERWRITE);
}
#endif
BSP_LED_On( LED_GREEN );
#endif
}
/*-----------------------------------------------------------*/
#if (DEMO_CFG_SERIAL_UPLOAD_ONLY != 1)
static void prvWifiConnect( void )
{
WIFINetworkParams_t xNetworkParams = { 0 };
WIFIReturnCode_t xWifiStatus = eWiFiSuccess;
WIFIIPConfiguration_t xIpConfig;
uint8_t *pucIPV4Byte;
size_t xSSIDLength, xPasswordLength;
/* Setup WiFi parameters to connect to access point. */
if( clientcredentialWIFI_SSID != NULL )
{
xSSIDLength = strlen( clientcredentialWIFI_SSID );
if( ( xSSIDLength > 0 ) && ( xSSIDLength <= wificonfigMAX_SSID_LEN ) )
{
xNetworkParams.ucSSIDLength = xSSIDLength;
memcpy( xNetworkParams.ucSSID, clientcredentialWIFI_SSID, xSSIDLength );
}
else
{
configPRINTF(( "Invalid WiFi SSID configured, empty or exceeds allowable length %d.\n", wificonfigMAX_SSID_LEN ));
xWifiStatus = eWiFiFailure;
}
}
else
{
configPRINTF(( "WiFi SSID is not configured.\n" ));
xWifiStatus = eWiFiFailure;
}
xNetworkParams.xSecurity = clientcredentialWIFI_SECURITY;
if( clientcredentialWIFI_SECURITY == eWiFiSecurityWPA2 )
{
if( clientcredentialWIFI_PASSWORD != NULL )
{
xPasswordLength = strlen( clientcredentialWIFI_PASSWORD );
if( ( xPasswordLength > 0 ) && ( xSSIDLength <= wificonfigMAX_PASSPHRASE_LEN ) )
{
xNetworkParams.xPassword.xWPA.ucLength = xPasswordLength;
memcpy( xNetworkParams.xPassword.xWPA.cPassphrase, clientcredentialWIFI_PASSWORD, xPasswordLength );
}
else
{
configPRINTF(( "Invalid WiFi password configured, empty password or exceeds allowable password length %d.\n", wificonfigMAX_PASSPHRASE_LEN ));
xWifiStatus = eWiFiFailure;
}
}
else
{
configPRINTF(( "WiFi password is not configured.\n" ));
xWifiStatus = eWiFiFailure;
}
}
xNetworkParams.ucChannel = 0;
if( xWifiStatus == eWiFiSuccess )
{
configPRINTF( ( "Connecting to WiFi..." ) );
/* Try connecting using provided wifi credentials. */
xWifiStatus = WIFI_ConnectAP( &( xNetworkParams ) );
if( xWifiStatus == eWiFiSuccess )
{
configPRINTF( ( "WiFi connected!") );
/* Get IP address of the device. */
xWifiStatus = WIFI_GetIPInfo( &xIpConfig );
if( xWifiStatus == eWiFiSuccess )
{
pucIPV4Byte = ( uint8_t * ) ( &xIpConfig.xIPAddress.ulAddress[0] );
configPRINTF( ( "IP Address acquired %d.%d.%d.%d.\r\n",
pucIPV4Byte[ 0 ], pucIPV4Byte[ 1 ], pucIPV4Byte[ 2 ], pucIPV4Byte[ 3 ] ) );
}
}
else
{
/* Connection failed configure softAP to allow user to set wifi credentials. */
configPRINTF( ( "WiFi failed to connect to AP %.*s.\r\n", xNetworkParams.ucSSIDLength, ( char * ) xNetworkParams.ucSSID ) );
}
}
if( xWifiStatus != eWiFiSuccess )
{
/* Enter SOFT AP mode to provision access point credentials. */
configPRINTF(( "Entering soft access point WiFi provisioning mode.\n" ));
xWifiStatus = eWiFiSuccess;
if( wificonfigACCESS_POINT_SSID_PREFIX != NULL )
{
xSSIDLength = strlen( wificonfigACCESS_POINT_SSID_PREFIX );
if( ( xSSIDLength > 0 ) && ( xSSIDLength <= wificonfigMAX_SSID_LEN ) )
{
xNetworkParams.ucSSIDLength = xSSIDLength;
memcpy( xNetworkParams.ucSSID, clientcredentialWIFI_SSID, xSSIDLength );
}
else
{
configPRINTF(( "Invalid AP SSID configured, empty or exceeds allowable length %d.\n", wificonfigMAX_SSID_LEN ));
xWifiStatus = eWiFiFailure;
}
}
else
{
configPRINTF(( "WiFi AP SSID is not configured.\n" ));
xWifiStatus = eWiFiFailure;
}
xNetworkParams.xSecurity = wificonfigACCESS_POINT_SECURITY;
if( wificonfigACCESS_POINT_SECURITY == eWiFiSecurityWPA2 )
{
if( wificonfigACCESS_POINT_PASSKEY != NULL )
{
xPasswordLength = strlen( wificonfigACCESS_POINT_PASSKEY );
if( ( xPasswordLength > 0 ) && ( xSSIDLength <= wificonfigMAX_PASSPHRASE_LEN ) )
{
xNetworkParams.xPassword.xWPA.ucLength = xPasswordLength;
memcpy( xNetworkParams.xPassword.xWPA.cPassphrase, wificonfigACCESS_POINT_PASSKEY, xPasswordLength );
}
else
{
configPRINTF(( "Invalid WiFi AP password, empty or exceeds allowable password length %d.\n", wificonfigMAX_PASSPHRASE_LEN ));
xWifiStatus = eWiFiFailure;
}
}
else
{
configPRINTF(( "WiFi AP password is not configured.\n" ));
xWifiStatus = eWiFiFailure;
}
}
xNetworkParams.ucChannel = wificonfigACCESS_POINT_CHANNEL;
if( xWifiStatus == eWiFiSuccess )
{
configPRINTF( ( "Connect to softAP %.*s using password %.*s. \r\n",
xNetworkParams.ucSSIDLength, ( char * ) xNetworkParams.ucSSID,
xNetworkParams.xPassword.xWPA.ucLength, xNetworkParams.xPassword.xWPA.cPassphrase ) );
do
{
xWifiStatus = WIFI_ConfigureAP( &xNetworkParams );
configPRINTF( ( "Connect to softAP and configure wiFi returned %d\r\n", xWifiStatus ) );
vTaskDelay( pdMS_TO_TICKS( 1000 ) );
} while( ( xWifiStatus != eWiFiSuccess ) && ( xWifiStatus != eWiFiNotSupported ) );
}
}
configASSERT( xWifiStatus == eWiFiSuccess );
}
#endif
/*-----------------------------------------------------------*/
/* configUSE_STATIC_ALLOCATION is set to 1, so the application must provide an
* implementation of vApplicationGetIdleTaskMemory() to provide the memory that is
* used by the Idle task. */
void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer,
StackType_t ** ppxIdleTaskStackBuffer,
uint32_t * pulIdleTaskStackSize )
{
/* If the buffers to be provided to the Idle task are declared inside this
* function then they must be declared static - otherwise they will be allocated on
* the stack and so not exists after this function exits. */
static StaticTask_t xIdleTaskTCB;
static StackType_t uxIdleTaskStack[ configMINIMAL_STACK_SIZE ];
/* Pass out a pointer to the StaticTask_t structure in which the Idle
* task's state will be stored. */
*ppxIdleTaskTCBBuffer = &xIdleTaskTCB;
/* Pass out the array that will be used as the Idle task's stack. */
*ppxIdleTaskStackBuffer = uxIdleTaskStack;
/* Pass out the size of the array pointed to by *ppxIdleTaskStackBuffer.
* Note that, as the array is necessarily of type StackType_t,
* configMINIMAL_STACK_SIZE is specified in words, not bytes. */
*pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;
}
/*-----------------------------------------------------------*/
/* configUSE_STATIC_ALLOCATION is set to 1, so the application must provide an
* implementation of vApplicationGetTimerTaskMemory() to provide the memory that is
* used by the RTOS daemon/time task. */
void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer,
StackType_t ** ppxTimerTaskStackBuffer,
uint32_t * pulTimerTaskStackSize )
{
/* If the buffers to be provided to the Timer task are declared inside this
* function then they must be declared static - otherwise they will be allocated on
* the stack and so not exists after this function exits. */
static StaticTask_t xTimerTaskTCB;
static StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ];
/* Pass out a pointer to the StaticTask_t structure in which the Idle
* task's state will be stored. */
*ppxTimerTaskTCBBuffer = &xTimerTaskTCB;
/* Pass out the array that will be used as the Timer task's stack. */
*ppxTimerTaskStackBuffer = uxTimerTaskStack;
/* Pass out the size of the array pointed to by *ppxTimerTaskStackBuffer.
* Note that, as the array is necessarily of type StackType_t,
* configMINIMAL_STACK_SIZE is specified in words, not bytes. */
*pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH;
}
/*-----------------------------------------------------------*/
/**
* @brief Publishes a character to the STM32L475 UART
*
* This is used to implement the tinyprintf created by Spare Time Labs
* http://www.sparetimelabs.com/tinyprintf/tinyprintf.php
*
* @param pv unused void pointer for compliance with tinyprintf
* @param ch character to be printed
*/
void vSTM32L475putc( void * pv,
char ch )
{
int32_t status;
do {
status = iot_uart_write_sync( xConsoleUart, ( uint8_t * ) &ch, 1 );
} while( status == IOT_UART_BUSY );
}
/*-----------------------------------------------------------*/
/**
* @brief Read a character from the STM32L475 UART
*
* Implemented by BHJ - Seems that it does not work
*
* @param pv unused void pointer for compliance with tinyprintf
* @param ch character to be printed
*/
void vSTM32L475getc( void * pv,
char * ch )
{
int32_t status;
int done = 0;
do {
status = iot_uart_read_sync( xConsoleUart, ( uint8_t * ) ch, 1 );
switch (status) {
case IOT_UART_SUCCESS:
done = 1;
break;
case IOT_UART_INVALID_VALUE:
LogError(("vSTM32L475getc(): IOT_UART_INVALID_VALUE"));
done = 1;
break;
case IOT_UART_READ_FAILED:
LogError(("vSTM32L475getc(): IOT_UART_READ_FAILED"));
done = 1;
break;
case IOT_UART_BUSY:
/* keep looping */
break;
case IOT_UART_FUNCTION_NOT_SUPPORTED:
LogError(("vSTM32L475getc(): IOT_UART_FUNCTION_NOT_SUPPORTED"));
done = 1;
break;
case IOT_UART_NOTHING_TO_CANCEL:
case IOT_UART_WRITE_FAILED:
default:
LogError(("vSTM32L475getc(): unexpected status"));
done = 1;
break;
}
} while (!done);
}
/*-----------------------------------------------------------*/
/**
* @brief Initializes the board.
*/
static void prvMiscInitialization( void )
{
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock. */
SystemClock_Config();
/* Heap_5 is being used because the RAM is not contiguous in memory, so the
* heap must be initialized. */
prvInitializeHeap();
// Enable usage fault and bus fault
SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk | SCB_SHCSR_BUSFAULTENA_Msk;
/* Init and start tracing */
xTraceEnable(TRC_START);
BSP_LED_Init( LED_GREEN );
BSP_PB_Init( BUTTON_USER, BUTTON_MODE_EXTI );
/* RNG init function. */
xHrng.Instance = RNG;
if( HAL_RNG_Init( &xHrng ) != HAL_OK )
{
Error_Handler();
}
/* RTC init. */
RTC_Init();
/* UART console init. */
Console_UART_Init();
vDfmSetGCCBuildID(gcc_build_id, 48);
printf("BuildID: %s\n", gcc_build_id);
#if (DEMO_CFG_SERIAL_UPLOAD_ONLY == 1)
// DFM can be initialized quite early when using the Serial upload
if (xDfmInitializeForLocalUse() == DFM_FAIL)
{
configPRINTF(("Failed to initialize DFM\r\n"));
}
#endif
}
DfmResult_t myGetUniqueSessionID(char cBuffer[], uint32_t ulSize, uint32_t* pulBytesWritten)
{
uint32_t nBytes;
nBytes = snprintf(cBuffer, ulSize, "S-%X-%X-%X", getHardwareRand(), getHardwareRand(), getHardwareRand());
if (nBytes > 0)
{
*pulBytesWritten = nBytes;
return DFM_SUCCESS;
}
return DFM_FAIL;
}
/*** Serial number addresses for STM32Lx ***/
#define DEVICE_ID1 (unsigned int*)(0x1FFF7590)
#define DEVICE_ID2 (unsigned int*)(0x1FFF7594)
#define DEVICE_ID3 (unsigned int*)(0x1FFF7598)
DfmResult_t myGetDeviceName(char cBuffer[], uint32_t ulSize, uint32_t* pulBytesWritten)
{
uint32_t nBytes;
nBytes = snprintf(cBuffer, ulSize, "D-%08X-%08X-%08X", *DEVICE_ID1, *DEVICE_ID2, *DEVICE_ID3);
if (nBytes > 0)
{
*pulBytesWritten = nBytes;
return DFM_SUCCESS;
}
return DFM_FAIL;
}
/*-----------------------------------------------------------*/
/**
* @brief Initializes the system clock.
*/
static void SystemClock_Config( void )
{
RCC_OscInitTypeDef xRCC_OscInitStruct;
RCC_ClkInitTypeDef xRCC_ClkInitStruct;
RCC_PeriphCLKInitTypeDef xPeriphClkInit;
xRCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_MSI;
xRCC_OscInitStruct.LSEState = RCC_LSE_ON;
xRCC_OscInitStruct.MSIState = RCC_MSI_ON;
xRCC_OscInitStruct.MSICalibrationValue = 0;
xRCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_11;
xRCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
xRCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
xRCC_OscInitStruct.PLL.PLLM = 6;
xRCC_OscInitStruct.PLL.PLLN = 20;
xRCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
xRCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
xRCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
if( HAL_RCC_OscConfig( &xRCC_OscInitStruct ) != HAL_OK )
{
Error_Handler();
}