Real-Time Embedded Network Stack
| 1 | #include "rtnet_stack.h" |
| 2 | #include <stdio.h> |
| 3 | #include <string.h> |
| 4 | |
| 5 | static const RTNET_IPv6Addr_t LOCAL_IP = { .addr = {0xFE,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0x10} }; |
| 6 | static const RTNET_MACAddr_t LOCAL_MAC = { .addr = {0x00,0xDE,0xAD,0xBE,0xEF,0x01} }; |
| 7 | static const RTNET_IPv6Addr_t REMOTE_IP = { .addr = {0x20,0x01,0x0D,0xB8,0,0,0,0,0,0,0,0,0,0,0,0x01} }; /* 2001:db8::1 */ |
| 8 | |
| 9 | static bool setup_stack(void) |
| 10 | { |
| 11 | if (RTNET_Initialize(&LOCAL_IP, &LOCAL_MAC) != RTNET_OK) { |
| 12 | printf("[demo] Init failed\n"); |
| 13 | return false; |
| 14 | } |
| 15 | |
| 16 | /* Add a host route to REMOTE_IP (direct for demo) */ |
| 17 | if (RTNET_AddRoute(&REMOTE_IP, 128U, NULL, 1U) != RTNET_OK) { |
| 18 | printf("[demo] Route add failed\n"); |
| 19 | return false; |
| 20 | } |
| 21 | |
| 22 | return true; |
| 23 | } |
| 24 | |
| 25 | static void demo_udp(void) |
| 26 | { |
| 27 | const uint8_t payload[] = "hello from host"; |
| 28 | RTNET_Error_t err = RTNET_UDP_Send(&REMOTE_IP, 12345U, 0U, |
| 29 | payload, (uint16_t)sizeof(payload), |
| 30 | RTNET_QOS_NORMAL); |
| 31 | printf("[demo][udp] send -> %d\n", err); |
| 32 | } |
| 33 | |
| 34 | static void demo_tcp(void) |
| 35 | { |
| 36 | uint8_t conn_id = 0U; |
| 37 | RTNET_Error_t err = RTNET_TCP_Connect(&REMOTE_IP, 80U, &conn_id); |
| 38 | printf("[demo][tcp] connect -> %d (conn=%u)\n", err, conn_id); |
| 39 | if (err == RTNET_OK) { |
| 40 | const uint8_t http_get[] = "GET / HTTP/1.1\r\nHost: demo\r\n\r\n"; |
| 41 | err = RTNET_TCP_Send(conn_id, http_get, (uint16_t)sizeof(http_get)); |
| 42 | printf("[demo][tcp] send -> %d\n", err); |
| 43 | err = RTNET_TCP_Close(conn_id); |
| 44 | printf("[demo][tcp] close -> %d\n", err); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | static void demo_mdns(void) |
| 49 | { |
| 50 | RTNET_mDNSRecord_t rec; |
| 51 | RTNET_Error_t err = RTNET_mDNS_Query("_http._tcp.local", &rec); |
| 52 | printf("[demo][mdns] query -> %d", err); |
| 53 | if (err == RTNET_OK) { |
| 54 | printf(" (port=%u)\n", rec.port); |
| 55 | } else { |
| 56 | printf("\n"); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | int main(void) |
| 61 | { |
| 62 | if (!setup_stack()) { |
| 63 | return -1; |
| 64 | } |
| 65 | |
| 66 | demo_udp(); |
| 67 | demo_tcp(); |
| 68 | demo_mdns(); |
| 69 | |
| 70 | /* Run a few maintenance ticks to emulate periodic servicing */ |
| 71 | for (int i = 0; i < 3; i++) { |
| 72 | RTNET_PeriodicTask(); |
| 73 | } |
| 74 | |
| 75 | RTNET_Statistics_t stats; |
| 76 | if (RTNET_GetStatistics(&stats) == RTNET_OK) { |
| 77 | printf("[demo][stats] tx=%lu rx=%lu dropped=%lu routing_err=%lu\n", |
| 78 | (unsigned long)stats.tx_packets, |
| 79 | (unsigned long)stats.rx_packets, |
| 80 | (unsigned long)stats.tx_dropped, |
| 81 | (unsigned long)stats.routing_errors); |
| 82 | } |
| 83 | |
| 84 | return 0; |
| 85 | } |
| 86 |