micropython-skills/network
MicroPython networking — WiFi STA/AP, HTTP requests, MQTT pub/sub, BLE, NTP time sync, WebSocket.
About this skill
This skill provides a comprehensive collection of MicroPython code templates for various networking functionalities on embedded devices like ESP32/ESP8266. It covers fundamental operations such as connecting to a WiFi network (Station mode), creating a WiFi hotspot (Access Point mode), performing HTTP GET and POST requests, and interacting with MQTT brokers for IoT messaging. The skill also includes templates for Bluetooth Low Energy (BLE), Network Time Protocol (NTP) synchronization, and WebSocket communication, making it a versatile toolkit for device connectivity. AI agents can leverage this skill to quickly generate accurate and functional MicroPython code snippets based on user requirements. This reduces the need for agents to "hallucinate" or search extensively for correct syntax and best practices in MicroPython networking. It empowers agents to build robust communication layers for IoT projects, handle data exchange, and ensure devices can interact effectively with the internet and other local devices. Developers, hobbyists, and engineers working with MicroPython-enabled hardware will find this skill invaluable. It streamlines the development process for network-enabled embedded applications, allowing for faster prototyping and deployment of smart devices that require internet access, local network control, or secure time synchronization.
Best use case
The primary use case is to facilitate the rapid development of network-enabled MicroPython applications on embedded systems. Developers and AI agents benefit by having immediate access to pre-tested, secure (with cautions noted), and optimized code for common networking tasks. This ensures devices can reliably connect to the internet, interact with cloud services, establish local communication, or maintain accurate time, significantly accelerating IoT project timelines.
MicroPython networking — WiFi STA/AP, HTTP requests, MQTT pub/sub, BLE, NTP time sync, WebSocket.
Users can expect to receive generated MicroPython code that successfully performs specified networking operations on their device, along with status or result feedback.
Practical example
Example input
Write MicroPython code to connect to a WiFi network named 'MyHomeNet' with password 'secure_password' and print its IP configuration.
Example output
```python
import network, time, json
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect("MyHomeNet", "secure_password")
# ... (connection logic)
print("RESULT:" + json.dumps({"ip": "192.168.1.100", "mask": "255.255.255.0", "gateway": "192.168.1.1", "dns": "8.8.8.8"}))
```When to use this skill
- Developing MicroPython applications requiring WiFi connectivity (Station or Access Point modes).
- Implementing HTTP client, MQTT, BLE, or WebSocket communication on embedded devices.
- Synchronizing MicroPython device time using NTP.
- When an AI agent needs to generate secure and functional network code for MicroPython.
When not to use this skill
- For networking tasks on platforms other than MicroPython (e.g., CircuitPython, standard Python, C++).
- If highly optimized, low-level network driver development is required beyond common application-level patterns.
- When working with network protocols not explicitly covered by the skill (e.g., custom industrial protocols).
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/network/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How micropython-skills/network Compares
| Feature / Agent | micropython-skills/network | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
MicroPython networking — WiFi STA/AP, HTTP requests, MQTT pub/sub, BLE, NTP time sync, WebSocket.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Cursor vs Codex for AI Workflows
Compare Cursor and Codex for AI coding workflows, repository assistance, debugging, refactoring, and reusable developer skills.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
SKILL.md Source
# Network
Code templates for network communication on MicroPython devices.
WiFi and network operations are **Cautious tier** — inform the user before connecting.
WiFi credentials should never be hardcoded in files saved to the device.
Use variables or prompt the user for values.
## WiFi Station Mode (Connect to Router)
```python
import network, time, json
try:
sta = network.WLAN(network.STA_IF)
sta.active(True)
ssid = "YOUR_SSID" # Replace with actual value
password = "YOUR_PASS" # Replace with actual value
sta.connect(ssid, password)
timeout = 15
start = time.time()
while not sta.isconnected():
if time.time() - start > timeout:
print("ERROR:WiFi connection timed out after " + str(timeout) + "s")
raise SystemExit
time.sleep(0.5)
ip, mask, gw, dns = sta.ifconfig()
print("RESULT:" + json.dumps({
"ip": ip, "mask": mask, "gateway": gw, "dns": dns,
}))
except Exception as e:
print("ERROR:" + str(e))
```
## WiFi Access Point Mode
Create a WiFi hotspot on the device:
```python
import network, json
try:
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid="ESP32-AP", password="12345678", authmode=network.AUTH_WPA2_PSK)
ip, mask, gw, dns = ap.ifconfig()
print("RESULT:" + json.dumps({
"mode": "AP",
"ssid": "ESP32-AP",
"ip": ip,
}))
except Exception as e:
print("ERROR:" + str(e))
```
## HTTP Client (urequests)
GET request:
```python
import urequests, json
try:
r = urequests.get("http://httpbin.org/get")
print("RESULT:" + json.dumps({
"status": r.status_code,
"body_preview": r.text[:200],
}))
r.close()
except Exception as e:
print("ERROR:" + str(e))
```
POST with JSON:
```python
import urequests, json
try:
data = {"sensor": "dht22", "temp": 23.5}
r = urequests.post(
"http://example.com/api/data",
json=data,
headers={"Content-Type": "application/json"}
)
print("RESULT:" + json.dumps({"status": r.status_code}))
r.close()
except Exception as e:
print("ERROR:" + str(e))
```
Note: `urequests` is included in most MicroPython firmware builds. For HTTPS, the device needs sufficient memory (ESP32 usually OK, ESP8266 may struggle).
## MQTT Publish / Subscribe
Using the built-in `umqtt.simple` module:
```python
from umqtt.simple import MQTTClient
import json, time
try:
client = MQTTClient(
"esp32_client", # Client ID
"broker.hivemq.com", # Broker address
port=1883,
)
client.connect()
print("LOG:Connected to MQTT broker")
# Publish
topic = "test/esp32"
payload = json.dumps({"temp": 23.5, "hum": 61})
client.publish(topic, payload)
print("RESULT:" + json.dumps({
"action": "publish",
"topic": topic,
"payload": payload,
}))
client.disconnect()
except Exception as e:
print("ERROR:" + str(e))
```
Subscribe with callback:
```python
from umqtt.simple import MQTTClient
import json, time
try:
received = []
def on_message(topic, msg):
received.append({"topic": topic.decode(), "msg": msg.decode()})
client = MQTTClient("esp32_sub", "broker.hivemq.com", port=1883)
client.set_callback(on_message)
client.connect()
client.subscribe(b"test/commands")
print("LOG:Subscribed, waiting for messages...")
# Check for messages with timeout
deadline = time.time() + 10
while time.time() < deadline:
client.check_msg()
time.sleep(0.1)
if received:
break
client.disconnect()
print("RESULT:" + json.dumps({"received": received}))
except Exception as e:
print("ERROR:" + str(e))
```
Note: If `umqtt` is not available, install it: `mpremote mip install umqtt.simple`
## BLE (Bluetooth Low Energy)
ESP32 BLE advertising example:
```python
import bluetooth, json, struct
try:
ble = bluetooth.BLE()
ble.active(True)
name = "ESP32-BLE"
# Encode advertising payload
adv_data = bytearray()
# Flags
adv_data += struct.pack("BBB", 2, 0x01, 0x06)
# Complete name
name_bytes = name.encode()
adv_data += struct.pack("BB", len(name_bytes) + 1, 0x09) + name_bytes
ble.gap_advertise(100000, adv_data) # Advertise every 100ms
print("RESULT:" + json.dumps({
"ble_active": True,
"name": name,
"advertising": True,
}))
except Exception as e:
print("ERROR:" + str(e))
```
BLE scan for nearby devices:
```python
import bluetooth, json, time
try:
ble = bluetooth.BLE()
ble.active(True)
devices = []
def scan_cb(event, data):
if event == 5: # _IRQ_SCAN_RESULT
addr_type, addr, adv_type, rssi, adv_data = data
addr_hex = ":".join("{:02x}".format(b) for b in addr)
devices.append({"addr": addr_hex, "rssi": rssi})
ble.irq(scan_cb)
ble.gap_scan(5000, 30000, 30000) # Scan for 5 seconds
time.sleep(6)
# Deduplicate by address
seen = {}
for d in devices:
if d["addr"] not in seen or d["rssi"] > seen[d["addr"]]["rssi"]:
seen[d["addr"]] = d
print("RESULT:" + json.dumps({"ble_devices": list(seen.values()), "count": len(seen)}))
except Exception as e:
print("ERROR:" + str(e))
```
## NTP Time Sync
Synchronize device clock from the internet:
```python
import ntptime, time, json
try:
ntptime.settime()
t = time.localtime()
print("RESULT:" + json.dumps({
"synced": True,
"utc": "{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}Z".format(*t[:6]),
}))
except Exception as e:
print("ERROR:NTP sync failed: " + str(e))
```
Note: Device must be connected to WiFi first. NTP uses UDP port 123.
## WebSocket (Minimal Server)
Run a simple WebSocket echo server on the device — useful for real-time data streaming to a browser:
```python
import socket, json, hashlib, binascii
try:
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 8080))
s.listen(1)
print("LOG:WebSocket server on port 8080")
print("RESULT:" + json.dumps({"server": "started", "port": 8080}))
# Accept one connection for demo, then close
# For production, use asyncio-based server
s.close()
except Exception as e:
print("ERROR:" + str(e))
```
For full WebSocket support, consider `micropython-async` or `microdot` framework.Related Skills
micropython-skills/sensor
MicroPython sensor reading — DHT11/22, BME280, MPU6050, ADC, ultrasonic HC-SR04, photoresistor, generic I2C sensors.
micropython-skills/algorithm
MicroPython on-device algorithms — PID controller, moving average, Kalman filter, state machine, task scheduler, data logger.
Go Production Engineering
You are a Go production engineering expert. Follow this system for every Go project — from architecture decisions through production deployment. Apply phases sequentially for new projects; use individual phases as needed for existing codebases.
Database Engineering Mastery
> Complete database design, optimization, migration, and operations system. From schema design to production monitoring — covers PostgreSQL, MySQL, SQLite, and general SQL patterns.
afrexai-code-reviewer
Enterprise-grade code review agent. Reviews PRs, diffs, or code files for security vulnerabilities, performance issues, error handling gaps, architecture smells, and test coverage. Works with any language, any repo, no dependencies required.
API Documentation Generator
Generate production-ready API documentation from endpoint descriptions. Outputs OpenAPI 3.0, markdown reference docs, and SDK quickstart guides.
bili-rs
Development skill for bili-rs, a Rust CLI tool for Bilibili (B站). Use when implementing features, fixing bugs, or extending the bilibili-cli-rust codebase. Provides architecture conventions, API endpoints, coding patterns, and project-specific constraints. Triggers on tasks involving adding CLI commands, calling Bilibili APIs, handling authentication, implementing output formatting, or working with the layered cli/commands/client/payloads architecture.
Puppeteer
Automate Chrome and Chromium with Puppeteer for scraping, testing, screenshots, and browser workflows.
pharaoh
Codebase knowledge graph with 23 development workflow skills. Query architecture, dependencies, blast radius, dead code, and test coverage via MCP. Requires GitHub App installation (read-only repo access) and OAuth authentication. Connects to external MCP server at mcp.pharaoh.so.
git-commit-helper
Generate standardized git commit messages following Conventional Commits format. Use this skill when the user asks to commit code, write a commit message, or create a git commit. Enforces team conventions for type prefixes, scope naming, message length, and breaking change documentation.
ask-claude
Delegate a task to Claude Code CLI and immediately report the result back in chat. Supports persistent sessions with full context memory. Safe execution: no data exfiltration, no external calls, file operations confined to workspace. Use when the user asks to run Claude, delegate a coding task, continue a previous Claude session, or any task benefiting from Claude Code's tools (file editing, code analysis, bash, etc.).
bnbchain-mcp
Interact with the BNB Chain Model Context Protocol (MCP) server. Blocks, contracts, tokens, NFTs, wallet, Greenfield, and ERC-8004 agent tools. Use npx @bnb-chain/mcp@latest or read the official skill page.