| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213 |
- import asyncio
- import json
- import os
- from datetime import time, datetime
- import ezdxf
- import requests
- from flask import Flask, request, jsonify, send_from_directory, send_file
- from tqdm import tqdm
- import core
- from drawer import ShaftDrawer, TunDrawer, WindowDrawer, GateDrawer, FanMainDrawer, FanSystemDrawer, WindFlowDrawer
- from drawer.WindBridgeDrawer import WindBridgeDrawer
- app = Flask(__name__)
- cur_dir = os.getcwd()
- url = 'http://192.168.183.216:8008/python/tunCAD'
- @app.route('/sysvent/draw/<int:model_id>', methods=['GET'])
- def post_json(model_id):
- # 从数据库中查找template
- # template = select_template_by_id(template_id) template = 'template/moban.dxf'
- data = request.json
- now = datetime.now()
- current_time_str = now.strftime("%Y_%m_%d_%H_%M_%S")
- json_file_name = f'{cur_dir}\\save\\{current_time_str}.json'
- dxf_file_name = f'{cur_dir}\\save\\{current_time_str}.DXF'
- with open(json_file_name, 'w', encoding='utf-8') as f:
- json.dump(data, f, ensure_ascii=False, indent=4)
- # asyncio.run(async_write_dxf_file(templateFile=template, node_list=data, save_name=dxf_file_name))
- res = {
- "code": 200,
- "msg": "success",
- 'data': {
- 'filename': f'{current_time_str}.DXF'
- }
- }
- return jsonify(res), 200
- @app.route('/sysvent/download/<int:model_id>', methods=['GET'])
- def download_dxf_file(model_id):
- # 指定文件的完整路径
- filename = str(model_id) + ".dxf"
- cad_json = request_graph_point(model_id)
- draw_system_vent(cad_json,model_id)
- file_path = f'save\\{filename}'
- # 使用send_file发送文件,as_attachment=True表示以附件形式发送
- return send_file(file_path, as_attachment=True)
- def request_graph_point(model_id):
- response = requests.get(url)
- print(f"请求耗时 {response.elapsed.total_seconds()} 秒")
- cad_json = {}
- if response.status_code == 200:
- cad_json = response.json() # 将响应内容解析为JSON格式
- else:
- print(f"请求失败,状态码:{response.status_code}")
- return cad_json
- def calculate_route_middle(wind_flow_unit):
- path_start = wind_flow_unit[0]['x'], wind_flow_unit[0]['z']
- path_end = wind_flow_unit[-1]['x'], wind_flow_unit[-1]['z']
- path_middle = core.find_point_on_line(path_start, path_end, 1 / 2)
- route = core.calculate_angle_with_x_axis(path_start, path_end)
- return path_middle, route
- def draw_system_vent(cad_json, model_id):
- doc = ezdxf.new('R2000')
- doc.styles.add("LiberationSerif", font="LiberationSerif.ttf")
- msp = doc.modelspace()
- node_list = cad_json["tunsMapCAD"]
- tun_list = []
- window_list = []
- gate_list = []
- fan_list = []
- for node in node_list:
- node = node[1]
- tun = {
- "vec12": node["vec12"],
- "vec34": node["vec34"],
- "tun_id": node["ntunid"],
- "from": (node["nfrom"]["x"], node["nfrom"]["z"]),
- "to": (node["nto"]["x"], node["nto"]["z"]),
- "layer_id": node["nlayerid"],
- "width": node["fwidth"],
- "type": node["tunType"],
- "angle": node["angleRad"],
- "route": core.calculate_angle_with_x_axis((node["nfrom"]["x"], node["nfrom"]["z"]),
- (node["nto"]["x"], node["nto"]["z"]))
- }
- tun_list.append(tun)
- for window in node["windows"]:
- window["route"] = tun["route"]
- window["gap"] = node["fwidth"]
- window_list.extend(node["windows"])
- for gate in node["gates"]:
- gate["route"] = tun["route"]
- gate["gap"] = node["fwidth"]
- gate_list.extend(node["gates"])
- for fan in node["fans"]:
- fan["route"] = tun["route"]
- fan["gap"] = node["fwidth"]
- fan_list.extend(node["fans"])
- for tun in tqdm(tun_list, desc=' 【巷道绘制中】'):
- if tun['type'] == '1':
- shaft_center = tun['from'][0], tun['from'][1]
- sd = ShaftDrawer(msp, tun['width'], shaft_center, tun["route"], 42)
- sd.draw_shaft_drawer()
- else:
- vec12 = []
- vec34 = []
- for item in tun['vec12']:
- vec12.append({
- "x": item["x"],
- "y": item["z"]
- })
- for item in tun['vec34']:
- vec12.append({
- "x": item["x"],
- "y": item["z"]
- })
- color = core.get_color_by_layer(tun['layer_id'])
- td = TunDrawer(msp, tun['layer_id'], color, vec12, vec34, tun["from"], tun["to"])
- td.draw_tun()
- for window in tqdm(window_list, desc=f' 【风窗绘制中】'):
- point_c = window['x'], window['z']
- wd = WindowDrawer(msp, window["gap"], point_c, window["route"])
- wd.draw_window()
- for gate in tqdm(gate_list, desc=f' 【风窗绘制中】'):
- point_c = gate['x'], gate['z']
- gd = GateDrawer(msp, gate["gap"], point_c, gate["route"])
- gd.draw_gate()
- for fan in tqdm(fan_list, desc=f' 【风扇绘制中】'):
- if 'fanmain' in str(fan['strtype']):
- point_c = fan['x'], fan['z']
- fmd = FanMainDrawer(msp, fan["gap"], point_c, fan["route"])
- fmd.draw_fan_main()
- if 'fansystem' in str(fan['strtype']):
- point_c = fan['x'], fan['z']
- fsd = FanSystemDrawer(msp, fan["gap"], point_c, fan["route"])
- fsd.draw_fan_system()
- path_point_layers = cad_json["pathPointMap"]
- for path_point in path_point_layers:
- in_paths = path_point[1]['inPaths']
- for in_path in tqdm(in_paths, desc=f'图层{path_point[0]} 【进风方向绘制中】'):
- if len(in_path) != 0:
- path_middle, route = calculate_route_middle(in_path)
- wfd = WindFlowDrawer(msp, 5, path_middle, route, 3)
- wfd.draw_wind_flow()
- no_paths = path_point[1]['noPaths']
- for no_path in tqdm(no_paths, desc=f'图层{path_point[0]} 【未指定方向绘制中】'):
- if len(no_path) != 0:
- path_middle, route = calculate_route_middle(no_path)
- wfd = WindFlowDrawer(msp, 5, path_middle, route, 3)
- wfd.draw_wind_flow()
- out_paths = path_point[1]['outPaths']
- for out_path in tqdm(out_paths, desc=f'图层{path_point[0]} 【回风方向绘制中】'):
- if len(out_path) != 0:
- path_middle, route = calculate_route_middle(out_path)
- wfd = WindFlowDrawer(msp, 5, path_middle, route, 1)
- wfd.draw_wind_flow()
- use_paths = path_point[1]['usePaths']
- for use_path in tqdm(use_paths, desc=f'图层{path_point[0]} 【用风方向绘制中】'):
- if len(use_path) != 0:
- path_middle, route = calculate_route_middle(use_path)
- wfd = WindFlowDrawer(msp, 5, path_middle, route, 1)
- layer_map = cad_json["layerMap"]
- for layer in layer_map:
- cross_nodes = layer[1]['crossNodes']
- for cross_node in tqdm(cross_nodes, desc=f'图层{layer[0]} 【风桥绘制中】'):
- center = cross_node['crossPoint']['x'], -cross_node['crossPoint']['y']
- tun = [tun_ for tun_ in tun_list if tun_.get("tun_id") == cross_node['tun1Id']][0]
- route = core.calculate_angle_with_x_axis(tun["from"], tun["to"])
- line_1 = (tun["vec12"][0]["x"], tun["vec12"][0]["z"]), (tun["vec12"][-1]["x"], tun["vec12"][-1]["z"])
- line_2 = (tun["vec34"][0]["x"], tun["vec34"][0]["z"]), (tun["vec34"][-1]["x"], tun["vec34"][-1]["z"])
- gap = core.min_distance_between_segments(line_1,
- line_2)
- wbd = WindBridgeDrawer(msp, center, cross_node['tun1Id'], cross_node['tun2Id'], layer[0], tun["angle"], gap)
- wbd.draw_wind_bridge_drawer()
- doc.saveas(f'save/{str(model_id)}.dxf')
- if __name__ == '__main__':
- app.run(debug=True)
|