| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 超轻量级伺服驱动选型工具 - 纯内置模块版本
- 使用 Python 内置 http.server 模块,无需额外依赖
- """
- import os
- import sys
- import json
- import threading
- from http.server import HTTPServer, SimpleHTTPRequestHandler
- from urllib.parse import parse_qs, urlparse
- # 伺服电机参数数据库
- SERVO_MOTORS = [
- {"model": "ECMA-C20604RS", "power": 0.4, "torque": 1.27, "speed": 3000, "inertia": 0.00015},
- {"model": "ECMA-C20804RS", "power": 0.75, "torque": 2.39, "speed": 3000, "inertia": 0.00028},
- {"model": "ECMA-C20807RS", "power": 0.75, "torque": 2.39, "speed": 3000, "inertia": 0.00028},
- {"model": "ECMA-C21007RS", "power": 1.5, "torque": 4.77, "speed": 3000, "inertia": 0.00056},
- {"model": "ECMA-C21307RS", "power": 2.0, "torque": 6.37, "speed": 3000, "inertia": 0.00075},
- {"model": "ECMA-C21807RS", "power": 3.0, "torque": 9.55, "speed": 3000, "inertia": 0.00112},
- {"model": "ECMA-C22010RS", "power": 4.0, "torque": 12.73, "speed": 3000, "inertia": 0.00150},
- ]
- class ServoHandler(SimpleHTTPRequestHandler):
- def do_GET(self):
- if self.path == '/':
- self.send_response(200)
- self.send_header('Content-type', 'text/html; charset=utf-8')
- self.end_headers()
- html_content = self.get_html_content()
- self.wfile.write(html_content.encode('utf-8'))
- elif self.path == '/api/motors':
- self.send_response(200)
- self.send_header('Content-type', 'application/json; charset=utf-8')
- self.end_headers()
- self.wfile.write(json.dumps(SERVO_MOTORS, ensure_ascii=False).encode('utf-8'))
- else:
- super().do_GET()
- def do_POST(self):
- if self.path == '/api/calculate':
- content_length = int(self.headers['Content-Length'])
- post_data = self.rfile.read(content_length).decode('utf-8')
- params = json.loads(post_data)
-
- # 简单的选型计算逻辑
- results = self.calculate_selection(params)
-
- self.send_response(200)
- self.send_header('Content-type', 'application/json; charset=utf-8')
- self.end_headers()
- self.wfile.write(json.dumps(results, ensure_ascii=False).encode('utf-8'))
- def calculate_selection(self, params):
- """简单的伺服电机选型计算"""
- required_torque = float(params.get('torque', 0))
- required_speed = float(params.get('speed', 0))
- safety_factor = float(params.get('safety', 1.5))
-
- suitable_motors = []
- for motor in SERVO_MOTORS:
- if (motor['torque'] >= required_torque * safety_factor and
- motor['speed'] >= required_speed):
- suitable_motors.append(motor)
-
- return {
- 'suitable_motors': suitable_motors,
- 'required_torque': required_torque,
- 'required_speed': required_speed,
- 'safety_factor': safety_factor
- }
- def get_html_content(self):
- return '''<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>伺服驱动选型工具 - 超轻量版</title>
- <style>
- body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
- .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
- h1 { color: #333; text-align: center; }
- .form-group { margin: 15px 0; }
- label { display: block; margin-bottom: 5px; font-weight: bold; }
- input, select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
- button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; width: 100%; margin-top: 10px; }
- button:hover { background: #0056b3; }
- .results { margin-top: 20px; padding: 15px; background: #e9ecef; border-radius: 4px; }
- .motor-item { padding: 10px; margin: 5px 0; background: white; border-radius: 4px; border-left: 4px solid #007bff; }
- </style>
- </head>
- <body>
- <div class="container">
- <h1>伺服驱动选型工具</h1>
- <div class="form-group">
- <label for="torque">所需扭矩 (N·m):</label>
- <input type="number" id="torque" step="0.1" value="1.0">
- </div>
- <div class="form-group">
- <label for="speed">所需转速 (rpm):</label>
- <input type="number" id="speed" value="1000">
- </div>
- <div class="form-group">
- <label for="safety">安全系数:</label>
- <input type="number" id="safety" step="0.1" value="1.5">
- </div>
- <button onclick="calculateSelection()">计算选型</button>
- <div id="results" class="results" style="display:none;"></div>
- </div>
- <script>
- async function calculateSelection() {
- const torque = document.getElementById('torque').value;
- const speed = document.getElementById('speed').value;
- const safety = document.getElementById('safety').value;
-
- const response = await fetch('/api/calculate', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({torque, speed, safety})
- });
-
- const data = await response.json();
- displayResults(data);
- }
-
- function displayResults(data) {
- const resultsDiv = document.getElementById('results');
- if (data.suitable_motors.length === 0) {
- resultsDiv.innerHTML = '<p>未找到合适的伺服电机型号。请调整参数或联系技术支持。</p>';
- } else {
- let html = `<p>找到 ${data.suitable_motors.length} 个合适的型号:</p>`;
- data.suitable_motors.forEach(motor => {
- html += `<div class="motor-item">
- <strong>${motor.model}</strong><br>
- 功率: ${motor.power}kW | 扭矩: ${motor.torque}N·m | 转速: ${motor.speed}rpm
- </div>`;
- });
- resultsDiv.innerHTML = html;
- }
- resultsDiv.style.display = 'block';
- }
-
- // 加载电机列表
- window.onload = function() {
- console.log('伺服驱动选型工具 - 超轻量版已加载');
- };
- </script>
- </body>
- </html>'''
- def run_server(port=8080):
- """运行服务器"""
- server_address = ('', port)
- httpd = HTTPServer(server_address, ServoHandler)
- print(f"🚀 启动伺服驱动选型工具 (超轻量版)...")
- print(f"📁 工作目录: {os.getcwd()}")
- print(f"🌐 访问地址: http://localhost:{port}")
- print(f"💡 提示: 按 Ctrl+C 停止服务器")
- try:
- httpd.serve_forever()
- except KeyboardInterrupt:
- print("\n👋 服务器已停止")
- httpd.shutdown()
- if __name__ == "__main__":
- port = 8080
- if len(sys.argv) > 1:
- port = int(sys.argv[1])
- run_server(port)
|