92 Commits

Author SHA1 Message Date
Ian Gulliver 5bad374129 limen: extract udp into its own static library 2026-05-01 13:52:30 -07:00
Ian Gulliver f1bc6381db limen: extract igmp into its own static library 2026-05-01 13:47:41 -07:00
Ian Gulliver 22ead50a00 limen: extract icmp; convert constructor-based self-registration to explicit init() 2026-05-01 13:44:54 -07:00
Ian Gulliver f8b258f92e limen: extract arp into its own static library 2026-05-01 13:35:42 -07:00
Ian Gulliver b29dd149e3 limen: extract ipv4 into its own static library 2026-05-01 13:23:12 -07:00
Ian Gulliver fc0c948b23 limen: merge net+eth into eth lib; ipv4 owns its IP 2026-05-01 11:03:17 -07:00
Ian Gulliver 6505aec466 limen: move remaining util headers into util/ 2026-05-01 10:50:16 -07:00
Ian Gulliver 2eb11398c6 limen: move ring_buffer into util 2026-05-01 10:48:18 -07:00
Ian Gulliver b6ac9dce59 limen: header doc comments on util data structures 2026-05-01 10:47:09 -07:00
Ian Gulliver 57313f836c limen: extract msgpack and util libs; split msgpack header/cpp 2026-05-01 10:43:38 -07:00
Ian Gulliver 94afcf39e7 limen: extract debug_log into its own static library 2026-05-01 10:33:48 -07:00
Ian Gulliver e89e72ca59 limen: net::/ipv4:: namespace, mac/addr filter framework, registry overflow logging 2026-05-01 10:16:07 -07:00
Ian Gulliver c4335a0737 limen: split w6300 into its own static library to enforce layer isolation 2026-04-30 23:14:50 -07:00
Ian Gulliver 7b8dd66185 move w6300/dispatch/net stack to limen submodule 2026-04-19 17:38:29 -07:00
Ian Gulliver 4db5c36931 Self-registering IP-protocol and UDP-port dispatch; move picomap-specific constants out of generic net/dispatch layers 2026-04-19 08:39:13 -07:00
Ian Gulliver 7e493b7d70 Ethertype handler registry: arp/ipv4 self-register via __attribute__((constructor)), drop threaded mac/ip/subnet params 2026-04-19 08:26:57 -07:00
Ian Gulliver 59829b569e Strip over-commenting in test_handlers.cpp 2026-04-19 08:13:16 -07:00
Ian Gulliver 32044a5cbd Eliminate std::function: fn-pointer callbacks, per-test test_state structs, udp.cpp with link-time udp::client::handler, udp::address 2026-04-19 00:32:13 -07:00
Ian Gulliver 40f7fb5941 Drop handle_udp parameter threading: ipv4::handle calls net_handle_udp directly 2026-04-17 14:55:09 -07:00
Ian Gulliver e2daf04bed Drop send_raw parameter threading: arp/icmp/igmp/ipv4 call net_send_raw directly 2026-04-17 14:35:10 -07:00
Ian Gulliver cdc113285a Remove USB/serial support: network-only protocol, drop tinyusb and PICOBOOT 2026-04-17 11:20:57 -07:00
Ian Gulliver 23587c41e2 SHA-256 hash verification of flash slots, pico_hash_binary, flash:: namespace, ring_buffer iterator, non-destructive log 2026-04-12 23:47:00 +09:00
Ian Gulliver cc37b711a4 Return error on inner decode failure instead of hanging, split flash-status output 2026-04-12 22:27:21 +09:00
Ian Gulliver 11c101c235 Flash status: scan PICOBIN blocks for per-slot validity and version 2026-04-12 22:22:54 +09:00
Ian Gulliver 819632a7ea Fix A/B partition link: B partition declares its A partner, not vice versa 2026-04-12 21:54:57 +09:00
Ian Gulliver 8da5ff9886 A/B partition table, embed in both firmware targets 2026-04-12 21:47:12 +09:00
Ian Gulliver a41ee70a3c Build epoch in info, flash-status command, cmake version embedding 2026-04-12 09:02:31 +09:00
Ian Gulliver 21c7900444 Watchdog timer, boot reason tracking, net_poll frame limit, reboot/picoboot CLI commands 2026-04-12 08:27:21 +09:00
Ian Gulliver 6c3e0757f9 Boot reason via watchdog scratch register, reboot/picoboot CLI commands, enum msgpack support 2026-04-12 08:17:22 +09:00
Ian Gulliver 9b7362c460 Rename ping_rate/ping_rate_1k to packet_rate/byte_rate, use 1400-byte payloads 2026-04-12 07:55:30 +09:00
Ian Gulliver 761b740c10 Zero-copy ethernet TX: encode directly into prepend_buffer, add info/test skills 2026-04-12 07:50:20 +09:00
Ian Gulliver 846d6bb201 Clean up load logging, capture build output via slog, use cmake --build 2026-04-11 22:38:16 +09:00
Ian Gulliver 5f2268f5e1 Unified --usb/--udp/--iface target flags for all CLI commands 2026-04-11 22:33:55 +09:00
Ian Gulliver e3d97f4946 In-app flash write, UF2 parser, remove picotool dependency, reboot command 2026-04-11 22:26:54 +09:00
Ian Gulliver a635aa04e0 Level-triggered w6300 interrupt, drain until empty, rearm after drain 2026-04-11 21:51:22 +09:00
Ian Gulliver 8b69917e1d Biffer buffers, more aggressive tests 2026-04-11 21:32:50 +09:00
Ian Gulliver 59d67c740c Replace net_poll budget with snapshot-based drain: read available bytes once, stop when consumed 2026-04-11 20:51:42 +09:00
Ian Gulliver ecc8271648 Remove unused sorted_list 2026-04-11 20:45:04 +09:00
Ian Gulliver 1c8c645878 Clean up callback_list, remove sentinel/active/tail, callbacks return bool for removal, register before send 2026-04-11 15:01:37 +09:00
Ian Gulliver 938b4b8a4c Limit net_poll to 2 frames per iteration, pipeline=2 for both rate tests 2026-04-11 14:36:40 +09:00
Ian Gulliver fec0a0f765 Replace sorted_list/vector with callback_list doubly-linked list for timers and frame callbacks 2026-04-11 14:26:53 +09:00
Ian Gulliver aa349e1a36 Add debug logging to overflow/error paths, fix pipeline=2 drop 2026-04-11 09:48:25 +09:00
Ian Gulliver f7baf60249 Pipeline ping rate tests, small=1 large=2 in-flight 2026-04-11 09:29:34 +09:00
Ian Gulliver 1843660e6f Add ping rate tests, discover_peer helper, standardize prepend_buffer to 4096 2026-04-11 09:17:46 +09:00
Ian Gulliver a6225faa2b Add IGMP, prepend_buffer/parse_buffer, split UDP header, discovery tests, test all 2026-04-11 09:04:55 +09:00
Ian Gulliver e486f6501a Cancellable timers: sorted_list::remove, timer cancel, replace done flag with timer cancellation 2026-04-11 08:28:32 +09:00
Ian Gulliver 3a3c5873c3 Add dlogf printf formatting, ipv4::to_string helper, clean up string building 2026-04-11 08:21:59 +09:00
Ian Gulliver c35c1de76a Split net stack into eth/arp/ipv4/icmp, deferred handler responses, ping tests 2026-04-11 08:15:41 +09:00
Ian Gulliver 34efaeefd5 Add list-tests protocol message, test subcommands, extract test handlers 2026-04-11 07:25:16 +09:00
Ian Gulliver f6d8847bcf Fix packer: store span_writer by reference, not copy 2026-04-10 23:23:58 +09:00
Ian Gulliver 7264611f99 Zero-copy decode: span-based Envelope and DecodedMessage, defer usb_rx_buf clear 2026-04-10 23:08:51 +09:00
Ian Gulliver 76c519c17a Overflow detection, span-based signatures, flatten control flow 2026-04-10 23:02:07 +09:00
Ian Gulliver 8408603390 Zero-copy encode: pack response body in place, single shared tx_buf, drain rx loop 2026-04-10 22:48:28 +09:00
Ian Gulliver 58db392bf3 Simplify handler signatures: return response struct, typed_handler does encoding 2026-04-10 22:21:31 +09:00
Ian Gulliver e2a5d97dae Zero-copy TX: span_writer packer, static buffers, no vector returns 2026-04-10 22:18:44 +09:00
Ian Gulliver 94895fd2fe Move picoboot reboot into handler via dispatch_schedule_ms 2026-04-10 22:04:38 +09:00
Ian Gulliver f2d98ef4f1 Skip net_poll and timers unless their interrupt has fired 2026-04-10 22:00:34 +09:00
Ian Gulliver 8edf8c2d4f Remove unused iodata_t, PIO_OFFSET_WRITE_BITS, trim intr_kind, move sock_count to cpp 2026-04-10 21:51:58 +09:00
Ian Gulliver c961499239 Remove socket IO mode (nonblock unnecessary with pre-checked recv buffer) 2026-04-10 21:45:43 +09:00
Ian Gulliver 0d41f63533 Strip non-MACRAW enums, unused macros, and set_socket_dest_mac 2026-04-10 21:42:20 +09:00
Ian Gulliver 394628b8da MACRAW-only: simplify send/recv API, remove non-MACRAW code paths and unused types 2026-04-10 21:37:03 +09:00
Ian Gulliver bee0fa3aef Remove critical section code, unused constants, and unused register definitions 2026-04-10 21:27:01 +09:00
Ian Gulliver ff9f9a5c1f Remove unused W6300 register accessors and internal functions 2026-04-10 21:18:43 +09:00
Ian Gulliver af308b5aac Remove unused W6300 API: phy, net config, TCP, keepalive, peek, and related types 2026-04-10 21:06:52 +09:00
Ian Gulliver 712110aace Remove unused interrupt code: enable_interrupt_pin, CHECK markers, dead comments 2026-04-10 20:54:07 +09:00
Ian Gulliver 0c11cbb1d1 WFI with interrupt-driven wakeup for USB and W6300 2026-04-10 12:55:04 +09:00
Ian Gulliver 3d20bf4c33 Per-packet source tracking in transport, via/from in info output 2026-04-07 22:30:26 +09:00
Ian Gulliver f96ed20aa0 Fix broadcast collection: UDP reader blocks until deadline, 500ms timeout everywhere 2026-04-07 22:22:19 +09:00
Ian Gulliver e301c672a9 Broadcast discovery with InfoAll, interface broadcast detection, clean output 2026-04-07 22:12:20 +09:00
Ian Gulliver 7034391d4d UDP transport with broadcast support, -udp and -iface flags on info 2026-04-07 21:44:35 +09:00
Ian Gulliver 9989d8c66a Add UDP transport with picomap port 28781, info -udp flag 2026-04-07 21:36:50 +09:00
Ian Gulliver 3d749add7d Compose eth header into ipv4_header, use icmp_echo struct, protocol switch in handle_ipv4 2026-04-07 12:31:27 +09:00
Ian Gulliver f161dda60a Rewrite net.cpp to use packed structs for frame encoding/decoding 2026-04-07 12:21:41 +09:00
Ian Gulliver b0294fada3 Fix broadcast ping reply source IP, accept broadcast destinations 2026-04-07 12:18:07 +09:00
Ian Gulliver 31b2c16b07 Debug log with dlog_if_slow, MACRAW ping working, wfi disabled 2026-04-07 12:09:18 +09:00
Ian Gulliver d215ddc6f2 Add debug log ring buffer with timestamps, log CLI subcommand 2026-04-07 09:18:43 +09:00
Ian Gulliver ffcbaf0665 Merge info/load/test CLIs into unified picomap subcommand CLI 2026-04-07 08:37:34 +09:00
Ian Gulliver a7381ca435 MACRAW net stack, slog, load -target flag, LED blink, net_poll disabled pending SPI fix 2026-04-07 08:34:29 +09:00
Ian Gulliver a9193d51e4 Switch commands to slog, disable net_poll pending fix 2026-04-07 07:43:16 +09:00
Ian Gulliver 46db2fd966 MACRAW IP stack with ARP/ICMP, stable device ordering, LED blink on test 2026-04-07 07:34:24 +09:00
Ian Gulliver 642e2ff318 Remove leading underscores and mixed case from w6300 internal symbols 2026-04-07 07:15:24 +09:00
Ian Gulliver 3c320cf466 Rename screaming case symbols to snake_case in w6300 public API 2026-04-07 07:09:11 +09:00
Ian Gulliver 843a286631 Remove multicast socket polling, fix USB responsiveness 2026-04-07 07:04:53 +09:00
Ian Gulliver e60479bad8 Switch to IPv4 zeroconf, add test framework with discovery test, fix serial enumeration 2026-04-07 06:58:39 +09:00
Ian Gulliver b8c0e6be66 Handlers return multiple responses, dispatch polls sockets for UDP commands 2026-04-06 20:22:40 +09:00
Ian Gulliver f837937cb7 Add firmware_name to info response 2026-04-06 20:09:30 +09:00
Ian Gulliver 49bbe1b29c Split dispatch init/run, join IPv6 multicast discovery group in firmware 2026-04-06 20:01:22 +09:00
Ian Gulliver 00b960d81d Add dispatch loop, copy_to_ram, retry picotool load without sleep 2026-04-06 17:36:41 +09:00
Ian Gulliver b197f0bfa7 Extract picoboot and info handlers into lib/handlers 2026-04-06 17:24:34 +09:00
Ian Gulliver 00ab432a72 Add IPv6 link-local address to net_init and info response, use WaitGroup.Go 2026-04-06 17:20:13 +09:00
Ian Gulliver 1fa1b2076c Poll for BOOTSEL readiness instead of fixed sleep, load with -x 2026-04-06 09:19:26 +09:00
Ian Gulliver ee8563ab69 Remove DHCP client, preserved on dhcp-wip branch 2026-04-06 09:10:50 +09:00
36 changed files with 992 additions and 3959 deletions
+7
View File
@@ -0,0 +1,7 @@
---
name: info
description: Query device info from connected Picos. Use when the user says "info", "check devices", or wants to verify devices are responding.
user-invocable: true
---
Run `go run ./cmd/picomap/ info` from the project root. This queries all connected devices and prints board ID, MAC, IP, and firmware name.
+5 -3
View File
@@ -4,8 +4,10 @@ description: Build firmware, load it onto the Pico, and reboot. Use when the use
user-invocable: true
---
Run `go run ./cmd/load/` from the project root. This builds both firmware targets, loads picomap onto the first device and picomap_test onto the second, and reboots both.
Run `go run ./cmd/picomap/ load` from the project root. This builds both firmware targets, loads picomap onto the first device and picomap_test onto the second, and reboots both.
After loading, run `go run ./cmd/info/` to verify both devices are responding.
To load a single target: `go run ./cmd/picomap/ load picomap` or `go run ./cmd/picomap/ load picomap_test`.
After modifying the load command itself (cmd/load/, lib/wire/, lib/picoserial/), run it twice: once to load the firmware, once to verify the load process still works end-to-end.
After loading, run `go run ./cmd/picomap/ info` to verify devices are responding.
After modifying the CLI itself (cmd/picomap/, lib/), run load twice: once to load the firmware, once to verify the load process still works end-to-end.
+10
View File
@@ -0,0 +1,10 @@
---
name: test
description: Run device tests on connected Picos. Use when the user says "test", "run tests", or wants to verify firmware behavior.
user-invocable: true
---
Run `go run ./cmd/picomap/ test all` from the project root. This runs all registered tests on the test device.
To list available tests: `go run ./cmd/picomap/ test list`
To run a specific test: `go run ./cmd/picomap/ test run <name>`
+3
View File
@@ -0,0 +1,3 @@
[submodule "firmware/limen"]
path = firmware/limen
url = git@g.fc.run:embed/limen.git
-69
View File
@@ -1,69 +0,0 @@
package main
import (
"fmt"
"os"
"sync"
"time"
"github.com/theater/picomap/lib/client"
)
type deviceResult struct {
dev string
info *client.ResponseInfo
err error
}
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func run() error {
devs, err := client.ListSerial()
if err != nil {
return err
}
if len(devs) == 0 {
return fmt.Errorf("no devices found")
}
results := make([]deviceResult, len(devs))
var wg sync.WaitGroup
for i, dev := range devs {
wg.Add(1)
go func() {
defer wg.Done()
results[i].dev = dev
c, err := client.NewSerial(dev, 2*time.Second)
if err != nil {
results[i].err = err
return
}
info, err := c.Info()
c.Close()
results[i].info = info
results[i].err = err
}()
}
wg.Wait()
for _, r := range results {
fmt.Printf("Device: %s\n", r.dev)
if r.err != nil {
fmt.Fprintf(os.Stderr, " error: %v\n", r.err)
continue
}
fmt.Printf(" Board ID: %02X%02X%02X%02X%02X%02X%02X%02X\n",
r.info.BoardID[0], r.info.BoardID[1], r.info.BoardID[2], r.info.BoardID[3],
r.info.BoardID[4], r.info.BoardID[5], r.info.BoardID[6], r.info.BoardID[7])
fmt.Printf(" MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
r.info.MAC[0], r.info.MAC[1], r.info.MAC[2],
r.info.MAC[3], r.info.MAC[4], r.info.MAC[5])
}
return nil
}
-158
View File
@@ -1,158 +0,0 @@
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
"github.com/theater/picomap/lib/client"
"github.com/theater/picomap/lib/picotool"
)
func main() {
wd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
buildDir := filepath.Join(wd, "firmware", "build")
if err := run(buildDir); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func build(buildDir string) error {
fmt.Println("Configuring...")
cmake := exec.Command("cmake", "-S", filepath.Join(filepath.Dir(buildDir)), "-B", buildDir)
cmake.Stdout = os.Stdout
cmake.Stderr = os.Stderr
if err := cmake.Run(); err != nil {
return fmt.Errorf("cmake failed: %w", err)
}
fmt.Println("Building...")
cmd := exec.Command("make", "-C", buildDir)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("build failed: %w", err)
}
return nil
}
func boardSerial(id [8]byte) string {
return fmt.Sprintf("%02X%02X%02X%02X%02X%02X%02X%02X",
id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7])
}
func run(buildDir string) error {
if err := build(buildDir); err != nil {
return err
}
devs, err := client.ListSerial()
if err != nil {
return err
}
if len(devs) < 2 {
return fmt.Errorf("expected 2 devices, found %d", len(devs))
}
serials := make([]string, 2)
errs := make([]error, 2)
var wg sync.WaitGroup
for i := range 2 {
wg.Add(1)
go func() {
defer wg.Done()
c, err := client.NewSerial(devs[i], 2*time.Second)
if err != nil {
errs[i] = err
return
}
info, err := c.Info()
c.Close()
if err != nil {
errs[i] = err
return
}
serials[i] = boardSerial(info.BoardID)
}()
}
wg.Wait()
for i, err := range errs {
if err != nil {
return fmt.Errorf("info %s: %w", devs[i], err)
}
}
fmt.Println("Sending PICOBOOT requests...")
for i := range 2 {
wg.Add(1)
go func() {
defer wg.Done()
c, err := client.NewSerial(devs[i], 2*time.Second)
if err != nil {
errs[i] = err
return
}
err = c.PICOBOOT()
c.Close()
if err != nil {
errs[i] = fmt.Errorf("PICOBOOT %s: %w", devs[i], err)
}
}()
}
wg.Wait()
for _, err := range errs {
if err != nil {
return err
}
}
time.Sleep(2 * time.Second)
uf2s := []string{
filepath.Join(buildDir, "picomap.uf2"),
filepath.Join(buildDir, "picomap_test.uf2"),
}
fmt.Println("Loading firmware...")
for i := range 2 {
wg.Add(1)
go func() {
defer wg.Done()
errs[i] = picotool.Load(uf2s[i], serials[i])
}()
}
wg.Wait()
for i, err := range errs {
if err != nil {
return fmt.Errorf("load %s: %w", serials[i], err)
}
}
fmt.Println("Rebooting...")
for i := range 2 {
wg.Add(1)
go func() {
defer wg.Done()
errs[i] = picotool.Reboot(serials[i])
}()
}
wg.Wait()
for i, err := range errs {
if err != nil {
return fmt.Errorf("reboot %s: %w", serials[i], err)
}
}
fmt.Println("Done.")
return nil
}
+522
View File
@@ -0,0 +1,522 @@
package main
import (
"encoding/hex"
"flag"
"fmt"
"log/slog"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/theater/picomap/lib/client"
"github.com/theater/picomap/lib/uf2"
)
type target struct {
name string
client *client.Client
}
type targetFlags struct {
udp string
iface string
}
func addTargetFlags(fs *flag.FlagSet) *targetFlags {
tf := &targetFlags{}
fs.StringVar(&tf.udp, "udp", "", "comma-separated UDP IP addresses")
fs.StringVar(&tf.iface, "iface", "", "network interface for multicast discovery")
return tf
}
func (tf *targetFlags) connect(timeout time.Duration) ([]target, error) {
var targets []target
if tf.udp != "" {
for _, addr := range strings.Split(tf.udp, ",") {
addr = strings.TrimSpace(addr)
c, err := client.NewUDP(addr, tf.iface, timeout)
if err != nil {
return nil, fmt.Errorf("udp %s: %w", addr, err)
}
targets = append(targets, target{addr, c})
}
}
if tf.iface != "" && tf.udp == "" {
bcast, err := client.InterfaceBroadcast(tf.iface)
if err != nil {
return nil, err
}
c, err := client.NewUDP(bcast, tf.iface, timeout)
if err != nil {
return nil, err
}
infos, err := c.InfoAll()
c.Close()
if err != nil {
return nil, fmt.Errorf("discovery: %w", err)
}
for _, r := range infos {
uc, err := client.NewUDP(r.From, tf.iface, timeout)
if err != nil {
return nil, fmt.Errorf("udp %s: %w", r.From, err)
}
targets = append(targets, target{r.From, uc})
}
}
if len(targets) == 0 {
return nil, fmt.Errorf("no devices found")
}
return targets, nil
}
func closeTargets(targets []target) {
for _, t := range targets {
t.client.Close()
}
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: picomap <command> [args...]\n\ncommands:\n info\n flash-status\n load\n log\n reboot\n test\n")
os.Exit(1)
}
cmd := os.Args[1]
args := os.Args[2:]
var err error
switch cmd {
case "info":
err = cmdInfo(args)
case "flash-status":
err = cmdFlashStatus(args)
case "load":
err = cmdLoad(args)
case "log":
err = cmdLog(args)
case "reboot":
err = cmdReboot(args)
case "test":
err = cmdTestGroup(args)
default:
fmt.Fprintf(os.Stderr, "usage: picomap <command> [args...]\n\ncommands:\n info\n flash-status\n load\n log\n reboot\n test\n")
os.Exit(1)
}
if err != nil {
slog.Error("fatal", "err", err)
os.Exit(1)
}
}
func printInfo(via string, info *client.ResponseInfo) {
slog.Info("device",
"via", via,
"board_id", hex.EncodeToString(info.BoardID[:]),
"mac", net.HardwareAddr(info.MAC[:]).String(),
"ip", net.IP(info.IP[:]).String(),
"firmware", info.FirmwareName,
"boot", info.Boot.String(),
"build_epoch", info.BuildEpoch)
}
func cmdInfo(args []string) error {
fs := flag.NewFlagSet("info", flag.ExitOnError)
tf := addTargetFlags(fs)
fs.Parse(args)
targets, err := tf.connect(500*time.Millisecond)
if err != nil {
return err
}
defer closeTargets(targets)
for _, t := range targets {
info, err := t.client.Info()
if err != nil {
slog.Error("info error", "via", t.name, "err", err)
continue
}
printInfo(t.name, info)
}
return nil
}
func cmdLog(args []string) error {
fs := flag.NewFlagSet("log", flag.ExitOnError)
tf := addTargetFlags(fs)
fs.Parse(args)
targets, err := tf.connect(500*time.Millisecond)
if err != nil {
return err
}
defer closeTargets(targets)
for _, t := range targets {
log := slog.With("dev", t.name)
resp, err := t.client.Log()
if err != nil {
log.Error("log error", "err", err)
continue
}
if len(resp.Entries) == 0 {
log.Info("no debug messages")
continue
}
for _, e := range resp.Entries {
log.Info("dlog", "t_us", e.TimestampUS, "msg", e.Message)
}
}
return nil
}
func cmdFlashStatus(args []string) error {
fs := flag.NewFlagSet("flash-status", flag.ExitOnError)
tf := addTargetFlags(fs)
fs.Parse(args)
targets, err := tf.connect(500 * time.Millisecond)
if err != nil {
return err
}
defer closeTargets(targets)
for _, t := range targets {
status, err := t.client.FlashStatus()
if err != nil {
slog.Error("flash-status error", "via", t.name, "err", err)
continue
}
log := slog.With("via", t.name)
log.Info("flash-status", "boot_partition", status.BootPartition)
log.Info("slot-a", "valid", status.SlotA.Valid, "version", status.SlotA.Version, "hash_ok", status.SlotA.HashOK)
log.Info("slot-b", "valid", status.SlotB.Valid, "version", status.SlotB.Version, "hash_ok", status.SlotB.HashOK)
}
return nil
}
func cmdReboot(args []string) error {
fs := flag.NewFlagSet("reboot", flag.ExitOnError)
tf := addTargetFlags(fs)
fs.Parse(args)
targets, err := tf.connect(500 * time.Millisecond)
if err != nil {
return err
}
defer closeTargets(targets)
for _, t := range targets {
if err := t.client.Reboot(); err != nil {
slog.Error("reboot error", "via", t.name, "err", err)
continue
}
slog.Info("rebooted", "via", t.name)
}
return nil
}
func boardSerial(id [8]byte) string {
return fmt.Sprintf("%02X%02X%02X%02X%02X%02X%02X%02X",
id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7])
}
func runCmd(name string, args ...string) error {
cmd := exec.Command(name, args...)
out, err := cmd.CombinedOutput()
if len(out) > 0 {
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
slog.Info(name, "msg", line)
}
}
if err != nil {
return fmt.Errorf("%s failed: %w", name, err)
}
return nil
}
func buildFirmware(buildDir string) error {
srcDir := filepath.Dir(buildDir)
if err := runCmd("cmake", "-S", srcDir, "-B", buildDir); err != nil {
return err
}
return runCmd("cmake", "--build", buildDir)
}
func cmdLoad(args []string) error {
fs := flag.NewFlagSet("load", flag.ExitOnError)
tf := addTargetFlags(fs)
dryRun := fs.Bool("dry-run", false, "parse UF2 and log operations without flashing")
fs.Parse(args)
loadTarget := "all"
if fs.NArg() > 0 {
loadTarget = fs.Arg(0)
}
wd, err := os.Getwd()
if err != nil {
return err
}
buildDir := filepath.Join(wd, "firmware", "build")
if err := buildFirmware(buildDir); err != nil {
return err
}
type firmwareTarget struct {
name string
uf2 string
}
allTargets := []firmwareTarget{
{"picomap", filepath.Join(buildDir, "picomap.uf2")},
{"picomap_test", filepath.Join(buildDir, "picomap_test.uf2")},
}
var fwTargets []firmwareTarget
switch loadTarget {
case "all":
fwTargets = allTargets
case "picomap":
fwTargets = allTargets[:1]
case "picomap_test":
fwTargets = allTargets[1:]
default:
return fmt.Errorf("unknown target %q", loadTarget)
}
targets, err := tf.connect(5*time.Second)
if err != nil {
return err
}
defer closeTargets(targets)
if len(targets) < len(fwTargets) {
return fmt.Errorf("need %d device(s), found %d", len(fwTargets), len(targets))
}
type deviceInfo struct {
target target
serial string
fw firmwareTarget
}
devices := make([]deviceInfo, len(fwTargets))
for i, t := range targets[:len(fwTargets)] {
info, err := t.client.Info()
if err != nil {
return fmt.Errorf("[%s] info: %w", t.name, err)
}
devices[i] = deviceInfo{
target: t,
serial: boardSerial(info.BoardID),
fw: fwTargets[i],
}
slog.Info("got info", "dev", t.name, "serial", devices[i].serial, "firmware", info.FirmwareName)
}
errs := make([]error, len(devices))
var wg sync.WaitGroup
for i := range devices {
log := slog.With("dev", devices[i].target.name, "serial", devices[i].serial)
wg.Go(func() {
log.Info("flashing", "uf2", devices[i].fw.name)
errs[i] = flashDevice(devices[i].target.client, devices[i].fw.uf2, *dryRun, log)
if errs[i] == nil {
log.Info("flashed", "uf2", devices[i].fw.name)
}
})
}
wg.Wait()
for i, err := range errs {
if err != nil {
return fmt.Errorf("[%s] flash: %w", devices[i].serial, err)
}
}
slog.Info("done")
return nil
}
func flashDevice(c *client.Client, uf2Path string, dryRun bool, log *slog.Logger) error {
blocks, err := uf2.Parse(uf2Path)
if err != nil {
return fmt.Errorf("parse uf2: %w", err)
}
log.Info("parsed uf2", "blocks", len(blocks))
const sectorSize = 4096
if dryRun {
erased := make(map[uint32]bool)
for _, b := range blocks {
sector := b.Addr &^ (sectorSize - 1)
if !erased[sector] {
log.Info("erasing", "addr", fmt.Sprintf("%08x", sector))
erased[sector] = true
}
log.Info("writing", "addr", fmt.Sprintf("%08x", b.Addr), "len", len(b.Data))
}
return nil
}
erased := make(map[uint32]bool)
for _, b := range blocks {
sector := b.Addr &^ (sectorSize - 1)
if !erased[sector] {
if err := c.FlashErase(sector, sectorSize); err != nil {
return fmt.Errorf("erase %08x: %w", sector, err)
}
erased[sector] = true
}
if err := c.FlashWrite(b.Addr, b.Data); err != nil {
return fmt.Errorf("write %08x: %w", b.Addr, err)
}
}
log.Info("rebooting")
c.Reboot()
return nil
}
func findTestDevice(args []string) (target, error) {
fs := flag.NewFlagSet("test", flag.ExitOnError)
tf := addTargetFlags(fs)
fs.Parse(args)
targets, err := tf.connect(10*time.Second)
if err != nil {
return target{}, err
}
for _, t := range targets {
info, err := t.client.Info()
if err != nil {
t.client.Close()
continue
}
if info.FirmwareName == "picomap_test" {
for _, other := range targets {
if other.name != t.name {
other.client.Close()
}
}
return t, nil
}
t.client.Close()
}
return target{}, fmt.Errorf("no picomap_test device found")
}
func cmdTestGroup(args []string) error {
if len(args) < 1 {
return fmt.Errorf("usage: picomap test <list|run|all> [args...]")
}
switch args[0] {
case "list":
return cmdTestList(args[1:])
case "run":
return cmdTestRun(args[1:])
case "all":
return cmdTestAll(args[1:])
default:
return fmt.Errorf("usage: picomap test <list|run|all> [args...]")
}
}
func cmdTestList(args []string) error {
t, err := findTestDevice(args)
if err != nil {
return err
}
defer t.client.Close()
result, err := t.client.ListTests()
if err != nil {
return fmt.Errorf("remote: %w", err)
}
for _, name := range result.Names {
slog.Info("test", "dev", t.name, "name", name)
}
return nil
}
func cmdTestAll(args []string) error {
t, err := findTestDevice(args)
if err != nil {
return err
}
defer t.client.Close()
list, err := t.client.ListTests()
if err != nil {
return fmt.Errorf("remote: %w", err)
}
log := slog.With("dev", t.name)
failed := 0
for _, name := range list.Names {
log.Info("running test", "name", name)
result, err := t.client.Test(name)
if err != nil {
log.Error("error", "name", name, "err", err)
failed++
continue
}
for _, msg := range result.Messages {
log.Info("remote", "name", name, "msg", msg)
}
if result.Pass {
log.Info("PASS", "name", name)
} else {
log.Error("FAIL", "name", name)
failed++
}
}
if failed > 0 {
log.Error("tests failed", "count", failed)
os.Exit(1)
}
log.Info("all tests passed", "count", len(list.Names))
return nil
}
func cmdTestRun(args []string) error {
if len(args) < 1 {
return fmt.Errorf("usage: picomap test run <name>")
}
name := args[0]
t, err := findTestDevice(args[1:])
if err != nil {
return err
}
defer t.client.Close()
log := slog.With("dev", t.name)
log.Info("running test", "name", name)
result, err := t.client.Test(name)
if err != nil {
return fmt.Errorf("remote: %w", err)
}
for _, msg := range result.Messages {
log.Info("remote", "msg", msg)
}
if result.Pass {
log.Info("PASS")
} else {
log.Error("FAIL")
os.Exit(1)
}
return nil
}
+14 -23
View File
@@ -9,29 +9,20 @@ set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 23)
pico_sdk_init()
set(LIB_SOURCES
lib/dhcp.cpp
lib/net.cpp
lib/tusb_config.cpp
w6300/w6300.cpp
)
add_subdirectory(limen)
set(LIB_DEPS pico_stdlib pico_rand tinyusb_device tinyusb_board hardware_pio hardware_spi hardware_dma hardware_clocks)
string(TIMESTAMP BUILD_EPOCH "%s" UTC)
math(EXPR VERSION_MAJOR "${BUILD_EPOCH} >> 16")
math(EXPR VERSION_MINOR "${BUILD_EPOCH} & 65535")
add_executable(picomap firmware.cpp ${LIB_SOURCES})
target_include_directories(picomap PRIVATE include w6300)
target_compile_options(picomap PRIVATE -Wall -Wextra -Wno-unused-parameter)
pico_generate_pio_header(picomap ${CMAKE_CURRENT_LIST_DIR}/w6300/qspi.pio)
pico_enable_stdio_usb(picomap 0)
pico_enable_stdio_uart(picomap 0)
pico_add_extra_outputs(picomap)
target_link_libraries(picomap ${LIB_DEPS})
add_executable(picomap firmware.cpp)
target_link_libraries(picomap PRIVATE limen)
pico_set_binary_version(picomap MAJOR ${VERSION_MAJOR} MINOR ${VERSION_MINOR})
target_compile_definitions(picomap PRIVATE BUILD_EPOCH=${BUILD_EPOCH})
limen_configure_executable(picomap)
add_executable(picomap_test test.cpp ${LIB_SOURCES})
target_include_directories(picomap_test PRIVATE include w6300)
target_compile_options(picomap_test PRIVATE -Wall -Wextra -Wno-unused-parameter)
pico_generate_pio_header(picomap_test ${CMAKE_CURRENT_LIST_DIR}/w6300/qspi.pio)
pico_enable_stdio_usb(picomap_test 0)
pico_enable_stdio_uart(picomap_test 0)
pico_add_extra_outputs(picomap_test)
target_link_libraries(picomap_test ${LIB_DEPS})
add_executable(picomap_test test.cpp)
target_link_libraries(picomap_test PRIVATE limen)
pico_set_binary_version(picomap_test MAJOR ${VERSION_MAJOR} MINOR ${VERSION_MINOR})
target_compile_definitions(picomap_test PRIVATE BUILD_EPOCH=${BUILD_EPOCH})
limen_configure_executable(picomap_test)
+19 -62
View File
@@ -1,66 +1,23 @@
#include "pico/stdlib.h"
#include "pico/bootrom.h"
#include "pico/unique_id.h"
#include "tusb.h"
#include "wire.h"
#include "usb_cdc.h"
#include "timer_queue.h"
#include "dhcp.h"
#include "net.h"
#include "w6300.h"
#include "dispatch.h"
#include "handlers.h"
#include "igmp.h"
static usb_cdc usb;
static timer_queue timers;
std::string_view firmware_name = "picomap";
uint32_t firmware_build_epoch = BUILD_EPOCH;
static constexpr handler_entry handlers[] = {
{RequestInfo::ext_id, typed_handler<RequestInfo, handle_info>},
{RequestLog::ext_id, typed_handler<RequestLog, handle_log>},
{RequestFlashErase::ext_id, typed_handler<RequestFlashErase, handle_flash_erase>},
{RequestFlashWrite::ext_id, typed_handler<RequestFlashWrite, handle_flash_write>},
{RequestReboot::ext_id, typed_handler<RequestReboot, handle_reboot>},
{RequestFlashStatus::ext_id, typed_handler<RequestFlashStatus, handle_flash_status>},
};
int main() {
tusb_init();
net_init();
auto ninfo = w6300::get_net_info();
dhcp_start(timers, ninfo.mac);
static static_vector<uint8_t, 256> rx_buf;
while (true) {
tud_task();
usb.drain();
timers.run();
while (tud_cdc_available()) {
uint8_t byte;
if (tud_cdc_read(&byte, 1) != 1) break;
rx_buf.push_back(byte);
auto msg = try_decode(rx_buf);
if (!msg) {
if (rx_buf.full()) rx_buf.clear();
continue;
}
rx_buf.clear();
switch (msg->type_id) {
case RequestPICOBOOT::ext_id:
usb.send(encode_response(msg->message_id, ResponsePICOBOOT{}));
sleep_ms(100);
reset_usb_boot(0, 1);
break;
case RequestInfo::ext_id: {
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 ninfo = w6300::get_net_info();
resp.mac = ninfo.mac;
usb.send(encode_response(msg->message_id, resp));
break;
}
}
}
__wfi();
}
handlers_init();
dispatch_init(PICOMAP_PORT_BE);
igmp::join(PICOMAP_DISCOVERY_GROUP);
handlers_start();
dispatch_run(handlers);
}
-5
View File
@@ -1,5 +0,0 @@
#pragma once
#include <array>
#include "timer_queue.h"
void dhcp_start(timer_queue& timers, const std::array<uint8_t, 6>& mac);
-79
View File
@@ -1,79 +0,0 @@
#pragma once
#include <cstdint>
#include <cstddef>
namespace halfsiphash {
namespace detail {
constexpr uint32_t rotl(uint32_t x, int b) {
return (x << b) | (x >> (32 - b));
}
constexpr uint32_t load_le32(const uint8_t *p) {
return static_cast<uint32_t>(p[0])
| (static_cast<uint32_t>(p[1]) << 8)
| (static_cast<uint32_t>(p[2]) << 16)
| (static_cast<uint32_t>(p[3]) << 24);
}
inline void store_le32(uint8_t *p, uint32_t v) {
p[0] = static_cast<uint8_t>(v);
p[1] = static_cast<uint8_t>(v >> 8);
p[2] = static_cast<uint8_t>(v >> 16);
p[3] = static_cast<uint8_t>(v >> 24);
}
inline void sipround(uint32_t &v0, uint32_t &v1, uint32_t &v2, uint32_t &v3) {
v0 += v1; v1 = rotl(v1, 5); v1 ^= v0; v0 = rotl(v0, 16);
v2 += v3; v3 = rotl(v3, 8); v3 ^= v2;
v0 += v3; v3 = rotl(v3, 7); v3 ^= v0;
v2 += v1; v1 = rotl(v1, 13); v1 ^= v2; v2 = rotl(v2, 16);
}
} // namespace detail
// Compute HalfSipHash-2-4 with an 8-byte key, returning a 32-bit hash.
inline uint32_t hash32(const uint8_t *data, size_t len, const uint8_t key[8]) {
using namespace detail;
uint32_t k0 = load_le32(key);
uint32_t k1 = load_le32(key + 4);
uint32_t v0 = 0 ^ k0;
uint32_t v1 = 0 ^ k1;
uint32_t v2 = UINT32_C(0x6c796765) ^ k0;
uint32_t v3 = UINT32_C(0x74656462) ^ k1;
const uint8_t *end = data + len - (len % 4);
for (const uint8_t *p = data; p != end; p += 4) {
uint32_t m = load_le32(p);
v3 ^= m;
sipround(v0, v1, v2, v3);
sipround(v0, v1, v2, v3);
v0 ^= m;
}
uint32_t b = static_cast<uint32_t>(len) << 24;
switch (len & 3) {
case 3: b |= static_cast<uint32_t>(end[2]) << 16; [[fallthrough]];
case 2: b |= static_cast<uint32_t>(end[1]) << 8; [[fallthrough]];
case 1: b |= static_cast<uint32_t>(end[0]); break;
case 0: break;
}
v3 ^= b;
sipround(v0, v1, v2, v3);
sipround(v0, v1, v2, v3);
v0 ^= b;
v2 ^= 0xff;
sipround(v0, v1, v2, v3);
sipround(v0, v1, v2, v3);
sipround(v0, v1, v2, v3);
sipround(v0, v1, v2, v3);
return v1 ^ v3;
}
} // namespace halfsiphash
-792
View File
@@ -1,792 +0,0 @@
#pragma once
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <expected>
#include <iterator>
#include <limits>
#include <memory>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <vector>
namespace msgpack {
enum class error_code {
overflow,
empty,
lack,
invalid,
type_error,
};
namespace format {
constexpr uint8_t POSITIVE_FIXINT_MIN = 0x00;
constexpr uint8_t POSITIVE_FIXINT_MAX = 0x7F;
constexpr uint8_t FIXMAP_MIN = 0x80;
constexpr uint8_t FIXMAP_MAX = 0x8F;
constexpr uint8_t FIXARRAY_MIN = 0x90;
constexpr uint8_t FIXARRAY_MAX = 0x9F;
constexpr uint8_t FIXSTR_MIN = 0xA0;
constexpr uint8_t FIXSTR_MAX = 0xBF;
constexpr uint8_t NEGATIVE_FIXINT_MIN = 0xE0;
constexpr uint8_t NEGATIVE_FIXINT_MAX = 0xFF;
constexpr uint8_t NIL = 0xC0;
constexpr uint8_t NEVER_USED = 0xC1;
constexpr uint8_t FALSE = 0xC2;
constexpr uint8_t TRUE = 0xC3;
constexpr uint8_t BIN8 = 0xC4;
constexpr uint8_t BIN16 = 0xC5;
constexpr uint8_t BIN32 = 0xC6;
constexpr uint8_t EXT8 = 0xC7;
constexpr uint8_t EXT16 = 0xC8;
constexpr uint8_t EXT32 = 0xC9;
constexpr uint8_t FLOAT32 = 0xCA;
constexpr uint8_t FLOAT64 = 0xCB;
constexpr uint8_t UINT8 = 0xCC;
constexpr uint8_t UINT16 = 0xCD;
constexpr uint8_t UINT32 = 0xCE;
constexpr uint8_t UINT64 = 0xCF;
constexpr uint8_t INT8 = 0xD0;
constexpr uint8_t INT16 = 0xD1;
constexpr uint8_t INT32 = 0xD2;
constexpr uint8_t INT64 = 0xD3;
constexpr uint8_t FIXEXT1 = 0xD4;
constexpr uint8_t FIXEXT2 = 0xD5;
constexpr uint8_t FIXEXT4 = 0xD6;
constexpr uint8_t FIXEXT8 = 0xD7;
constexpr uint8_t FIXEXT16 = 0xD8;
constexpr uint8_t STR8 = 0xD9;
constexpr uint8_t STR16 = 0xDA;
constexpr uint8_t STR32 = 0xDB;
constexpr uint8_t ARRAY16 = 0xDC;
constexpr uint8_t ARRAY32 = 0xDD;
constexpr uint8_t MAP16 = 0xDE;
constexpr uint8_t MAP32 = 0xDF;
constexpr bool is_positive_fixint(uint8_t b) { return b <= POSITIVE_FIXINT_MAX; }
constexpr bool is_fixmap(uint8_t b) { return b >= FIXMAP_MIN && b <= FIXMAP_MAX; }
constexpr bool is_fixarray(uint8_t b) { return b >= FIXARRAY_MIN && b <= FIXARRAY_MAX; }
constexpr bool is_fixstr(uint8_t b) { return b >= FIXSTR_MIN && b <= FIXSTR_MAX; }
constexpr bool is_negative_fixint(uint8_t b) { return b >= NEGATIVE_FIXINT_MIN; }
} // namespace format
template <typename T>
using result = std::expected<T, error_code>;
template <typename T>
result<T> body_number(const uint8_t *p, int size) {
if (size < 1 + static_cast<int>(sizeof(T))) {
return std::unexpected(error_code::lack);
}
if constexpr (sizeof(T) == 1) {
return static_cast<T>(p[1]);
} else if constexpr (sizeof(T) == 2) {
return static_cast<T>((p[1] << 8) | p[2]);
} else if constexpr (sizeof(T) == 4) {
uint8_t buf[] = {p[4], p[3], p[2], p[1]};
T val;
__builtin_memcpy(&val, buf, sizeof(T));
return val;
} else if constexpr (sizeof(T) == 8) {
uint8_t buf[] = {p[8], p[7], p[6], p[5], p[4], p[3], p[2], p[1]};
T val;
__builtin_memcpy(&val, buf, sizeof(T));
return val;
} else {
return std::unexpected(error_code::invalid);
}
}
struct body_info {
int header; // bytes before the body (includes format byte + length fields + ext type byte)
uint32_t body; // body size in bytes (0 for containers, computed for variable-length)
};
inline result<body_info> get_body_info(const uint8_t *p, int size) {
if (size < 1) return std::unexpected(error_code::empty);
uint8_t b = p[0];
using namespace format;
if (is_positive_fixint(b)) return body_info{1, 0};
if (is_negative_fixint(b)) return body_info{1, 0};
if (is_fixmap(b)) return body_info{1, 0}; // container
if (is_fixarray(b)) return body_info{1, 0}; // container
if (is_fixstr(b)) return body_info{1, static_cast<uint32_t>(b & 0x1F)};
switch (b) {
case NIL: case FALSE: case TRUE:
return body_info{1, 0};
case NEVER_USED:
return std::unexpected(error_code::invalid);
case BIN8: { auto n = body_number<uint8_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+1, *n}; }
case BIN16: { auto n = body_number<uint16_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+2, *n}; }
case BIN32: { auto n = body_number<uint32_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+4, *n}; }
case EXT8: { auto n = body_number<uint8_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+1+1, *n}; }
case EXT16: { auto n = body_number<uint16_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+2+1, *n}; }
case EXT32: { auto n = body_number<uint32_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+4+1, *n}; }
case FLOAT32: return body_info{1, 4};
case FLOAT64: return body_info{1, 8};
case UINT8: return body_info{1, 1};
case UINT16: return body_info{1, 2};
case UINT32: return body_info{1, 4};
case UINT64: return body_info{1, 8};
case INT8: return body_info{1, 1};
case INT16: return body_info{1, 2};
case INT32: return body_info{1, 4};
case INT64: return body_info{1, 8};
case FIXEXT1: return body_info{1+1, 1};
case FIXEXT2: return body_info{1+1, 2};
case FIXEXT4: return body_info{1+1, 4};
case FIXEXT8: return body_info{1+1, 8};
case FIXEXT16: return body_info{1+1, 16};
case STR8: { auto n = body_number<uint8_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+1, *n}; }
case STR16: { auto n = body_number<uint16_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+2, *n}; }
case STR32: { auto n = body_number<uint32_t>(p, size); if (!n) return std::unexpected(n.error()); return body_info{1+4, *n}; }
case ARRAY16: case ARRAY32:
case MAP16: case MAP32:
return body_info{1 + (b == ARRAY16 || b == MAP16 ? 2 : 4), 0}; // container
default:
return std::unexpected(error_code::invalid);
}
}
class packer {
public:
using buffer = std::vector<std::uint8_t>;
private:
std::shared_ptr<buffer> m_buffer;
template <typename T> void push_big_endian(T n) {
auto p = reinterpret_cast<std::uint8_t *>(&n) + (sizeof(T) - 1);
for (size_t i = 0; i < sizeof(T); ++i, --p) {
m_buffer->push_back(*p);
}
}
template <class Range> void push(const Range &r) {
m_buffer->insert(m_buffer->end(), std::begin(r), std::end(r));
}
public:
packer() : m_buffer(std::make_shared<buffer>()) {}
packer(const std::shared_ptr<buffer> &buf) : m_buffer(buf) {}
packer(const packer &) = delete;
packer &operator=(const packer &) = delete;
using pack_result = result<std::reference_wrapper<packer>>;
pack_result pack_nil() {
m_buffer->push_back(format::NIL);
return *this;
}
pack_result pack_bool(bool v) {
m_buffer->push_back(v ? format::TRUE : format::FALSE);
return *this;
}
template <typename T>
pack_result pack_integer(T n) {
if constexpr (std::is_signed_v<T>) {
if (n >= 0 && n <= 0x7F) {
m_buffer->push_back(static_cast<uint8_t>(n));
} else if (n >= -32 && n < 0) {
m_buffer->push_back(static_cast<uint8_t>(n)); // negative fixint
} else if (n >= std::numeric_limits<int8_t>::min() && n <= std::numeric_limits<int8_t>::max()) {
m_buffer->push_back(format::INT8);
m_buffer->push_back(static_cast<uint8_t>(n));
} else if (n >= std::numeric_limits<int16_t>::min() && n <= std::numeric_limits<int16_t>::max()) {
m_buffer->push_back(format::INT16);
push_big_endian(static_cast<int16_t>(n));
} else if (n >= std::numeric_limits<int32_t>::min() && n <= std::numeric_limits<int32_t>::max()) {
m_buffer->push_back(format::INT32);
push_big_endian(static_cast<int32_t>(n));
} else {
m_buffer->push_back(format::INT64);
push_big_endian(static_cast<int64_t>(n));
}
} else {
if (n <= 0x7F) {
m_buffer->push_back(static_cast<uint8_t>(n));
} else if (n <= std::numeric_limits<uint8_t>::max()) {
m_buffer->push_back(format::UINT8);
m_buffer->push_back(static_cast<uint8_t>(n));
} else if (n <= std::numeric_limits<uint16_t>::max()) {
m_buffer->push_back(format::UINT16);
push_big_endian(static_cast<uint16_t>(n));
} else if (n <= std::numeric_limits<uint32_t>::max()) {
m_buffer->push_back(format::UINT32);
push_big_endian(static_cast<uint32_t>(n));
} else {
m_buffer->push_back(format::UINT64);
push_big_endian(static_cast<uint64_t>(n));
}
}
return *this;
}
pack_result pack_float(float n) {
m_buffer->push_back(format::FLOAT32);
push_big_endian(n);
return *this;
}
pack_result pack_double(double n) {
m_buffer->push_back(format::FLOAT64);
push_big_endian(n);
return *this;
}
template <class Range>
pack_result pack_str(const Range &r) {
auto sz = static_cast<size_t>(std::distance(std::begin(r), std::end(r)));
if (sz < 32) {
m_buffer->push_back(format::FIXSTR_MIN | static_cast<uint8_t>(sz));
} else if (sz <= std::numeric_limits<uint8_t>::max()) {
m_buffer->push_back(format::STR8);
m_buffer->push_back(static_cast<uint8_t>(sz));
} else if (sz <= std::numeric_limits<uint16_t>::max()) {
m_buffer->push_back(format::STR16);
push_big_endian(static_cast<uint16_t>(sz));
} else if (sz <= std::numeric_limits<uint32_t>::max()) {
m_buffer->push_back(format::STR32);
push_big_endian(static_cast<uint32_t>(sz));
} else {
return std::unexpected(error_code::overflow);
}
push(r);
return *this;
}
pack_result pack_str(const char *s) {
return pack_str(std::string_view(s));
}
template <class Range>
pack_result pack_bin(const Range &r) {
auto sz = static_cast<size_t>(std::distance(std::begin(r), std::end(r)));
if (sz <= std::numeric_limits<uint8_t>::max()) {
m_buffer->push_back(format::BIN8);
m_buffer->push_back(static_cast<uint8_t>(sz));
} else if (sz <= std::numeric_limits<uint16_t>::max()) {
m_buffer->push_back(format::BIN16);
push_big_endian(static_cast<uint16_t>(sz));
} else if (sz <= std::numeric_limits<uint32_t>::max()) {
m_buffer->push_back(format::BIN32);
push_big_endian(static_cast<uint32_t>(sz));
} else {
return std::unexpected(error_code::overflow);
}
push(r);
return *this;
}
pack_result pack_array(size_t n) {
if (n <= 15) {
m_buffer->push_back(format::FIXARRAY_MIN | static_cast<uint8_t>(n));
} else if (n <= std::numeric_limits<uint16_t>::max()) {
m_buffer->push_back(format::ARRAY16);
push_big_endian(static_cast<uint16_t>(n));
} else if (n <= std::numeric_limits<uint32_t>::max()) {
m_buffer->push_back(format::ARRAY32);
push_big_endian(static_cast<uint32_t>(n));
} else {
return std::unexpected(error_code::overflow);
}
return *this;
}
pack_result pack_map(size_t n) {
if (n <= 15) {
m_buffer->push_back(format::FIXMAP_MIN | static_cast<uint8_t>(n));
} else if (n <= std::numeric_limits<uint16_t>::max()) {
m_buffer->push_back(format::MAP16);
push_big_endian(static_cast<uint16_t>(n));
} else if (n <= std::numeric_limits<uint32_t>::max()) {
m_buffer->push_back(format::MAP32);
push_big_endian(static_cast<uint32_t>(n));
} else {
return std::unexpected(error_code::overflow);
}
return *this;
}
template <class Range>
pack_result pack_ext(char type, const Range &r) {
auto sz = static_cast<size_t>(std::distance(std::begin(r), std::end(r)));
switch (sz) {
case 1: m_buffer->push_back(format::FIXEXT1); break;
case 2: m_buffer->push_back(format::FIXEXT2); break;
case 4: m_buffer->push_back(format::FIXEXT4); break;
case 8: m_buffer->push_back(format::FIXEXT8); break;
case 16: m_buffer->push_back(format::FIXEXT16); break;
default:
if (sz <= std::numeric_limits<uint8_t>::max()) {
m_buffer->push_back(format::EXT8);
m_buffer->push_back(static_cast<uint8_t>(sz));
} else if (sz <= std::numeric_limits<uint16_t>::max()) {
m_buffer->push_back(format::EXT16);
push_big_endian(static_cast<uint16_t>(sz));
} else if (sz <= std::numeric_limits<uint32_t>::max()) {
m_buffer->push_back(format::EXT32);
push_big_endian(static_cast<uint32_t>(sz));
} else {
return std::unexpected(error_code::overflow);
}
}
m_buffer->push_back(static_cast<uint8_t>(type));
push(r);
return *this;
}
template <typename T>
requires std::is_integral_v<T> && (!std::is_same_v<T, bool>)
pack_result pack(T n) { return pack_integer(n); }
pack_result pack(bool v) { return pack_bool(v); }
pack_result pack(float v) { return pack_float(v); }
pack_result pack(double v) { return pack_double(v); }
pack_result pack(const char *v) { return pack_str(v); }
pack_result pack(std::string_view v) { return pack_str(v); }
pack_result pack(const std::string &v) { return pack_str(v); }
pack_result pack(const std::vector<uint8_t> &v) { return pack_bin(v); }
template <size_t N>
pack_result pack(const std::array<uint8_t, N> &v) { return pack_bin(v); }
template <typename... Ts>
pack_result pack(const std::tuple<Ts...> &t) {
auto r = pack_array(sizeof...(Ts));
if (!r) return r;
return pack_tuple_elements(t, std::index_sequence_for<Ts...>{});
}
template <typename T>
requires requires(const T &v) { { T::ext_id } -> std::convertible_to<int8_t>; v.as_tuple(); }
pack_result pack(const T &v) {
packer inner;
auto r = inner.pack(v.as_tuple());
if (!r) return r;
return pack_ext(T::ext_id, inner.get_payload());
}
template <typename T>
requires (requires(const T &v) { v.as_tuple(); } && !requires { { T::ext_id } -> std::convertible_to<int8_t>; })
pack_result pack(const T &v) {
return pack(v.as_tuple());
}
private:
template <typename Tuple, size_t... Is>
pack_result pack_tuple_elements(const Tuple &t, std::index_sequence<Is...>) {
pack_result r = *this;
((r = r ? r->get().pack(std::get<Is>(t)) : r), ...);
return r;
}
public:
const buffer &get_payload() const { return *m_buffer; }
};
class parser {
const uint8_t *m_p = nullptr;
int m_size = 0;
result<uint8_t> header_byte() const {
if (m_size < 1) return std::unexpected(error_code::empty);
return m_p[0];
}
public:
parser() = default;
parser(const std::vector<uint8_t> &v)
: m_p(v.data()), m_size(static_cast<int>(v.size())) {}
parser(const uint8_t *p, int size)
: m_p(p), m_size(size < 0 ? 0 : size) {}
bool is_empty() const { return m_size == 0; }
const uint8_t *data() const { return m_p; }
int size() const { return m_size; }
result<parser> advance(int n) const {
if (n > m_size) return std::unexpected(error_code::lack);
return parser(m_p + n, m_size - n);
}
result<parser> next() const {
auto hdr = header_byte();
if (!hdr) return std::unexpected(hdr.error());
if (is_array()) {
auto info = get_body_info(m_p, m_size);
if (!info) return std::unexpected(info.error());
auto cnt = count();
if (!cnt) return std::unexpected(cnt.error());
auto cur = advance(info->header);
if (!cur) return std::unexpected(cur.error());
for (uint32_t i = 0; i < *cnt; ++i) {
auto n = cur->next();
if (!n) return std::unexpected(n.error());
cur = *n;
}
return *cur;
} else if (is_map()) {
auto info = get_body_info(m_p, m_size);
if (!info) return std::unexpected(info.error());
auto cnt = count();
if (!cnt) return std::unexpected(cnt.error());
auto cur = advance(info->header);
if (!cur) return std::unexpected(cur.error());
for (uint32_t i = 0; i < *cnt; ++i) {
auto k = cur->next();
if (!k) return std::unexpected(k.error());
cur = *k;
auto v = cur->next();
if (!v) return std::unexpected(v.error());
cur = *v;
}
return *cur;
} else {
auto info = get_body_info(m_p, m_size);
if (!info) return std::unexpected(info.error());
auto total = info->header + static_cast<int>(info->body);
return advance(total);
}
}
bool is_nil() const {
auto h = header_byte();
return h && *h == format::NIL;
}
bool is_bool() const {
auto h = header_byte();
return h && (*h == format::TRUE || *h == format::FALSE);
}
bool is_number() const {
auto h = header_byte();
if (!h) return false;
uint8_t b = *h;
if (format::is_positive_fixint(b)) return true;
if (format::is_negative_fixint(b)) return true;
return b >= format::FLOAT32 && b <= format::INT64;
}
bool is_string() const {
auto h = header_byte();
if (!h) return false;
uint8_t b = *h;
if (format::is_fixstr(b)) return true;
return b == format::STR8 || b == format::STR16 || b == format::STR32;
}
bool is_binary() const {
auto h = header_byte();
if (!h) return false;
uint8_t b = *h;
return b == format::BIN8 || b == format::BIN16 || b == format::BIN32;
}
bool is_ext() const {
auto h = header_byte();
if (!h) return false;
uint8_t b = *h;
return (b >= format::FIXEXT1 && b <= format::FIXEXT16) ||
b == format::EXT8 || b == format::EXT16 || b == format::EXT32;
}
bool is_array() const {
auto h = header_byte();
if (!h) return false;
uint8_t b = *h;
if (format::is_fixarray(b)) return true;
return b == format::ARRAY16 || b == format::ARRAY32;
}
bool is_map() const {
auto h = header_byte();
if (!h) return false;
uint8_t b = *h;
if (format::is_fixmap(b)) return true;
return b == format::MAP16 || b == format::MAP32;
}
result<bool> get_bool() const {
auto h = header_byte();
if (!h) return std::unexpected(h.error());
if (*h == format::TRUE) return true;
if (*h == format::FALSE) return false;
return std::unexpected(error_code::type_error);
}
result<std::string_view> get_string() const {
auto h = header_byte();
if (!h) return std::unexpected(h.error());
uint8_t b = *h;
size_t offset, len;
if (format::is_fixstr(b)) {
len = b & 0x1F;
offset = 1;
} else if (b == format::STR8) {
auto n = body_number<uint8_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
len = *n; offset = 1 + 1;
} else if (b == format::STR16) {
auto n = body_number<uint16_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
len = *n; offset = 1 + 2;
} else if (b == format::STR32) {
auto n = body_number<uint32_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
len = *n; offset = 1 + 4;
} else {
return std::unexpected(error_code::type_error);
}
if (static_cast<int>(offset + len) > m_size) {
return std::unexpected(error_code::lack);
}
return std::string_view(reinterpret_cast<const char *>(m_p + offset), len);
}
result<std::string_view> get_binary_view() const {
auto h = header_byte();
if (!h) return std::unexpected(h.error());
uint8_t b = *h;
size_t offset, len;
if (b == format::BIN8) {
auto n = body_number<uint8_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
len = *n; offset = 1 + 1;
} else if (b == format::BIN16) {
auto n = body_number<uint16_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
len = *n; offset = 1 + 2;
} else if (b == format::BIN32) {
auto n = body_number<uint32_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
len = *n; offset = 1 + 4;
} else {
return std::unexpected(error_code::type_error);
}
if (static_cast<int>(offset + len) > m_size) {
return std::unexpected(error_code::lack);
}
return std::string_view(reinterpret_cast<const char *>(m_p + offset), len);
}
result<std::tuple<int8_t, std::string_view>> get_ext() const {
auto h = header_byte();
if (!h) return std::unexpected(h.error());
uint8_t b = *h;
int8_t ext_type;
size_t data_offset, data_len;
switch (b) {
case format::FIXEXT1: ext_type = m_p[1]; data_offset = 2; data_len = 1; break;
case format::FIXEXT2: ext_type = m_p[1]; data_offset = 2; data_len = 2; break;
case format::FIXEXT4: ext_type = m_p[1]; data_offset = 2; data_len = 4; break;
case format::FIXEXT8: ext_type = m_p[1]; data_offset = 2; data_len = 8; break;
case format::FIXEXT16: ext_type = m_p[1]; data_offset = 2; data_len = 16; break;
case format::EXT8: {
auto n = body_number<uint8_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
ext_type = m_p[2]; data_offset = 3; data_len = *n;
break;
}
case format::EXT16: {
auto n = body_number<uint16_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
ext_type = m_p[3]; data_offset = 4; data_len = *n;
break;
}
case format::EXT32: {
auto n = body_number<uint32_t>(m_p, m_size);
if (!n) return std::unexpected(n.error());
ext_type = m_p[5]; data_offset = 6; data_len = *n;
break;
}
default:
return std::unexpected(error_code::type_error);
}
if (static_cast<int>(data_offset + data_len) > m_size) {
return std::unexpected(error_code::lack);
}
return std::tuple{ext_type,
std::string_view(reinterpret_cast<const char *>(m_p + data_offset), data_len)};
}
template <typename T>
result<T> get_number() const {
auto h = header_byte();
if (!h) return std::unexpected(h.error());
uint8_t b = *h;
if (format::is_positive_fixint(b)) return static_cast<T>(b);
if (format::is_negative_fixint(b)) return static_cast<T>(static_cast<int8_t>(b));
switch (b) {
case format::UINT8: { auto n = body_number<uint8_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::UINT16: { auto n = body_number<uint16_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::UINT32: { auto n = body_number<uint32_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::UINT64: { auto n = body_number<uint64_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::INT8: { auto n = body_number<int8_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::INT16: { auto n = body_number<int16_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::INT32: { auto n = body_number<int32_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::INT64: { auto n = body_number<int64_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::FLOAT32: { auto n = body_number<float>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
case format::FLOAT64: { auto n = body_number<double>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<T>(*n); }
default:
return std::unexpected(error_code::type_error);
}
}
result<uint32_t> count() const {
auto h = header_byte();
if (!h) return std::unexpected(h.error());
uint8_t b = *h;
if (format::is_fixarray(b)) return static_cast<uint32_t>(b & 0x0F);
if (format::is_fixmap(b)) return static_cast<uint32_t>(b & 0x0F);
switch (b) {
case format::ARRAY16: { auto n = body_number<uint16_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<uint32_t>(*n); }
case format::ARRAY32: { auto n = body_number<uint32_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return *n; }
case format::MAP16: { auto n = body_number<uint16_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return static_cast<uint32_t>(*n); }
case format::MAP32: { auto n = body_number<uint32_t>(m_p, m_size); if (!n) return std::unexpected(n.error()); return *n; }
default:
return std::unexpected(error_code::type_error);
}
}
result<parser> first_item() const {
if (!is_array() && !is_map()) return std::unexpected(error_code::type_error);
auto info = get_body_info(m_p, m_size);
if (!info) return std::unexpected(info.error());
return advance(info->header);
}
parser operator[](int index) const {
auto cur = first_item();
if (!cur) return {};
for (int i = 0; i < index; ++i) {
auto n = cur->next();
if (!n) return {};
cur = *n;
}
return *cur;
}
};
template <typename T>
requires std::is_integral_v<T> && (!std::is_same_v<T, bool>)
result<parser> unpack(const parser &p, T &out) {
auto v = p.get_number<T>();
if (!v) return std::unexpected(v.error());
out = *v;
return p.next();
}
inline result<parser> unpack(const parser &p, bool &out) {
auto v = p.get_bool();
if (!v) return std::unexpected(v.error());
out = *v;
return p.next();
}
inline result<parser> unpack(const parser &p, std::string_view &out) {
auto v = p.get_string();
if (!v) return std::unexpected(v.error());
out = *v;
return p.next();
}
inline result<parser> unpack(const parser &p, std::string &out) {
auto v = p.get_string();
if (!v) return std::unexpected(v.error());
out = std::string(v->data(), v->size());
return p.next();
}
template <size_t N>
result<parser> unpack(const parser &p, std::array<uint8_t, N> &out) {
auto v = p.get_binary_view();
if (!v) return std::unexpected(v.error());
if (v->size() != N) return std::unexpected(error_code::type_error);
std::copy(v->begin(), v->end(), out.begin());
return p.next();
}
inline result<parser> unpack(const parser &p, std::vector<uint8_t> &out) {
auto v = p.get_binary_view();
if (!v) return std::unexpected(v.error());
out.assign(v->begin(), v->end());
return p.next();
}
template <typename... Ts, size_t... Is>
result<parser> unpack_tuple_elements(const parser &p, std::tuple<Ts...> &t, std::index_sequence<Is...>) {
result<parser> cur = p.first_item();
if (!cur) return cur;
((cur = cur ? unpack(*cur, std::get<Is>(t)) : cur), ...);
return cur;
}
template <typename... Ts>
result<parser> unpack(const parser &p, std::tuple<Ts...> &t) {
auto cnt = p.count();
if (!cnt) return std::unexpected(cnt.error());
if (*cnt != sizeof...(Ts)) return std::unexpected(error_code::type_error);
auto r = unpack_tuple_elements(p, t, std::index_sequence_for<Ts...>{});
if (!r) return r;
return p.next();
}
template <typename T>
requires (requires(T &v) { v.as_tuple(); } && !requires { { T::ext_id } -> std::convertible_to<int8_t>; })
result<parser> unpack(const parser &p, T &out) {
auto tup = out.as_tuple();
auto cnt = p.count();
if (!cnt) return std::unexpected(cnt.error());
if (*cnt != std::tuple_size_v<decltype(tup)>) return std::unexpected(error_code::type_error);
auto r = unpack_tuple_elements(p, tup, std::make_index_sequence<std::tuple_size_v<decltype(tup)>>{});
if (!r) return r;
return p.next();
}
template <typename T>
requires requires(T &v) { { T::ext_id } -> std::convertible_to<int8_t>; v.as_tuple(); }
result<parser> unpack(const parser &p, T &out) {
auto ext = p.get_ext();
if (!ext) return std::unexpected(ext.error());
auto [ext_type, ext_data] = *ext;
if (ext_type != T::ext_id) return std::unexpected(error_code::type_error);
parser inner(reinterpret_cast<const uint8_t *>(ext_data.data()),
static_cast<int>(ext_data.size()));
auto tup = out.as_tuple();
auto r = unpack_tuple_elements(inner, tup, std::make_index_sequence<std::tuple_size_v<decltype(tup)>>{});
if (!r) return r;
return p.next();
}
} // namespace msgpack
-3
View File
@@ -1,3 +0,0 @@
#pragma once
bool net_init();
-44
View File
@@ -1,44 +0,0 @@
#pragma once
#include <array>
#include <cstdint>
#include <span>
template <uint16_t N>
struct ring_buffer {
std::array<uint8_t, N> data = {};
uint16_t head = 0;
uint16_t tail = 0;
uint16_t used() const { return tail - head; }
uint16_t free() const { return N - used(); }
bool empty() const { return head == tail; }
void push(std::span<const uint8_t> src) {
if (src.size() > free()) return;
for (auto b : src)
data[(tail++) % N] = b;
}
uint16_t peek(std::span<uint8_t> dst) const {
uint16_t len = dst.size() < used() ? dst.size() : used();
for (uint16_t i = 0; i < len; i++)
dst[i] = data[(head + i) % N];
return len;
}
void consume(uint16_t len) {
head += len;
if (head >= N) {
head -= N;
tail -= N;
}
}
std::span<const uint8_t> read_contiguous() const {
uint16_t offset = head % N;
uint16_t contig = N - offset;
uint16_t pending = used();
uint16_t len = pending < contig ? pending : contig;
return {data.data() + offset, len};
}
};
-58
View File
@@ -1,58 +0,0 @@
#pragma once
#include <cstdint>
#include <new>
#include <utility>
template <typename T, int N>
struct sorted_list {
struct node {
alignas(T) uint8_t storage[sizeof(T)];
node* next = nullptr;
T& value() { return *reinterpret_cast<T*>(storage); }
const T& value() const { return *reinterpret_cast<const T*>(storage); }
};
node nodes[N];
node* head = nullptr;
node* free_head = &nodes[0];
sorted_list() {
for (int i = 0; i < N - 1; i++) nodes[i].next = &nodes[i + 1];
nodes[N - 1].next = nullptr;
}
bool empty() const { return head == nullptr; }
bool full() const { return free_head == nullptr; }
T& front() { return head->value(); }
const T& front() const { return head->value(); }
void insert(T value) {
if (full()) return;
node* n = free_head;
free_head = n->next;
new (n->storage) T(std::move(value));
if (!head || n->value() < head->value()) {
n->next = head;
head = n;
return;
}
node* cur = head;
while (cur->next && !(n->value() < cur->next->value()))
cur = cur->next;
n->next = cur->next;
cur->next = n;
}
void pop_front() {
if (empty()) return;
node* n = head;
head = n->next;
n->value().~T();
n->next = free_head;
free_head = n;
}
};
-33
View File
@@ -1,33 +0,0 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <cstring>
template <typename T, size_t Capacity>
class static_vector {
T m_data[Capacity];
size_t m_size = 0;
public:
void push_back(const T &v) {
if (m_size < Capacity) m_data[m_size++] = v;
}
void clear() { m_size = 0; }
size_t size() const { return m_size; }
size_t capacity() const { return Capacity; }
bool full() const { return m_size >= Capacity; }
bool empty() const { return m_size == 0; }
T *data() { return m_data; }
const T *data() const { return m_data; }
T &operator[](size_t i) { return m_data[i]; }
const T &operator[](size_t i) const { return m_data[i]; }
T *begin() { return m_data; }
T *end() { return m_data + m_size; }
const T *begin() const { return m_data; }
const T *end() const { return m_data + m_size; }
};
-50
View File
@@ -1,50 +0,0 @@
#pragma once
#include <functional>
#include "pico/time.h"
#include "sorted_list.h"
struct timer_entry {
absolute_time_t when;
std::function<void()> fn;
};
inline bool operator<(const timer_entry& a, const timer_entry& b) {
return absolute_time_diff_us(b.when, a.when) < 0;
}
struct timer_queue {
sorted_list<timer_entry, 16> queue;
alarm_id_t alarm = -1;
void schedule(absolute_time_t when, std::function<void()> fn) {
queue.insert({when, std::move(fn)});
arm();
}
void schedule_ms(uint32_t ms, std::function<void()> fn) {
schedule(make_timeout_time_ms(ms), std::move(fn));
}
void run() {
while (!queue.empty()) {
auto& front = queue.front();
if (absolute_time_diff_us(get_absolute_time(), front.when) > 0) break;
auto fn = std::move(front.fn);
queue.pop_front();
fn();
}
arm();
}
bool empty() const { return queue.empty(); }
private:
static int64_t alarm_cb(alarm_id_t, void*) { return 0; }
void arm() {
if (alarm >= 0) cancel_alarm(alarm);
alarm = -1;
if (!queue.empty())
alarm = add_alarm_at(queue.front().when, alarm_cb, nullptr, false);
}
};
-7
View File
@@ -1,7 +0,0 @@
#pragma once
#define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE
#define CFG_TUD_CDC 1
#define CFG_TUD_CDC_RX_BUFSIZE 256
#define CFG_TUD_CDC_TX_BUFSIZE 256
#define CFG_TUD_CDC_EP_BUFSIZE 64
-31
View File
@@ -1,31 +0,0 @@
#pragma once
#include <cstdint>
#include <span>
#include <vector>
#include "tusb.h"
#include "ring_buffer.h"
struct usb_cdc {
ring_buffer<512> tx;
void send(std::span<const uint8_t> data) {
tx.push(data);
drain();
}
void send(const std::vector<uint8_t>& data) {
send(std::span<const uint8_t>{data});
}
void drain() {
while (!tx.empty()) {
uint32_t avail = tud_cdc_write_available();
if (avail == 0) break;
auto chunk = tx.read_contiguous();
if (chunk.size() > avail) chunk = chunk.first(avail);
tud_cdc_write(chunk.data(), chunk.size());
tx.consume(chunk.size());
}
tud_cdc_write_flush();
}
};
-96
View File
@@ -1,96 +0,0 @@
#pragma once
#include <array>
#include <cstdint>
#include <string>
#include <tuple>
#include <vector>
#include "msgpack.h"
#include "halfsiphash.h"
#include "static_vector.h"
struct Envelope {
static constexpr int8_t ext_id = 0;
uint32_t message_id;
uint32_t checksum;
std::vector<uint8_t> payload;
auto as_tuple() const { return std::tie(message_id, checksum, payload); }
auto as_tuple() { return std::tie(message_id, checksum, payload); }
};
struct DeviceError {
static constexpr int8_t ext_id = 1;
uint32_t code;
std::string message;
auto as_tuple() const { return std::tie(code, message); }
auto as_tuple() { return std::tie(code, message); }
};
struct RequestPICOBOOT {
static constexpr int8_t ext_id = 2;
auto as_tuple() const { return std::tie(); }
auto as_tuple() { return std::tie(); }
};
struct ResponsePICOBOOT {
static constexpr int8_t ext_id = 3;
auto as_tuple() const { return std::tie(); }
auto as_tuple() { return std::tie(); }
};
struct RequestInfo {
static constexpr int8_t ext_id = 4;
auto as_tuple() const { return std::tie(); }
auto as_tuple() { return std::tie(); }
};
struct ResponseInfo {
static constexpr int8_t ext_id = 5;
std::array<uint8_t, 8> board_id;
std::array<uint8_t, 6> mac;
auto as_tuple() const { return std::tie(board_id, mac); }
auto as_tuple() { return std::tie(board_id, mac); }
};
static constexpr uint8_t hash_key[8] = {};
struct DecodedMessage {
uint32_t message_id;
int8_t type_id;
};
inline std::vector<uint8_t> pack_envelope(uint32_t message_id, const std::vector<uint8_t> &payload) {
uint32_t checksum = halfsiphash::hash32(payload.data(), payload.size(), hash_key);
msgpack::packer p;
p.pack(Envelope{message_id, checksum, payload});
return p.get_payload();
}
template <typename T>
inline std::vector<uint8_t> encode_response(uint32_t message_id, const T &msg) {
msgpack::packer inner;
inner.pack(msg);
return pack_envelope(message_id, inner.get_payload());
}
inline msgpack::result<DecodedMessage> try_decode(const uint8_t *data, size_t len) {
msgpack::parser p(data, static_cast<int>(len));
Envelope env;
auto r = msgpack::unpack(p, env);
if (!r) return std::unexpected(r.error());
uint32_t expected = halfsiphash::hash32(env.payload.data(), env.payload.size(), hash_key);
if (env.checksum != expected) return std::unexpected(msgpack::error_code::invalid);
msgpack::parser inner(env.payload.data(), static_cast<int>(env.payload.size()));
if (!inner.is_ext()) return std::unexpected(msgpack::error_code::type_error);
auto ext = inner.get_ext();
if (!ext) return std::unexpected(ext.error());
return DecodedMessage{env.message_id, std::get<0>(*ext)};
}
template <size_t N>
inline msgpack::result<DecodedMessage> try_decode(const static_vector<uint8_t, N> &buf) {
return try_decode(buf.data(), buf.size());
}
-55
View File
@@ -1,55 +0,0 @@
#include "dhcp.h"
#include <span>
#include "pico/rand.h"
#include "w6300.h"
namespace dhcp_opt {
constexpr uint8_t message_type = 53;
constexpr uint8_t param_request = 55;
constexpr uint8_t end = 255;
constexpr uint8_t discover = 1;
constexpr uint8_t subnet_mask = 1;
}
struct __attribute__((packed)) dhcp_discover {
uint8_t op = 1;
uint8_t htype = 1;
uint8_t hlen = 6;
uint8_t hops = 0;
uint32_t xid = __builtin_bswap32(static_cast<uint32_t>(get_rand_64()));
uint16_t secs = 0;
uint16_t flags = __builtin_bswap16(0x8000);
std::array<uint8_t, 4> ciaddr = {};
std::array<uint8_t, 4> yiaddr = {};
std::array<uint8_t, 4> siaddr = {};
std::array<uint8_t, 4> giaddr = {};
std::array<uint8_t, 16> chaddr = {};
std::array<uint8_t, 64> sname = {};
std::array<uint8_t, 128> file = {};
std::array<uint8_t, 4> magic = {99, 130, 83, 99};
uint8_t opt_msg_type[3] = {dhcp_opt::message_type, 1, dhcp_opt::discover};
uint8_t opt_params[3] = {dhcp_opt::param_request, 1, dhcp_opt::subnet_mask};
uint8_t opt_end = dhcp_opt::end;
};
static_assert(sizeof(dhcp_discover) == 247);
static void send_discover(timer_queue& timers, const std::array<uint8_t, 6>& mac) {
auto sn = w6300::socket_id{0};
w6300::open_socket(sn, w6300::protocol::udp, w6300::port_num{68}, w6300::sock_flag::none);
dhcp_discover pkt;
std::copy(mac.begin(), mac.end(), pkt.chaddr.begin());
w6300::ip_address broadcast = {};
broadcast.ip = {255, 255, 255, 255};
broadcast.len = 4;
w6300::sendto(sn, std::span{reinterpret_cast<uint8_t*>(&pkt), sizeof(pkt)}, broadcast, w6300::port_num{67});
timers.schedule_ms(5000, [&timers, mac]() { send_discover(timers, mac); });
}
void dhcp_start(timer_queue& timers, const std::array<uint8_t, 6>& mac) {
send_discover(timers, mac);
}
-24
View File
@@ -1,24 +0,0 @@
#include "net.h"
#include "pico/unique_id.h"
#include "w6300.h"
bool net_init() {
w6300::init_spi();
w6300::init_critical_section();
w6300::reset();
w6300::init();
if (!w6300::check()) return false;
pico_unique_board_id_t uid;
pico_get_unique_board_id(&uid);
w6300::net_info info = {};
info.mac[0] = (uid.id[0] & 0xFC) | 0x02;
info.mac[1] = uid.id[1];
info.mac[2] = uid.id[2];
info.mac[3] = uid.id[3];
info.mac[4] = uid.id[4];
info.mac[5] = uid.id[5];
w6300::init_net(info);
return true;
}
-82
View File
@@ -1,82 +0,0 @@
#include <cstring>
#include "pico/unique_id.h"
#include "tusb.h"
constexpr uint16_t USB_VID = 0x2E8A;
constexpr uint16_t USB_PID = 0x000A;
static constexpr tusb_desc_device_t desc_device = {
sizeof(tusb_desc_device_t),
TUSB_DESC_DEVICE,
0x0200,
TUSB_CLASS_MISC,
MISC_SUBCLASS_COMMON,
MISC_PROTOCOL_IAD,
CFG_TUD_ENDPOINT0_SIZE,
USB_VID,
USB_PID,
0x0100,
1, 2, 3,
1,
};
enum { ITF_NUM_CDC, ITF_NUM_CDC_DATA, ITF_NUM_TOTAL };
constexpr uint8_t EPNUM_CDC_NOTIF = 0x81;
constexpr uint8_t EPNUM_CDC_OUT = 0x02;
constexpr uint8_t EPNUM_CDC_IN = 0x82;
constexpr uint16_t CONFIG_TOTAL_LEN = TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN;
static uint8_t const desc_configuration[] = {
TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0x00, 100),
TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 0, EPNUM_CDC_NOTIF, 8, EPNUM_CDC_OUT, EPNUM_CDC_IN, 64),
};
static constexpr const char* string_desc[] = {
"\x09\x04",
"picomap",
"picomap",
nullptr,
};
static uint16_t desc_str_buf[33];
extern "C" {
uint8_t const* tud_descriptor_device_cb(void) {
return reinterpret_cast<uint8_t const*>(&desc_device);
}
uint8_t const* tud_descriptor_configuration_cb(uint8_t index) {
return desc_configuration;
}
uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
uint8_t chr_count;
if (index == 0) {
memcpy(&desc_str_buf[1], string_desc[0], 2);
chr_count = 1;
} else if (index == 3) {
pico_unique_board_id_t uid;
pico_get_unique_board_id(&uid);
chr_count = 0;
for (int i = 0; i < 8; i++) {
desc_str_buf[1 + chr_count++] = "0123456789ABCDEF"[uid.id[i] >> 4];
desc_str_buf[1 + chr_count++] = "0123456789ABCDEF"[uid.id[i] & 0xF];
}
} else {
if (index >= sizeof(string_desc) / sizeof(string_desc[0])) return nullptr;
const char* str = string_desc[index];
if (!str) return nullptr;
chr_count = strlen(str);
if (chr_count > 31) chr_count = 31;
for (uint8_t i = 0; i < chr_count; i++)
desc_str_buf[1 + i] = str[i];
}
desc_str_buf[0] = static_cast<uint16_t>((TUSB_DESC_STRING << 8) | (2 * chr_count + 2));
return desc_str_buf;
}
} // extern "C"
+1
Submodule firmware/limen added at 30f3eae111
+33 -51
View File
@@ -1,58 +1,40 @@
#include "pico/stdlib.h"
#include "pico/bootrom.h"
#include "pico/unique_id.h"
#include "tusb.h"
#include "wire.h"
#include "usb_cdc.h"
#include "net.h"
#include "w6300.h"
#include "hardware/gpio.h"
#include "dispatch.h"
#include "handlers.h"
#include "igmp.h"
#include "test_handlers.h"
static usb_cdc usb;
static constexpr uint8_t LED_PIN = 25;
static void led_toggle() {
gpio_xor_mask(1 << LED_PIN);
dispatch_schedule_ms(1000, led_toggle);
}
std::string_view firmware_name = "picomap_test";
uint32_t firmware_build_epoch = BUILD_EPOCH;
static constexpr handler_entry handlers[] = {
{RequestInfo::ext_id, typed_handler<RequestInfo, handle_info>},
{RequestLog::ext_id, typed_handler<RequestLog, handle_log>},
{RequestFlashErase::ext_id, typed_handler<RequestFlashErase, handle_flash_erase>},
{RequestFlashWrite::ext_id, typed_handler<RequestFlashWrite, handle_flash_write>},
{RequestReboot::ext_id, typed_handler<RequestReboot, handle_reboot>},
{RequestFlashStatus::ext_id, typed_handler<RequestFlashStatus, handle_flash_status>},
{RequestListTests::ext_id, typed_handler<RequestListTests, handle_list_tests>},
{RequestTest::ext_id, typed_handler<RequestTest, handle_test>},
};
int main() {
tusb_init();
net_init();
handlers_init();
dispatch_init(PICOMAP_PORT_BE);
igmp::join(PICOMAP_DISCOVERY_GROUP);
handlers_start();
static static_vector<uint8_t, 256> rx_buf;
gpio_init(LED_PIN);
gpio_set_dir(LED_PIN, GPIO_OUT);
dispatch_schedule_ms(1000, led_toggle);
while (true) {
tud_task();
usb.drain();
while (tud_cdc_available()) {
uint8_t byte;
if (tud_cdc_read(&byte, 1) != 1) break;
rx_buf.push_back(byte);
auto msg = try_decode(rx_buf);
if (!msg) {
if (rx_buf.full()) rx_buf.clear();
continue;
}
rx_buf.clear();
switch (msg->type_id) {
case RequestPICOBOOT::ext_id:
usb.send(encode_response(msg->message_id, ResponsePICOBOOT{}));
sleep_ms(100);
reset_usb_boot(0, 1);
break;
case RequestInfo::ext_id: {
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 ninfo = w6300::get_net_info();
resp.mac = ninfo.mac;
usb.send(encode_response(msg->message_id, resp));
break;
}
}
}
__wfi();
}
dispatch_run(handlers);
}
-18
View File
@@ -1,18 +0,0 @@
.program qspi
.side_set 1
write_bits:
out pins, 4 side 0
jmp x-- write_bits side 1
set pins 0 side 0
public write_bits_end:
read_byte_delay:
set pindirs 0 side 0
read_byte:
set x 0 side 1
read_bits:
in pins, 4 side 0
jmp x-- read_bits side 1
in pins, 4 side 0
jmp y-- read_byte side 0
public read_bits_end:
File diff suppressed because it is too large Load Diff
-267
View File
@@ -1,267 +0,0 @@
#pragma once
#include <array>
#include <cstdint>
#include <expected>
#include <optional>
#include <span>
namespace w6300 {
constexpr int SOCK_COUNT = 8;
enum class socket_id : uint8_t {};
enum class port_num : uint16_t {};
enum class sock_error : int16_t {
busy = 0,
sock_num = -1,
sock_opt = -2,
sock_init = -3,
sock_closed = -4,
sock_mode = -5,
sock_flag = -6,
sock_status = -7,
arg = -10,
port_zero = -11,
ip_invalid = -12,
timeout = -13,
data_len = -14,
buffer = -15,
fatal_packlen = -1001,
};
enum class protocol : uint8_t {
tcp = 0x01,
udp = 0x02,
ipraw = 0x03,
macraw = 0x07,
tcp6 = 0x09,
udp6 = 0x0A,
ipraw6 = 0x0B,
tcp_dual = 0x0D,
udp_dual = 0x0E,
};
enum class sock_flag : uint8_t {
none = 0,
multi_enable = 1 << 7,
ether_own = 1 << 7,
broad_block = 1 << 6,
tcp_fpsh = 1 << 6,
tcp_nodelay = 1 << 5,
igmp_ver2 = 1 << 5,
solicit_block = 1 << 5,
ether_multi4b = 1 << 5,
uni_block = 1 << 4,
ether_multi6b = 1 << 4,
force_arp = 1 << 0,
dha_manual = 1 << 1,
io_nonblock = 1 << 3,
};
constexpr sock_flag operator|(sock_flag a, sock_flag b) {
return static_cast<sock_flag>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b));
}
constexpr uint8_t operator&(sock_flag a, sock_flag b) {
return static_cast<uint8_t>(a) & static_cast<uint8_t>(b);
}
enum class pack_info : uint8_t {
none = 0x00,
first = 1 << 1,
remained = 1 << 2,
completed = 1 << 3,
ipv6_lla = (1 << 7) | (1 << 4),
ipv6_multi = (1 << 7) | (1 << 5),
ipv6_allnode = (1 << 7) | (1 << 6),
ipv6 = 1 << 7,
};
constexpr pack_info operator|(pack_info a, pack_info b) {
return static_cast<pack_info>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b));
}
constexpr uint8_t operator&(pack_info a, pack_info b) {
return static_cast<uint8_t>(a) & static_cast<uint8_t>(b);
}
enum class srcv6_prefer : uint8_t {
auto_select = 0x00,
lla = 0x02,
gua = 0x03,
};
enum class tcp_sock_info : uint8_t {
mode = 1 << 2,
op = 1 << 1,
sip = 1 << 0,
};
enum class sock_io_mode : uint8_t {
block = 0,
nonblock = 1,
};
enum intr_kind : uint32_t {
IK_PPPOE_TERMINATED = (1 << 0), IK_DEST_UNREACH = (1 << 1), IK_IP_CONFLICT = (1 << 2),
IK_DEST_UNREACH6 = (1 << 4), IK_WOL = (1 << 7), IK_NET_ALL = 0x97,
IK_SOCK_0 = (1 << 8), IK_SOCK_1 = (1 << 9), IK_SOCK_2 = (1 << 10), IK_SOCK_3 = (1 << 11),
IK_SOCK_4 = (1 << 12), IK_SOCK_5 = (1 << 13), IK_SOCK_6 = (1 << 14), IK_SOCK_7 = (1 << 15),
IK_SOCK_ALL = (0xFF << 8),
IK_SOCKL_TOUT = (1 << 16), IK_SOCKL_ARP4 = (1 << 17), IK_SOCKL_PING4 = (1 << 18),
IK_SOCKL_ARP6 = (1 << 19), IK_SOCKL_PING6 = (1 << 20), IK_SOCKL_NS = (1 << 21),
IK_SOCKL_RS = (1 << 22), IK_SOCKL_RA = (1 << 23), IK_SOCKL_ALL = (0xFF << 16),
IK_INT_ALL = 0x00FFFF97
};
struct phy_conf {
uint8_t by;
uint8_t mode;
uint8_t speed;
uint8_t duplex;
};
enum ipconf_mode : uint8_t {
NETINFO_NONE = 0x00, NETINFO_STATIC_V4 = 0x01, NETINFO_STATIC_V6 = 0x02,
NETINFO_STATIC_ALL = 0x03, NETINFO_SLAAC_V6 = 0x04,
NETINFO_DHCP_V4 = 0x10, NETINFO_DHCP_V6 = 0x20, NETINFO_DHCP_ALL = 0x30
};
enum dhcp_mode : uint8_t { NETINFO_STATIC = 1, NETINFO_DHCP };
struct net_info {
std::array<uint8_t, 6> mac;
std::array<uint8_t, 4> ip;
std::array<uint8_t, 4> sn;
std::array<uint8_t, 4> gw;
std::array<uint8_t, 16> lla;
std::array<uint8_t, 16> gua;
std::array<uint8_t, 16> sn6;
std::array<uint8_t, 16> gw6;
std::array<uint8_t, 4> dns;
std::array<uint8_t, 16> dns6;
ipconf_mode ipmode;
dhcp_mode dhcp;
};
enum netmode_type : uint32_t {
NM_IPB_V4 = (1 << 0), NM_IPB_V6 = (1 << 1), NM_WOL = (1 << 2),
NM_PB6_MULTI = (1 << 4), NM_PB6_ALLNODE = (1 << 5), NM_MR_MASK = 0x37,
NM_PPPoE = (1 << 8), NM_DHA_SELECT = (1 << 15), NM_MR2_MASK = (0x09 << 8),
NM_PB4_ALL = (1 << 16), NM_TRSTB_V4 = (1 << 17), NM_PARP_V4 = (1 << 18),
NM_UNRB_V4 = (1 << 19), NM_NET4_MASK = (0x0F << 16),
NM_PB6_ALL = (1 << 24), NM_TRSTB_V6 = (1 << 25), NM_PARP_V6 = (1 << 26),
NM_UNRB_V6 = (1 << 27), NM_NET6_MASK = (0x0F << 24),
NM_MASK_ALL = 0x0F0F0937
};
struct net_timeout {
uint8_t s_retry_cnt;
uint16_t s_time_100us;
uint8_t sl_retry_cnt;
uint16_t sl_time_100us;
};
struct ip_address {
std::array<uint8_t, 16> ip;
uint8_t len;
};
struct prefix {
uint8_t len;
uint8_t flag;
uint32_t valid_lifetime;
uint32_t preferred_lifetime;
std::array<uint8_t, 16> prefix;
};
struct arp_request {
ip_address destinfo;
std::array<uint8_t, 6> dha;
};
struct ping_request {
uint16_t id;
uint16_t seq;
ip_address destinfo;
};
void init_spi();
void init_critical_section();
void reset();
void init();
bool check();
void init_net(const net_info& info);
void soft_reset();
int8_t init_buffers(std::span<const uint8_t> txsize, std::span<const uint8_t> rxsize);
void clear_interrupt(intr_kind intr);
intr_kind get_interrupt();
void set_interrupt_mask(intr_kind intr);
intr_kind get_interrupt_mask();
int8_t get_phy_link();
int8_t get_phy_power_mode();
void reset_phy();
void set_phy_conf(const phy_conf& conf);
phy_conf get_phy_conf();
phy_conf get_phy_status();
void set_phy_power_mode(uint8_t pmode);
void set_net_info(const net_info& info);
net_info get_net_info();
void set_net_mode(netmode_type mode);
netmode_type get_net_mode();
void set_timeout(const net_timeout& timeout);
net_timeout get_timeout();
int8_t send_arp(arp_request& arp);
int8_t send_ping(const ping_request& ping);
int8_t send_dad(std::span<const uint8_t, 16> ipv6);
int8_t send_slaac(prefix& pfx);
int8_t send_unsolicited();
int8_t get_prefix(prefix& pfx);
std::expected<socket_id, sock_error> open_socket(socket_id sn, protocol proto, port_num port, sock_flag flag);
std::expected<void, sock_error> close(socket_id sn);
std::expected<void, sock_error> listen(socket_id sn);
std::expected<void, sock_error> disconnect(socket_id sn);
std::expected<uint16_t, sock_error> send(socket_id sn, std::span<const uint8_t> buf);
std::expected<uint16_t, sock_error> recv(socket_id sn, std::span<uint8_t> buf);
std::expected<void, sock_error> connect(socket_id sn, const ip_address& addr, port_num port);
std::expected<uint16_t, sock_error> sendto(socket_id sn, std::span<const uint8_t> buf, const ip_address& addr, port_num port);
std::expected<uint16_t, sock_error> recvfrom(socket_id sn, std::span<uint8_t> buf, ip_address& addr, port_num& port);
std::expected<void, sock_error> set_socket_io_mode(socket_id sn, sock_io_mode mode);
sock_io_mode get_socket_io_mode(socket_id sn);
uint16_t get_socket_max_tx(socket_id sn);
uint16_t get_socket_max_rx(socket_id sn);
std::expected<void, sock_error> clear_socket_interrupt(socket_id sn, uint8_t flags);
uint8_t get_socket_interrupt(socket_id sn);
std::expected<void, sock_error> set_socket_interrupt_mask(socket_id sn, uint8_t mask);
uint8_t get_socket_interrupt_mask(socket_id sn);
std::expected<void, sock_error> set_socket_prefer(socket_id sn, srcv6_prefer pref);
srcv6_prefer get_socket_prefer(socket_id sn);
void set_socket_ttl(socket_id sn, uint8_t ttl);
uint8_t get_socket_ttl(socket_id sn);
void set_socket_tos(socket_id sn, uint8_t tos);
uint8_t get_socket_tos(socket_id sn);
void set_socket_mss(socket_id sn, uint16_t mss);
uint16_t get_socket_mss(socket_id sn);
void set_socket_dest_ip(socket_id sn, const ip_address& addr);
ip_address get_socket_dest_ip(socket_id sn);
void set_socket_dest_port(socket_id sn, port_num port);
port_num get_socket_dest_port(socket_id sn);
std::expected<void, sock_error> send_keepalive(socket_id sn);
void set_socket_keepalive_auto(socket_id sn, uint8_t interval);
uint8_t get_socket_keepalive_auto(socket_id sn);
uint16_t get_socket_send_buf(socket_id sn);
uint16_t get_socket_recv_buf(socket_id sn);
uint8_t get_socket_status(socket_id sn);
uint8_t get_socket_ext_status(socket_id sn);
uint8_t get_socket_mode(socket_id sn);
uint16_t get_socket_remain_size(socket_id sn);
pack_info get_socket_pack_info(socket_id sn);
std::optional<uint16_t> peek_socket_msg(socket_id sn, std::span<const uint8_t> submsg);
} // namespace w6300
+1 -6
View File
@@ -2,9 +2,4 @@ module github.com/theater/picomap
go 1.25.0
require go.bug.st/serial v1.6.4
require (
github.com/creack/goselect v0.1.2 // indirect
golang.org/x/sys v0.19.0 // indirect
)
require golang.org/x/sys v0.19.0
-12
View File
@@ -1,14 +1,2 @@
github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=
github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A=
go.bug.st/serial v1.6.4/go.mod h1:nofMJxTeNVny/m6+KaafC6vJGj3miwQZ6vW4BZUGJPI=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+81 -35
View File
@@ -7,7 +7,6 @@ import (
"github.com/theater/picomap/lib/halfsiphash"
"github.com/theater/picomap/lib/msgpack"
"io"
)
var HashKey = [8]byte{}
@@ -15,7 +14,8 @@ var HashKey = [8]byte{}
type transport interface {
Send(data []byte) error
SetReadTimeout(timeout time.Duration)
Reader() io.Reader
Recv() (data []byte, from string, err error)
Broadcast() bool
Close() error
}
@@ -44,51 +44,97 @@ func (c *Client) send(msg any) (uint32, error) {
return id, c.transport.Send(data)
}
func (c *Client) receive(expectedID uint32) (any, error) {
c.transport.SetReadTimeout(c.timeout)
dec := msgpack.NewDecoder(c.transport.Reader())
var env Envelope
if err := dec.Decode(&env); err != nil {
return nil, fmt.Errorf("decode envelope: %w", err)
}
if env.MessageID != expectedID {
return nil, fmt.Errorf("message id mismatch: got %d, want %d", env.MessageID, expectedID)
}
expected := halfsiphash.Sum32(env.Payload, HashKey)
if env.Checksum != expected {
return nil, fmt.Errorf("checksum mismatch: got %08x, want %08x", env.Checksum, expected)
}
var inner any
if err := msgpack.Unmarshal(env.Payload, &inner); err != nil {
return nil, fmt.Errorf("decode inner: %w", err)
}
if devErr, ok := inner.(*DeviceError); ok {
return nil, devErr
}
return inner, nil
type Response[T any] struct {
From string
Value *T
}
func roundTrip[T any](c *Client, req any) (*T, error) {
func roundTrip[T any](c *Client, req any) ([]Response[T], error) {
id, err := c.send(req)
if err != nil {
return nil, err
}
resp, err := c.receive(id)
c.transport.SetReadTimeout(c.timeout)
broadcast := c.transport.Broadcast()
var results []Response[T]
for {
data, from, err := c.transport.Recv()
if err != nil {
break
}
var env Envelope
if err := msgpack.Unmarshal(data, &env); err != nil {
continue
}
if env.MessageID != id {
continue
}
expected := halfsiphash.Sum32(env.Payload, HashKey)
if env.Checksum != expected {
continue
}
var inner any
if err := msgpack.Unmarshal(env.Payload, &inner); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if devErr, ok := inner.(*DeviceError); ok {
return nil, devErr
}
if typed, ok := inner.(*T); ok {
results = append(results, Response[T]{From: from, Value: typed})
if !broadcast {
break
}
}
}
return results, nil
}
func first[T any](results []Response[T], err error) (*T, error) {
if err != nil {
return nil, err
}
typed, ok := resp.(*T)
if !ok {
return nil, fmt.Errorf("unexpected response: %T", resp)
if len(results) == 0 {
return nil, fmt.Errorf("no response")
}
return typed, nil
}
func (c *Client) PICOBOOT() error {
_, err := roundTrip[ResponsePICOBOOT](c, &RequestPICOBOOT{})
return err
return results[0].Value, nil
}
func (c *Client) Info() (*ResponseInfo, error) {
return first(roundTrip[ResponseInfo](c, &RequestInfo{}))
}
func (c *Client) InfoAll() ([]Response[ResponseInfo], error) {
return roundTrip[ResponseInfo](c, &RequestInfo{})
}
func (c *Client) Log() (*ResponseLog, error) {
return first(roundTrip[ResponseLog](c, &RequestLog{}))
}
func (c *Client) FlashErase(addr, length uint32) error {
_, err := first(roundTrip[ResponseFlashErase](c, &RequestFlashErase{Addr: addr, Len: length}))
return err
}
func (c *Client) FlashWrite(addr uint32, data []byte) error {
_, err := first(roundTrip[ResponseFlashWrite](c, &RequestFlashWrite{Addr: addr, Data: data}))
return err
}
func (c *Client) Reboot() error {
_, err := first(roundTrip[ResponseReboot](c, &RequestReboot{}))
return err
}
func (c *Client) FlashStatus() (*ResponseFlashStatus, error) {
return first(roundTrip[ResponseFlashStatus](c, &RequestFlashStatus{}))
}
func (c *Client) ListTests() (*ResponseListTests, error) {
return first(roundTrip[ResponseListTests](c, &RequestListTests{}))
}
func (c *Client) Test(name string) (*ResponseTest, error) {
return first(roundTrip[ResponseTest](c, &RequestTest{Name: name}))
}
-53
View File
@@ -1,53 +0,0 @@
package client
import (
"fmt"
"io"
"time"
"go.bug.st/serial"
"go.bug.st/serial/enumerator"
)
func ListSerial() ([]string, error) {
ports, err := enumerator.GetDetailedPortsList()
if err != nil {
return nil, fmt.Errorf("enumerating ports: %w", err)
}
var result []string
for _, p := range ports {
if p.IsUSB {
result = append(result, p.Name)
}
}
return result, nil
}
type serialTransport struct {
port serial.Port
}
func NewSerial(portName string, timeout time.Duration) (*Client, error) {
port, err := serial.Open(portName, &serial.Mode{BaudRate: 115200})
if err != nil {
return nil, fmt.Errorf("opening %s: %w", portName, err)
}
return &Client{transport: &serialTransport{port: port}, timeout: timeout}, nil
}
func (t *serialTransport) Send(data []byte) error {
_, err := t.port.Write(data)
return err
}
func (t *serialTransport) SetReadTimeout(timeout time.Duration) {
t.port.SetReadTimeout(timeout)
}
func (t *serialTransport) Reader() io.Reader {
return t.port
}
func (t *serialTransport) Close() error {
return t.port.Close()
}
+95 -7
View File
@@ -2,13 +2,89 @@ package client
import "github.com/theater/picomap/lib/msgpack"
type RequestPICOBOOT struct{}
type ResponsePICOBOOT struct{}
type RequestInfo struct{}
type BootReason uint8
const (
BootCold BootReason = 0
BootReboot BootReason = 1
BootWatchdog BootReason = 2
)
func (b BootReason) String() string {
switch b {
case BootCold:
return "cold"
case BootReboot:
return "reboot"
case BootWatchdog:
return "watchdog"
default:
return "unknown"
}
}
type ResponseInfo struct {
BoardID [8]byte
MAC [6]byte
BoardID [8]byte
MAC [6]byte
IP [4]byte
FirmwareName string
Boot BootReason
BuildEpoch uint32
}
type RequestLog struct{}
type LogEntry struct {
TimestampUS uint32
Message string
}
type ResponseLog struct {
Entries []LogEntry
}
type RequestFlashErase struct {
Addr uint32
Len uint32
}
type ResponseFlashErase struct{}
type RequestFlashWrite struct {
Addr uint32
Data []byte
}
type ResponseFlashWrite struct{}
type RequestReboot struct{}
type ResponseReboot struct{}
type RequestFlashStatus struct{}
type SlotInfo struct {
Valid bool
Version uint32
HashOK bool
}
type ResponseFlashStatus struct {
BootPartition int8
SlotA SlotInfo
SlotB SlotInfo
}
type RequestListTests struct{}
type ResponseListTests struct {
Names []string
}
type RequestTest struct {
Name string
}
type ResponseTest struct {
Pass bool
Messages []string
}
type DeviceError struct {
@@ -29,8 +105,20 @@ type Envelope struct {
func init() {
msgpack.RegisterExt(0, (*Envelope)(nil))
msgpack.RegisterExt(1, (*DeviceError)(nil))
msgpack.RegisterExt(2, (*RequestPICOBOOT)(nil))
msgpack.RegisterExt(3, (*ResponsePICOBOOT)(nil))
msgpack.RegisterExt(4, (*RequestInfo)(nil))
msgpack.RegisterExt(5, (*ResponseInfo)(nil))
msgpack.RegisterExt(6, (*RequestLog)(nil))
msgpack.RegisterExt(7, (*ResponseLog)(nil))
msgpack.RegisterExt(8, (*RequestFlashErase)(nil))
msgpack.RegisterExt(9, (*ResponseFlashErase)(nil))
msgpack.RegisterExt(10, (*RequestFlashWrite)(nil))
msgpack.RegisterExt(11, (*ResponseFlashWrite)(nil))
msgpack.RegisterExt(12, (*RequestReboot)(nil))
msgpack.RegisterExt(13, (*ResponseReboot)(nil))
msgpack.RegisterExt(14, (*RequestFlashStatus)(nil))
msgpack.RegisterExt(15, (*ResponseFlashStatus)(nil))
msgpack.RegisterExt(125, (*RequestListTests)(nil))
msgpack.RegisterExt(124, (*ResponseListTests)(nil))
msgpack.RegisterExt(127, (*RequestTest)(nil))
msgpack.RegisterExt(126, (*ResponseTest)(nil))
}
+130
View File
@@ -0,0 +1,130 @@
package client
import (
"fmt"
"net"
"syscall"
"time"
"golang.org/x/sys/unix"
)
const PicomapPort = 28781
type udpTransport struct {
conn *net.UDPConn
addr *net.UDPAddr
broadcast bool
}
func interfaceIPv4Net(name string) (net.IP, *net.IPNet, error) {
ifi, err := net.InterfaceByName(name)
if err != nil {
return nil, nil, fmt.Errorf("interface %s: %w", name, err)
}
addrs, err := ifi.Addrs()
if err != nil {
return nil, nil, fmt.Errorf("interface %s addrs: %w", name, err)
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok {
if ip4 := ipnet.IP.To4(); ip4 != nil {
return ip4, ipnet, nil
}
}
}
return nil, nil, fmt.Errorf("interface %s has no IPv4 address", name)
}
func broadcastAddr(ip net.IP, mask net.IPMask) net.IP {
bcast := make(net.IP, 4)
ip4 := ip.To4()
for i := range 4 {
bcast[i] = ip4[i] | ^mask[i]
}
return bcast
}
func InterfaceBroadcast(name string) (string, error) {
ip, ipnet, err := interfaceIPv4Net(name)
if err != nil {
return "", err
}
return broadcastAddr(ip, ipnet.Mask).String(), nil
}
func enableBroadcast(conn *net.UDPConn) error {
raw, err := conn.SyscallConn()
if err != nil {
return fmt.Errorf("syscall conn: %w", err)
}
var serr error
raw.Control(func(fd uintptr) {
serr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_BROADCAST, 1)
})
return serr
}
func isInterfaceBroadcast(iface string, ip net.IP) bool {
if iface == "" {
return false
}
localIP, ipnet, err := interfaceIPv4Net(iface)
if err != nil {
return false
}
return ip.Equal(broadcastAddr(localIP, ipnet.Mask)) || ip.Equal(net.IPv4bcast)
}
func NewUDP(addr string, iface string, timeout time.Duration) (*Client, error) {
raddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", addr, PicomapPort))
if err != nil {
return nil, fmt.Errorf("resolve %s: %w", addr, err)
}
var laddr *net.UDPAddr
if iface != "" {
ip, _, err := interfaceIPv4Net(iface)
if err != nil {
return nil, err
}
laddr = &net.UDPAddr{IP: ip, Port: 0}
}
conn, err := net.ListenUDP("udp4", laddr)
if err != nil {
return nil, fmt.Errorf("listen: %w", err)
}
if err := enableBroadcast(conn); err != nil {
conn.Close()
return nil, fmt.Errorf("SO_BROADCAST: %w", err)
}
bcast := isInterfaceBroadcast(iface, raddr.IP)
return &Client{transport: &udpTransport{conn: conn, addr: raddr, broadcast: bcast}, timeout: timeout}, nil
}
func (t *udpTransport) Send(data []byte) error {
_, err := t.conn.WriteToUDP(data, t.addr)
return err
}
func (t *udpTransport) SetReadTimeout(timeout time.Duration) {
t.conn.SetReadDeadline(time.Now().Add(timeout))
}
func (t *udpTransport) Recv() ([]byte, string, error) {
buf := make([]byte, 1500)
n, addr, err := t.conn.ReadFromUDP(buf)
if err != nil {
return nil, "", err
}
return buf[:n], addr.IP.String(), nil
}
func (t *udpTransport) Broadcast() bool { return t.broadcast }
func (t *udpTransport) Close() error {
return t.conn.Close()
}
-24
View File
@@ -1,24 +0,0 @@
package picotool
import (
"fmt"
"os/exec"
)
func Load(uf2Path string, serial string) error {
cmd := exec.Command("picotool", "load", uf2Path, "--ser", serial)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("picotool load: %w\n%s", err, out)
}
return nil
}
func Reboot(serial string) error {
cmd := exec.Command("picotool", "reboot", "--ser", serial)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("picotool reboot: %w\n%s", err, out)
}
return nil
}
+71
View File
@@ -0,0 +1,71 @@
package uf2
import (
"encoding/binary"
"fmt"
"os"
"sort"
)
const (
blockSize = 512
magic0 = 0x0A324655
magic1 = 0x9E5D5157
magicEnd = 0x0AB16F30
flagNotMainFlash = 0x00000001
flagFamilyIDPresent = 0x00002000
absoluteFamilyID = 0xe48bff57
)
type Block struct {
Addr uint32
Data []byte
}
func Parse(path string) ([]Block, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
if len(data)%blockSize != 0 {
return nil, fmt.Errorf("file size %d not multiple of %d", len(data), blockSize)
}
var blocks []Block
for i := 0; i < len(data); i += blockSize {
b := data[i : i+blockSize]
m0 := binary.LittleEndian.Uint32(b[0:4])
m1 := binary.LittleEndian.Uint32(b[4:8])
me := binary.LittleEndian.Uint32(b[508:512])
if m0 != magic0 || m1 != magic1 || me != magicEnd {
return nil, fmt.Errorf("block %d: bad magic", i/blockSize)
}
flags := binary.LittleEndian.Uint32(b[8:12])
if flags&flagNotMainFlash != 0 {
continue
}
if flags&flagFamilyIDPresent != 0 {
familyID := binary.LittleEndian.Uint32(b[28:32])
if familyID == absoluteFamilyID {
continue
}
}
addr := binary.LittleEndian.Uint32(b[12:16])
size := binary.LittleEndian.Uint32(b[16:20])
if size > 256 {
return nil, fmt.Errorf("block %d: data size %d > 256", i/blockSize, size)
}
blocks = append(blocks, Block{
Addr: addr,
Data: make([]byte, size),
})
copy(blocks[len(blocks)-1].Data, b[32:32+size])
}
sort.Slice(blocks, func(i, j int) bool {
return blocks[i].Addr < blocks[j].Addr
})
return blocks, nil
}