web.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import asyncio
  2. import json
  3. import os
  4. from datetime import time, datetime
  5. import ezdxf
  6. import requests
  7. from flask import Flask, request, jsonify, send_from_directory, send_file
  8. from tqdm import tqdm
  9. import core
  10. from drawer import ShaftDrawer, TunDrawer, WindowDrawer, GateDrawer, FanMainDrawer, FanSystemDrawer, WindFlowDrawer
  11. from drawer.WindBridgeDrawer import WindBridgeDrawer
  12. app = Flask(__name__)
  13. cur_dir = os.getcwd()
  14. url = 'http://192.168.183.216:8008/python/tunCAD'
  15. @app.route('/sysvent/draw/<int:model_id>', methods=['GET'])
  16. def post_json(model_id):
  17. # 从数据库中查找template
  18. # template = select_template_by_id(template_id) template = 'template/moban.dxf'
  19. data = request.json
  20. now = datetime.now()
  21. current_time_str = now.strftime("%Y_%m_%d_%H_%M_%S")
  22. json_file_name = f'{cur_dir}\\save\\{current_time_str}.json'
  23. dxf_file_name = f'{cur_dir}\\save\\{current_time_str}.DXF'
  24. with open(json_file_name, 'w', encoding='utf-8') as f:
  25. json.dump(data, f, ensure_ascii=False, indent=4)
  26. # asyncio.run(async_write_dxf_file(templateFile=template, node_list=data, save_name=dxf_file_name))
  27. res = {
  28. "code": 200,
  29. "msg": "success",
  30. 'data': {
  31. 'filename': f'{current_time_str}.DXF'
  32. }
  33. }
  34. return jsonify(res), 200
  35. @app.route('/sysvent/download/<int:model_id>', methods=['GET'])
  36. def download_dxf_file(model_id):
  37. # 指定文件的完整路径
  38. filename = str(model_id) + ".dxf"
  39. cad_json = request_graph_point(model_id)
  40. draw_system_vent(cad_json,model_id)
  41. file_path = f'save\\{filename}'
  42. # 使用send_file发送文件,as_attachment=True表示以附件形式发送
  43. return send_file(file_path, as_attachment=True)
  44. def request_graph_point(model_id):
  45. response = requests.get(url)
  46. print(f"请求耗时 {response.elapsed.total_seconds()} 秒")
  47. cad_json = {}
  48. if response.status_code == 200:
  49. cad_json = response.json() # 将响应内容解析为JSON格式
  50. else:
  51. print(f"请求失败,状态码:{response.status_code}")
  52. return cad_json
  53. def calculate_route_middle(wind_flow_unit):
  54. path_start = wind_flow_unit[0]['x'], wind_flow_unit[0]['z']
  55. path_end = wind_flow_unit[-1]['x'], wind_flow_unit[-1]['z']
  56. path_middle = core.find_point_on_line(path_start, path_end, 1 / 2)
  57. route = core.calculate_angle_with_x_axis(path_start, path_end)
  58. return path_middle, route
  59. def draw_system_vent(cad_json, model_id):
  60. doc = ezdxf.new('R2000')
  61. doc.styles.add("LiberationSerif", font="LiberationSerif.ttf")
  62. msp = doc.modelspace()
  63. node_list = cad_json["tunsMapCAD"]
  64. tun_list = []
  65. window_list = []
  66. gate_list = []
  67. fan_list = []
  68. for node in node_list:
  69. node = node[1]
  70. tun = {
  71. "vec12": node["vec12"],
  72. "vec34": node["vec34"],
  73. "tun_id": node["ntunid"],
  74. "from": (node["nfrom"]["x"], node["nfrom"]["z"]),
  75. "to": (node["nto"]["x"], node["nto"]["z"]),
  76. "layer_id": node["nlayerid"],
  77. "width": node["fwidth"],
  78. "type": node["tunType"],
  79. "angle": node["angleRad"],
  80. "route": core.calculate_angle_with_x_axis((node["nfrom"]["x"], node["nfrom"]["z"]),
  81. (node["nto"]["x"], node["nto"]["z"]))
  82. }
  83. tun_list.append(tun)
  84. for window in node["windows"]:
  85. window["route"] = tun["route"]
  86. window["gap"] = node["fwidth"]
  87. window_list.extend(node["windows"])
  88. for gate in node["gates"]:
  89. gate["route"] = tun["route"]
  90. gate["gap"] = node["fwidth"]
  91. gate_list.extend(node["gates"])
  92. for fan in node["fans"]:
  93. fan["route"] = tun["route"]
  94. fan["gap"] = node["fwidth"]
  95. fan_list.extend(node["fans"])
  96. for tun in tqdm(tun_list, desc=' 【巷道绘制中】'):
  97. if tun['type'] == '1':
  98. shaft_center = tun['from'][0], tun['from'][1]
  99. sd = ShaftDrawer(msp, tun['width'], shaft_center, tun["route"], 42)
  100. sd.draw_shaft_drawer()
  101. else:
  102. vec12 = []
  103. vec34 = []
  104. for item in tun['vec12']:
  105. vec12.append({
  106. "x": item["x"],
  107. "y": item["z"]
  108. })
  109. for item in tun['vec34']:
  110. vec12.append({
  111. "x": item["x"],
  112. "y": item["z"]
  113. })
  114. color = core.get_color_by_layer(tun['layer_id'])
  115. td = TunDrawer(msp, tun['layer_id'], color, vec12, vec34, tun["from"], tun["to"])
  116. td.draw_tun()
  117. for window in tqdm(window_list, desc=f' 【风窗绘制中】'):
  118. point_c = window['x'], window['z']
  119. wd = WindowDrawer(msp, window["gap"], point_c, window["route"])
  120. wd.draw_window()
  121. for gate in tqdm(gate_list, desc=f' 【风窗绘制中】'):
  122. point_c = gate['x'], gate['z']
  123. gd = GateDrawer(msp, gate["gap"], point_c, gate["route"])
  124. gd.draw_gate()
  125. for fan in tqdm(fan_list, desc=f' 【风扇绘制中】'):
  126. if 'fanmain' in str(fan['strtype']):
  127. point_c = fan['x'], fan['z']
  128. fmd = FanMainDrawer(msp, fan["gap"], point_c, fan["route"])
  129. fmd.draw_fan_main()
  130. if 'fansystem' in str(fan['strtype']):
  131. point_c = fan['x'], fan['z']
  132. fsd = FanSystemDrawer(msp, fan["gap"], point_c, fan["route"])
  133. fsd.draw_fan_system()
  134. path_point_layers = cad_json["pathPointMap"]
  135. for path_point in path_point_layers:
  136. in_paths = path_point[1]['inPaths']
  137. for in_path in tqdm(in_paths, desc=f'图层{path_point[0]} 【进风方向绘制中】'):
  138. if len(in_path) != 0:
  139. path_middle, route = calculate_route_middle(in_path)
  140. wfd = WindFlowDrawer(msp, 5, path_middle, route, 3)
  141. wfd.draw_wind_flow()
  142. no_paths = path_point[1]['noPaths']
  143. for no_path in tqdm(no_paths, desc=f'图层{path_point[0]} 【未指定方向绘制中】'):
  144. if len(no_path) != 0:
  145. path_middle, route = calculate_route_middle(no_path)
  146. wfd = WindFlowDrawer(msp, 5, path_middle, route, 3)
  147. wfd.draw_wind_flow()
  148. out_paths = path_point[1]['outPaths']
  149. for out_path in tqdm(out_paths, desc=f'图层{path_point[0]} 【回风方向绘制中】'):
  150. if len(out_path) != 0:
  151. path_middle, route = calculate_route_middle(out_path)
  152. wfd = WindFlowDrawer(msp, 5, path_middle, route, 1)
  153. wfd.draw_wind_flow()
  154. use_paths = path_point[1]['usePaths']
  155. for use_path in tqdm(use_paths, desc=f'图层{path_point[0]} 【用风方向绘制中】'):
  156. if len(use_path) != 0:
  157. path_middle, route = calculate_route_middle(use_path)
  158. wfd = WindFlowDrawer(msp, 5, path_middle, route, 1)
  159. layer_map = cad_json["layerMap"]
  160. for layer in layer_map:
  161. cross_nodes = layer[1]['crossNodes']
  162. for cross_node in tqdm(cross_nodes, desc=f'图层{layer[0]} 【风桥绘制中】'):
  163. center = cross_node['crossPoint']['x'], -cross_node['crossPoint']['y']
  164. tun = [tun_ for tun_ in tun_list if tun_.get("tun_id") == cross_node['tun1Id']][0]
  165. route = core.calculate_angle_with_x_axis(tun["from"], tun["to"])
  166. line_1 = (tun["vec12"][0]["x"], tun["vec12"][0]["z"]), (tun["vec12"][-1]["x"], tun["vec12"][-1]["z"])
  167. line_2 = (tun["vec34"][0]["x"], tun["vec34"][0]["z"]), (tun["vec34"][-1]["x"], tun["vec34"][-1]["z"])
  168. gap = core.min_distance_between_segments(line_1,
  169. line_2)
  170. wbd = WindBridgeDrawer(msp, center, cross_node['tun1Id'], cross_node['tun2Id'], layer[0], tun["angle"], gap)
  171. wbd.draw_wind_bridge_drawer()
  172. doc.saveas(f'save/{str(model_id)}.dxf')
  173. if __name__ == '__main__':
  174. app.run(debug=True)