Esp32基础(①②大模型控制)

控制灯泡

micropython

python 复制代码
from microdot import Microdot
import network, time, ujson
from machine import Pin

# 灯泡映射
lamp_pins = {
    "1": Pin(15, Pin.OUT),
    "2": Pin(2, Pin.OUT),
    "3": Pin(0, Pin.OUT),
    "4": Pin(4, Pin.OUT),
    "5": Pin(16, Pin.OUT),
    "6": Pin(17, Pin.OUT),
    "7": Pin(5, Pin.OUT),
    "8": Pin(18, Pin.OUT),
}
for p in lamp_pins.values():
    p.value(0)

# WiFi 配置
WIFI_SSID = "Xiaomi_313F"
WIFI_PASSWORD = "zzzzxxxx"

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print(f"正在连接 {WIFI_SSID}...")
        wlan.connect(WIFI_SSID, WIFI_PASSWORD)
        timeout = 10
        while not wlan.isconnected() and timeout > 0:
            time.sleep(1)
            timeout -= 1
    if wlan.isconnected():
        ip_info = wlan.ifconfig()
        print("WiFi 已连接,IP 信息:", ip_info)
        # ip_info[0] 就是分配到的局域网 IP
        print("设备局域网 IP 地址:", ip_info[0])
        return True
    else:
        print("WiFi 连接失败")
        return False

# Microdot
app = Microdot()

@app.route('/control', methods=['POST'])
def control(request):
    try:
        data = request.json
        for act in data:  # data 是 JSON 数组
            lamp = act["lamp"]
            state = act["state"]
            if lamp in lamp_pins:
                lamp_pins[lamp].value(1 if state else 0)
        return {"ok": True}
    except Exception as e:
        return {"ok": False, "error": str(e)}, 500

if __name__ == "__main__":
    if connect_wifi():
        print("启动 Web API 服务器...")
        app.run(host="0.0.0.0", port=80)

flask python

python 复制代码
from flask import Flask, request, jsonify
import requests
import json

app = Flask(__name__)

# DeepSeek API 配置
API_URL = "https://api.deepseek.com/chat/completions"
API_KEY = "sk-c6bb5e9814784f378xxx"
MODEL = "deepseek-chat"   

# ESP32 配置(替换成你实际的 ESP32 局域网 IP)
ESP32_URL = "http://192.168.10.126/control"

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    user_text = data.get("chat", "")

    # 提示词:告诉AI灯泡和GPIO映射关系
    system_prompt = (
        "你是ESP32灯光控制助手。"
        "灯泡编号与GPIO对应关系如下:"
        "1→15, 2→2, 3→0, 4→4, 5→16, 6→17, 7→5, 8→18。"
        "用户会说类似 '1 2 3灯亮 其他灯泡灭掉'。"
        "请输出严格的JSON数组,例如:"
        "[{\"lamp\":\"1\",\"state\":1},{\"lamp\":\"2\",\"state\":1},{\"lamp\":\"3\",\"state\":1},{\"lamp\":\"4\",\"state\":0},...]"
    )

    payload = {
        "model": MODEL,
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_text}
        ],
        "temperature": 0.2,
        "max_tokens": 200
    }
    headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

    # 调用 DeepSeek API
    r = requests.post(API_URL, headers=headers, json=payload)
    resp = r.json()
    ai_result = resp["choices"][0]["message"]["content"]

    # 尝试解析 JSON
    try:
        actions = json.loads(ai_result)
    except Exception as e:
        return jsonify({"ok": False, "error": f"AI返回不是合法JSON: {ai_result}"}), 500

    # 转发给 ESP32 的 /control
    try:
        esp32_resp = requests.post(ESP32_URL, json=actions, timeout=5)
        return jsonify({
            "ok": True,
            "ai_result": actions,
            "esp32_response": esp32_resp.json()
        })
    except Exception as e:
        return jsonify({"ok": False, "error": f"ESP32请求失败: {str(e)}", "ai_result": actions}), 500


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

改进流水灯

micropython

python 复制代码
from microdot import Microdot
import network, time, ujson
from machine import Pin

# 灯泡映射
lamp_pins = {
    "1": Pin(15, Pin.OUT),
    "2": Pin(2, Pin.OUT),
    "3": Pin(0, Pin.OUT),
    "4": Pin(4, Pin.OUT),
    "5": Pin(16, Pin.OUT),
    "6": Pin(17, Pin.OUT),
    "7": Pin(5, Pin.OUT),
    "8": Pin(18, Pin.OUT),
}
for p in lamp_pins.values():
    p.value(0)

# WiFi 配置
WIFI_SSID = "Xiaomi_313F"
WIFI_PASSWORD = "zzzzxxxx"

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print(f"正在连接 {WIFI_SSID}...")
        wlan.connect(WIFI_SSID, WIFI_PASSWORD)
        timeout = 10
        while not wlan.isconnected() and timeout > 0:
            time.sleep(1)
            timeout -= 1
    if wlan.isconnected():
        ip_info = wlan.ifconfig()
        print("WiFi 已连接,IP 信息:", ip_info)
        # ip_info[0] 就是分配到的局域网 IP
        print("设备局域网 IP 地址:", ip_info[0])
        return True
    else:
        print("WiFi 连接失败")
        return False

# Microdot
app = Microdot()

@app.route('/control', methods=['POST'])
def control(request):
    try:
        data = request.json  # JSON数组
        for act in data:
            lamp = act.get("lamp")
            state = act.get("state", 0)
            delay = act.get("delay", 0)
            if lamp in lamp_pins:
                lamp_pins[lamp].value(1 if state else 0)
            if delay > 0:
                time.sleep_ms(delay)
        return {"ok": True}
    except Exception as e:
        return {"ok": False, "error": str(e)}, 500


if __name__ == "__main__":
    if connect_wifi():
        print("启动 Web API 服务器...")
        app.run(host="0.0.0.0", port=80)

flask python

python 复制代码
from flask import Flask, request, jsonify
import requests
import json

app = Flask(__name__)

API_URL = "https://api.deepseek.com/chat/completions"
API_KEY = "sk-c6bb5e9814784f378ddabxxxx"
MODEL = "deepseek-chat"

ESP32_URL = "http://192.168.10.126/control"

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    user_text = data.get("chat", "")

    system_prompt = (
        "你是ESP32灯光控制助手。"
        "灯泡编号与GPIO对应关系如下:"
        "1→15, 2→2, 3→0, 4→4, 5→16, 6→17, 7→5, 8→18。"
        "用户可能会说 '做一个流水灯,每个灯间隔0.5秒'。"
        "请输出严格的JSON数组,每个元素包含: lamp(灯编号), state(0或1), delay(毫秒)。"
        "例如: "
        "[{\"lamp\":\"1\",\"state\":1,\"delay\":500},{\"lamp\":\"1\",\"state\":0,\"delay\":0},{\"lamp\":\"2\",\"state\":1,\"delay\":500}]"
    )

    payload = {
        "model": MODEL,
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_text}
        ],
        "temperature": 0.2,
        "max_tokens": 300
    }
    headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

    r = requests.post(API_URL, headers=headers, json=payload)
    resp = r.json()
    ai_result = resp["choices"][0]["message"]["content"]

    try:
        actions = json.loads(ai_result)
    except Exception:
        return jsonify({"ok": False, "error": f"AI返回不是合法JSON: {ai_result}"}), 500

    try:
        esp32_resp = requests.post(ESP32_URL, json=actions, timeout=10)
        return jsonify({
            "ok": True,
            "ai_result": actions,
            "esp32_response": esp32_resp.json()
        })
    except Exception as e:
        return jsonify({"ok": False, "error": f"ESP32请求失败: {str(e)}", "ai_result": actions}), 500

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

增加While/For

micropython

python 复制代码
from microdot import Microdot
import network, time, ujson
from machine import Pin

# 灯泡映射
lamp_pins = {
    "1": Pin(15, Pin.OUT),
    "2": Pin(2, Pin.OUT),
    "3": Pin(0, Pin.OUT),
    "4": Pin(4, Pin.OUT),
    "5": Pin(16, Pin.OUT),
    "6": Pin(17, Pin.OUT),
    "7": Pin(5, Pin.OUT),
    "8": Pin(18, Pin.OUT),
}
for p in lamp_pins.values():
    p.value(0)

# WiFi 配置
WIFI_SSID = "Xiaomi_313F"
WIFI_PASSWORD = "zzzzxxxx"

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print(f"正在连接 {WIFI_SSID}...")
        wlan.connect(WIFI_SSID, WIFI_PASSWORD)
        timeout = 10
        while not wlan.isconnected() and timeout > 0:
            time.sleep(1)
            timeout -= 1
    if wlan.isconnected():
        ip_info = wlan.ifconfig()
        print("WiFi 已连接,IP 信息:", ip_info)
        print("设备局域网 IP 地址:", ip_info[0])
        return True
    else:
        print("WiFi 连接失败")
        return False

# Microdot
app = Microdot()

@app.route('/control', methods=['POST'])
def control(request):
    try:
        data = request.json
        print("收到数据:", data)

        # 如果是 list 包裹 dict(AI 返回 [ { "type":"for",... } ])
        if isinstance(data, list):
            if len(data) == 1 and isinstance(data[0], dict) and "type" in data[0]:
                data = data[0]  # 解包
            else:
                run_actions(data)
                return {"ok": True}

        # 如果是 dict → 可能是 for 或 while
        if isinstance(data, dict):
            if data.get("type") == "for":
                count = data.get("count", 1)
                actions = data.get("actions", [])
                for _ in range(count):
                    run_actions(actions)

            elif data.get("type") == "while":
                duration = data.get("duration_sec", 60)
                actions = data.get("actions", [])
                end_time = time.time() + duration
                while time.time() < end_time:
                    run_actions(actions)

            else:
                return {"ok": False, "error": "未知类型"}, 400

        return {"ok": True}
    except Exception as e:
        return {"ok": False, "error": str(e)}, 500


def run_actions(actions):
    for act in actions:
        lamp = act.get("lamp")
        state = act.get("state", 0)
        delay = act.get("delay", 0)
        print("执行动作:", lamp, state, delay)  # 调试输出
        if lamp in lamp_pins:
            lamp_pins[lamp].value(1 if state else 0)
        if delay > 0:
            time.sleep_ms(delay)


if __name__ == "__main__":
    if connect_wifi():
        print("启动 Web API 服务器...")
        app.run(host="0.0.0.0", port=80)

flask python

python 复制代码
from flask import Flask, request, jsonify
import requests
import json

app = Flask(__name__)

API_URL = "https://api.deepseek.com/chat/completions"
API_KEY = "sk-c6bb5e9814784f378ddaxxxx"
MODEL = "deepseek-chat"

ESP32_URL = "http://192.168.10.126/control"

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    user_text = data.get("chat", "")

    system_prompt = (
        "你是ESP32灯光控制助手。"
        "灯泡编号与GPIO对应关系如下:"
        "1→15, 2→2, 3→0, 4→4, 5→16, 6→17, 7→5, 8→18。"
        "用户可能会说 '做一个流水灯,循环4次' 或 '来回闪烁20分钟'。"
        "请输出严格的JSON。支持三种模式:"
        "1. 单步序列: [ {\"lamp\":\"1\",\"state\":1,\"delay\":300}, ... ]"
        "2. for循环: {\"type\":\"for\",\"count\":N,\"actions\":[...同上...]}"
        "3. while循环: {\"type\":\"while\",\"duration_sec\":T,\"actions\":[...同上...]}"
        "只输出严格的 JSON,不要任何解释、注释、换行符之外的内容。如果输出 JSON 对象,必须完整闭合。"
    )

    payload = {
        "model": MODEL,
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_text}
        ],
        "temperature": 0.2,
        "max_tokens": 2000
    }
    headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

    r = requests.post(API_URL, headers=headers, json=payload)
    resp = r.json()
    ai_result = resp["choices"][0]["message"]["content"]

    try:
        actions = json.loads(ai_result)
    except Exception:
        return jsonify({"ok": False, "error": f"AI返回不是合法JSON: {ai_result}"}), 500

    try:
        print(actions)
        esp32_resp = requests.post(ESP32_URL, json=actions, timeout=10)
        return jsonify({
            "ok": True,
            "ai_result": actions,
            "esp32_response": esp32_resp.json()
        })
    except Exception as e:
        return jsonify({"ok": False, "error": f"ESP32请求失败: {str(e)}", "ai_result": actions}), 500

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

123

相关推荐
zone773910 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant10 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来11 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_11 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend12 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽12 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python