#include "handlers.h" #include "pico/unique_id.h" #include "pico/bootrom.h" #include "hardware/flash.h" #include "hardware/watchdog.h" #include "dispatch.h" #include "net.h" #include "debug_log.h" static constexpr uint32_t XIP_BASE_ADDR = 0x10000000; static constexpr uint32_t FLASH_SIZE = 2 * 1024 * 1024; std::optional handle_picoboot(const responder&, const RequestPICOBOOT&) { dispatch_schedule_ms(100, []{ reset_usb_boot(0, 1); }); return ResponsePICOBOOT{}; } std::optional handle_info(const responder&, const RequestInfo&) { ResponseInfo resp; pico_unique_board_id_t uid; pico_get_unique_board_id(&uid); std::copy(uid.id, uid.id + 8, resp.board_id.begin()); auto& ns = net_get_state(); resp.mac = ns.mac; resp.ip = ns.ip; resp.firmware_name = firmware_name; return resp; } std::optional handle_log(const responder&, const RequestLog&) { ResponseLog resp; for (auto& e : dlog_drain()) resp.entries.push_back(LogEntry{e.timestamp_us, std::move(e.message)}); return resp; } std::optional handle_flash_erase(const responder&, const RequestFlashErase& req) { if (req.addr < XIP_BASE_ADDR || req.addr + req.len > XIP_BASE_ADDR + FLASH_SIZE) { dlogf("flash erase: out of range %08lx+%lu", static_cast(req.addr), static_cast(req.len)); return std::nullopt; } uint32_t offset = req.addr - XIP_BASE_ADDR; if (offset % FLASH_SECTOR_SIZE != 0 || req.len % FLASH_SECTOR_SIZE != 0 || req.len == 0) { dlogf("flash erase: bad alignment %08lx+%lu", static_cast(req.addr), static_cast(req.len)); return std::nullopt; } flash_range_erase(offset, req.len); return ResponseFlashErase{}; } std::optional handle_flash_write(const responder&, const RequestFlashWrite& req) { if (req.addr < XIP_BASE_ADDR || req.addr + req.data.size() > XIP_BASE_ADDR + FLASH_SIZE) { dlogf("flash write: out of range %08lx+%zu", static_cast(req.addr), req.data.size()); return std::nullopt; } uint32_t offset = req.addr - XIP_BASE_ADDR; if (offset % FLASH_PAGE_SIZE != 0 || req.data.size() % FLASH_PAGE_SIZE != 0 || req.data.empty()) { dlogf("flash write: bad alignment %08lx+%zu", static_cast(req.addr), req.data.size()); return std::nullopt; } flash_range_program(offset, req.data.data(), req.data.size()); return ResponseFlashWrite{}; } std::optional handle_reboot(const responder&, const RequestReboot&) { dispatch_schedule_ms(100, []{ watchdog_reboot(0, 0, 0); }); return ResponseReboot{}; }