Compare commits

...

2 Commits

Author SHA1 Message Date
Arkitu
317b8084e0 organise code 2025-04-08 20:08:03 +02:00
Arkitu
0c0024d66c working turns! 2025-04-08 17:39:59 +02:00
8 changed files with 453 additions and 298 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
/target
/wifi.json

20
Cargo.lock generated
View File

@ -812,6 +812,7 @@ checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
dependencies = [
"defmt",
"hash32",
"serde",
"stable_deref_trait",
]
@ -1090,6 +1091,8 @@ dependencies = [
"panic-probe",
"portable-atomic",
"rand_core",
"serde",
"serde-json-core",
"static_cell",
]
@ -1295,6 +1298,12 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2"
[[package]]
name = "ryu"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
name = "same-file"
version = "1.0.6"
@ -1334,6 +1343,17 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde-json-core"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b81787e655bd59cecadc91f7b6b8651330b2be6c33246039a65e5cd6f4e0828"
dependencies = [
"heapless",
"ryu",
"serde",
]
[[package]]
name = "serde_derive"
version = "1.0.219"

View File

@ -3,6 +3,10 @@ name = "pico-website"
version = "0.1.0"
edition = "2024"
[features]
wifi-connect = ["dep:serde-json-core", "dep:serde"] # you need to add a wifi.conf file with your wifi credentials (for example : "Example Wifi name:pa$$w0rd")
default = ["wifi-connect"]
[dependencies]
embassy-executor = { git = "https://github.com/embassy-rs/embassy", features = [
"defmt",
@ -25,8 +29,8 @@ embassy-net = { git = "https://github.com/embassy-rs/embassy", features = [
"proto-ipv4",
"tcp",
"dhcpv4",
"dns",
"icmp",
# "dns",
# "icmp",
"packet-trace"
] }
cyw43-pio = {git = "https://github.com/embassy-rs/embassy"}
@ -44,3 +48,5 @@ heapless = "*"
rand_core = "*"
log = "*"
serde-json-core = {version = "*", optional = true}
serde = {version = "*", optional = true, default-features = false, features = ["derive"]}

162
src/game.rs Normal file
View File

@ -0,0 +1,162 @@
use core::{ops::Not, sync::atomic::Ordering};
use heapless::Vec;
use pico_website::unwrap;
use portable_atomic::{AtomicBool, AtomicU32};
use core::fmt::Write;
use crate::socket::HttpResCode;
static TURN: AtomicBool = AtomicBool::new(false);
// bits [0; 8] : player zero board / bits [9; 17] : player one board
static BOARD: AtomicU32 = AtomicU32::new(0);
pub struct GameClient {
res_buf: Vec<u8, 4096>
}
impl GameClient {
pub fn new() -> Self {
Self {
res_buf: Vec::new(),
}
}
pub async fn handle_request<'a>(&'a mut self, path: &str, team: Team) -> (HttpResCode, &'static str, &'a [u8]) {
if (path.starts_with("/ttt/cell") && path.len() == 10) || path == "/ttt/board" {
let mut board = BOARD.load(Ordering::Acquire);
let mut turn = TURN.load(Ordering::Acquire);
// just return correct board in case of unauthorized move
if path.starts_with("/ttt/cell") && team == turn.into() {
let clicked_c: Cell = match TryInto::<Cell>::try_into(
unwrap(path.chars().nth(9).ok_or("no 9th char")).await,
) {
Ok(c) => c,
Err(_) => return (HttpResCode::NotFound, "", &[]),
};
if board
& ((2_u32.pow(clicked_c as u32))
+ (2_u32.pow(9 + clicked_c as u32)))
!= 0
{
return (HttpResCode::Forbidden, "", &[]);
}
board = board | 2_u32.pow((team as u32 * 9) + clicked_c as u32);
turn = (!team).into();
BOARD.store(board, Ordering::Release);
TURN.store(turn, Ordering::Release);
}
self.res_buf.clear();
for c in 0..=8 {
let picked_by = if board & 2_u32.pow(c) != 0 {
Some(Team::Zero)
} else if board & 2_u32.pow(9 + c) != 0 {
Some(Team::One)
} else {
None
};
match picked_by {
Some(Team::Zero) => {
unwrap(self.res_buf
.extend_from_slice(
b"<div class=\"cell\" style=\"background-color:blue\"></div>",
)).await;
}
Some(Team::One) => {
unwrap(self.res_buf.extend_from_slice(
b"<div class=\"cell\" style=\"background-color:red\"></div>",
)).await;
}
None => if team == turn.into() {
unwrap(write!(
self.res_buf,
"<button class=\"cell\" hx-post=\"/ttt/cell{}\" hx-trigger=\"click\" hx-target=\"#grid\" hx-swap=\"innerHTML\"></button>",
c
)).await;
} else {
unwrap(self.res_buf.extend_from_slice(
b"<div class=\"cell\"></div>",
)).await;
}
};
}
(HttpResCode::Ok, "html", &self.res_buf)
} else {
(HttpResCode::NotFound, "", &[])
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Team {
Zero = 0,
One = 1,
}
impl From<bool> for Team {
fn from(value: bool) -> Self {
if value { Team::One } else { Team::Zero }
}
}
impl Into<bool> for Team {
fn into(self) -> bool {
match self {
Team::Zero => false,
Team::One => true
}
}
}
impl Not for Team {
type Output = Team;
fn not(self) -> Self::Output {
match self {
Team::Zero => Team::One,
Team::One => Team::Zero
}
}
}
#[derive(Debug, Clone, Copy)]
enum Cell {
C0 = 0,
C1 = 1,
C2 = 2,
C3 = 3,
C4 = 4,
C5 = 5,
C6 = 6,
C7 = 7,
C8 = 8,
}
impl TryFrom<char> for Cell {
type Error = ();
fn try_from(value: char) -> Result<Self, Self::Error> {
Ok(match value {
'0' => Cell::C0,
'1' => Cell::C1,
'2' => Cell::C2,
'3' => Cell::C3,
'4' => Cell::C4,
'5' => Cell::C5,
'6' => Cell::C6,
'7' => Cell::C7,
'8' => Cell::C8,
_ => return Err(()),
})
}
}
impl TryFrom<u8> for Cell {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
Ok(match value {
0 => Cell::C0,
1 => Cell::C1,
2 => Cell::C2,
3 => Cell::C3,
4 => Cell::C4,
5 => Cell::C5,
6 => Cell::C6,
7 => Cell::C7,
8 => Cell::C8,
_ => return Err(()),
})
}
}

17
src/lib.rs Normal file
View File

@ -0,0 +1,17 @@
#![no_std]
use core::fmt::Debug;
use embassy_time::Timer;
use log::error;
pub async fn unwrap<T, E: Debug>(res: Result<T, E>) -> T {
match res {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR : {:?}", e);
loop {
Timer::after_millis(0).await;
}
}
}
}

View File

@ -4,14 +4,10 @@
#![feature(impl_trait_in_assoc_type)]
#![feature(slice_split_once)]
use core::fmt::{Debug, Write};
use core::str::from_utf8;
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use cortex_m::interrupt::Mutex;
use core::net::Ipv4Addr;
use cyw43_pio::{DEFAULT_CLOCK_DIVIDER, PioSpi};
use embassy_executor::Spawner;
use embassy_net::tcp::TcpSocket;
use embassy_net::{Config, Stack, StackResources};
use embassy_net::{Config, DhcpConfig, StackResources};
use embassy_rp::bind_interrupts;
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Level, Output};
@ -19,14 +15,14 @@ use embassy_rp::peripherals::USB;
use embassy_rp::peripherals::{DMA_CH0, PIO0};
use embassy_rp::pio::{InterruptHandler as PioInterruptHandler, Pio};
use embassy_rp::usb::{Driver, InterruptHandler as UsbInterruptHandler};
use embassy_time::Duration;
use embassy_time::Timer;
use embedded_io_async::Write as _;
use heapless::{String, Vec};
use log::{debug, info, warn};
use log::info;
use rand_core::RngCore;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};
use pico_website::unwrap;
mod socket;
mod game;
bind_interrupts!(struct Irqs {
USBCTRL_IRQ => UsbInterruptHandler<USB>;
@ -76,13 +72,14 @@ async fn main(spawner: Spawner) {
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;
spawner.spawn(cyw43_task(runner)).unwrap();
unwrap(spawner.spawn(cyw43_task(runner))).await;
control.init(clm).await;
control
.set_power_management(cyw43::PowerManagementMode::PowerSave)
.await;
#[cfg(not(feature = "wifi-connect"))]
// 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(192, 254, 0, 2), 16),
@ -90,11 +87,26 @@ async fn main(spawner: Spawner) {
gateway: None,
});
#[cfg(feature = "wifi-connect")]
let wifi_conf = unwrap(serde_json_core::from_slice::<WifiConnectConf>(include_bytes!("../wifi.json"))).await.0;
// Use a link-local address for communication without DHCP server
// let config = Config::dhcpv4(embassy_net::DhcpConfig::default());
#[cfg(feature = "wifi-connect")]
let config = match wifi_conf.ip {
Some(ip) => Config::ipv4_static(embassy_net::StaticConfigV4 {
address: embassy_net::Ipv4Cidr::new(ip, 24),
dns_servers: heapless::Vec::new(),
gateway: None,
}),
None => Config::dhcpv4(DhcpConfig::default())
};
// Generate random seed
let seed = rng.next_u64();
// Init network stack
static RESOURCES: StaticCell<StackResources<2>> = StaticCell::new();
static RESOURCES: StaticCell<StackResources<4>> = StaticCell::new();
let (stack, runner) = embassy_net::new(
net_device,
config,
@ -102,296 +114,51 @@ async fn main(spawner: Spawner) {
seed,
);
spawner.spawn(net_task(runner)).unwrap();
unwrap(spawner.spawn(net_task(runner))).await;
#[cfg(not(feature = "wifi-connect"))]
//control.start_ap_open("cyw43", 5).await;
control.start_ap_wpa2("cyw43", "password", 5).await;
spawner.spawn(listen_task(stack, Team::Zero, 80)).unwrap();
spawner.spawn(listen_task(stack, Team::One, 81)).unwrap();
}
static TURN: AtomicBool = AtomicBool::new(false);
// bits [0; 8] : player zero board / bits [9; 17] : player one board
static BOARD: AtomicU32 = AtomicU32::new(0);
#[embassy_executor::task(pool_size = 2)]
async fn listen_task(stack: Stack<'static>, team: Team, port: u16) {
loop {
info!("team:{:?}", team);
}
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let mut buf = [0; 4096];
let mut res_head_buf = Vec::<u8, 4096>::new();
let mut res_buf = Vec::<u8, 4096>::new();
loop {
Timer::after_secs(0).await;
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(Duration::from_secs(30)));
info!("Socket {:?}: Listening on TCP:{}...", team, port);
if let Err(e) = socket.accept(port).await {
warn!("accept error: {:?}", e);
continue;
}
info!(
"Socket {:?}: Received connection from {:?}",
team,
socket.remote_endpoint()
);
#[cfg(feature = "wifi-connect")]
{
loop {
Timer::after_secs(0).await;
let n = match socket.read(&mut buf).await {
Ok(0) => {
warn!("read EOF");
break;
}
Ok(n) => n,
Err(e) => {
warn!("Socket {:?}: read error: {:?}", team, e);
break;
}
};
info!(
"Socket {:?}: request :\n{}",
team,
from_utf8(&buf[..n]).unwrap()
);
Timer::after_secs(0).await;
let mut headers: &[u8] = &buf[..n];
let mut content: &[u8] = &[];
for i in 0..(n - 1) {
if &buf[i..i + 1] == b"\r\n" {
headers = &buf[0..i];
if i + 2 < n {
content = &buf[i + 2..n];
}
match control
.join(wifi_conf.name, cyw43::JoinOptions::new(wifi_conf.password.as_bytes()))
.await
{
Ok(_) => break,
Err(err) => {
info!("join failed with status={}", err.status);
}
}
let mut headers = headers.split(|x| *x == b'\n');
let (request_type, path) = match headers.next() {
None => {
warn!("Empty request");
break;
}
Some(l1) => {
let mut l1 = l1.split(|x| *x == b' ');
(
match l1.next() {
Some(b"GET") => HttpRequestType::Get,
Some(b"POST") => HttpRequestType::Post,
Some(t) => {
warn!("Unknown request type : {}", from_utf8(t).unwrap());
break;
}
None => {
warn!("No request type");
break;
}
},
match l1.next() {
Some(path) => from_utf8(path).unwrap(),
None => {
warn!("No path");
break;
}
},
)
}
};
let (code, res_type, res_content): (HttpResCode, &str, &[u8]) = match path {
"/" => (HttpResCode::Ok, "html", include_bytes!("../web/index.html")),
"/htmx.min.js" => (
HttpResCode::Ok,
"javascript",
include_bytes!("../web/htmx.min.js"),
),
"/htmx.js" => (
HttpResCode::Ok,
"javascript",
include_bytes!("../web/htmx.js"),
),
p => 'res: {
if (p.starts_with("/ttt/cell") && p.len() == 10) || p == "/ttt/board" {
let mut board = BOARD.load(Ordering::Acquire);
if p.starts_with("/ttt/cell") {
let clicked_c: Cell =
match TryInto::<Cell>::try_into(p.chars().nth(9).unwrap()) {
Ok(c) => c,
Err(_) => break 'res (HttpResCode::NotFound, "", &[]),
};
if board
& ((2_u32.pow(clicked_c as u32))
+ (2_u32.pow(9 + clicked_c as u32)))
!= 0
{
break 'res (HttpResCode::Forbidden, "", &[]);
}
board = board | 2_u32.pow((team as u32 * 9) + clicked_c as u32);
BOARD.store(board, Ordering::Release);
}
res_buf.clear();
for c in 0..=8 {
let picked_by = if board & 2_u32.pow(c) != 0 {
Some(Team::Zero)
} else if board & 2_u32.pow(9 + c) != 0 {
Some(Team::One)
} else {
None
};
match picked_by {
Some(Team::Zero) => {
res_buf
.extend_from_slice(
b"<div class=\"cell\" style=\"background-color:blue\"></div>",
)
.unwrap();
}
Some(Team::One) => {
res_buf.extend_from_slice(
b"<div class=\"cell\" style=\"background-color:red\"></div>",
)
.unwrap();
}
None => {
write!(
&mut res_buf,
"<button class=\"cell\" hx-post=\"/ttt/cell{}\" hx-trigger=\"click\" hx-target=\"#grid\" hx-swap=\"innerHTML\"></button>",
c
).unwrap();
}
};
}
(HttpResCode::Ok, "html", &res_buf)
} else {
(HttpResCode::NotFound, "", &[])
}
}
};
res_head_buf.clear();
if let Err(e) = write!(
&mut res_head_buf,
"{}\r\n\
Content-Type: text/{}\r\n\
Content-Length: {}\r\n\r\n",
Into::<&str>::into(code),
res_type,
res_content.len()
) {
warn!("res buffer write error: {:?}", e);
break;
}
info!(
"Socket {:?}: response :\n{}",
team,
from_utf8(&res_head_buf).unwrap()
);
Timer::after_secs(0).await;
match socket.write_all(&res_head_buf).await {
Ok(()) => {}
Err(e) => {
warn!("write error: {:?}", e);
break;
}
};
match socket.write_all(&res_content).await {
Ok(()) => {}
Err(e) => {
warn!("write error: {:?}", e);
break;
}
};
}
info!("Network joined!");
info!("waiting for link...");
stack.wait_link_up().await;
// Wait for DHCP, not necessary when using static IP
info!("waiting for DHCP...");
stack.wait_config_up().await;
// while !stack.is_config_up() {
// Timer::after_millis(100).await;
// }
info!("DHCP is now up!");
info!(
"ip : {}",
unwrap(stack.config_v4().ok_or("no dhcp config"))
.await
.address
)
}
unwrap(spawner.spawn(socket::listen_task(stack, game::Team::Zero, 80))).await;
unwrap(spawner.spawn(socket::listen_task(stack, game::Team::One, 81))).await;
}
enum HttpRequestType {
Get,
Post,
}
#[derive(Debug, Clone, Copy)]
enum HttpResCode {
Ok,
NotFound,
Forbidden,
}
impl Into<&str> for HttpResCode {
fn into(self) -> &'static str {
match self {
HttpResCode::Ok => "HTTP/1.1 200 OK",
HttpResCode::NotFound => "HTTP/1.1 404 NOT FOUND",
HttpResCode::Forbidden => "HTTP/1.1 403 FORBIDDEN",
}
}
}
#[derive(Debug, Clone, Copy)]
enum Team {
Zero = 0,
One = 1,
}
impl From<bool> for Team {
fn from(value: bool) -> Self {
if value { Team::One } else { Team::Zero }
}
}
#[derive(Debug, Clone, Copy)]
enum Cell {
C0 = 0,
C1 = 1,
C2 = 2,
C3 = 3,
C4 = 4,
C5 = 5,
C6 = 6,
C7 = 7,
C8 = 8,
}
impl TryFrom<char> for Cell {
type Error = ();
fn try_from(value: char) -> Result<Self, Self::Error> {
Ok(match value {
'0' => Cell::C0,
'1' => Cell::C1,
'2' => Cell::C2,
'3' => Cell::C3,
'4' => Cell::C4,
'5' => Cell::C5,
'6' => Cell::C6,
'7' => Cell::C7,
'8' => Cell::C8,
_ => return Err(()),
})
}
}
impl TryFrom<u8> for Cell {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
Ok(match value {
0 => Cell::C0,
1 => Cell::C1,
2 => Cell::C2,
3 => Cell::C3,
4 => Cell::C4,
5 => Cell::C5,
6 => Cell::C6,
7 => Cell::C7,
8 => Cell::C8,
_ => return Err(()),
})
}
}
#[cfg(feature="wifi-connect")]
#[derive(serde::Deserialize)]
struct WifiConnectConf<'a> {
name: &'a str,
password: &'a str,
ip: Option<Ipv4Addr>
}

182
src/socket.rs Normal file
View File

@ -0,0 +1,182 @@
use core::str::from_utf8;
use embassy_net::tcp::TcpSocket;
use embassy_time::{Duration, Timer};
use heapless::Vec;
use log::{info, warn};
use pico_website::unwrap;
use embedded_io_async::Write as _;
use core::fmt::Write;
use crate::game::{self, GameClient, Team};
#[embassy_executor::task(pool_size = 2)]
pub async fn listen_task(stack: embassy_net::Stack<'static>, team: Team, port: u16) {
// loop {
// info!("team:{:?}", team);
// Timer::after_millis(0).await;
// }
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let mut buf = [0; 4096];
let mut res_head_buf = Vec::<u8, 4096>::new();
let mut game_client = GameClient::new();
loop {
Timer::after_secs(0).await;
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(Duration::from_secs(30)));
info!("Socket {:?}: Listening on TCP:{}...", team, port);
if let Err(e) = socket.accept(port).await {
warn!("accept error: {:?}", e);
continue;
}
info!(
"Socket {:?}: Received connection from {:?}",
team,
socket.remote_endpoint()
);
loop {
Timer::after_secs(0).await;
let n = match socket.read(&mut buf).await {
Ok(0) => {
warn!("read EOF");
break;
}
Ok(n) => n,
Err(e) => {
warn!("Socket {:?}: read error: {:?}", team, e);
break;
}
};
let mut headers: &[u8] = &buf[..n];
let mut content: &[u8] = &[];
for i in 0..(n - 1) {
if &buf[i..i + 1] == b"\r\n" {
headers = &buf[0..i];
if i + 2 < n {
content = &buf[i + 2..n];
}
}
}
let mut headers = headers.split(|x| *x == b'\n');
let (request_type, path) = match headers.next() {
None => {
warn!("Empty request");
break;
}
Some(l1) => {
let mut l1 = l1.split(|x| *x == b' ');
(
match l1.next() {
Some(b"GET") => HttpRequestType::Get,
Some(b"POST") => HttpRequestType::Post,
Some(t) => {
warn!("Unknown request type : {}", unwrap(from_utf8(t)).await);
break;
}
None => {
warn!("No request type");
break;
}
},
match l1.next() {
Some(path) => unwrap(from_utf8(path)).await,
None => {
warn!("No path");
break;
}
},
)
}
};
info!(
"Socket {:?}: {:?} request for {}",
team,
request_type,
path
);
Timer::after_secs(0).await;
let (code, res_type, res_content): (HttpResCode, &str, &[u8]) = match path {
"/" => (HttpResCode::Ok, "html", include_bytes!("../web/index.html")),
"/htmx.min.js" => (
HttpResCode::Ok,
"javascript",
include_bytes!("../web/htmx.min.js"),
),
"/htmx.js" => (
HttpResCode::Ok,
"javascript",
include_bytes!("../web/htmx.js"),
),
p => game_client.handle_request(p, team).await
};
res_head_buf.clear();
if let Err(e) = write!(
&mut res_head_buf,
"{}\r\n\
Content-Type: text/{}\r\n\
Content-Length: {}\r\n\r\n",
Into::<&str>::into(code),
res_type,
res_content.len()
) {
warn!("res buffer write error: {:?}", e);
break;
}
match socket.write_all(&res_head_buf).await {
Ok(()) => {}
Err(e) => {
warn!("write error: {:?}", e);
break;
}
};
match socket.write_all(&res_content).await {
Ok(()) => {}
Err(e) => {
warn!("write error: {:?}", e);
break;
}
};
}
}
}
#[derive(Clone, Copy, Debug)]
enum HttpRequestType {
Get,
Post,
}
impl Into<&str> for HttpRequestType {
fn into(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Post => "POST"
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum HttpResCode {
Ok,
NotFound,
Forbidden,
}
impl Into<&str> for HttpResCode {
fn into(self) -> &'static str {
match self {
HttpResCode::Ok => "HTTP/1.1 200 OK",
HttpResCode::NotFound => "HTTP/1.1 404 NOT FOUND",
HttpResCode::Forbidden => "HTTP/1.1 403 FORBIDDEN",
}
}
}

View File

@ -23,7 +23,7 @@
id="grid"
hx-post="/ttt/board"
hx-swap="innerHTML"
hx-trigger="load"
hx-trigger="every 1s"
></div>
</body>
</html>