You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 rivejä
2.8 KiB

  1. # // /Users/zhangzhiqi/Library/Mobile Documents/M6HJR9W95L~com~textasticapp~textastic/Documents/PycharmProjects/PythonAll/自己的/面试相关题目/Answer_0813.py
  2. # // Copyright (c) 2023.
  3. # // @Time : 2023/8/13 9:54:11
  4. # // @Author : 张稚琦
  5. # // @Address: 广东省深圳市科瑞智造产业园瑞明大厦A座 18楼
  6. # // @Email : zhang@zhang.mba / zhangzhiqi828@gmail.com / zhangzhiqi@lh83.onmicrosoft.com / 2272358828@qq.com / zhangzhiqi@innorev.com.cn
  7. # // @Personal Blog: https://zhang.mba
  8. # // @File : Answer_0813.py
  9. # // @LastModified: 2023/8/13 上午9:54
  10. # // @ProjectName : PythonAll
  11. #
  12. import json # 导入json库,用于处理JSON数据
  13. from flask import Flask, request, jsonify # 导入Flask、request和jsonify模块
  14. import paho.mqtt.client as mqtt # 导入mqtt模块
  15. app = Flask(__name__) # 创建Flask应用
  16. mqtt_client = mqtt.Client() # 创建MQTT客户端实例
  17. mqtt_client.connect("公司设备MQTT代理服务器地址", 1883) # 连接到MQTT代理服务器
  18. @app.route('/motor_control', methods=['POST'])
  19. def motor_control():
  20. """
  21. 控制电机的接口
  22. """
  23. data = request.get_json() # 从请求中获取JSON数据
  24. topic = '/motor/{}/{}'.format(data['model'], data['id']) # 生成电机控制主题
  25. payload = generate_motor_payload(data) # 生成电机控制消息负载
  26. mqtt_client.publish(topic, json.dumps(payload)) # 发布消息到MQTT代理
  27. return jsonify({'message': 'Motor control request sent'}) # 返回JSON响应
  28. @app.route('/claw_control', methods=['POST'])
  29. def claw_control():
  30. """
  31. 控制爪子的接口
  32. """
  33. data = request.get_json() # 从请求中获取JSON数据
  34. topic = '/claw/{}/{}'.format(data['model'], data['id']) # 生成爪子控制主题
  35. payload = generate_claw_payload(data) # 生成爪子控制消息负载
  36. mqtt_client.publish(topic, json.dumps(payload)) # 发布消息到MQTT代理
  37. return jsonify({'message': 'Claw control request sent'}) # 返回JSON响应
  38. def generate_motor_payload(data):
  39. """
  40. 生成控制电机的消息负载
  41. """
  42. payload = {
  43. "MesType": "Request",
  44. "ClientId": "1",
  45. "DeviceID": data['id'],
  46. "Function": data['function'],
  47. "Set": {
  48. "P_pos": data['position'],
  49. "P_vel": data['velocity'],
  50. "P_mode": data['mode']
  51. }
  52. }
  53. return payload
  54. def generate_claw_payload(data):
  55. """
  56. 生成控制爪子的消息负载
  57. """
  58. payload = {
  59. "MesType": "Request",
  60. "ClientId": "2",
  61. "DeviceID": data['id'],
  62. "Function": data['function'],
  63. "Set": {
  64. "GripPos": data['grip_pos'],
  65. "GripI": data['grip_current'],
  66. "GripVel": data['grip_velocity']
  67. }
  68. }
  69. return payload