switched inside controller to esp32

This commit is contained in:
Andy Killorin 2024-11-13 11:36:58 -05:00
parent ead78021d7
commit 6f5efa3e18
Signed by: ank
GPG key ID: 23F9463ECB67FE8C
7 changed files with 632 additions and 2133 deletions

View file

@ -1,10 +1,16 @@
#[target.'cfg(all(target_arch = "arm", target_os = "none"))'] [target.xtensa-esp32-none-elf]
#runner = "probe-rs run --chip RP2040" runner = "espflash flash --monitor"
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
runner = "elf2uf2-rs --deploy --serial --verbose"
[build]
target = "thumbv6m-none-eabi" # Cortex-M0 and Cortex-M0+
[env] [env]
DEFMT_LOG = "debug" ESP_LOG="info"
[build]
rustflags = [
"-C", "link-arg=-nostartfiles",
]
target = "xtensa-esp32-none-elf"
[unstable]
build-std = ["alloc", "core"]

4
inside/.gitignore vendored
View file

@ -1 +1,3 @@
target debug/
target/
**/*.rs.bk

2261
inside/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,71 +1,50 @@
[package] [package]
edition = "2021"
name = "inside" name = "inside"
version = "0.1.0" version = "0.1.0"
license = "MIT OR Apache-2.0" edition = "2021"
[dependencies] [dependencies]
embassy-executor = { version = "0.6.0", git="https://github.com/embassy-rs/embassy", features = ["task-arena-size-98304", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } blocking-network-stack = { git = "https://github.com/bjoernQ/blocking-network-stack.git", rev = "1c581661d78e0cf0f17b936297179b993fb149d7" }
embassy-time = { version = "0.3.2", git="https://github.com/embassy-rs/embassy", features = ["defmt", "defmt-timestamp-uptime"] } esp-backtrace = { version = "0.14.2", features = [
embassy-rp = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp2040"] } "esp32",
embassy-usb = { version = "0.3.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] } "exception-handler",
embassy-net = { version = "0.4.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] } "panic-handler",
embassy-net-wiznet = { version = "0.1.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] } "println",
embassy-futures = { version = "0.1.0", git="https://github.com/embassy-rs/embassy"} ] }
embassy-usb-logger = { version = "0.2.0", git="https://github.com/embassy-rs/embassy" } esp-hal = { version = "0.21.0", features = [ "esp32" ] }
cyw43 = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "firmware-logs", "bluetooth"] } esp-println = { version = "0.12.0", features = ["esp32", "log"] }
cyw43-pio = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] } log = { version = "0.4.22" }
esp-alloc = { version = "0.5.0" }
defmt = "0.3" embedded-io = "0.6.1"
defmt-rtt = "0.4" esp-wifi = { version = "0.10.1", features = [
fixed = "1.23.1" "esp32",
fixed-macro = "1.2" "phy-enable-usb",
"utils",
# for web request example "wifi",
reqwless = { version = "0.12.0", features = ["defmt",]} ] }
serde = { version = "1.0.203", default-features = false, features = ["derive"] } heapless = { version = "0.8.0", default-features = false }
serde-json-core = "0.5.1" smoltcp = { version = "0.11.0", default-features = false, features = [
"medium-ethernet",
# for assign resources example "proto-dhcpv4",
assign-resources = { git = "https://github.com/adamgreig/assign-resources", rev = "94ad10e2729afdf0fd5a77cd12e68409a982f58a" } "proto-igmp",
"proto-ipv4",
#cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } "socket-dhcpv4",
cortex-m = { version = "0.7.6", features = ["inline-asm"] } "socket-icmp",
cortex-m-rt = "0.7.0" "socket-raw",
critical-section = "1.1" "socket-tcp",
panic-probe = { version = "0.3", features = ["print-defmt"] } "socket-udp",
display-interface-spi = "0.4.1" ] }
embedded-graphics = "0.7.1"
st7789 = "0.6.1"
display-interface = "0.4.1"
byte-slice-cast = { version = "1.2.0", default-features = false }
smart-leds = "0.3.0"
heapless = "0.8"
usbd-hid = "0.8.1"
embedded-hal-1 = { package = "embedded-hal", version = "1.0" }
embedded-hal-async = "1.0"
embedded-hal-bus = { version = "0.1", features = ["async"] }
embedded-io-async = { version = "0.6.1", features = ["defmt-03"] }
embedded-storage = { version = "0.3" }
static_cell = "2.1"
portable-atomic = { version = "1.5", features = ["critical-section"] }
log = "0.4"
pio-proc = "0.2"
pio = "0.2.1"
rand = { version = "0.8.5", default-features = false }
embedded-sdmmc = "0.7.0"
bt-hci = { version = "0.1.0", default-features = false, features = ["defmt"] }
hex = { version = "0.4.3", default-features=false}
[profile.release]
debug = 2
lto = true
opt-level = 'z'
[profile.dev] [profile.dev]
# Rust debug is too slow.
# For debug builds always builds with some optimization
opt-level = "s"
[profile.release]
codegen-units = 1 # LLVM can perform better optimizations using a single thread
debug = 2 debug = 2
lto = true debug-assertions = false
opt-level = "z" incremental = false
lto = 'fat'
opt-level = 's'
overflow-checks = false

View file

@ -1,36 +1,5 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() { fn main() {
// Put `memory.x` in our output directory and ensure it's println!("cargo:rustc-link-arg-bins=-Tlinkall.x");
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
// By default, Cargo will re-run a build script whenever println!("cargo:rustc-link-arg-bins=-Trom_functions.x");
// any file in the project changes. By specifying `memory.x`
// here, we ensure the build script is only re-run when
// `memory.x` is changed.
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=--nmagic");
println!("cargo:rustc-link-arg-bins=-Tlink.x");
println!("cargo:rustc-link-arg-bins=-Tlink-rp.x");
println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
} }

View file

@ -1,17 +0,0 @@
MEMORY {
BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100
FLASH : ORIGIN = 0x10000100, LENGTH = 2048K - 0x100
/* Pick one of the two options for RAM layout */
/* OPTION A: Use all RAM banks as one big block */
/* Reasonable, unless you are doing something */
/* really particular with DMA or other concurrent */
/* access that would benefit from striping */
RAM : ORIGIN = 0x20000000, LENGTH = 264K
/* OPTION B: Keep the unstriped sections separate */
/* RAM: ORIGIN = 0x20000000, LENGTH = 256K */
/* SCRATCH_A: ORIGIN = 0x20040000, LENGTH = 4K */
/* SCRATCH_B: ORIGIN = 0x20041000, LENGTH = 4K */
}

View file

@ -1,213 +1,146 @@
//! This example uses the RP Pico W board Wifi chip (cyw43).
//! Creates an Access point Wifi network and creates a TCP endpoint on port 1234.
#![no_std] #![no_std]
#![no_main] #![no_main]
#![allow(async_fn_in_trait)]
use core::array; use embedded_io::{Read, Write};
use core::fmt::Formatter; use esp_backtrace as _;
use core::panic::PanicInfo; use esp_hal::{delay::Delay, prelude::*, rng::Rng, time::{self, Duration}};
use core::str::from_utf8; use esp_println::{print, println};
use esp_wifi::wifi::{utils::create_network_interface, AccessPointInfo, ClientConfiguration, Configuration, WifiError, WifiStaDevice};
use smoltcp::iface::{SocketSet, SocketStorage};
use blocking_network_stack::{ipv4, Stack};
use bt_hci::cmd::info; extern crate alloc;
use cyw43_pio::PioSpi;
use embassy_rp::pwm::{self, Pwm};
use fixed::FixedU16;
use log::*;
//use embassy_rp::i2c::InterruptHandler;
use embassy_executor::Spawner;
use embassy_net::tcp::TcpSocket;
use embassy_net::{Config, StackResources};
use embassy_rp::bind_interrupts;
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Level, Output};
use embassy_rp::peripherals::{DMA_CH0, PIO0, USB};
use embassy_rp::pio::{InterruptHandler, Pio};
use embassy_rp::usb::Driver;
use embassy_time::{Duration, Timer};
use embedded_io_async::Write;
use rand::RngCore;
use reqwless::response;
use static_cell::StaticCell;
use defmt_rtt as _;
bind_interrupts!(struct Irqs { #[entry]
PIO0_IRQ_0 => InterruptHandler<PIO0>; fn main() -> ! {
USBCTRL_IRQ => embassy_rp::usb::InterruptHandler<USB>; #[allow(unused)]
});
#[embassy_executor::task] let mut config = esp_hal::Config::default();
async fn logger_task(driver: Driver<'static, USB>) { config.cpu_clock = CpuClock::max();
embassy_usb_logger::run!(1024, log::LevelFilter::Debug, driver); let peripherals = esp_hal::init(config);
}
#[embassy_executor::task] let delay = Delay::new();
async fn cyw43_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { esp_alloc::heap_allocator!(72 * 1024);
runner.run().await
}
#[embassy_executor::task] esp_println::logger::init_logger_from_env();
async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! {
runner.run().await
}
#[panic_handler] let timg0 = esp_hal::timer::timg::TimerGroup::new(peripherals.TIMG0);
fn panic( info: &PanicInfo) -> ! { let mut rng = Rng::new(peripherals.RNG);
error!("{}", info); let init = esp_wifi::init(
loop { } esp_wifi::EspWifiInitFor::Wifi,
} timg0.timer0,
rng.clone(),
peripherals.RADIO_CLK,
)
.unwrap();
fn run_motor(pwm_c: &mut pwm::Config, pwm: &mut Pwm, pulse: u16) { let mut wifi = peripherals.WIFI;
pwm_c.compare_b = pulse; let mut socket_set_entries: [SocketStorage; 3] = Default::default();
pwm.set_config(&pwm_c); let (iface, device, mut controller, mut socket_set) =
} create_network_interface(&init, &mut wifi, WifiStaDevice, &mut socket_set_entries).unwrap();
async fn open_door(mut pwm_c: &mut pwm::Config, mut pwm: &mut Pwm<'_>) { let now = || time::now().duration_since_epoch().to_millis();
run_motor(&mut pwm_c, &mut pwm, 0x13DF); // up let mut stack = Stack::new(iface, device, socket_set, now, rng.random());
Timer::after_millis(3000).await;
run_motor(&mut pwm_c, &mut pwm, 0x123C); // down
Timer::after_millis(750).await;
run_motor(&mut pwm_c, &mut pwm, 4687); // stop
}
#[embassy_executor::main] let client_config = Configuration::Client(ClientConfiguration {
async fn main(spawner: Spawner) { ssid: "🐟".try_into().unwrap(),
password: "ilcougars1234".try_into().unwrap(),
..Default::default()
let p = embassy_rp::init(Default::default());
let mut rng = RoscRng;
let driver = Driver::new(p.USB, Irqs);
spawner.spawn(logger_task(driver)).unwrap();
let mut c: pwm::Config = Default::default();
c.divider = 40.into();
c.top = 62_500; // 20ms
c.compare_b = 4687; // 1.5ms
let mut pwm = Pwm::new_output_b(p.PWM_SLICE0, p.PIN_1, c.clone());
let fw = include_bytes!("../../cyw43-firmware/43439A0.bin");
let clm = include_bytes!("../../cyw43-firmware/43439A0_clm.bin");
// To make flashing faster for development, you may want to flash the firmwares independently
// at hardcoded addresses, instead of baking them into the program with `include_bytes!`:
// probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000
// probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000
//let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) };
//let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) };
let pwr = Output::new(p.PIN_23, Level::Low);
let cs = Output::new(p.PIN_25, Level::High);
let mut pio = Pio::new(p.PIO0, Irqs);
let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, p.PIN_24, p.PIN_29, p.DMA_CH0);
static STATE: StaticCell<cyw43::State> = StaticCell::new();
let state = STATE.init(cyw43::State::new());
let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await;
defmt::unwrap!(spawner.spawn(cyw43_task(runner)));
control.init(clm).await;
control
.set_power_management(cyw43::PowerManagementMode::PowerSave)
.await;
// Use a link-local address for communication without DHCP server
let config = Config::ipv4_static(embassy_net::StaticConfigV4 {
address: embassy_net::Ipv4Cidr::new(embassy_net::Ipv4Address::new(169, 254, 1, 1), 16),
dns_servers: heapless::Vec::new(),
gateway: None,
}); });
let res = controller.set_configuration(&client_config);
log::info!("{:?}",res);
// Generate random seed controller.start().unwrap();
let seed = rng.next_u64();
// Init network stack let res: Result<(heapless::Vec<AccessPointInfo, 10>, usize), WifiError> = controller.scan_n();
static RESOURCES: StaticCell<StackResources<3>> = StaticCell::new(); if let Ok((res, _count)) = res {
let (stack, runner) = embassy_net::new(net_device, config, RESOURCES.init(StackResources::new()), seed); for ap in res {
log::info!("{:?}", ap);
defmt::unwrap!(spawner.spawn(net_task(runner)));
//control.start_ap_open("door409", 5).await;
control.start_ap_wpa2("door409", "babelite", 5).await;
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let mut buf = [0; 4096];
loop {
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(Duration::from_secs(3)));
let mut c: pwm::Config = Default::default();
c.divider = 40.into();
c.top = 62_500; // 20ms
// 3125 counts per ms
c.compare_b = 4687; // 1.5ms
pwm.set_config(&c);
control.gpio_set(0, false).await;
info!("Listening on TCP:1234...");
if let Err(e) = socket.accept(1234).await {
warn!("accept error: {:?}", e);
continue;
}
info!("Received connection from {:?}", socket.remote_endpoint());
control.gpio_set(0, true).await;
loop {
let mut n = match socket.read(&mut buf).await {
Ok(0) => {
warn!("read EOF");
break;
}
Ok(n) => n,
Err(e) => {
warn!("read error: {:?}", e);
break;
}
};
info!("rxd {}", from_utf8(&buf[..n]).unwrap());
Timer::after_millis(30).await;
let mut segs = buf[..n].trim_ascii().split(|c| *c == ' ' as u8);
match char::from_u32(segs.next().unwrap()[0] as u32).unwrap() {
'D' => {
let pwr: [u8;2] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
info!("power {pwr:?}");
let pwr = u16::from_be_bytes(pwr);
c.compare_b = pwr;
info!("power {pwr:?}");
pwm.set_config(&c);
},
'B' => {
let buf: [u8;8] = hex::FromHex::from_hex(segs.next().unwrap()).unwrap();
let card: u64 = u64::from_ne_bytes(buf);
info!("card {card:#16x}");
open_door(&mut c, &mut pwm).await;
},
_ => {}
}
//let mut response: [u8;2] = [0;2];
//let _ = bus.read_async(0xC0u16, &mut response).await;
//let _ = hex::encode_to_slice(response, &mut buf);
match socket.write_all(&buf[..n]).await {
Ok(()) => {}
Err(e) => {
warn!("write error: {:?}", e);
break;
}
};
} }
} }
log::info!("connecting: {:?}", controller.connect());
loop {
match controller.is_connected() {
Ok(true) => break,
Ok(false) => {}
Err(err) => {
log::error!("{:?}", err);
log::info!("connecting: {:?}", controller.connect());
}
}
}
log::info!("the wifi device is connected");
stack
.set_iface_configuration(&ipv4::Configuration::Client(
ipv4::ClientConfiguration::Fixed(
ipv4::ClientSettings {
ip: ipv4::Ipv4Addr::new(10,0,0,2),
subnet: ipv4::Subnet {
gateway: ipv4::Ipv4Addr::new(10,0,0,1),
mask: ipv4::Mask(24),
},
dns: None,
secondary_dns: None,
},
),
))
.unwrap();
let mut rx_buffer = [0u8; 1536];
let mut tx_buffer = [0u8; 1536];
let mut socket = stack.get_socket(&mut rx_buffer, &mut tx_buffer);
socket.listen(4595).unwrap();
loop {
socket.work();
if !socket.is_open() {
socket.listen(4595).unwrap();
}
if socket.is_connected() {
let mut time_out = false;
let deadline = time::now() + Duration::secs(3);
let mut buffer = [0u8; 1024];
let mut pos = 0;
log::info!("connected");
while let Ok(len) = socket.read(&mut buffer[pos..]) {
let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) };
if to_print.contains("\r\n") {
print!("{}", to_print);
println!();
break;
}
pos += len;
if time::now() > deadline {
println!("Timeout");
time_out = true;
break;
}
}
if !time_out {
let _ = socket.write_all(
b"test\r\n"
);
socket.flush().unwrap();
}
socket.close();
log::info!("ending transaction");
}
//let deadline = time::now() + Duration::secs(5);
//while time::now() < deadline {
// socket.work();
//}
}
} }