import network
import socket
import json
import ubinascii
# 获取设备ID(可以根据实际情况获取,比如使用设备的MAC地址)
device_id = ubinascii.hexlify(network.WLAN(network.STA_IF
import network
import socket
import json
import ubinascii
# 获取设备ID(可以根据实际情况获取,比如使用设备的MAC地址)
device_id = ubinascii.hexlify(network.WLAN(network.STA_IF).config('mac')).decode()
# 设置Wi-Fi AP
def create_ap():
wlan = network.WLAN(network.AP_IF)
wlan.active(True)
ssid = 'LHKJ-' + device_id
password = '12345678'
# 设置AP的SSID和密码
wlan.config(essid=ssid, password=password, authmode=network.AUTH_WPA2_PSK)
# 设置静态IP(使用 ifconfig 来配置)
wlan.ifconfig(('192.168.4.1', '255.255.255.0', '192.168.4.1', '8.8.8.8')) # 需要用 ifconfig 设置
print('AP created: SSID =', ssid)
# 获取并打印服务器端IP地址(供客户端知晓)
ip_address = wlan.ifconfig()[0]
print("Server IP address in the Wi-Fi network:", ip_address)
# 解析HTTP请求头,获取请求路径等信息
def parse_request(request):
lines = request.decode().splitlines()
method, path, version = lines[0].split(' ')
headers = {}
for line in lines[1:]:
if line.strip() == "":
break
key, value = line.split(': ', 1)
headers[key.lower()] = value
return method, path, headers
# 解析GET请求的查询参数
def parse_query_params(path):
params = {}
if '?' in path:
# 提取查询部分并解析
query_string = path.split('?', 1)[1]
# 分割查询参数
for param in query_string.split('&'):
key_value = param.split('=', 1)
if len(key_value) == 2:
key, value = key_value
params[key] = value
return params
# 创建HTTP服务器
def create_http_server():
addr = socket.getaddrinfo('0.0.0.0', 8989)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('Listening on', addr)
while True:
cl, addr = s.accept()
print('Client connected from', addr)
request = cl.recv(1024)
print('Request:', request)
# 解析请求
method, path, headers = parse_request(request)
print('Parsed Request:')
print('Method:', method)
print('Path:', path)
print('Headers:', headers)
# 处理GET请求
if method == 'GET':
if path.startswith('/led'):
# 解析查询参数
params = parse_query_params(path)
name = params.get('name', '')
if name:
# 返回带有name的JSON响应
response = {
"code": 200,
"data": {"name": name}
}
else:
# 如果没有提供name参数,返回错误信息
response = {
"code": 400,
"message": "Missing 'name' parameter"
}
response_str = json.dumps(response)
# 发送响应
cl.send('HTTP/1.1 200 OK\r\n')
cl.send('Content-Type: application/json\r\n')
cl.send('Content-Length: %d\r\n' % len(response_str))
cl.send('\r\n')
cl.send(response_str)
else:
# 对其他不识别的路径返回404
response = {
"code": 404,
"message": "Not Found"
}
response_str = json.dumps(response)
cl.send('HTTP/1.1 404 Not Found\r\n')
cl.send('Content-Type: application/json\r\n')
cl.send('Content-Length: %d\r\n' % len(response_str))
cl.send('\r\n')
cl.send(response_str)
# 处理POST请求
elif method == 'POST':
if path == '/led':
# 模拟处理逻辑
data = {"name": "33"}
response = {
"code": 200,
"data": data
}
response_str = json.dumps(response)
# 发送响应
cl.send('HTTP/1.1 200 OK\r\n')
cl.send('Content-Type: application/json\r\n')
cl.send('Content-Length: %d\r\n' % len(response_str))
cl.send('\r\n')
cl.send(response_str)
else:
# 对其他不识别的路径返回404
response = {
"code": 404,
"message": "Not Found"
}
response_str = json.dumps(response)
cl.send('HTTP/1.1 404 Not Found\r\n')
cl.send('Content-Type: application/json\r\n')
cl.send('Content-Length: %d\r\n' % len(response_str))
cl.send('\r\n')
cl.send(response_str)
else:
# 对非POST请求返回405(方法不允许)
response = {
"code": 405,
"message": "Method Not Allowed"
}
response_str = json.dumps(response)
cl.send('HTTP/1.1 405 Method Not Allowed\r\n')
cl.send('Content-Type: application/json\r\n')
cl.send('Content-Length: %d\r\n' % len(response_str))
cl.send('\r\n')
cl.send(response_str)
cl.close()
# 初始化Wi-Fi和HTTP服务器
create_ap()
create_http_server()