### Flash DHCP Example Source: https://github.com/soypat/cyw43439/blob/main/README.md Use this command to flash the DHCP example to the Pico board after setting up Wi-Fi credentials. ```shell tinygo flash -target=pico -stack-size=8kb -scheduler=tasks -monitor ./examples/dhcp ``` -------------------------------- ### Flash Pico W with CYW43439 Signal Analyze Example Source: https://github.com/soypat/cyw43439/blob/main/examples/cyw43439-signal-analyze/README.md Use this command to flash the Pico W with the signal analyze example. Ensure you have TinyGo installed and the correct target and tags specified. ```sh tinygo flash -target=pico -tags=cy43nopio ./examples/cyw43439-signal-analyze ``` -------------------------------- ### Flash DHCP Example with Heap Debugging Source: https://github.com/soypat/cyw43439/blob/main/README.md Flash the DHCP example with heap debugging enabled using the `debugheaplog` build tag. This enables a simpler logger that avoids allocations and logs heap increments. ```shell tinygo flash -target=pico -stack-size=8kb -scheduler=tasks -monitor -tags=debugheaplog ./examples/dhcp ``` -------------------------------- ### Network Stack Integration with DHCP Source: https://context7.com/soypat/cyw43439/llms.txt This example demonstrates setting up a network stack with WiFi connection and obtaining an IP address via DHCP. It requires the cywnet helper package and configures a logger for the device. ```go package main import ( "log/slog" "machine" "net" "net/netip" "time" "github.com/soypat/cyw43439" "github.com/soypat/cyw43439/examples/cywnet" ) const ( ssid = "MyNetwork" password = "MyPassword" ) func main() { time.Sleep(2 * time.Second) println("Starting DHCP example") logger := slog.New(slog.NewTextHandler(machine.Serial, &slog.HandlerOptions{ Level: slog.LevelInfo, })) devcfg := cyw43439.DefaultWifiConfig() devcfg.Logger = logger // Create configured stack with WiFi connection stack, err := cywnet.NewConfiguredPicoWithStack(ssid, password, devcfg, cywnet.StackConfig{ Hostname: "pico-dhcp", }) if err != nil { panic(err.Error()) } // Start network stack processing loop go func() { for { send, recv, _ := stack.RecvAndSend() if send == 0 && recv == 0 { time.Sleep(5 * time.Millisecond) } } }() // Perform DHCP to get IP address requestedIP := netip.AddrFrom4([4]byte{192, 168, 1, 99}) dhcpResults, err := stack.SetupWithDHCP(cywnet.DHCPConfig{ RequestedAddr: requestedIP, }) if err != nil { panic("DHCP failed: " + err.Error()) } lstack := stack.LnetoStack() gatewayHW := lstack.Gateway6() logger.Info("DHCP complete", slog.String("ip", dhcpResults.AssignedAddr.String()), slog.String("router", dhcpResults.Router.String()), slog.String("gateway", net.HardwareAddr(gatewayHW[:]).String()), ) // Network is now ready for TCP/UDP operations select {} } ``` -------------------------------- ### Flash Blinky Example Source: https://github.com/soypat/cyw43439/blob/main/README.md Use this command to flash the blinky example to the Pico board. ```shell tinygo flash -target=pico -stack-size=8kb -scheduler=tasks -monitor ./examples/blinky ``` -------------------------------- ### Control Onboard LED with CYW43439 GPIO Source: https://context7.com/soypat/cyw43439/llms.txt Shows how to control the Pico W's onboard LED (GPIO 0) using the CYW43439 driver. This example does not require WiFi or Bluetooth setup. ```go package main import ( "time" "github.com/soypat/cyw43439" ) func main() { dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultWifiConfig() err := dev.Init(cfg) if err != nil { panic(err.Error()) } // Blink the onboard LED (GPIO 0) for { // Turn LED on err = dev.GPIOSet(0, true) if err != nil { println("GPIO error:", err.Error()) } time.Sleep(500 * time.Millisecond) // Turn LED off err = dev.GPIOSet(0, false) if err != nil { println("GPIO error:", err.Error()) } time.Sleep(500 * time.Millisecond) } } ``` -------------------------------- ### Run Local HTTP Server Source: https://github.com/soypat/cyw43439/blob/main/examples/http-client/README.md Execute this command to start a local HTTP server. Ensure you are in the root directory of the project. ```shell go run ./examples/server ``` -------------------------------- ### TCP Client Connection Source: https://context7.com/soypat/cyw43439/llms.txt This example demonstrates establishing a TCP client connection to a remote server. It requires initializing the network stack and configuring TCP connection parameters like buffer sizes and packet queue. ```go package main import ( "errors" "io" "net" "net/netip" "time" "github.com/soypat/cyw43439" "github.com/soypat/cyw43439/examples/cywnet" "github.com/soypat/lneto/tcp" ) func main() { // ... (Initialize stack as shown in DHCP example) ... stack, _ := cywnet.NewConfiguredPicoWithStack("SSID", "pass", cyw43439.DefaultWifiConfig(), cywnet.StackConfig{ Hostname: "tcp-client", MaxActiveTCPPorts: 1, }) go loopStack(stack) stack.SetupWithDHCP(cywnet.DHCPConfig{}) // Configure TCP connection var conn tcp.Conn conn.Configure(tcp.ConnConfig{ RxBuf: make([]byte, 512), TxBuf: make([]byte, 512), TxPacketQueueSize: 3, }) // Dial remote server lstack := stack.LnetoStack() rstack := lstack.StackRetrying(cywnet.DefaultStackBackoff) targetAddr := netip.AddrPortFrom( netip.AddrFrom4([4]byte{192, 168, 1, 100}), 8080, ) localPort := uint16(lstack.Prand32()>>17) + 1 err := rstack.DoDialTCP(&conn, localPort, targetAddr, 6*time.Second, 2) if err != nil { panic("Dial failed: " + err.Error()) } defer conn.Close() // Send data conn.Write([]byte("Hello, Server!")) // Receive response buf := make([]byte, 256) for { n, err := conn.Read(buf) if errors.Is(err, net.ErrClosed) || errors.Is(err, io.EOF) { break } if n > 0 { println("Received:", string(buf[:n])) } time.Sleep(5 * time.Millisecond) } } func loopStack(stack *cywnet.Stack) { for { send, recv, _ := stack.RecvAndSend() if send == 0 && recv == 0 { time.Sleep(5 * time.Millisecond) } } } ``` -------------------------------- ### Start a WiFi Access Point Source: https://context7.com/soypat/cyw43439/llms.txt Create a WiFi access point (hotspot) with optional password protection. Specify the SSID, password (8-63 characters), and channel for the access point. ```go package main import "github.com/soypat/cyw43439" func main() { dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultWifiConfig() err := dev.Init(cfg) if err != nil { panic(err.Error()) } // Start WPA2 protected access point on channel 6 ssid := "PicoW-AP" password := "securepassword123" // 8-63 characters channel := uint8(6) err = dev.StartAP(ssid, password, channel) if err != nil { panic("StartAP failed: " + err.Error()) } // Start open (unprotected) access point err = dev.StartAP("PicoW-Open", "", 11) if err != nil { panic(err.Error()) } println("Access Point started") } ``` -------------------------------- ### Get Hardware MAC Address Source: https://context7.com/soypat/cyw43439/llms.txt Retrieve the device's 6-byte MAC address for network identification. The address can be converted to a `net.HardwareAddr` for standard formatting. ```go package main import ( "net" "github.com/soypat/cyw43439" ) func main() { dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultWifiConfig() err := dev.Init(cfg) if err != nil { panic(err.Error()) } // Get MAC address as [6]byte mac, err := dev.HardwareAddr6() if err != nil { panic("Failed to get MAC: " + err.Error()) } // Convert to net.HardwareAddr for formatting hwAddr := net.HardwareAddr(mac[:]) println("MAC Address:", hwAddr.String()) // Output: MAC Address: aa:bb:cc:dd:ee:ff } ``` -------------------------------- ### Run HTTP Server on Pico W Source: https://context7.com/soypat/cyw43439/llms.txt Initializes the network stack, sets up a TCP listener on port 80, and handles incoming HTTP requests to serve a web page. Requires 'index.html' to be embedded. ```go package main import ( _ "embed" "net/netip" "strconv" "time" "github.com/soypat/cyw43439" "github.com/soypat/cyw43439/examples/cywnet" "github.com/soypat/lneto/http/httpraw" "github.com/soypat/lneto/tcp" "github.com/soypat/lneto/x/xnet" ) //go:embed index.html var webPage []byte func main() { // Initialize stack stack, _ := cywnet.NewConfiguredPicoWithStack("SSID", "pass", cyw43439.DefaultWifiConfig(), cywnet.StackConfig{ Hostname: "http-pico", MaxActiveTCPPorts: 1, }) go loopStack(stack) dhcpResults, _ := stack.SetupWithDHCP(cywnet.DHCPConfig{}) // Create TCP connection pool tcpPool, _ := xnet.NewTCPPool(xnet.TCPPoolConfig{ PoolSize: 3, QueueSize: 3, TxBufSize: len(webPage) + 128, RxBufSize: 256, EstablishedTimeout: 5 * time.Second, ClosingTimeout: 5 * time.Second, NewUserData: func() any { var hdr httpraw.Header hdr.Reset(make([]byte, 512)) return &hdr }, }) // Create and register listener lstack := stack.LnetoStack() var listener tcp.Listener listener.Reset(80, tcpPool) lstack.RegisterListener(&listener) listenAddr := netip.AddrPortFrom(dhcpResults.AssignedAddr, 80) println("Listening on http://" + listenAddr.String()) // Accept connections for { if listener.NumberOfReadyToAccept() == 0 { time.Sleep(5 * time.Millisecond) tcpPool.CheckTimeouts() continue } conn, userData, _ := listener.TryAccept() go handleHTTP(conn, userData.(*httpraw.Header)) } } func handleHTTP(conn *tcp.Conn, hdr *httpraw.Header) { defer conn.Close() // Read request buf := make([]byte, 256) for { n, _ := conn.Read(buf) if n > 0 { hdr.ReadFromBytes(buf[:n]) needMore, _ := hdr.TryParse(false) if !needMore { break } } } // Send response hdr.Reset(nil) hdr.SetProtocol("HTTP/1.1") hdr.SetStatus("200", "OK") hdr.Set("Content-Type", "text/html") hdr.Set("Content-Length", strconv.Itoa(len(webPage))) responseHeader, _ := hdr.AppendResponse(buf[:0]) conn.Write(responseHeader) conn.Write(webPage) } func loopStack(stack *cywnet.Stack) { for { send, recv, _ := stack.RecvAndSend() if send == 0 && recv == 0 { time.Sleep(5 * time.Millisecond) } } } ``` -------------------------------- ### Initialize CYW43439 Device for Pico W Source: https://context7.com/soypat/cyw43439/llms.txt Create and initialize a CYW43439 device instance for a Pico W board. Ensure firmware is loaded during initialization. Configure logging for debugging. ```go package main import ( "log/slog" "machine" "time" "github.com/soypat/cyw43439" ) func main() { time.Sleep(2 * time.Second) // Allow USB connection time // Create device instance for Pico W dev := cyw43439.NewPicoWDevice() // Configure with WiFi firmware cfg := cyw43439.DefaultWifiConfig() cfg.Logger = slog.New(slog.NewTextHandler(machine.Serial, &slog.HandlerOptions{ Level: slog.LevelInfo, })) // Initialize the device (loads firmware) err := dev.Init(cfg) if err != nil { panic("Init failed: " + err.Error()) } println("CYW43439 initialized successfully") } ``` -------------------------------- ### Simplified LED Blink using pico-blink Package Source: https://context7.com/soypat/cyw43439/llms.txt A simplified approach to blinking the onboard LED using the `pico-blink` convenience package. This method automatically initializes the device. ```go package main import ( "time" blink "github.com/soypat/cyw43439/examples/pico-blink" ) func main() { led := blink.LED led.Configure() // Initializes device automatically for { led.High() time.Sleep(time.Second) led.Low() time.Sleep(time.Second) } } ``` -------------------------------- ### Flash Pico W with HTTP Client Source: https://github.com/soypat/cyw43439/blob/main/examples/http-client/README.md Flash the Pico W board with the HTTP client program and monitor its output. Adjust stack size if necessary. ```shell tinygo flash -target=pico -stack-size=8kb -monitor ./examples/http-client/ ``` -------------------------------- ### Run download test Source: https://github.com/soypat/cyw43439/blob/main/examples/http-bench/index-bench.html Initiates a download test by fetching data from the '/download' endpoint. Updates UI with progress and results. Requires 'setBusy', 'setResult', 'log', 'formatBytes', and 'formatSpeed' functions. ```javascript function runDownload(size) { if (busy) return; setBusy(true); setResult('Downloading (' + size + ')...'); log('--- Download ' + size + ' ---'); var start = performance.now(); fetch('/download?size=' + size).then(function(r) { return r.arrayBuffer(); }).then(function(buf) { var ms = performance.now() - start; log('Received ' + formatBytes(buf.byteLength) + ' in ' + ms.toFixed(0) + ' ms @ '+formatSpeed(buf.byteLength, ms)); setResult('Download: ' + formatSpeed(buf.byteLength, ms)); setBusy(false); }).catch(function(e) { log('Error: ' + e); setResult('Download failed'); setBusy(false); }); } ``` -------------------------------- ### Configure CYW43439 for WiFi, Bluetooth, or Combined Use Source: https://context7.com/soypat/cyw43439/llms.txt Utilize preset configurations for WiFi-only, Bluetooth-only, or combined WiFi+Bluetooth operation. Initialize the device with the chosen configuration. ```go package main import "github.com/soypat/cyw43439" func main() { dev := cyw43439.NewPicoWDevice() // WiFi-only configuration (most common) wifiCfg := cyw43439.DefaultWifiConfig() // Bluetooth-only configuration btCfg := cyw43439.DefaultBluetoothConfig() // Combined WiFi + Bluetooth configuration wifiBtCfg := cyw43439.DefaultWifiBluetoothConfig() // Initialize with chosen configuration err := dev.Init(wifiCfg) if err != nil { panic(err.Error()) } } ``` -------------------------------- ### Send and Receive Ethernet Frames with CYW43439 Source: https://context7.com/soypat/cyw43439/llms.txt Demonstrates low-level Ethernet frame transmission and reception. Requires setting up a receive handler and polling for incoming packets. ```go package main import ( "time" "github.com/soypat/cyw43439" ) func main() { dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultWifiConfig() err := dev.Init(cfg) if err != nil { panic(err.Error()) } // Set up receive handler for incoming Ethernet frames dev.RecvEthHandle(func(pkt []byte) error { println("Received packet, length:", len(pkt)) // Process Ethernet frame (14-byte header + payload) if len(pkt) >= 14 { // pkt[0:6] - Destination MAC // pkt[6:12] - Source MAC // pkt[12:14] - EtherType } return nil }) // Poll for incoming packets for { gotPacket, err := dev.PollOne() if err != nil { println("Poll error:", err.Error()) } if gotPacket { println("Processed incoming packet") } time.Sleep(5 * time.Millisecond) } } func sendFrame(dev *cyw43439.Device) { // Construct Ethernet frame (example ARP request) frame := make([]byte, 42) // ... populate frame ... err := dev.SendEth(frame) if err != nil { println("Send failed:", err.Error()) } } ``` -------------------------------- ### Direct HCI Read/Write Methods Source: https://context7.com/soypat/cyw43439/llms.txt Use these methods for direct HCI communication without the io.ReadWriter wrapper. Ensure the buffer is 4-byte aligned when reading. ```go package main import ( "time" "github.com/soypat/cyw43439" ) func main() { dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultBluetoothConfig() err := dev.Init(cfg) if err != nil { panic(err.Error()) } // Write HCI packet directly hciPacket := []byte{0x01, 0x03, 0x0c, 0x00} n, err := dev.WriteHCI(hciPacket) if err != nil { panic("WriteHCI: " + err.Error()) } println("Wrote", n, "bytes") // Check buffered data time.Sleep(100 * time.Millisecond) buffered := dev.BufferedHCI() println("Buffered HCI bytes:", buffered) // Read response (buffer must be 4-byte aligned) if buffered > 0 { alignedLen := (buffered + 3) &^ 3 // Round up to 4 buf := make([]byte, alignedLen) n, err := dev.ReadHCI(buf) if err != nil { panic("ReadHCI: " + err.Error()) } println("Read", n, "bytes from HCI") } } ``` -------------------------------- ### Join a WiFi Network with Authentication Source: https://context7.com/soypat/cyw43439/llms.txt Connect to a WiFi network using various authentication methods including Open, WPA, WPA2, and WPA3. The authentication method can be auto-detected from the passphrase or explicitly set. ```go package main import ( "github.com/soypat/cyw43439" ) func main() { dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultWifiConfig() err := dev.Init(cfg) if err != nil { panic(err.Error()) } // Join WPA2 network (auto-detected from passphrase) err = dev.Join("MyNetworkSSID", cyw43439.JoinOptions{ Passphrase: "MySecretPassword", }) if err != nil { panic("Join failed: " + err.Error()) } // For explicit authentication method: err = dev.Join("SecureNetwork", cyw43439.JoinOptions{ Auth: cyw43439.JoinAuthWPA3, Passphrase: "WPA3Password", }) // For open networks: err = dev.Join("OpenNetwork", cyw43439.JoinOptions{ Auth: cyw43439.JoinAuthOpen, }) // Check connection status if dev.IsLinkUp() { println("Successfully connected to WiFi") } } ``` -------------------------------- ### Run upload test Source: https://github.com/soypat/cyw43439/blob/main/examples/http-bench/index-bench.html Initiates an upload test by sending data to the '/upload' endpoint. Updates UI with progress and results. Requires 'setBusy', 'setResult', 'log', 'formatBytes', and 'formatSpeed' functions. ```javascript function runUpload(size) { if (busy) return; setBusy(true); setResult('Uploading (' + formatBytes(size) + ')...'); log('--- Upload ' + formatBytes(size) + ' ---'); var payload = new Uint8Array(size); for (var i = 0; i < size; i++) payload[i] = i & 0xff; var start = performance.now(); fetch('/upload', { method: 'POST', headers: {'Content-Type': 'application/octet-stream'}, body: payload }).then(function(r) { return r.text(); }).then(function(text) { var ms = performance.now() - start; log('Sent ' + formatBytes(size) + ' in ' + ms.toFixed(0) + ' ms @ ' +formatSpeed(size, ms)); log('Server: ' + text); setResult('Upload: ' + formatSpeed(size, ms)); setBusy(false); }).catch(function(e) { log('Error: ' + e); setResult('Upload failed'); setBusy(false); }); } ``` -------------------------------- ### Bluetooth HCI Interface Operations with CYW43439 Source: https://context7.com/soypat/cyw43439/llms.txt Demonstrates accessing the Bluetooth HCI interface for sending commands and receiving responses. Configures a logger for debug output. ```go package main import ( "log/slog" "machine" "time" "github.com/soypat/cyw43439" ) func main() { time.Sleep(time.Second) dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultBluetoothConfig() cfg.Logger = slog.New(slog.NewTextHandler(machine.USBCDC, &slog.HandlerOptions{ Level: slog.LevelDebug, })) err := dev.Init(cfg) if err != nil { panic("Init failed: " + err.Error()) } // Get io.ReadWriter interface for HCI hci, err := dev.HCIReadWriter() if err != nil { panic("HCI not available: " + err.Error()) } // Send HCI command hciCmd := []byte{0x01, 0x03, 0x0c, 0x00} // HCI Reset command n, err := hci.Write(hciCmd) if err != nil { panic("WriteHCI failed: " + err.Error()) } println("Wrote", n, "bytes to HCI") // Read HCI response buf := make([]byte, 256) for { time.Sleep(100 * time.Millisecond) // Check if data is available if hci.Buffered() == 0 { continue } n, err := hci.Read(buf) if err != nil { println("ReadHCI error:", err.Error()) continue } println("Received", n, "bytes from HCI") break } } ``` -------------------------------- ### Enable Multicast Reception Source: https://context7.com/soypat/cyw43439/llms.txt Configures the CYW43439 chip to receive multicast frames, essential for protocols like mDNS. Requires joining a WiFi network first. ```go package main import "github.com/soypat/cyw43439" func main() { dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultWifiConfig() err := dev.Init(cfg) if err != nil { panic(err.Error()) } // Join WiFi network first err = dev.Join("SSID", cyw43439.JoinOptions{Passphrase: "password"}) if err != nil { panic(err.Error()) } // Register multicast MAC addresses with the WiFi chip // This enables reception of multicast frames (e.g., mDNS) multicastMACs := [][6]byte{ {0x01, 0x00, 0x5e, 0x00, 0x00, 0xfb}, // IPv4 mDNS } err = dev.SetMulticastList(multicastMACs) if err != nil { panic("SetMulticastList failed: " + err.Error()) } println("Multicast reception enabled") } ``` -------------------------------- ### HTTP Client Output Log Source: https://github.com/soypat/cyw43439/blob/main/examples/http-client/README.md This log shows the typical output when the HTTP client successfully connects to a Wi-Fi network, obtains an IP address via DHCP, establishes a TCP connection, sends an HTTP request, and receives a response. ```log time=1970-01-01T00:00:01.593Z level=INFO msg=cyw43439:Init duration=1.583062s time=1970-01-01T00:00:01.594Z level=INFO msg="joining WPA secure network" ssid="WHITTINGSLOW 2.4" passlen=10 time=1970-01-01T00:00:05.039Z level=INFO msg="wifi join success!" mac=28:cd:c1:05:4d:bb time=1970-01-01T00:00:05.041Z level=INFO msg="DHCP ongoing..." time=1970-01-01T00:00:05.042Z level=INFO msg=DHCP:tx msg=Discover time=1970-01-01T00:00:05.093Z level=INFO msg=DHCP:rx msg=Offer time=1970-01-01T00:00:05.094Z level=INFO msg=DHCP:tx msg=Request time=1970-01-01T00:00:05.144Z level=INFO msg=DHCP:rx msg=Ack time=1970-01-01T00:00:05.542Z level=INFO msg="DHCP complete" cidrbits=24 ourIP=192.168.0.68 dns=192.168.0.1 broadcast=192.168.0.255 gateway="invalid IP" router=192.168.0.1 dhcp=192.168.0.1 hostname=tinygo-http-client lease=1h0m0s renewal=30m0s rebinding=52m30s time=1970-01-01T00:00:05.674Z level=INFO msg=tcp:ready clientaddr=192.168.0.68:53691 serveraddr=192.168.0.44:8080 1970/01/01 00:00:10 INFO dialing serveraddr=192.168.0.44:8080 time=1970-01-01T00:00:10.754Z level=INFO msg=TCP:rx-statechange port=53691 old=SynSent new=Established rxflags=[SYN,ACK] got HTTP response! HTTP/1.1 200 OK Date: Mon, 18 Mar 2024 00:00:26 GMT Content-Length: 65 Content-Type: text/plain; charset=utf-8 Dear 192.168.0.68:53691, Greetings from qtpi @ 192.168.0.44:8080 1970/01/01 00:00:11 ERROR tcpconn:closing err=done 1970/01/01 00:00:11 INFO tcpconn:waiting state=FinWait1 time=1970-01-01T00:00:11.315Z level=INFO msg=TCP:tx-statechange port=53691 old=Established new=FinWait1 txflags=[FIN,ACK] time=1970-01-01T00:00:11.366Z level=INFO msg=TCP:rx-statechange port=53691 old=FinWait1 new=TimeWait rxflags=[FIN,ACK] ``` -------------------------------- ### Define Mock SPI Pins for Logic Analyzer Source: https://github.com/soypat/cyw43439/blob/main/examples/cyw43439-signal-analyze/README.md Declare mock pins for SPI data, clock, and chip select. Attach your logic analyzer to these GPIO pins for signal analysis. These pins should not be shared with the original implementation. ```go // Mock pins can be any not shared by original implementation. // Attach your logic analyzer to these. MOCK_DAT = machine.GPIO4 MOCK_CLK = machine.GPIO5 MOCK_CS = machine.GPIO6 ``` -------------------------------- ### Reset CYW43439 Device Source: https://context7.com/soypat/cyw43439/llms.txt Performs a power cycle on the CYW43439 chip to return it to its initial state. Re-initialization is required after a reset. ```go package main import ( "time" "github.com/soypat/cyw43439" ) func main() { dev := cyw43439.NewPicoWDevice() cfg := cyw43439.DefaultWifiConfig() err := dev.Init(cfg) if err != nil { panic(err.Error()) } // ... use device ... // Reset the device (power cycle) dev.Reset() // Must re-initialize after reset time.Sleep(100 * time.Millisecond) err = dev.Init(cfg) if err != nil { panic("Re-init failed: " + err.Error()) } } ``` -------------------------------- ### Format bytes to human-readable string Source: https://github.com/soypat/cyw43439/blob/main/examples/http-bench/index-bench.html Converts a byte count into a string with appropriate units (B, KB, MB). ```javascript function formatBytes(b) { if (b >= 1024*1024) return (b/(1024*1024)).toFixed(1) + ' MB'; if (b >= 1024) return (b/1024).toFixed(1) + ' KB'; return b + ' B'; } ``` -------------------------------- ### Toggle LED event listener Source: https://github.com/soypat/cyw43439/blob/main/examples/http-bench/index-bench.html Attaches a click event listener to the element with ID 'toggleButton' to send a request to the '/toggle-led' endpoint. ```javascript document.getElementById('toggleButton').addEventListener('click', function() { fetch('/toggle-led'); }); ``` -------------------------------- ### Format speed in bits per second Source: https://github.com/soypat/cyw43439/blob/main/examples/http-bench/index-bench.html Converts a speed in bits per second to a human-readable string with units (bps, kbps, Mbps). ```javascript function formatSpeed(bytes, ms) { var bps = (bytes * 8) / (ms / 1000); if (bps >= 1e6) return (bps / 1e6).toFixed(2) + ' Mbps'; if (bps >= 1e3) return (bps / 1e3).toFixed(1) + ' kbps'; return bps.toFixed(0) + ' bps'; } ``` -------------------------------- ### Log messages to the UI Source: https://github.com/soypat/cyw43439/blob/main/examples/http-bench/index-bench.html Appends a message to the log element and scrolls to the bottom. Ensure the 'log' element exists in the HTML. ```javascript function log(msg) { var el = document.getElementById('log'); el.innerHTML += msg + '
'; el.scrollTop = el.scrollHeight; } ``` -------------------------------- ### Add Click Requester JavaScript Function Source: https://github.com/soypat/cyw43439/blob/main/examples/http-server/index.html Attaches a click event listener to an HTML element that makes an XMLHttpRequest to a specified URI. Ensure the element with the given ID exists and the request URI is valid. ```javascript function addClickRequester(elementId, requestUri) { document.getElementById(elementId).addEventListener('click', function() { var xhr = new XMLHttpRequest(); xhr.open('GET', requestUri, true); xhr.onload = function() { if (xhr.status === 200) console.log('Request successful!'); }; xhr.send(); }); } addClickRequester('toggleButton', '/toggle-led'); ``` -------------------------------- ### Set the result message Source: https://github.com/soypat/cyw43439/blob/main/examples/http-bench/index-bench.html Updates the text content of the element with ID 'result'. ```javascript function setResult(msg) { document.getElementById('result').innerText = msg; } ``` -------------------------------- ### Control button enabled/disabled state Source: https://github.com/soypat/cyw43439/blob/main/examples/http-bench/index-bench.html Sets a global busy flag and enables/disables all buttons on the page. Use this to prevent actions while an operation is in progress. ```javascript function setBusy(b) { busy = b; var btns = document.querySelectorAll('button'); for (var i = 0; i < btns.length; i++) btns[i].disabled = b; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.