92 lines
3.7 KiB
Python
Raw Normal View History

2026-04-12 14:44:05 +08:00
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': '后退中'})
2026-04-13 16:51:31 +08:00
elif direction == 'left':
print("控制垃圾桶左移")
motor.move_left(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '左移中'})
elif direction == 'right':
print("控制垃圾桶右移")
motor.move_right(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '右移中'})
elif direction == 'rotate_left':
print("控制垃圾桶左旋转")
motor.rotate_left(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '左旋转中'})
elif direction == 'rotate_right':
print("控制垃圾桶右旋转")
motor.rotate_right(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '右旋转中'})
elif direction == 'forward_left':
print("控制垃圾桶左前移动")
motor.move_left_forward(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '左前移动中'})
elif direction == 'forward_right':
print("控制垃圾桶右前移动")
motor.move_right_forward(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '右前移动中'})
elif direction == 'backward_left':
print("控制垃圾桶左后移动")
motor.move_left_backward(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '左后移动中'})
elif direction == 'backward_right':
print("控制垃圾桶右后移动")
motor.move_right_backward(speed=0.6)
# 不使用time.sleep让电机持续运行
return jsonify({'status': 'success', 'message': '右后移动中'})
2026-04-12 14:44:05 +08:00
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)