From 3ae9e3e24a57effb107acea96719955db9f699c8 Mon Sep 17 00:00:00 2001 From: Scott Mabin Date: Thu, 20 Jul 2023 12:13:09 +0100 Subject: [PATCH] Replace the hardcoded ip address with a dns lookup --- Cargo.toml | 2 +- src/main.rs | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5e825a3..bd2c453 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ heapless = "0.7.16" esp-backtrace = { version = "0.7.0", features = ["esp32c3", "panic-handler", "exception-handler", "print-uart"] } esp-println = { version = "0.5.0", features = ["esp32c3","log"] } embedded-svc = { version = "0.25.0", default-features = false} -embassy-net = { version = "0.1.0", features = ["nightly", "tcp", "udp", "dhcpv4", "medium-ethernet", "proto-ipv6", "log"] } +embassy-net = { version = "0.1.0", features = ["nightly", "tcp", "udp", "dhcpv4", "medium-ethernet", "proto-ipv6", "log", "dns"] } embassy-executor = { version = "0.2.0", features = ["nightly", "integrated-timers", "arch-riscv32", "executor-thread"] } embassy-time = { version = "0.1.1", features = ["nightly"] } embedded-hal = { version = "0.2.7", features = ["unproven"] } diff --git a/src/main.rs b/src/main.rs index cad3638..06a3b12 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,7 +28,7 @@ use embassy_time::{Duration, Timer}; use embassy_executor::_export::StaticCell; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Stack, StackResources}; +use embassy_net::{Config, Stack, StackResources, dns::DnsQueryType}; use heapless::String; use core::fmt::Write; @@ -124,7 +124,15 @@ async fn task(stack: &'static Stack>, i2c: I2C<'static, I2C0 socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - let remote_endpoint = (Ipv4Address::new(52, 57, 158, 144), 1883); + let address = match stack.dns_query("broker.hivemq.com", DnsQueryType::A).await.map(|a| a[0]) { + Ok(address) => address, + Err(e) => { + println!("DNS lookup error: {e:?}"); + continue + } + }; + + let remote_endpoint = (address, 1883); println!("connecting..."); let connection = socket.connect(remote_endpoint).await; if let Err(e) = connection {