Path: blob/master/Tools/scripts/convert_plane_PID.py
9422 views
#!/usr/bin/env python312# flake8: noqa34'''5convert fixed wing PIDs in a parameter file from old system to ACPID system6'''78import os9import re1011found_line = False12changed_param = False1314def process_file(fname):15global found_line16global changed_param1718found_line = False19changed_param = False2021print("Processing %s" % fname)22lines = open(fname).readlines()23for i in range(len(lines)):24lines[i] = lines[i].rstrip()25while lines[len(lines)-1].strip() == "":26lines = lines[:-1]2728def find_line(pname):29global found_line30for i in range(len(lines)):31if lines[i].startswith(pname) and not lines[i][len(pname)].isalpha():32found_line = True33return i34return None3536def find_param(pname, dvalue):37i = find_line(pname)38if i is None:39return dvalue40s = lines[i].replace(","," ")41a = s.split()42return float(a[1])4344def set_param(pname, value, old_name):45global changed_param46i = find_line(pname)47if i is None:48i = find_line(old_name)49if i is None:50changed_param = True51lines.append("%s %f" % (pname, value))52return53# maintain separator if possible54sep = " "55m = re.match("[A-Z_0-9]+([\s,]+)[0-9.-]+", lines[i])56if m is not None:57sep = m.group(1)58changed_param = True59lines[i] = "%s%s%f" % (pname, sep, value)6061print("Converting pitch")62FF = find_param("PTCH2SRV_FF", 0)63P = find_param("PTCH2SRV_P", 1.0)64I = find_param("PTCH2SRV_I", 0.3)65D = find_param("PTCH2SRV_D", 0.04)66IMAX = find_param("PTCH2SRV_IMAX", 3000)67TCONST = find_param("PTCH2SRV_TCONST", 0.5)6869if FF <= 0:70I = max(I,0.3)7172kp_ff = max((P - I * TCONST) * TCONST - D, 0)73if found_line:74set_param("PTCH_RATE_FF", FF + kp_ff, "PTCH2SRV_FF")75set_param("PTCH_RATE_P", D, "PTCH2SRV_P")76set_param("PTCH_RATE_I", I * TCONST, "PTCH2SRV_I")77set_param("PTCH_RATE_D", 0, "PTCH2SRV_D")78set_param("PTCH_RATE_IMAX", IMAX/4500.0, "PTCH2SRV_IMAX")7980found_line = False8182print("Converting roll")83FF = find_param("RLL2SRV_FF", 0)84P = find_param("RLL2SRV_P", 1.0)85I = find_param("RLL2SRV_I", 0.3)86D = find_param("RLL2SRV_D", 0.08)87IMAX = find_param("RLL2SRV_IMAX", 3000)88TCONST = find_param("RLL2SRV_TCONST", 0.5)8990kp_ff = max((P - I * TCONST) * TCONST - D, 0)91if found_line:92set_param("RLL_RATE_FF", FF + kp_ff, "RLL2SRV_FF")93set_param("RLL_RATE_P", D, "RLL2SRV_P")94set_param("RLL_RATE_I", I * TCONST, "RLL2SRV_I")95set_param("RLL_RATE_D", 0, "RLL2SRV_D")96set_param("RLL_RATE_IMAX", IMAX/4500.0, "RLL2SRV_IMAX")9798if not changed_param:99print("No fixed wing PID params")100return101102print("Writing")103tfile = fname + ".tmp"104f = open(tfile,"w")105for i in range(len(lines)):106f.write("%s\n" % lines[i])107f.close()108os.rename(tfile, fname)109110import argparse111parser = argparse.ArgumentParser(description='convert plane PIDs from old to new system')112113parser.add_argument('param_file', nargs='+')114args = parser.parse_args()115116for f in args.param_file:117process_file(f)118119120