2026-04-12 14:44:05 +08:00

52 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from flask import Flask, send_file, request, jsonify, send_from_directory
import motor
import time
import os
app = Flask(__name__)
# 静态文件路由
@app.route('/CSS/<path:filename>')
def serve_css(filename):
return send_from_directory('CSS', filename)
@app.route('/Javascript/<path:filename>')
def serve_js(filename):
return send_from_directory('Javascript', filename)
# 主页路由
@app.route('/')
def index():
return send_file('index.html')
# 控制电机路由
@app.route('/control', methods=['POST'])
def control():
data = request.get_json()
direction = data.get('direction')
# forward 与 backward 反向调整
try:
if direction == 'forward':
print("控制垃圾桶前进")
motor.backward(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '前进中'})
elif direction == 'backward':
print("控制垃圾桶后退")
motor.forward(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '后退中'})
elif direction == 'stop':
print("停止垃圾桶")
motor.stop()
return jsonify({'status': 'success', 'message': '已停止'})
else:
return jsonify({'status': 'error', 'message': '无效的方向'})
except Exception as e:
print(f"控制出错: {e}")
return jsonify({'status': 'error', 'message': f'控制出错: {e}'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)