Seregon/rtnet-stack

Real-Time Embedded Network Stack

C/66 B/No license
examples/udp_echo_server/main.c
1#include "rtnet_stack.h"
2#include <stdio.h>
3#include <string.h>
4 
5static const RTNET_IPv6Addr_t LOCAL_IP = { .addr = {0xFE,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,1} };
6static const RTNET_MACAddr_t LOCAL_MAC = { .addr = {0x00,0x11,0x22,0x33,0x44,0x55} };
7static const RTNET_IPv6Addr_t REMOTE_IP = { .addr = {0xFE,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,2} };
8 
9/* On target: invoke from Ethernet RX ISR with the received frame */
10static void ethernet_rx_handler(const uint8_t* frame, uint16_t length)
11{
12 if ((frame != NULL) && (length > 0U)) {
13 (void)RTNET_ProcessRxPacket(frame, length);
14 }
15}
16 
17static bool init_stack(void)
18{
19 if (RTNET_Initialize(&LOCAL_IP, &LOCAL_MAC) != RTNET_OK) {
20 printf("[udp_echo] Init failed\n");
21 return false;
22 }
23 
24 /* Add link-local /64 for echo traffic */
25 RTNET_IPv6Addr_t prefix = LOCAL_IP;
26 prefix.addr[15] = 0;
27 if (RTNET_AddRoute(&prefix, 64U, NULL, 1U) != RTNET_OK) {
28 printf("[udp_echo] Route add failed\n");
29 return false;
30 }
31 
32 return true;
33}
34 
35static void send_echo_demo(void)
36{
37 const uint8_t echo_payload[] = "echo";
38 RTNET_Error_t err = RTNET_UDP_Send(&REMOTE_IP, 7U, 0U,
39 echo_payload, (uint16_t)sizeof(echo_payload),
40 RTNET_QOS_NORMAL);
41 if (err != RTNET_OK) {
42 printf("[udp_echo] UDP send error: %d\n", err);
43 }
44}
45 
46int main(void)
47{
48 if (!init_stack()) {
49 return -1;
50 }
51 
52 for (;;) {
53 /* In real firmware, feed frames from ETH driver to the stack */
54 ethernet_rx_handler(NULL, 0);
55 
56 /* Reply/demo send (would typically be triggered by received data) */
57 send_echo_demo();
58 
59 /* Periodic maintenance for aging and timeouts */
60 RTNET_PeriodicTask();
61 }
62}
63