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

相关推荐
eqwaak02 小时前
Pillow高级实战案例:图像处理的进阶应用
开发语言·python·科技·语言模型·pillow
dengzhenyue2 小时前
矩形碰撞检测
开发语言·前端·javascript
凤年徐2 小时前
【C++模板编程】从泛型思想到实战应用
java·c语言·开发语言·c++
倔强青铜三2 小时前
苦练Python第54天:比较运算魔术方法全解析,让你的对象“懂大小、能排序”!
人工智能·python·面试
科技苑2 小时前
Python 图像处理技巧指南
python
倔强青铜三2 小时前
苦练Python第53天:数值运算魔术方法从入门到精通
人工智能·python·面试
Q_Q5110082853 小时前
python+springboot+uniapp基于微信小程序的停车场管理系统 弹窗提示和车牌识别
vue.js·spring boot·python·django·flask·uni-app·node.js
大飞pkz3 小时前
【设计模式】组合模式
开发语言·设计模式·c#·组合模式
yaso_zhang3 小时前
jetpack6.1 的新 pytorch 2.5.1 版本在哪里?下载中心仅提供 pytorch v2.5.0a0。
人工智能·pytorch·python