I2C detection works well

This commit is contained in:
Priec
2026-01-08 20:55:28 +01:00
parent 70c37c344b
commit d8b4352a0f
16 changed files with 2388 additions and 0 deletions

View File

@@ -0,0 +1,185 @@
// src/bin/main.rs
#![no_std]
#![no_main]
#![deny(
clippy::mem_forget,
reason = "mem::forget is generally not safe to do with esp_hal types"
)]
use embassy_executor::Spawner;
use embassy_futures::select::{select, Either};
use embassy_net::{Runner, StackResources};
use embassy_time::{Duration, Timer};
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::{clock::CpuClock, rng::Rng, timer::timg::TimerGroup};
use esp_wifi::{
init,
wifi::{ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiState},
EspWifiController,
};
use log::info;
use rust_mqtt::packet::v5::publish_packet::QualityOfService;
use projekt_final::mqtt::client::{
mqtt_events, mqtt_publish, mqtt_subscribe, mqtt_task, IncomingMsg,
};
use projekt_final::i2c::com::i2c_check;
use defmt_rtt as _;
extern crate alloc;
esp_bootloader_esp_idf::esp_app_desc!();
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
const SSID: &str = env!("SSID");
const PASSWORD: &str = env!("PASSWORD");
#[esp_hal_embassy::main]
async fn main(spawner: Spawner) -> ! {
esp_println::logger::init_logger_from_env();
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
let peripherals = esp_hal::init(config);
esp_alloc::heap_allocator!(size: 72 * 1024);
let timg0 = TimerGroup::new(peripherals.TIMG0);
let mut rng = Rng::new(peripherals.RNG);
let esp_wifi_ctrl = &*mk_static!(
EspWifiController<'static>,
init(timg0.timer0, rng.clone()).unwrap()
);
let (controller, interfaces) =
esp_wifi::wifi::new(&esp_wifi_ctrl, peripherals.WIFI).unwrap();
let wifi_interface = interfaces.sta;
let timg1 = TimerGroup::new(peripherals.TIMG1);
esp_hal_embassy::init(timg1.timer0);
let config = embassy_net::Config::dhcpv4(Default::default());
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
// Init network stack
let (stack, runner) = embassy_net::new(
wifi_interface,
config,
mk_static!(StackResources<3>, StackResources::<3>::new()),
seed,
);
spawner.spawn(connection(controller)).ok();
spawner.spawn(net_task(runner)).ok();
// Wait for link up
loop {
if stack.is_link_up() {
break;
}
Timer::after(Duration::from_millis(500)).await;
}
info!("Waiting to get IP address...");
loop {
if let Some(config) = stack.config_v4() {
info!("Got IP: {}", config.address);
break;
}
Timer::after(Duration::from_millis(500)).await;
}
spawner.spawn(mqtt_task(stack)).expect("failed to spawn MQTT task");
info!("MQTT task started");
spawner.spawn(i2c_check()).expect("failed to spawn I2C task");
info!("I2C scan task started");
mqtt_publish("esp32/topic", b"hello from ESP32 (init)", QualityOfService::QoS1, false).await;
info!("Sent initial MQTT message");
mqtt_subscribe("esp32/topic").await;
// Get a receiver for incoming MQTT messages
let mqtt_rx = mqtt_events();
loop {
// Drive both: either process an MQTT message or publish periodically
match select(mqtt_rx.receive(), Timer::after(Duration::from_secs(5))).await
{
// Received inbound MQTT message (from broker)
Either::First(msg) => {
handle_incoming(msg);
}
// Time-based example publish
Either::Second(_) => {
// mqtt_publish(
// "esp32/topic",
// b"hello from main",
// QualityOfService::QoS1,
// false,
// )
// .await;
}
}
}
}
fn handle_incoming(msg: IncomingMsg) {
if let Ok(txt) = core::str::from_utf8(&msg.payload) {
info!("MAIN RX [{}]: {}", msg.topic.as_str(), txt);
info!("Received MQTT message -> topic: '{}', payload: '{}'", msg.topic.as_str(), txt);
} else {
info!("MAIN RX [{}]: {:?}", msg.topic.as_str(), msg.payload);
}
}
#[embassy_executor::task]
async fn connection(mut controller: WifiController<'static>) {
info!("start connection task");
info!("Device capabilities: {:?}", controller.capabilities());
loop {
match esp_wifi::wifi::wifi_state() {
WifiState::StaConnected => {
controller.wait_for_event(WifiEvent::StaDisconnected).await;
Timer::after(Duration::from_millis(5000)).await
}
_ => {}
}
if !matches!(controller.is_started(), Ok(true)) {
let client_config = Configuration::Client(ClientConfiguration {
ssid: SSID.into(),
password: PASSWORD.into(),
..Default::default()
});
controller.set_configuration(&client_config).unwrap();
info!("Starting wifi");
controller.start_async().await.unwrap();
info!("Wifi started!");
}
info!("About to connect...");
match controller.connect_async().await {
Ok(_) => info!("Wifi connected!"),
Err(e) => {
info!("Failed to connect to wifi: {e:?}");
Timer::after(Duration::from_millis(5000)).await
}
}
}
}
#[embassy_executor::task]
async fn net_task(mut runner: Runner<'static, WifiDevice<'static>>) {
runner.run().await
}

View File

@@ -0,0 +1,37 @@
// src/i2c/com.rs
use embassy_executor::task;
use embassy_time::{Duration, Timer};
use esp_hal::{
gpio::Io,
i2c::master::{Config, I2c},
peripherals::Peripherals,
};
use esp_println::println;
#[task]
pub async fn i2c_check() {
let peripherals = unsafe { Peripherals::steal() };
let _io = Io::new(peripherals.IO_MUX);
let sda = peripherals.GPIO21;
let scl = peripherals.GPIO22;
let mut i2c = I2c::new(peripherals.I2C0, Config::default())
.expect("Failed to initialize I2C")
.with_sda(sda)
.with_scl(scl);
loop {
println!("I2C bus scan start");
// Skenujeme adresy 0x03 až 0x77
for addr in 0x03..0x78 {
// Skúsime zapísať prázdne dáta na adresu
if i2c.write(addr, &[]).is_ok() {
println!("Device found at address 0x{:02X}", addr);
}
}
println!("Scan finished");
Timer::after(Duration::from_secs(5)).await;
}
}

View File

@@ -0,0 +1,3 @@
// src/i2c/mod.rs
pub mod com;

4
mqtt_display/src/lib.rs Normal file
View File

@@ -0,0 +1,4 @@
#![no_std]
pub mod mqtt;
pub mod i2c;

View File

@@ -0,0 +1,230 @@
// src/mqtt/client.rs
use embassy_futures::select::{select, Either};
use embassy_net::{tcp::TcpSocket, Stack};
use embassy_time::{Duration, Timer};
use log::info;
use rust_mqtt::client::client::MqttClient;
use rust_mqtt::client::client_config::{ClientConfig, MqttVersion};
use rust_mqtt::packet::v5::publish_packet::QualityOfService;
use rust_mqtt::packet::v5::reason_codes::ReasonCode;
use rust_mqtt::utils::rng_generator::CountingRng;
use static_cell::ConstStaticCell;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::{Channel, Receiver};
use heapless::{String as HString, Vec as HVec};
use crate::mqtt::config::mqtt_broker_endpoint;
const RECONNECT_DELAY_SECS: u64 = 5;
const KEEPALIVE_SECS: u64 = 60;
const PING_PERIOD: Duration = Duration::from_secs(KEEPALIVE_SECS / 2);
// Limits for small, static buffers (no heap)
pub const TOPIC_MAX: usize = 128;
pub const PAYLOAD_MAX: usize = 512;
const COMMAND_QUEUE: usize = 8;
const EVENT_QUEUE: usize = 8;
// TCP socket buffers (for embassy-net TcpSocket)
static TCP_RX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]);
static TCP_TX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]);
// MQTT client buffers (separate from the TcpSocket's buffers)
static MQTT_TX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
static MQTT_RX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
// Tie TcpSocket lifetime to session
type Client<'a, 'net> = MqttClient<'a, TcpSocket<'net>, 8, CountingRng>;
#[derive(Clone)]
pub struct IncomingMsg {
pub topic: HString<TOPIC_MAX>,
pub payload: HVec<u8, PAYLOAD_MAX>,
}
#[derive(Clone)]
struct PublishMsg {
topic: HString<TOPIC_MAX>,
payload: HVec<u8, PAYLOAD_MAX>,
qos: QualityOfService,
retain: bool,
}
#[derive(Clone)]
enum Command {
Publish(PublishMsg),
Subscribe(HString<TOPIC_MAX>),
}
static CMD_CHAN: Channel<CriticalSectionRawMutex, Command, COMMAND_QUEUE> = Channel::new();
static EVT_CHAN: Channel<CriticalSectionRawMutex, IncomingMsg, EVENT_QUEUE> = Channel::new();
// Public API
pub async fn mqtt_publish(topic: &str, payload: &[u8], qos: QualityOfService, retain: bool) {
CMD_CHAN
.send(Command::Publish(PublishMsg {
topic: truncate_str::<TOPIC_MAX>(topic),
payload: truncate_payload(payload),
qos,
retain,
}))
.await;
}
pub async fn mqtt_subscribe(topic: &str) {
CMD_CHAN.send(Command::Subscribe(truncate_str::<TOPIC_MAX>(topic))).await;
}
pub fn mqtt_events(
) -> Receiver<'static, CriticalSectionRawMutex, IncomingMsg, EVENT_QUEUE> {
EVT_CHAN.receiver()
}
// Helper functions for memory-safe truncation
fn truncate_str<const N: usize>(s: &str) -> HString<N> {
let mut h = HString::new();
let _ = h.push_str(&s[..s.len().min(N)]);
h
}
fn truncate_payload(data: &[u8]) -> HVec<u8, PAYLOAD_MAX> {
let mut v = HVec::new();
let _ = v.extend_from_slice(&data[..data.len().min(PAYLOAD_MAX)]);
v
}
// MQTT configuration and client setup
fn build_client_config() -> ClientConfig<'static, 8, CountingRng> {
let mut cfg = ClientConfig::new(MqttVersion::MQTTv5, CountingRng(0));
cfg.keep_alive = KEEPALIVE_SECS as u16;
cfg.add_client_id("esp32-client");
cfg
}
fn build_client<'a, 'net>(
socket: TcpSocket<'net>,
mqtt_tx: &'a mut [u8],
mqtt_rx: &'a mut [u8],
) -> Client<'a, 'net> {
let mqtt_tx_len = mqtt_tx.len();
let mqtt_rx_len = mqtt_rx.len();
MqttClient::new(socket, mqtt_tx, mqtt_tx_len, mqtt_rx, mqtt_rx_len, build_client_config())
}
// Connection lifecycle and main session loop
async fn connect_tcp<'net>(socket: &mut TcpSocket<'net>) -> Result<(), ()> {
match socket.connect(mqtt_broker_endpoint()).await {
Ok(_) => {
info!("Connected TCP to MQTT broker");
Ok(())
}
Err(e) => {
info!("TCP connect failed: {:?}", e);
Err(())
}
}
}
async fn connect_mqtt(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
client.connect_to_broker().await
}
async fn run_loop(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
let default_topic = "esp32/topic";
match client.subscribe_to_topic(default_topic).await {
Ok(_) => info!("Subscribed to '{}'", default_topic),
Err(e) => info!("Default subscribe failed: {:?}", e),
};
loop {
let net_or_ping = select(client.receive_message(), Timer::after(PING_PERIOD));
match select(CMD_CHAN.receive(), net_or_ping).await {
Either::First(cmd) => handle_command(client, cmd).await?,
Either::Second(Either::First(result)) => handle_incoming(result).await?,
Either::Second(Either::Second(_)) => client.send_ping().await?,
}
}
}
async fn handle_command(client: &mut Client<'_, '_>, cmd: Command) -> Result<(), ReasonCode> {
match cmd {
Command::Publish(msg) => {
client
.send_message(msg.topic.as_str(), &msg.payload, msg.qos, msg.retain)
.await
}
Command::Subscribe(topic) => {
client.subscribe_to_topic(topic.as_str()).await?;
info!("Subscribed to '{}'", topic);
Ok(())
}
}
}
async fn handle_incoming(result: Result<(&str, &[u8]), ReasonCode>) -> Result<(), ReasonCode> {
let (topic, payload) = result?;
EVT_CHAN
.send(IncomingMsg {
topic: truncate_str::<TOPIC_MAX>(topic),
payload: truncate_payload(payload),
})
.await;
Ok(())
}
// Session and reconnect control
async fn run_one_session(
stack: Stack<'static>,
tcp_rx: &mut [u8],
tcp_tx: &mut [u8],
mqtt_tx: &mut [u8],
mqtt_rx: &mut [u8],
) -> Result<(), ()> {
let mut socket = TcpSocket::new(stack, tcp_rx, tcp_tx);
if connect_tcp(&mut socket).await.is_err() {
return Err(());
}
let mut client = build_client(socket, mqtt_tx, mqtt_rx);
match connect_mqtt(&mut client).await {
Ok(_) => info!("MQTT CONNACK received"),
Err(reason) => {
info!("MQTT connect failed: {:?}", reason);
return Err(());
}
}
run_loop(&mut client).await.map_err(|_| ())
}
// Main MQTT embassy task
#[embassy_executor::task]
pub async fn mqtt_task(stack: Stack<'static>) {
info!("MQTT task starting...");
let tcp_rx = TCP_RX_BUFFER.take();
let tcp_tx = TCP_TX_BUFFER.take();
let mqtt_tx = MQTT_TX_BUF.take();
let mqtt_rx = MQTT_RX_BUF.take();
loop {
let _ = run_one_session(
stack,
&mut tcp_rx[..],
&mut tcp_tx[..],
&mut mqtt_tx[..],
&mut mqtt_rx[..],
)
.await;
info!(
"Reconnecting in {}s after session end/failure",
RECONNECT_DELAY_SECS
);
Timer::after(Duration::from_secs(RECONNECT_DELAY_SECS)).await;
}
}

View File

@@ -0,0 +1,122 @@
// src/mqtt/config.rs
#![allow(dead_code)]
use embassy_net::{IpAddress, Ipv4Address, Ipv6Address};
// Compile-time values injected by build.rs
const BROKER_IP: &str = env!("BROKER_IP");
const BROKER_PORT: &str = env!("BROKER_PORT");
pub fn mqtt_broker_endpoint() -> (IpAddress, u16) {
(parse_ip(BROKER_IP), parse_port(BROKER_PORT))
}
fn parse_port(s: &str) -> u16 {
let p: u16 = s
.parse()
.unwrap_or_else(|_| panic!("BROKER_PORT must be a valid u16 (1..=65535)"));
assert!(p != 0, "BROKER_PORT cannot be 0");
p
}
fn parse_ip(s: &str) -> IpAddress {
if s.contains(':') {
IpAddress::Ipv6(parse_ipv6(s))
} else {
IpAddress::Ipv4(parse_ipv4(s))
}
}
fn parse_ipv4(s: &str) -> Ipv4Address {
let mut it = s.split('.');
let a = parse_octet(it.next(), 1);
let b = parse_octet(it.next(), 2);
let c = parse_octet(it.next(), 3);
let d = parse_octet(it.next(), 4);
assert!(it.next().is_none(), "Too many IPv4 octets");
Ipv4Address::new(a, b, c, d)
}
fn parse_octet(part: Option<&str>, idx: usize) -> u8 {
let p = part.unwrap_or_else(|| panic!("IPv4 missing octet {}", idx));
let v: u16 = p
.parse()
.unwrap_or_else(|_| panic!("Invalid IPv4 octet {}: {}", idx, p));
assert!(v <= 255, "IPv4 octet {} out of range: {}", idx, v);
v as u8
}
// Minimal IPv6 parser with '::' compression. Does not handle IPv4-embedded IPv6.
fn parse_ipv6(s: &str) -> Ipv6Address {
assert!(
!s.contains('.'),
"IPv4-embedded IPv6 like ::ffff:192.0.2.1 not supported; \
use pure hex IPv6"
);
let has_double = s.contains("::");
let (left_s, right_s) = if has_double {
let mut sp = s.splitn(2, "::");
(sp.next().unwrap_or(""), sp.next().unwrap_or(""))
} else {
(s, "")
};
let mut left = [0u16; 8];
let mut right = [0u16; 8];
let mut ll = 0usize;
let mut rl = 0usize;
if !left_s.is_empty() {
for part in left_s.split(':') {
left[ll] = parse_group(part);
ll += 1;
assert!(ll <= 8, "Too many IPv6 groups on the left");
}
}
if !right_s.is_empty() {
for part in right_s.split(':') {
right[rl] = parse_group(part);
rl += 1;
assert!(rl <= 8, "Too many IPv6 groups on the right");
}
}
let zeros = if has_double {
assert!(ll + rl < 8, "Invalid IPv6 '::' usage");
8 - (ll + rl)
} else {
assert!(ll == 8, "IPv6 must have 8 groups without '::'");
0
};
let mut g = [0u16; 8];
let mut idx = 0usize;
for i in 0..ll {
g[idx] = left[i];
idx += 1;
}
for _ in 0..zeros {
g[idx] = 0;
idx += 1;
}
for i in 0..rl {
g[idx] = right[i];
idx += 1;
}
assert!(idx == 8, "IPv6 did not resolve to 8 groups");
Ipv6Address::new(g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7])
}
fn parse_group(part: &str) -> u16 {
assert!(
!part.is_empty(),
"Empty IPv6 group (use '::' instead for compression)"
);
assert!(part.len() <= 4, "IPv6 group too long: {}", part);
u16::from_str_radix(part, 16)
.unwrap_or_else(|_| panic!("Invalid IPv6 hex group: {}", part))
}

View File

@@ -0,0 +1,4 @@
// src/mqtt/mod.rs
pub mod client;
pub mod config;