Browse Source

first commit

Haobin Luo 1 year ago
commit
0fe7f1c758
4 changed files with 379 additions and 0 deletions
  1. 3 0
      .gitignore
  2. 70 0
      app.py
  3. 107 0
      csvread.py
  4. 199 0
      stkcom.py

+ 3 - 0
.gitignore

@@ -0,0 +1,3 @@
+*.ipynb
+main.py
+__pycache__

+ 70 - 0
app.py

@@ -0,0 +1,70 @@
+from flask import Flask, request, jsonify
+import json
+from csvread import read_dddd_data, read_satellite_data, get_position_by_time
+from stkcom import *
+
+# 开启http server
+app = Flask(__name__)
+
+# 存储dddd数据、satellite数据
+dddd_array = []
+satellite_array = []
+
+@app.route("/")
+def hello_world():
+    return "这是电子gf弹道服务器"
+
+@app.route("/traj", methods=["GET","POST"])
+def get_traj():
+    # 1. 启动STK
+    root = activeSTK()
+    if root is None:
+        print("启动STK失败")
+    else:
+        print("启动STK成功")
+        # axois用这个
+        # xdparams = request.get_json(force=True)
+        # postman用这个
+        xdjson = request.form.to_dict()
+        # xdjson = json.loads(xdparams)
+        # 1.解析想定
+        (
+            begintime,
+            endtime,
+            timestep,
+            id,
+            xdname,
+            redunit,
+            blueunit,
+            satellite,
+            center,
+        ) = get_data_from_json(xdjson)
+        starttime, stoptime, duration = datetime_transform(begintime, endtime)
+        # 2.创建场景
+        ret = createScenario(
+            root,
+            xdname,
+            starttime,
+            stoptime,
+            duration
+        )
+        # 3.导出轨迹文件
+        exportMovementFile(root, redunit, satellite, starttime, stoptime, timestep)
+
+        # 从轨迹文件中读取轨迹数据
+        for i in range(len(redunit)):
+            str = redunit[i].get("name") + '.csv'
+            dddd_array.append(read_dddd_data("C:\\fire\\simulation",str))
+
+        for i in range(len(satellite)):
+            str = satellite[i].get("name") + '.csv'
+            satellite_array.append((read_satellite_data("C:\\fire\\simulation",str)))
+
+        # 获取最终要返回给请求端的json list
+        final_data = get_position_by_time(starttime, stoptime, dddd_array, satellite_array, timestep, redunit, satellite)
+
+        return jsonify({"status":"success"},{"data":final_data}), 200
+    
+# @app.route("/pos", methods=["GET","POST"])
+# def get_pos():
+    

+ 107 - 0
csvread.py

@@ -0,0 +1,107 @@
+import csv
+import re
+import datetime
+import os
+
+# read_dddd_data:读取弹道导弹轨迹
+def read_dddd_data(filedir=".", filename="./dddd1.csv"):
+    filepath = os.path.join(filedir, filename)
+    data = []
+    pattern = r"(\d+\s\w+\s\d+\s\d{2}:\d{2}:\d{2}.\d{3})\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)"
+    # pattern = r'\s+(\d+\s\w+\s\d+\s\d{2}:\d{2}:\d{2}\.\d{3})\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)'
+
+    # 打开CSV文件并读取内容
+    with open(filepath, newline="") as csvfile:
+        reader = csv.reader(csvfile)
+        # 跳过CSV文件的第一行,即标题行
+        next(reader)
+        next(reader)
+        next(reader)
+        next(reader)
+        next(reader)
+        next(reader)
+        next(reader)
+        # 逐行读取CSV文件内容并添加到data列表中
+        for row in reader:
+            match = re.match(pattern, row[0])
+            split_data = row[0].split("   ")
+            if match:
+                # 将匹配的内容存储到result_array中
+                data.append(
+                    [match.group(1), match.group(2), match.group(3), match.group(4)]
+                )
+    return data
+
+# read_satellite_data:读取卫星轨迹
+def read_satellite_data(filedir="", filename="./dddd1.csv"):
+    filepath = os.path.join(filedir, filename)
+    data = []
+    # pattern = r'(\d+\s\w+\s\d+\s\d{2}:\d{2}:\d{2}.\d{3})\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)'
+    pattern = r"\s+(\d+\s\w+\s\d+\s\d{2}:\d{2}:\d{2}\.\d{3})\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)"
+
+    # 打开CSV文件并读取内容
+    with open(filepath, newline="") as csvfile:
+        reader = csv.reader(csvfile)
+        # 跳过CSV文件的第一行,即标题行
+        next(reader)
+        next(reader)
+        next(reader)
+        next(reader)
+        next(reader)
+        next(reader)
+        next(reader)
+        # 逐行读取CSV文件内容并添加到data列表中
+        for row in reader:
+            match = re.match(pattern, row[0])
+            split_data = row[0].split("   ")
+            if match:
+                # 将匹配的内容存储到result_array中
+                data.append(
+                    [match.group(1), match.group(2), match.group(3), match.group(4)]
+                )
+    return data
+
+# read_satellite_data:返回全部轨迹
+def get_position_by_time(
+    starttime, stoptime, dddd_array, satellite_array, timestep, redunit, satellite
+):
+    
+    # microseconds = ".000"
+    # starttime = starttime + microseconds
+    # stoptime = stoptime + microseconds
+    start_time_obj = datetime.datetime.strptime(starttime, "%d %B %Y %H:%M:%S.%f")
+    stop_time_obj = datetime.datetime.strptime(stoptime, "%d %B %Y %H:%M:%S.%f")
+    
+    # 使用timedelta增加时间
+    current_time = start_time_obj
+    index = 0
+    final_data = []
+    # while current_time + microseconds != stoptime:
+    while current_time <= stop_time_obj:
+        obj = {}
+        for i in range(len(dddd_array)):
+            if index < len(dddd_array[i]):
+                item = dddd_array[i][index]
+                obj["dateTime"] = item[0]
+                obj[redunit[i].get("name")] = {
+                    "time": item[0],
+                    "x": item[1],
+                    "y": item[2],
+                    "z": item[3],
+                }
+        for j in range(len(satellite_array)):
+            if index < len(satellite_array[j]):
+                obj["dateTime"] = item[0]
+                item = satellite_array[j][index]
+                obj[satellite[j].get("name")] = {
+                    "time": item[0],
+                    "x": item[1],
+                    "y": item[2],
+                    "z": item[3],
+                }
+        final_data.append(obj)
+
+        current_time  = current_time + datetime.timedelta(seconds=int(timestep))
+        index = index + 1
+
+    return final_data

+ 199 - 0
stkcom.py

@@ -0,0 +1,199 @@
+from comtypes.gen import STKUtil, STKObjects
+from comtypes.client import CreateObject, GetActiveObject
+import json
+import datetime
+import pythoncom
+
+
+# get_data_from_json:解析想定文件
+def get_data_from_json(xdjson):
+    begintime = xdjson["starttime"]
+    endtime = xdjson["endtime"]
+    timestep = xdjson["steptime"]
+    id = xdjson["id"]
+    name = xdjson["xdname"]
+    redunit = json.loads(xdjson["redunit"])
+    blueunit = json.loads(xdjson["blueunit"])
+    satellite = json.loads(xdjson["satellite"])
+    center = json.loads(xdjson["center"])
+
+    return begintime, endtime, timestep, id, name, redunit, blueunit, satellite, center
+
+
+# datetime_transform:转换时间格式
+def datetime_transform(begintime, endtime):
+    date_time1 = datetime.datetime.strptime(begintime, "%Y-%m-%d %H:%M:%S")
+    date_time2 = datetime.datetime.strptime(endtime, "%Y-%m-%d %H:%M:%S")
+    # 去掉日期中的前导0
+    formatted_day1 = date_time1.strftime("%d").lstrip("0")
+    # 去掉日期中的前导0
+    formatted_day2 = date_time2.strftime("%d").lstrip("0")
+    # 计算两个日期之间的时间差
+    time_difference = date_time2 - date_time1
+
+    microseconds = ".00"
+    starttime = date_time1.strftime(f"{formatted_day1} %B %Y %H:%M:%S")
+    stoptime = date_time2.strftime(f"{formatted_day2} %B %Y %H:%M:%S")
+    starttime = starttime + microseconds
+    stoptime = stoptime + microseconds
+    return starttime, stoptime, time_difference
+
+
+# activeSTK:启动STK,返回句柄
+def activeSTK():
+    pythoncom.CoInitialize()
+
+    # uiApplication=CreateObject("STK11.Application")
+    uiApplication = GetActiveObject("STK11.Application")
+
+    # uiApplication.Visible=False
+    # uiApplication.Visible=True
+    uiApplication.UserControl = True
+
+    root = uiApplication.Personality2
+    return root
+
+
+# createScenario:创建场景
+def createScenario(root, xdname, starttime, stoptime, duration):
+    # if root.CurrentScenario is not None:
+    #     # If there is an existing scenario, close all scenarios
+    #     root.CloseScenario()
+    #     print("Closed existing scenarios.")
+    # root.NewScenario(xdname)
+
+    scenario = root.CurrentScenario
+    # 2. Set the analytical time period.
+    scenario2 = scenario.QueryInterface(STKObjects.IAgScenario)
+
+    # 计算相差的小时数
+    hours_difference = int(duration.total_seconds() / 3600)
+    hours_number = "+" + str(hours_difference) + "hr"
+
+    # scenario2.SetTimePeriod('Today','+24hr')
+    scenario2.SetTimePeriod(starttime, hours_number)
+    # scenario2.StartTime = begintime
+    # scenario2.StopTime = endtime
+
+    # 3. Reset the animation time.
+    root.Rewind()
+    print("创建场景成功")
+    return 1
+
+
+# exportMovementFile: 导出运动轨迹
+def exportMovementFile(root, redunit, satelliteJson, starttime, stoptime, steptime):
+    scenario = root.CurrentScenario
+    # 依次创建弹道导弹模型
+    for i in range(len(redunit)):
+        missile = scenario.Children.New(STKObjects.eMissile, redunit[i].get("name"))
+        missile2 = missile.QueryInterface(STKObjects.IAgMissile)
+        command = (
+            "Missile */Missile/"
+            + redunit[i].get("name")
+            + ' Trajectory "'
+            + starttime
+            + '" 10.0 LnLatGeoD '
+            + str(
+                redunit[i]
+                .get("component_movementjson")
+                .get("properties")
+                .get("launch_lat")
+            )
+            + " "
+            + str(
+                redunit[i]
+                .get("component_movementjson")
+                .get("properties")
+                .get("launch_lon")
+            )
+            + " "
+            + str(
+                redunit[i]
+                .get("component_movementjson")
+                .get("properties")
+                .get("launch_h")
+            )
+            + " ApogeeAlt "
+            + str(
+                redunit[i]
+                .get("component_movementjson")
+                .get("properties")
+                .get("apogee_height")
+            )
+            + " ImLatGeoD "
+            + str(
+                redunit[i]
+                .get("component_movementjson")
+                .get("properties")
+                .get("target_lat")
+            )
+            + " "
+            + str(
+                redunit[i]
+                .get("component_movementjson")
+                .get("properties")
+                .get("target_lon")
+            )
+            + " "
+            + str(
+                redunit[i]
+                .get("component_movementjson")
+                .get("properties")
+                .get("target_h")
+            )
+        )
+        root.ExecuteCommand(command)
+
+    # #依次导出弹道导弹模型轨迹文件
+    for i in range(len(redunit)):
+        root.ExecuteCommand(
+            "ReportCreate */Missile/"
+            + redunit[i].get("name")
+            + ' Type Save Style "Installed Styles/Fixed Position Velocity" File "C:\\fire\\simulation\\'
+            + redunit[i].get("name")
+            + '.csv" TimePeriod "'
+            + starttime
+            + '" "'
+            + stoptime
+            + '" TimeStep 10.0'
+        )
+
+    # 依次创建预警卫星模型
+    for i in range(len(satelliteJson)):
+        satellite = scenario.Children.New(
+            STKObjects.eSatellite, satelliteJson[i].get("name")
+        )
+        satellite2 = satellite.QueryInterface(STKObjects.IAgSatellite)
+        satname = satelliteJson[i].get("name")
+        satobj = satelliteJson[i].get(satname)
+        command = (
+            "SetState */Satellite/"
+            + satname
+            + ' TLE "'
+            + satobj.get("properties").get("TLE_LINE1")
+            + '" "'
+            + satobj.get("properties").get("TLE_LINE2")
+            + '" TimePeriod "'
+            + starttime
+            + '" "'
+            + stoptime
+            + '" TimeStep 10.0'
+        )
+        root.ExecuteCommand(command)
+
+    # 依次导出预警卫星模型轨迹文件
+    for i in range(len(satelliteJson)):
+        root.ExecuteCommand(
+            "ReportCreate */Satellite/"
+            + satelliteJson[i].get("name")
+            + ' Type Save Style "Installed Styles/Fixed Position Velocity" File "C:\\fire\\simulation\\'
+            + satelliteJson[i].get("name")
+            + '.csv" TimePeriod "'
+            + starttime
+            + '" "'
+            + stoptime
+            + '" TimeStep 10.0'
+        )
+
+    print("导出文件成功")