21 struct net_if* iface = net_if_get_default();
22 struct net_linkaddr* addr = net_if_get_link_addr(iface);
23 uint8_t* mac = addr->addr;
29 struct in_addr ip = make_ip(0);
30 return begin(mac, ip,
false);
33 bool begin(uint8_t* mac,
struct in_addr ip) {
34 bool static_ip = (ip.s_addr != 0);
35 return begin(mac, ip, static_ip);
44 bool linkUp()
const {
return _link_up; }
46 const struct in_addr&
localIP()
const {
return _ip; }
49 static char buf[NET_IPV4_ADDR_LEN];
50 net_addr_ntop(AF_INET, &_ip, buf,
sizeof(buf));
67 bool begin(uint8_t* mac,
struct in_addr ip,
bool static_ip) {
70 _iface = net_if_get_default();
72 LOGE(
"No network interface");
77 net_if_set_link_addr(_iface, mac, 6, NET_LINK_ETHERNET);
85 net_mgmt_init_event_callback(&_ip_cb, ip_event_handler,
86 NET_EVENT_IPV4_ADDR_ADD);
88 net_mgmt_add_event_callback(&_ip_cb);
91 LOGI(
"Ethernet: static IP");
93 net_if_ipv4_addr_add(_iface, &ip, NET_ADDR_MANUAL, 0);
100 LOGI(
"Ethernet: DHCP");
102 net_dhcpv4_start(_iface);
111 static void ip_event_handler(
struct net_mgmt_event_callback* cb,
112 uint64_t event,
struct net_if* iface) {
113 if (!_instance)
return;
115 if (event != NET_EVENT_IPV4_ADDR_ADD)
return;
117 struct net_if_ipv4* ipv4 = iface->config.ip.ipv4;
120 for (
int i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) {
121#if KERNEL_VERSION_NUMBER >= ZEPHYR_VERSION(3, 4, 0)
122 struct net_if_addr_ipv4* entry = &ipv4->unicast[i];
123 struct net_if_addr* addr = &entry->ipv4;
125 struct net_if_addr* addr = &ipv4->unicast[i];
128 if (addr->is_used && addr->addr_type == NET_ADDR_DHCP &&
129 addr->address.family == AF_INET) {
130 _instance->_ip = addr->address.in_addr;
131 _instance->_ip_ready =
true;
133 char buf[NET_IPV4_ADDR_LEN];
134 net_addr_ntop(AF_INET, &_instance->_ip, buf,
sizeof(buf));
136 LOGI(
"Ethernet IP: %s", buf);
147 static inline struct in_addr make_ip(uint32_t v = 0) {
154 struct net_if* _iface =
nullptr;
156 struct in_addr _ip = {};
157 volatile bool _ip_ready =
false;
158 volatile bool _link_up =
false;
160 struct net_mgmt_event_callback _ip_cb;
162 static EthernetZephyr* _instance;