added freeRTOS on linux build

This commit is contained in:
2024-07-12 16:56:31 +02:00
parent a7336c7f75
commit 976e079d02
16 changed files with 576 additions and 321 deletions

View File

@ -1 +1 @@
target_sources(${TARGET_NAME} PRIVATE main.c testIp.c freeRTOS_rust_helper.c)
target_sources(${TARGET_NAME} PRIVATE mission.c freeRTOS_rust_helper.c)

View File

@ -2,15 +2,17 @@
#include "semphr.h"
#include "task.h"
#include <string.h>
// TODO namespace the names
SemaphoreHandle_t global_threading_semaphore = NULL;
uint8_t global_threading_available_c() {
if (global_threading_semaphore == NULL) {
global_threading_semaphore = xSemaphoreCreateBinary();
//xSemaphoreGive(global_threading_semaphore);
// xSemaphoreGive(global_threading_semaphore);
}
if (uxSemaphoreGetCount(global_threading_semaphore) == 1) {
return 1;
@ -19,22 +21,42 @@ uint8_t global_threading_available_c() {
}
}
void enable_global_threading_c() {
xSemaphoreGive(global_threading_semaphore);
}
void enable_global_threading_c() { xSemaphoreGive(global_threading_semaphore); }
void disable_global_threading_c() {
xSemaphoreTake(global_threading_semaphore, portMAX_DELAY);
}
const char *get_task_name() { return pcTaskGetName(NULL); }
const char *INVALID_TASK = "invalid task";
const char *get_task_name() {
/* this function is called from rust's panic,
* so we need to be extra sure to not cause another
* one. pcTaskGetName will trigger an assertion
* on debug builds if no task is running so we
* check if the current task is valid before using it.
* xTaskGetCurrentTaskHandle seems to be a lightweight
* way to do that */
void *task_handle = xTaskGetCurrentTaskHandle();
if (task_handle == NULL) {
return INVALID_TASK;
}
const char *name = pcTaskGetName(NULL);
if (name == NULL) {
return INVALID_TASK;
}
if (strlen(name) > configMAX_TASK_NAME_LEN) {
return INVALID_TASK;
}
return name;
}
void stop_it() { taskENTER_CRITICAL(); }
// TODO return some error code?
void *create_task(TaskFunction_t taskFunction, void *parameter,
uint32_t stack_size) {
//TODO verify uint32_t vs configSTACK_DEPTH_TYPE
// TODO verify uint32_t vs configSTACK_DEPTH_TYPE
TaskHandle_t newTask;
BaseType_t result =
xTaskCreate(taskFunction, "rust", stack_size, parameter, 4, &newTask);
@ -46,16 +68,18 @@ void *create_task(TaskFunction_t taskFunction, void *parameter,
}
void task_delay(uint32_t milliseconds) {
//TODO verify uint32_t vs TickType_t
// TODO verify uint32_t vs TickType_t
vTaskDelay(pdMS_TO_TICKS(milliseconds));
}
void delete_task(void * task){
vTaskSuspend(task); //we can not use vDeleteTask as it would free the allocated memory which is forbidden using heap1 (which we use)
void delete_task(void *task) {
vTaskSuspend(
task); // we can not use vDeleteTask as it would free the allocated memory
// which is forbidden using heap1 (which we use)
}
void *create_queue(uint32_t length, uint32_t element_size) {
//TODO verify uint32_t vs UBaseType_t
// TODO verify uint32_t vs UBaseType_t
QueueHandle_t newQueue = xQueueCreate(length, element_size);
return newQueue;
}
@ -76,11 +100,9 @@ uint8_t queue_send(void *queue, void *message) {
}
}
void *create_mutex() {
return xSemaphoreCreateRecursiveMutex();
}
void *create_mutex() { return xSemaphoreCreateRecursiveMutex(); }
uint8_t take_mutex(void * handle) {
uint8_t take_mutex(void *handle) {
// TODO check if global semaphore is free (ie, we are doing multitasking)
// if not, pointers are invalid, bail out
if (xSemaphoreTakeRecursive(handle, portMAX_DELAY) == pdPASS) {
@ -90,7 +112,7 @@ uint8_t take_mutex(void * handle) {
}
}
uint8_t give_mutex(void * handle) {
uint8_t give_mutex(void *handle) {
// TODO check if global semaphore is free (ie, we are doing multitasking)
// if not, pointers are invalid, bail out
if (xSemaphoreGiveRecursive(handle) == pdPASS) {

View File

@ -1,430 +0,0 @@
/*
* FreeRTOS V202212.00
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/******************************************************************************
*
* See http://www.freertos.org/RTOS-Xilinx-Zynq.html for instructions.
*
* This project provides three demo applications. A simple blinky style
* project, a more comprehensive test and demo application, and an lwIP example.
* The mainSELECTED_APPLICATION setting (defined in this file) is used to
* select between the three. The simply blinky demo is implemented and
* described in main_blinky.c. The more comprehensive test and demo application
* is implemented and described in main_full.c. The lwIP example is implemented
* and described in main_lwIP.c.
*
* This file implements the code that is not demo specific, including the
* hardware setup and FreeRTOS hook functions.
*
* !!! IMPORTANT NOTE !!!
* The GCC libraries that ship with the Xilinx SDK make use of the floating
* point registers. To avoid this causing corruption it is necessary to avoid
* their use unless a task has been given a floating point context. See
* https://www.FreeRTOS.org/Using-FreeRTOS-on-Cortex-A-Embedded-Processors.html
* for information on how to give a task a floating point context, and how to
* handle floating point operations in interrupts. As this demo does not give
* all tasks a floating point context main.c contains very basic C
* implementations of the standard C library functions memset(), memcpy() and
* memcmp(), which are are used by FreeRTOS itself. Defining these functions in
* the project prevents the linker pulling them in from the library. Any other
* standard C library functions that are used by the application must likewise
* be defined in C.
*
* ENSURE TO READ THE DOCUMENTATION PAGE FOR THIS PORT AND DEMO APPLICATION ON
* THE http://www.FreeRTOS.org WEB SITE FOR FULL INFORMATION ON USING THIS DEMO
* APPLICATION, AND ITS ASSOCIATE FreeRTOS ARCHITECTURE PORT!
*
*/
/* Standard includes. */
#include <limits.h>
#include <stdio.h>
/* Scheduler include files. */
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"
// /* Standard demo includes. */
// #include "EventGroupsDemo.h"
// #include "IntSemTest.h"
// #include "QueueOverwrite.h"
// #include "QueueSet.h"
// #include "StreamBufferDemo.h"
// #include "StreamBufferInterrupt.h"
// #include "TaskNotify.h"
// #include "TimerDemo.h"
// #include "partest.h"
/* Xilinx includes. */
// #include "platform.h"
#include "xil_exception.h"
#include "xparameters.h"
#include "xscugic.h"
#include "xscutimer.h"
#include "xuartps_hw.h"
/*
* Configure the hardware as necessary to run this demo.
*/
static void prvSetupHardware(void);
/*
* The Xilinx projects use a BSP that do not allow the start up code to be
* altered easily. Therefore the vector table used by FreeRTOS is defined in
* FreeRTOS_asm_vectors.S, which is part of this project. Switch to use the
* FreeRTOS vector table.
*/
extern void vPortInstallFreeRTOSVectorTable(void);
/* Prototypes for the standard FreeRTOS callback/hook functions implemented
within this file. */
void vApplicationMallocFailedHook(void);
void vApplicationIdleHook(void);
void vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName);
void vApplicationTickHook(void);
/* The private watchdog is used as the timer that generates run time
stats. This frequency means it will overflow quite quickly. */
XScuWdt xWatchDogInstance;
/*-----------------------------------------------------------*/
/* The interrupt controller is initialised in this file, and made available to
other modules. */
XScuGic xInterruptController;
extern SemaphoreHandle_t malloc_mutex;
/*-----------------------------------------------------------*/
void mission(void *);
void initFreeRTOSHelper();
int main(void) {
/* Configure the hardware ready to run the demo. */
prvSetupHardware();
// printf("Booting Software\n");
int taskParameters = 0;
static const size_t stackSizeWords = 102400;
StaticTask_t xTaskBuffer;
StackType_t xStack[stackSizeWords];
xTaskCreate(
mission, /* The function that implements the task. */
"init", /* The text name assigned to the task - for debug only as it is
not used by the kernel. */
10240, /* The size of the stack to allocate to the task. */
&taskParameters, /* The parameter passed to the task - not used in this
simple case. */
4, /* The priority assigned to the task. */
NULL);
vTaskStartScheduler();
/* If all is well, the scheduler will now be running, and the following
line will never be reached. If the following line does execute, then
there was either insufficient FreeRTOS heap memory available for the idle
and/or timer tasks to be created, or vTaskStartScheduler() was called from
User mode. See the memory management section on the FreeRTOS web site for
more details on the FreeRTOS heap http://www.freertos.org/a00111.html. The
mode from which main() is called is set in the C start up code and must be
a privileged mode (not user mode). */
for (;;)
;
/* Don't expect to reach here. */
return 0;
}
void testIp();
void rust_main();
// Marker for debugging sessions
__attribute__ ((noinline)) void done() {
asm ("");
}
void mission(void *) {
// printf("Starting Mission\n");
//testIp();
rust_main();
// printf("Started Tasks, deleting init task\n");
done();
vTaskDelete(NULL);
}
/*-----------------------------------------------------------*/
static void prvSetupHardware(void) {
BaseType_t xStatus;
XScuGic_Config *pxGICConfig;
/* Ensure no interrupts execute while the scheduler is in an inconsistent
state. Interrupts are automatically enabled when the scheduler is
started. */
portDISABLE_INTERRUPTS();
/* Obtain the configuration of the GIC. */
pxGICConfig = XScuGic_LookupConfig(XPAR_SCUGIC_SINGLE_DEVICE_ID);
/* Sanity check the FreeRTOSConfig.h settings are correct for the
hardware. */
configASSERT(pxGICConfig);
configASSERT(pxGICConfig->CpuBaseAddress ==
(configINTERRUPT_CONTROLLER_BASE_ADDRESS +
configINTERRUPT_CONTROLLER_CPU_INTERFACE_OFFSET));
configASSERT(pxGICConfig->DistBaseAddress ==
configINTERRUPT_CONTROLLER_BASE_ADDRESS);
/* Install a default handler for each GIC interrupt. */
xStatus = XScuGic_CfgInitialize(&xInterruptController, pxGICConfig,
pxGICConfig->CpuBaseAddress);
configASSERT(xStatus == XST_SUCCESS);
(void)xStatus; /* Remove compiler warning if configASSERT() is not defined. */
/* Initialise the LED port. */
// vParTestInitialise();
/* The Xilinx projects use a BSP that do not allow the start up code to be
altered easily. Therefore the vector table used by FreeRTOS is defined in
FreeRTOS_asm_vectors.S, which is part of this project. Switch to use the
FreeRTOS vector table. */
vPortInstallFreeRTOSVectorTable();
/* Initialise UART for use with QEMU. */
// XUartPs_ResetHw(0xE0000000);
// XUartPs_WriteReg(0xE0000000, XUARTPS_CR_OFFSET,
// ((u32)XUARTPS_CR_RX_DIS | (u32)XUARTPS_CR_TX_EN |
// (u32)XUARTPS_CR_STOPBRK));
}
/*-----------------------------------------------------------*/
void vApplicationMallocFailedHook(void) {
/* Called if a call to pvPortMalloc() fails because there is insufficient
free memory available in the FreeRTOS heap. pvPortMalloc() is called
internally by FreeRTOS API functions that create tasks, queues, software
timers, and semaphores. The size of the FreeRTOS heap is set by the
configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
taskDISABLE_INTERRUPTS();
//TODO panic
for (;;)
;
}
/*-----------------------------------------------------------*/
void vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName) {
(void)pcTaskName;
(void)pxTask;
/* Run time stack overflow checking is performed if
configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook
function is called if a stack overflow is detected. */
taskDISABLE_INTERRUPTS();
//TODO panic
for (;;)
;
}
/*-----------------------------------------------------------*/
void vApplicationIdleHook(void) {
volatile size_t xFreeHeapSpace, xMinimumEverFreeHeapSpace;
/* This is just a trivial example of an idle hook. It is called on each
cycle of the idle task. It must *NOT* attempt to block. In this case the
idle task just queries the amount of FreeRTOS heap that remains. See the
memory management section on the http://www.FreeRTOS.org web site for memory
management options. If there is a lot of heap memory free then the
configTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up
RAM. */
// xFreeHeapSpace = xPortGetFreeHeapSize();
// xMinimumEverFreeHeapSpace = xPortGetMinimumEverFreeHeapSize();
// /* Remove compiler warning about xFreeHeapSpace being set but never used.
// */ (void)xFreeHeapSpace; (void)xMinimumEverFreeHeapSpace;
}
/*-----------------------------------------------------------*/
void rust_assert_called(const char *pcFile, unsigned long ulLine);
void vAssertCalled(const char *pcFile, unsigned long ulLine) {
rust_assert_called(pcFile, ulLine);
volatile unsigned long ul = 0;
(void)pcFile;
(void)ulLine;
taskENTER_CRITICAL();
{
/* Set ul to a non-zero value using the debugger to step out of this
function. */
while (ul == 0) {
portNOP();
}
}
taskEXIT_CRITICAL();
}
/*-----------------------------------------------------------*/
void vApplicationTickHook(void) {
#if (mainSELECTED_APPLICATION == 1)
{
/* The full demo includes a software timer demo/test that requires
prodding periodically from the tick interrupt. */
vTimerPeriodicISRTests();
/* Call the periodic queue overwrite from ISR demo. */
vQueueOverwritePeriodicISRDemo();
/* Call the periodic event group from ISR demo. */
vPeriodicEventGroupsProcessing();
/* Use task notifications from an interrupt. */
xNotifyTaskFromISR();
/* Use mutexes from interrupts. */
vInterruptSemaphorePeriodicTest();
/* Writes to stream buffer byte by byte to test the stream buffer trigger
level functionality. */
vPeriodicStreamBufferProcessing();
/* Writes a string to a string buffer four bytes at a time to demonstrate
a stream being sent from an interrupt to a task. */
vBasicStreamBufferSendFromISR();
#if (configUSE_QUEUE_SETS == 1)
{ vQueueSetAccessQueueSetFromISR(); }
#endif
/* Test flop alignment in interrupts - calling printf from an interrupt
is BAD! */
#if (configASSERT_DEFINED == 1)
{
char cBuf[20];
UBaseType_t uxSavedInterruptStatus;
uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
{ sprintf(cBuf, "%1.3f", 1.234); }
portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
configASSERT(strcmp(cBuf, "1.234") == 0);
}
#endif /* configASSERT_DEFINED */
}
#endif
}
/*-----------------------------------------------------------*/
void vInitialiseTimerForRunTimeStats(void) {
XScuWdt_Config *pxWatchDogInstance;
uint32_t ulValue;
const uint32_t ulMaxDivisor = 0xff, ulDivisorShift = 0x08;
pxWatchDogInstance = XScuWdt_LookupConfig(XPAR_SCUWDT_0_DEVICE_ID);
XScuWdt_CfgInitialize(&xWatchDogInstance, pxWatchDogInstance,
pxWatchDogInstance->BaseAddr);
ulValue = XScuWdt_GetControlReg(&xWatchDogInstance);
ulValue |= ulMaxDivisor << ulDivisorShift;
XScuWdt_SetControlReg(&xWatchDogInstance, ulValue);
XScuWdt_LoadWdt(&xWatchDogInstance, UINT_MAX);
XScuWdt_SetTimerMode(&xWatchDogInstance);
XScuWdt_Start(&xWatchDogInstance);
}
/*-----------------------------------------------------------*/
/* 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 and configUSE_TIMERS are both set to 1, so the
application must provide an implementation of vApplicationGetTimerTaskMemory()
to provide the memory that is used by the Timer service task. */
void vApplicationGetTimerTaskMemory(StaticTask_t **ppxTimerTaskTCBBuffer,
StackType_t **ppxTimerTaskStackBuffer,
uint32_t *pulTimerTaskStackSize);
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 Timer
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;
}

102
mission/mission.c Normal file
View File

@ -0,0 +1,102 @@
/* Standard includes. */
#include <limits.h>
#include <stdio.h>
/* Scheduler include files. */
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"
void rust_main();
// called to stop execution (either a panic or program ended)
// to be implemented by bsp (do not return from it!)
void done();
void init_task(void *) {
// printf("Starting Mission\n");
rust_main();
// printf("Started Tasks, deleting init task\n");
done();
vTaskDelete(NULL);
}
void mission(void) {
int taskParameters = 0;
static const size_t stackSizeWords = 102400;
StaticTask_t xTaskBuffer;
StackType_t xStack[stackSizeWords];
xTaskCreate(init_task, /* The function that implements the task. */
"init", /* The text name assigned to the task - for debug only as
it is not used by the kernel. */
10240, /* The size of the stack to allocate to the task. */
&taskParameters, /* The parameter passed to the task - not used in
this simple case. */
4, /* The priority assigned to the task. */
NULL);
vTaskStartScheduler();
/* If all is well, the scheduler will now be running, and the following
line will never be reached. If the following line does execute, then
there was either insufficient FreeRTOS heap memory available for the idle
and/or timer tasks to be created, or vTaskStartScheduler() was called from
User mode. See the memory management section on the FreeRTOS web site for
more details on the FreeRTOS heap http://www.freertos.org/a00111.html. The
mode from which main() is called is set in the C start up code and must be
a privileged mode (not user mode). */
done();
for (;;)
;
/* Don't expect to reach here. */
return;
}
/*-----------------------------------------------------------*/
void vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName) {
(void)pcTaskName;
(void)pxTask;
/* Run time stack overflow checking is performed if
configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook
function is called if a stack overflow is detected. */
taskDISABLE_INTERRUPTS();
// TODO panic
for (;;)
;
}
/*-----------------------------------------------------------*/
void rust_alloc_failed();
void vApplicationMallocFailedHook(void) {
/* Called if a call to pvPortMalloc() fails because there is insufficient
free memory available in the FreeRTOS heap. pvPortMalloc() is called
internally by FreeRTOS API functions that create tasks, queues, software
timers, and semaphores. The size of the FreeRTOS heap is set by the
configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
taskDISABLE_INTERRUPTS();
rust_alloc_failed();
for (;;)
;
}
void rust_assert_called(const char *pcFile, unsigned long ulLine);
void vAssertCalled(const char *pcFile, unsigned long ulLine) {
taskDISABLE_INTERRUPTS();
rust_assert_called(pcFile, ulLine);
}
/*-----------------------------------------------------------*/
/*-----------------------------------------------------------*/

View File

@ -1,230 +0,0 @@
#include "FreeRTOS.h"
#include "lwip/init.h"
#include "lwip/sio.h"
#include "lwip/timeouts.h"
#include "lwip/udp.h"
#include "queue.h"
#include "task.h"
#include <lwip/ip_addr.h>
#include <lwip/netif.h>
#include <netif/slipif.h>
#include <xscugic.h>
#include <xuartps.h>
#undef XUARTPS_IXR_RXOVR
#define XUARTPS_IXR_RXOVR 0x00000020U /**< Rx Overrun error interrupt */
#define XUARTPS_IXR_RTRIG 0x00000001U /**< RX FIFO trigger interrupt. */
// #include <lwip/apps/tftp_server.h>
// void slipif_rxbyte_input(struct netif *netif, u8_t c);
// uint8_t packets = 0;
// static void *tftp_open(const char *fname, const char *mode, u8_t is_write) {
// LWIP_UNUSED_ARG(mode);
// packets = 100;
// return (void *)13;
// }
// static void tftp_close(void *handle) {}
// static int tftp_read(void *handle, void *buf, int bytes) {
// memset(buf, 'x', bytes);
// if (packets == 0) {
// return 0;
// } else {
// packets--;
// return bytes;
// }
// }
// static int tftp_write(void *handle, struct pbuf *p) { return 0; }
// /* For TFTP client only */
// static void tftp_error(void *handle, int err, const char *msg, int size) {}
// static const struct tftp_context tftp = {tftp_open, tftp_close, tftp_read,
// tftp_write, tftp_error};
struct netif netif;
QueueHandle_t uartIsrQueue;
extern XScuGic xInterruptController; /* Interrupt controller instance */
/** this is based on XUartPs_InterruptHandler() in xuartps_intr.c*/
void handleUARTInt(void *) {
u32 IsrStatus;
/*
* Read the interrupt ID register to determine which
* interrupt is active
*/
IsrStatus = XUartPs_ReadReg(STDIN_BASEADDRESS, XUARTPS_IMR_OFFSET);
IsrStatus &= XUartPs_ReadReg(STDIN_BASEADDRESS, XUARTPS_ISR_OFFSET);
// Onlx RX intterupts are enabled
// We do not care which interrupt actually triggered, just get all bytes
// available into the stack
uint8_t RecievedByte;
BaseType_t xHigherPriorityTaskWoken;
while (XUartPs_IsReceiveData(STDIN_BASEADDRESS)) {
RecievedByte = XUartPs_ReadReg(STDIN_BASEADDRESS, XUARTPS_FIFO_OFFSET);
xQueueSendToBackFromISR(uartIsrQueue, &RecievedByte,
&xHigherPriorityTaskWoken);
}
/* Clear the interrupt status. */
XUartPs_WriteReg(STDIN_BASEADDRESS, XUARTPS_ISR_OFFSET, IsrStatus);
/* directly yield if sending to the queue woke something in ourselves */
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
static struct udp_pcb *udpecho_raw_pcb;
static void
udpecho_raw_recv(void *arg, struct udp_pcb *upcb, struct pbuf *p,
const ip_addr_t *addr, u16_t port)
{
LWIP_UNUSED_ARG(arg);
if (p != NULL) {
/* send received packet back to sender */
udp_sendto(upcb, p, addr, port);
/* free the pbuf */
pbuf_free(p);
}
}
uint8_t data[] = {'1','2','3','4','5'};
void lwip_main(void *) {
struct pbuf* tx = pbuf_alloc_reference(data, sizeof(data), PBUF_REF);
ip_addr_t addr = IPADDR4_INIT_BYTES(10,0,0,13);
udp_sendto(udpecho_raw_pcb, tx, &addr, 1177);
pbuf_free(tx);
while (1) {
// slipif_rxbyte_input() is private, so we use slipif_poll and implement
// sio_tryread()
// sio_tryread() will do a blocking read with a timeout, so we get to check
// the timeouts even if no data is incoming
slipif_poll(&netif);
sys_check_timeouts();
}
}
// TODO define sio_fd_t to an int
uint32_t sio_data;
sio_fd_t sio_open(u8_t devnum) { return &sio_data; }
void sio_send(u8_t c, sio_fd_t fd) { XUartPs_SendByte(STDOUT_BASEADDRESS, c); }
u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len) {
if (len < 1) {
return 0;
}
BaseType_t result;
//need a timeout because lwip task needs to do background work
result = xQueueReceive(uartIsrQueue, data, pdMS_TO_TICKS(250));
if (result == pdTRUE) {
return 1;
} else {
return 0;
}
}
#ifdef LWIP_DEBUG
const char *lwip_strerr(err_t err) { return "Dafuq i know? I am a NOSYS"; }
#endif
u32_t sys_now(void) { return xTaskGetTickCount() * portTICK_PERIOD_MS; }
static StaticQueue_t xStaticQueue;
static const uint16_t QUEUE_LENGTH = 512;
uint8_t ucQueueStorageArea[512 * 1];
static const uint16_t stackSizeWords = 512;
StaticTask_t xTaskBuffer;
StackType_t xStack[512];
// void testIp() {
// uartIsrQueue =
// xQueueCreateStatic(QUEUE_LENGTH, 1, ucQueueStorageArea, &xStaticQueue);
// lwip_init();
// ip4_addr_t slip_addr = {PP_HTONL(LWIP_MAKEU32(10, 0, 0, 32))},
// slip_mask = {PP_HTONL(LWIP_MAKEU32(255, 255, 255, 0))},
// slip_gw = {PP_HTONL(LWIP_MAKEU32(10, 0, 0, 1))};
// netif_add(&netif, &slip_addr, &slip_mask, &slip_gw, NULL, slipif_init,
// netif_input);
// netif_set_default(&netif);
// // should be done by driver, which does not do it, so we do it here
// netif_set_link_up(&netif);
// netif_set_up(&netif);
// udpecho_raw_pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
// if (udpecho_raw_pcb != NULL) {
// err_t err;
// err = udp_bind(udpecho_raw_pcb, IP_ANY_TYPE, 7);
// if (err == ERR_OK) {
// udp_recv(udpecho_raw_pcb, udpecho_raw_recv, NULL);
// } else {
// /* TODO */
// }
// } else {
// /* TODO */
// }
// /* Install the UART Interrupt handler. */
// BaseType_t xStatus =
// XScuGic_Connect(&xInterruptController, STDIN_INT_NR,
// (Xil_ExceptionHandler)handleUARTInt, NULL);
// configASSERT(xStatus == XST_SUCCESS);
// (void)xStatus; /* Remove compiler warning if configASSERT() is not defined. */
// // Set trigger level to 62 of 64 bytes, giving interrupt some time to react
// XUartPs_WriteReg(STDIN_BASEADDRESS, XUARTPS_RXWM_OFFSET, 62);
// // Setting the rx timeout to n*4 -1 bits
// XUartPs_WriteReg(STDIN_BASEADDRESS, XUARTPS_RXTOUT_OFFSET, 50);
// // enable UART Interrupts
// u32 mask = XUARTPS_IXR_RTRIG | XUARTPS_IXR_RXOVR | XUARTPS_IXR_RXFULL |
// XUARTPS_IXR_TOUT;
// /* Write the mask to the IER Register */
// XUartPs_WriteReg(STDIN_BASEADDRESS, XUARTPS_IER_OFFSET, mask);
// /* Write the inverse of the Mask to the IDR register */
// XUartPs_WriteReg(STDIN_BASEADDRESS, XUARTPS_IDR_OFFSET, (~mask));
// /* Enable the interrupt for the UART1 in the interrupt controller. */
// XScuGic_Enable(&xInterruptController, STDIN_INT_NR);
// // Start lwip task
// xTaskCreateStatic(
// lwip_main, /* The function that implements the task. */
// "lwip", /* The text name assigned to the task - for debug
// only as it is not used by the kernel. */
// stackSizeWords, /* The size of the stack to allocate to the task. */
// NULL, /* The parameter passed to the task - not used in this
// simple case. */
// 4, /* The priority assigned to the task. */
// xStack, &xTaskBuffer);
// }