Advertisement
IndexCase

Scratchpad to TheWay converter

Sep 29th, 2023 (edited)
645
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.70 KB | Gaming | 0 0
  1. #By IndexCase 2023
  2.  
  3. import re
  4. import json
  5. import os
  6. import time
  7.  
  8. def dms_to_dd(d, m, s=0):
  9.     """Convert degrees, minutes, and seconds to decimal degrees."""
  10.     return d + m / 60 + s / 3600
  11.  
  12. def parse_waypoint(waypoint_raw):
  13.     lines = waypoint_raw.strip().split("\n")
  14.  
  15.     # Look for the WP: line
  16.     wp_name = None
  17.     if lines[0].startswith("WP:"):
  18.         wp_name = lines[0].split(":", 1)[1].strip()
  19.         # Remove the WP: line to ensure the following code works as expected
  20.         lines = lines[1:]
  21.  
  22.     # Look for DMS or DMM format
  23.     match_lat = re.search(r"N (\d+)°(\d+)'([\d.]+)?", lines[0])
  24.     match_long = re.search(r"E (\d+)°(\d+)'([\d.]+)?", lines[0])
  25.    
  26.     # Try DMM if DMS didn't match
  27.     if not match_lat or not match_long:
  28.         match_lat = re.search(r"N (\d+)°([\d.]+)'", lines[0])
  29.         match_long = re.search(r"E (\d+)°([\d.]+)'", lines[0])
  30.         if match_lat and match_long:
  31.             lat = dms_to_dd(float(match_lat.group(1)), float(match_lat.group(2)))
  32.             long = dms_to_dd(float(match_long.group(1)), float(match_long.group(2)))
  33.         else:
  34.             raise ValueError(f"Failed to parse lat-long from: \n{lines[0]}")
  35.     else:
  36.         lat = dms_to_dd(float(match_lat.group(1)), float(match_lat.group(2)), float(match_lat.group(3) or 0))
  37.         long = dms_to_dd(float(match_long.group(1)), float(match_long.group(2)), float(match_long.group(3) or 0))
  38.  
  39.     # Extract elevation in feet
  40.     match = next((re.search(r"(\d+)m", line) for line in lines if re.search(r"(\d+)m", line)), None)
  41.     if not match:
  42.         raise ValueError(f"Failed to parse elevation from waypoint data:\n{waypoint_raw}")
  43.     elevation = float(match.group(1))
  44.  
  45.     return {
  46.         "name": wp_name,   # It could be None here
  47.         "lat": lat,
  48.         "long": long,
  49.         "elev": elevation
  50.     }
  51.  
  52. def process_waypoints():
  53.     with open(input_file_path, 'r', encoding='utf-8') as file:
  54.         data = file.read()
  55.  
  56.     waypoints_raw = [chunk for chunk in data.strip().split("\n\n") if len(chunk.split("\n")) > 1]
  57.     print(f"Waypoints found: {waypoints_raw}")
  58.  
  59.     waypoints = []
  60.     for idx, waypoint_raw in enumerate(waypoints_raw):
  61.         try:
  62.             waypoint = parse_waypoint(waypoint_raw)
  63.             if not waypoint['name']:  # if no name is provided, use a default one
  64.                 waypoint['name'] = "WAYPOINT" + str(idx)
  65.             waypoints.append(waypoint)
  66.         except ValueError as e:
  67.             print(f"Skipped waypoint due to error: {e}")
  68.             continue
  69.  
  70.     json_output = []
  71.     for idx, waypoint in enumerate(waypoints):
  72.         waypoint_name = waypoint['name']
  73.         json_output.append({
  74.             "id": idx + 2,
  75.             "name": waypoint_name,
  76.             "lat": round(waypoint["lat"], 9),
  77.             "long": round(waypoint["long"], 9),
  78.             "elev": round(waypoint["elev"], 2)  # Rounded to two decimal places for feet
  79.         })
  80.  
  81.     output_file_path = os.path.join(script_directory, 'scratchpad.tw')
  82.     with open(output_file_path, 'w') as output_file:
  83.         output_file.write(json.dumps(json_output, separators=(',', ':')))
  84.  
  85. script_directory = os.path.dirname(os.path.abspath(__file__))
  86. input_file_path = os.path.join(script_directory, '0000.txt')
  87.  
  88. # Process waypoints once on start
  89. process_waypoints()
  90.  
  91. last_mod_time = os.path.getmtime(input_file_path)
  92.  
  93. while True:
  94.     try:
  95.         current_mod_time = os.path.getmtime(input_file_path)
  96.         if current_mod_time != last_mod_time:
  97.             process_waypoints()
  98.             last_mod_time = current_mod_time
  99.  
  100.         time.sleep(10)  # Check for changes every 10 seconds
  101.     except KeyboardInterrupt:
  102.         print("Stopping script.")
  103.         break
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement