|
| 1 | +#include <zephyr/kernel.h> |
| 2 | +#include <zephyr/logging/log.h> |
| 3 | +#include <zephyr/net/net_if.h> |
| 4 | +#include <zephyr/net/net_core.h> |
| 5 | +#include <zephyr/net/net_mgmt.h> |
| 6 | +#include <zephyr/net/ethernet.h> |
| 7 | + |
| 8 | +LOG_MODULE_REGISTER(eth, LOG_LEVEL_INF); |
| 9 | + |
| 10 | +#define ETH_STATIC_IP "169.254.0.1" |
| 11 | +#define ETH_NETMASK "255.255.0.0" |
| 12 | + |
| 13 | +static struct net_if *eth_iface; |
| 14 | +static struct net_mgmt_event_callback eth_cb; |
| 15 | +static bool eth_configured; |
| 16 | + |
| 17 | +static void eth_event_handler(struct net_mgmt_event_callback *cb, |
| 18 | + uint32_t mgmt_event, |
| 19 | + struct net_if *iface) |
| 20 | +{ |
| 21 | + if (iface != eth_iface) { |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + if (mgmt_event == NET_EVENT_IF_UP) { |
| 26 | + LOG_INF("Ethernet interface up"); |
| 27 | + } else if (mgmt_event == NET_EVENT_IF_DOWN) { |
| 28 | + LOG_WRN("Ethernet interface down"); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +extern "C" auto eth_init() -> int |
| 33 | +{ |
| 34 | + struct in_addr addr; |
| 35 | + struct in_addr netmask; |
| 36 | + struct net_if_addr *ifaddr; |
| 37 | + |
| 38 | + eth_iface = net_if_get_first_by_type(&NET_L2_GET_NAME(ETHERNET)); |
| 39 | + if (eth_iface == nullptr) { |
| 40 | + LOG_ERR("No Ethernet interface found"); |
| 41 | + return -ENODEV; |
| 42 | + } |
| 43 | + |
| 44 | + LOG_INF("Ethernet interface found: %s", net_if_get_device(eth_iface)->name); |
| 45 | + |
| 46 | + net_mgmt_init_event_callback(ð_cb, eth_event_handler, |
| 47 | + NET_EVENT_IF_UP | NET_EVENT_IF_DOWN); |
| 48 | + net_mgmt_add_event_callback(ð_cb); |
| 49 | + |
| 50 | + if (net_addr_pton(AF_INET, ETH_STATIC_IP, &addr) < 0) { |
| 51 | + LOG_ERR("Invalid IP address: %s", ETH_STATIC_IP); |
| 52 | + return -EINVAL; |
| 53 | + } |
| 54 | + |
| 55 | + if (net_addr_pton(AF_INET, ETH_NETMASK, &netmask) < 0) { |
| 56 | + LOG_ERR("Invalid netmask: %s", ETH_NETMASK); |
| 57 | + return -EINVAL; |
| 58 | + } |
| 59 | + |
| 60 | + ifaddr = net_if_ipv4_addr_add(eth_iface, &addr, NET_ADDR_MANUAL, 0); |
| 61 | + if (ifaddr == nullptr) { |
| 62 | + LOG_ERR("Failed to add IP address"); |
| 63 | + return -ENOMEM; |
| 64 | + } |
| 65 | + |
| 66 | + net_if_ipv4_set_netmask_by_addr(eth_iface, &addr, &netmask); |
| 67 | + |
| 68 | + eth_configured = true; |
| 69 | + LOG_INF("Ethernet configured with IP %s/%s", ETH_STATIC_IP, ETH_NETMASK); |
| 70 | + |
| 71 | + return 0; |
| 72 | +} |
| 73 | + |
| 74 | +extern "C" auto eth_is_configured() -> bool |
| 75 | +{ |
| 76 | + return eth_configured; |
| 77 | +} |
0 commit comments