INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
check for events, calling registered callbacks as needed
def check_events(self): '''check for events, calling registered callbacks as needed''' while self.event_count() > 0: event = self.get_event() for callback in self._callbacks: callback(event)
Updates LaserData.
def update(self): ''' Updates LaserData. ''' if self.hasproxy(): laserD = LaserData() values = [] data = self.proxy.getLaserData() #laserD.values = laser.distanceData for i in range (data.numLaser): values.append(data.distanceData[i] / 1000.0) laserD.maxAngle = data.maxAngle laserD.minAngle = data.minAngle laserD.maxRange = data.maxRange laserD.minRange = data.minRange laserD.values = values self.lock.acquire() self.laser = laserD self.lock.release()
return +1 or -1 for for sorting
def radius_cmp(a, b, offsets): '''return +1 or -1 for for sorting''' diff = radius(a, offsets) - radius(b, offsets) if diff > 0: return 1 if diff < 0: return -1 return 0
find best magnetometer offset fit to a log file
def magfit(logfile): '''find best magnetometer offset fit to a log file''' print("Processing log %s" % filename) mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps) data = [] last_t = 0 offsets = Vector3(0,0,0) # now gather all the data while True: m = mlog.recv_match(condition=args.condition) if m is None: break if m.get_type() == "SENSOR_OFFSETS": # update current offsets offsets = Vector3(m.mag_ofs_x, m.mag_ofs_y, m.mag_ofs_z) if m.get_type() == "RAW_IMU": mag = Vector3(m.xmag, m.ymag, m.zmag) # add data point after subtracting the current offsets data.append(mag - offsets + noise()) if m.get_type() == "MAG" and not args.mag2: offsets = Vector3(m.OfsX,m.OfsY,m.OfsZ) mag = Vector3(m.MagX,m.MagY,m.MagZ) data.append(mag - offsets + noise()) if m.get_type() == "MAG2" and args.mag2: offsets = Vector3(m.OfsX,m.OfsY,m.OfsZ) mag = Vector3(m.MagX,m.MagY,m.MagZ) data.append(mag - offsets + noise()) print("Extracted %u data points" % len(data)) print("Current offsets: %s" % offsets) orig_data = data data = select_data(data) # remove initial outliers data.sort(lambda a,b : radius_cmp(a,b,offsets)) data = data[len(data)/16:-len(data)/16] # do an initial fit (offsets, field_strength) = fit_data(data) for count in range(3): # sort the data by the radius data.sort(lambda a,b : radius_cmp(a,b,offsets)) print("Fit %u : %s field_strength=%6.1f to %6.1f" % ( count, offsets, radius(data[0], offsets), radius(data[-1], offsets))) # discard outliers, keep the middle 3/4 data = data[len(data)/8:-len(data)/8] # fit again (offsets, field_strength) = fit_data(data) print("Final : %s field_strength=%6.1f to %6.1f" % ( offsets, radius(data[0], offsets), radius(data[-1], offsets))) if args.plot: plot_data(orig_data, data)
plot data in 3D
def plot_data(orig_data, data): '''plot data in 3D''' import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt for dd, c in [(orig_data, 'r'), (data, 'b')]: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') xs = [ d.x for d in dd ] ys = [ d.y for d in dd ] zs = [ d.z for d in dd ] ax.scatter(xs, ys, zs, c=c, marker='o') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show()
find the of a token. Returns the offset in the string immediately after the matching end_token
def find_end(self, text, start_token, end_token, ignore_end_token=None): '''find the of a token. Returns the offset in the string immediately after the matching end_token''' if not text.startswith(start_token): raise MAVParseError("invalid token start") offset = len(start_token) nesting = 1 while nesting > 0: idx1 = text[offset:].find(start_token) idx2 = text[offset:].find(end_token) # Check for false positives due to another similar token # For example, make sure idx2 points to the second '}' in ${{field: ${name}}} if ignore_end_token: combined_token = ignore_end_token + end_token if text[offset+idx2:offset+idx2+len(combined_token)] == combined_token: idx2 += len(ignore_end_token) if idx1 == -1 and idx2 == -1: raise MAVParseError("token nesting error") if idx1 == -1 or idx1 > idx2: offset += idx2 + len(end_token) nesting -= 1 else: offset += idx1 + len(start_token) nesting += 1 return offset
find the of a variable
def find_var_end(self, text): '''find the of a variable''' return self.find_end(text, self.start_var_token, self.end_var_token)
find the of a repitition
def find_rep_end(self, text): '''find the of a repitition''' return self.find_end(text, self.start_rep_token, self.end_rep_token, ignore_end_token=self.end_var_token)
substitute variables in a string
def substitute(self, text, subvars={}, trim_leading_lf=None, checkmissing=None): '''substitute variables in a string''' if trim_leading_lf is None: trim_leading_lf = self.trim_leading_lf if checkmissing is None: checkmissing = self.checkmissing # handle repititions while True: subidx = text.find(self.start_rep_token) if subidx == -1: break endidx = self.find_rep_end(text[subidx:]) if endidx == -1: raise MAVParseError("missing end macro in %s" % text[subidx:]) part1 = text[0:subidx] part2 = text[subidx+len(self.start_rep_token):subidx+(endidx-len(self.end_rep_token))] part3 = text[subidx+endidx:] a = part2.split(':') field_name = a[0] rest = ':'.join(a[1:]) v = None if isinstance(subvars, dict): v = subvars.get(field_name, None) else: v = getattr(subvars, field_name, None) if v is None: raise MAVParseError('unable to find field %s' % field_name) t1 = part1 for f in v: t1 += self.substitute(rest, f, trim_leading_lf=False, checkmissing=False) if len(v) != 0 and t1[-1] in ["\n", ","]: t1 = t1[:-1] t1 += part3 text = t1 if trim_leading_lf: if text[0] == '\n': text = text[1:] while True: idx = text.find(self.start_var_token) if idx == -1: return text endidx = text[idx:].find(self.end_var_token) if endidx == -1: raise MAVParseError('missing end of variable: %s' % text[idx:idx+10]) varname = text[idx+2:idx+endidx] if isinstance(subvars, dict): if not varname in subvars: if checkmissing: raise MAVParseError("unknown variable in '%s%s%s'" % ( self.start_var_token, varname, self.end_var_token)) return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars, trim_leading_lf=False, checkmissing=False) value = subvars[varname] else: value = getattr(subvars, varname, None) if value is None: if checkmissing: raise MAVParseError("unknown variable in '%s%s%s'" % ( self.start_var_token, varname, self.end_var_token)) return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars, trim_leading_lf=False, checkmissing=False) text = text.replace("%s%s%s" % (self.start_var_token, varname, self.end_var_token), str(value)) return text
write to a file with variable substitution
def write(self, file, text, subvars={}, trim_leading_lf=True): '''write to a file with variable substitution''' file.write(self.substitute(text, subvars=subvars, trim_leading_lf=trim_leading_lf))
work out flight time for a log file
def flight_time(logfile): '''work out flight time for a log file''' print("Processing log %s" % filename) mlog = mavutil.mavlink_connection(filename) in_air = False start_time = 0.0 total_time = 0.0 total_dist = 0.0 t = None last_msg = None last_time_usec = None while True: m = mlog.recv_match(type=['GPS','GPS_RAW_INT'], condition=args.condition) if m is None: if in_air: total_time += time.mktime(t) - start_time if total_time > 0: print("Flight time : %u:%02u" % (int(total_time)/60, int(total_time)%60)) return (total_time, total_dist) if m.get_type() == 'GPS_RAW_INT': groundspeed = m.vel*0.01 status = m.fix_type time_usec = m.time_usec else: groundspeed = m.Spd status = m.Status time_usec = m.TimeUS if status < 3: continue t = time.localtime(m._timestamp) if groundspeed > args.groundspeed and not in_air: print("In air at %s (percent %.0f%% groundspeed %.1f)" % (time.asctime(t), mlog.percent, groundspeed)) in_air = True start_time = time.mktime(t) elif groundspeed < args.groundspeed and in_air: print("On ground at %s (percent %.1f%% groundspeed %.1f time=%.1f seconds)" % ( time.asctime(t), mlog.percent, groundspeed, time.mktime(t) - start_time)) in_air = False total_time += time.mktime(t) - start_time if last_msg is None or time_usec > last_time_usec or time_usec+30e6 < last_time_usec: if last_msg is not None: total_dist += distance_two(last_msg, m) last_msg = m last_time_usec = time_usec return (total_time, total_dist)
called in idle time
def idle_task(self): '''called in idle time''' if self.js is None: return for e in pygame.event.get(): # iterate over event stack #the following is somewhat custom for the specific joystick model: override = self.module('rc').override[:] for i in range(len(self.map)): m = self.map[i] if m is None: continue (axis, mul, add) = m if axis >= self.num_axes: continue v = int(self.js.get_axis(axis)*mul + add) v = max(min(v, 2000), 1000) override[i] = v if override != self.module('rc').override: self.module('rc').override = override self.module('rc').override_period.force()
return True if mtype matches pattern
def match_type(mtype, patterns): '''return True if mtype matches pattern''' for p in patterns: if fnmatch.fnmatch(mtype, p): return True return False
We convert RGB as BGR because OpenCV with RGB pass to YVU instead of YUV
def apply (self, img): yup,uup,vup = self.getUpLimit() ydwn,udwn,vdwn = self.getDownLimit() ''' We convert RGB as BGR because OpenCV with RGB pass to YVU instead of YUV''' yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) minValues = np.array([ydwn,udwn,vdwn],dtype=np.uint8) maxValues = np.array([yup,uup,vup], dtype=np.uint8) mask = cv2.inRange(yuv, minValues, maxValues) res = cv2.bitwise_and(img,img, mask= mask) return res
generate complete python implemenation
def generate(basename, xml): '''generate complete python implemenation''' if basename.endswith('.lua'): filename = basename else: filename = basename + '.lua' msgs = [] enums = [] filelist = [] for x in xml: msgs.extend(x.message) enums.extend(x.enum) filelist.append(os.path.basename(x.filename)) for m in msgs: if xml[0].little_endian: m.fmtstr = '<' else: m.fmtstr = '>' for f in m.ordered_fields: m.fmtstr += mavfmt(f) m.order_map = [ 0 ] * len(m.fieldnames) for i in range(0, len(m.fieldnames)): m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i]) print("Generating %s" % filename) outf = open(filename, "w") generate_preamble(outf) generate_msg_table(outf, msgs) generate_body_fields(outf) for m in msgs: generate_msg_fields(outf, m) for m in msgs: generate_payload_dissector(outf, m) generate_packet_dis(outf) # generate_enums(outf, enums) # generate_message_ids(outf, msgs) # generate_classes(outf, msgs) # generate_mavlink_class(outf, msgs, xml[0]) # generate_methods(outf, msgs) generate_epilog(outf) outf.close() print("Generated %s OK" % filename)
handle menu selections
def on_menu(self, event): '''handle menu selections''' state = self.state ret = self.menu.find_selected(event) if ret is None: return ret.call_handler() state.child_pipe_send.send(ret)
Voltage and current sensor data adc121_vspb_volt : Power board voltage sensor reading in volts (float) adc121_cspb_amp : Power board current sensor reading in amps (float) adc121_cs1_amp : Board current sensor 1 reading in amps (float) adc121_cs2_amp : Board current sensor 2 reading in amps (float)
def sens_power_encode(self, adc121_vspb_volt, adc121_cspb_amp, adc121_cs1_amp, adc121_cs2_amp): ''' Voltage and current sensor data adc121_vspb_volt : Power board voltage sensor reading in volts (float) adc121_cspb_amp : Power board current sensor reading in amps (float) adc121_cs1_amp : Board current sensor 1 reading in amps (float) adc121_cs2_amp : Board current sensor 2 reading in amps (float) ''' return MAVLink_sens_power_message(adc121_vspb_volt, adc121_cspb_amp, adc121_cs1_amp, adc121_cs2_amp)
Voltage and current sensor data adc121_vspb_volt : Power board voltage sensor reading in volts (float) adc121_cspb_amp : Power board current sensor reading in amps (float) adc121_cs1_amp : Board current sensor 1 reading in amps (float) adc121_cs2_amp : Board current sensor 2 reading in amps (float)
def sens_power_send(self, adc121_vspb_volt, adc121_cspb_amp, adc121_cs1_amp, adc121_cs2_amp, force_mavlink1=False): ''' Voltage and current sensor data adc121_vspb_volt : Power board voltage sensor reading in volts (float) adc121_cspb_amp : Power board current sensor reading in amps (float) adc121_cs1_amp : Board current sensor 1 reading in amps (float) adc121_cs2_amp : Board current sensor 2 reading in amps (float) ''' return self.send(self.sens_power_encode(adc121_vspb_volt, adc121_cspb_amp, adc121_cs1_amp, adc121_cs2_amp), force_mavlink1=force_mavlink1)
Maximum Power Point Tracker (MPPT) sensor data for solar module power performance tracking mppt_timestamp : MPPT last timestamp (uint64_t) mppt1_volt : MPPT1 voltage (float) mppt1_amp : MPPT1 current (float) mppt1_pwm : MPPT1 pwm (uint16_t) mppt1_status : MPPT1 status (uint8_t) mppt2_volt : MPPT2 voltage (float) mppt2_amp : MPPT2 current (float) mppt2_pwm : MPPT2 pwm (uint16_t) mppt2_status : MPPT2 status (uint8_t) mppt3_volt : MPPT3 voltage (float) mppt3_amp : MPPT3 current (float) mppt3_pwm : MPPT3 pwm (uint16_t) mppt3_status : MPPT3 status (uint8_t)
def sens_mppt_encode(self, mppt_timestamp, mppt1_volt, mppt1_amp, mppt1_pwm, mppt1_status, mppt2_volt, mppt2_amp, mppt2_pwm, mppt2_status, mppt3_volt, mppt3_amp, mppt3_pwm, mppt3_status): ''' Maximum Power Point Tracker (MPPT) sensor data for solar module power performance tracking mppt_timestamp : MPPT last timestamp (uint64_t) mppt1_volt : MPPT1 voltage (float) mppt1_amp : MPPT1 current (float) mppt1_pwm : MPPT1 pwm (uint16_t) mppt1_status : MPPT1 status (uint8_t) mppt2_volt : MPPT2 voltage (float) mppt2_amp : MPPT2 current (float) mppt2_pwm : MPPT2 pwm (uint16_t) mppt2_status : MPPT2 status (uint8_t) mppt3_volt : MPPT3 voltage (float) mppt3_amp : MPPT3 current (float) mppt3_pwm : MPPT3 pwm (uint16_t) mppt3_status : MPPT3 status (uint8_t) ''' return MAVLink_sens_mppt_message(mppt_timestamp, mppt1_volt, mppt1_amp, mppt1_pwm, mppt1_status, mppt2_volt, mppt2_amp, mppt2_pwm, mppt2_status, mppt3_volt, mppt3_amp, mppt3_pwm, mppt3_status)
Maximum Power Point Tracker (MPPT) sensor data for solar module power performance tracking mppt_timestamp : MPPT last timestamp (uint64_t) mppt1_volt : MPPT1 voltage (float) mppt1_amp : MPPT1 current (float) mppt1_pwm : MPPT1 pwm (uint16_t) mppt1_status : MPPT1 status (uint8_t) mppt2_volt : MPPT2 voltage (float) mppt2_amp : MPPT2 current (float) mppt2_pwm : MPPT2 pwm (uint16_t) mppt2_status : MPPT2 status (uint8_t) mppt3_volt : MPPT3 voltage (float) mppt3_amp : MPPT3 current (float) mppt3_pwm : MPPT3 pwm (uint16_t) mppt3_status : MPPT3 status (uint8_t)
def sens_mppt_send(self, mppt_timestamp, mppt1_volt, mppt1_amp, mppt1_pwm, mppt1_status, mppt2_volt, mppt2_amp, mppt2_pwm, mppt2_status, mppt3_volt, mppt3_amp, mppt3_pwm, mppt3_status, force_mavlink1=False): ''' Maximum Power Point Tracker (MPPT) sensor data for solar module power performance tracking mppt_timestamp : MPPT last timestamp (uint64_t) mppt1_volt : MPPT1 voltage (float) mppt1_amp : MPPT1 current (float) mppt1_pwm : MPPT1 pwm (uint16_t) mppt1_status : MPPT1 status (uint8_t) mppt2_volt : MPPT2 voltage (float) mppt2_amp : MPPT2 current (float) mppt2_pwm : MPPT2 pwm (uint16_t) mppt2_status : MPPT2 status (uint8_t) mppt3_volt : MPPT3 voltage (float) mppt3_amp : MPPT3 current (float) mppt3_pwm : MPPT3 pwm (uint16_t) mppt3_status : MPPT3 status (uint8_t) ''' return self.send(self.sens_mppt_encode(mppt_timestamp, mppt1_volt, mppt1_amp, mppt1_pwm, mppt1_status, mppt2_volt, mppt2_amp, mppt2_pwm, mppt2_status, mppt3_volt, mppt3_amp, mppt3_pwm, mppt3_status), force_mavlink1=force_mavlink1)
ASL-fixed-wing controller data timestamp : Timestamp (uint64_t) aslctrl_mode : ASLCTRL control-mode (manual, stabilized, auto, etc...) (uint8_t) h : See sourcecode for a description of these values... (float) hRef : (float) hRef_t : (float) PitchAngle : Pitch angle [deg] (float) PitchAngleRef : Pitch angle reference[deg] (float) q : (float) qRef : (float) uElev : (float) uThrot : (float) uThrot2 : (float) nZ : (float) AirspeedRef : Airspeed reference [m/s] (float) SpoilersEngaged : (uint8_t) YawAngle : Yaw angle [deg] (float) YawAngleRef : Yaw angle reference[deg] (float) RollAngle : Roll angle [deg] (float) RollAngleRef : Roll angle reference[deg] (float) p : (float) pRef : (float) r : (float) rRef : (float) uAil : (float) uRud : (float)
def aslctrl_data_encode(self, timestamp, aslctrl_mode, h, hRef, hRef_t, PitchAngle, PitchAngleRef, q, qRef, uElev, uThrot, uThrot2, nZ, AirspeedRef, SpoilersEngaged, YawAngle, YawAngleRef, RollAngle, RollAngleRef, p, pRef, r, rRef, uAil, uRud): ''' ASL-fixed-wing controller data timestamp : Timestamp (uint64_t) aslctrl_mode : ASLCTRL control-mode (manual, stabilized, auto, etc...) (uint8_t) h : See sourcecode for a description of these values... (float) hRef : (float) hRef_t : (float) PitchAngle : Pitch angle [deg] (float) PitchAngleRef : Pitch angle reference[deg] (float) q : (float) qRef : (float) uElev : (float) uThrot : (float) uThrot2 : (float) nZ : (float) AirspeedRef : Airspeed reference [m/s] (float) SpoilersEngaged : (uint8_t) YawAngle : Yaw angle [deg] (float) YawAngleRef : Yaw angle reference[deg] (float) RollAngle : Roll angle [deg] (float) RollAngleRef : Roll angle reference[deg] (float) p : (float) pRef : (float) r : (float) rRef : (float) uAil : (float) uRud : (float) ''' return MAVLink_aslctrl_data_message(timestamp, aslctrl_mode, h, hRef, hRef_t, PitchAngle, PitchAngleRef, q, qRef, uElev, uThrot, uThrot2, nZ, AirspeedRef, SpoilersEngaged, YawAngle, YawAngleRef, RollAngle, RollAngleRef, p, pRef, r, rRef, uAil, uRud)
ASL-fixed-wing controller debug data i32_1 : Debug data (uint32_t) i8_1 : Debug data (uint8_t) i8_2 : Debug data (uint8_t) f_1 : Debug data (float) f_2 : Debug data (float) f_3 : Debug data (float) f_4 : Debug data (float) f_5 : Debug data (float) f_6 : Debug data (float) f_7 : Debug data (float) f_8 : Debug data (float)
def aslctrl_debug_encode(self, i32_1, i8_1, i8_2, f_1, f_2, f_3, f_4, f_5, f_6, f_7, f_8): ''' ASL-fixed-wing controller debug data i32_1 : Debug data (uint32_t) i8_1 : Debug data (uint8_t) i8_2 : Debug data (uint8_t) f_1 : Debug data (float) f_2 : Debug data (float) f_3 : Debug data (float) f_4 : Debug data (float) f_5 : Debug data (float) f_6 : Debug data (float) f_7 : Debug data (float) f_8 : Debug data (float) ''' return MAVLink_aslctrl_debug_message(i32_1, i8_1, i8_2, f_1, f_2, f_3, f_4, f_5, f_6, f_7, f_8)
ASL-fixed-wing controller debug data i32_1 : Debug data (uint32_t) i8_1 : Debug data (uint8_t) i8_2 : Debug data (uint8_t) f_1 : Debug data (float) f_2 : Debug data (float) f_3 : Debug data (float) f_4 : Debug data (float) f_5 : Debug data (float) f_6 : Debug data (float) f_7 : Debug data (float) f_8 : Debug data (float)
def aslctrl_debug_send(self, i32_1, i8_1, i8_2, f_1, f_2, f_3, f_4, f_5, f_6, f_7, f_8, force_mavlink1=False): ''' ASL-fixed-wing controller debug data i32_1 : Debug data (uint32_t) i8_1 : Debug data (uint8_t) i8_2 : Debug data (uint8_t) f_1 : Debug data (float) f_2 : Debug data (float) f_3 : Debug data (float) f_4 : Debug data (float) f_5 : Debug data (float) f_6 : Debug data (float) f_7 : Debug data (float) f_8 : Debug data (float) ''' return self.send(self.aslctrl_debug_encode(i32_1, i8_1, i8_2, f_1, f_2, f_3, f_4, f_5, f_6, f_7, f_8), force_mavlink1=force_mavlink1)
Extended state information for ASLUAVs LED_status : Status of the position-indicator LEDs (uint8_t) SATCOM_status : Status of the IRIDIUM satellite communication system (uint8_t) Servo_status : Status vector for up to 8 servos (uint8_t) Motor_rpm : Motor RPM (float)
def asluav_status_encode(self, LED_status, SATCOM_status, Servo_status, Motor_rpm): ''' Extended state information for ASLUAVs LED_status : Status of the position-indicator LEDs (uint8_t) SATCOM_status : Status of the IRIDIUM satellite communication system (uint8_t) Servo_status : Status vector for up to 8 servos (uint8_t) Motor_rpm : Motor RPM (float) ''' return MAVLink_asluav_status_message(LED_status, SATCOM_status, Servo_status, Motor_rpm)
Extended state information for ASLUAVs LED_status : Status of the position-indicator LEDs (uint8_t) SATCOM_status : Status of the IRIDIUM satellite communication system (uint8_t) Servo_status : Status vector for up to 8 servos (uint8_t) Motor_rpm : Motor RPM (float)
def asluav_status_send(self, LED_status, SATCOM_status, Servo_status, Motor_rpm, force_mavlink1=False): ''' Extended state information for ASLUAVs LED_status : Status of the position-indicator LEDs (uint8_t) SATCOM_status : Status of the IRIDIUM satellite communication system (uint8_t) Servo_status : Status vector for up to 8 servos (uint8_t) Motor_rpm : Motor RPM (float) ''' return self.send(self.asluav_status_encode(LED_status, SATCOM_status, Servo_status, Motor_rpm), force_mavlink1=force_mavlink1)
Extended EKF state estimates for ASLUAVs timestamp : Time since system start [us] (uint64_t) Windspeed : Magnitude of wind velocity (in lateral inertial plane) [m/s] (float) WindDir : Wind heading angle from North [rad] (float) WindZ : Z (Down) component of inertial wind velocity [m/s] (float) Airspeed : Magnitude of air velocity [m/s] (float) beta : Sideslip angle [rad] (float) alpha : Angle of attack [rad] (float)
def ekf_ext_encode(self, timestamp, Windspeed, WindDir, WindZ, Airspeed, beta, alpha): ''' Extended EKF state estimates for ASLUAVs timestamp : Time since system start [us] (uint64_t) Windspeed : Magnitude of wind velocity (in lateral inertial plane) [m/s] (float) WindDir : Wind heading angle from North [rad] (float) WindZ : Z (Down) component of inertial wind velocity [m/s] (float) Airspeed : Magnitude of air velocity [m/s] (float) beta : Sideslip angle [rad] (float) alpha : Angle of attack [rad] (float) ''' return MAVLink_ekf_ext_message(timestamp, Windspeed, WindDir, WindZ, Airspeed, beta, alpha)
Extended EKF state estimates for ASLUAVs timestamp : Time since system start [us] (uint64_t) Windspeed : Magnitude of wind velocity (in lateral inertial plane) [m/s] (float) WindDir : Wind heading angle from North [rad] (float) WindZ : Z (Down) component of inertial wind velocity [m/s] (float) Airspeed : Magnitude of air velocity [m/s] (float) beta : Sideslip angle [rad] (float) alpha : Angle of attack [rad] (float)
def ekf_ext_send(self, timestamp, Windspeed, WindDir, WindZ, Airspeed, beta, alpha, force_mavlink1=False): ''' Extended EKF state estimates for ASLUAVs timestamp : Time since system start [us] (uint64_t) Windspeed : Magnitude of wind velocity (in lateral inertial plane) [m/s] (float) WindDir : Wind heading angle from North [rad] (float) WindZ : Z (Down) component of inertial wind velocity [m/s] (float) Airspeed : Magnitude of air velocity [m/s] (float) beta : Sideslip angle [rad] (float) alpha : Angle of attack [rad] (float) ''' return self.send(self.ekf_ext_encode(timestamp, Windspeed, WindDir, WindZ, Airspeed, beta, alpha), force_mavlink1=force_mavlink1)
Off-board controls/commands for ASLUAVs timestamp : Time since system start [us] (uint64_t) uElev : Elevator command [~] (float) uThrot : Throttle command [~] (float) uThrot2 : Throttle 2 command [~] (float) uAilL : Left aileron command [~] (float) uAilR : Right aileron command [~] (float) uRud : Rudder command [~] (float) obctrl_status : Off-board computer status (uint8_t)
def asl_obctrl_encode(self, timestamp, uElev, uThrot, uThrot2, uAilL, uAilR, uRud, obctrl_status): ''' Off-board controls/commands for ASLUAVs timestamp : Time since system start [us] (uint64_t) uElev : Elevator command [~] (float) uThrot : Throttle command [~] (float) uThrot2 : Throttle 2 command [~] (float) uAilL : Left aileron command [~] (float) uAilR : Right aileron command [~] (float) uRud : Rudder command [~] (float) obctrl_status : Off-board computer status (uint8_t) ''' return MAVLink_asl_obctrl_message(timestamp, uElev, uThrot, uThrot2, uAilL, uAilR, uRud, obctrl_status)
Off-board controls/commands for ASLUAVs timestamp : Time since system start [us] (uint64_t) uElev : Elevator command [~] (float) uThrot : Throttle command [~] (float) uThrot2 : Throttle 2 command [~] (float) uAilL : Left aileron command [~] (float) uAilR : Right aileron command [~] (float) uRud : Rudder command [~] (float) obctrl_status : Off-board computer status (uint8_t)
def asl_obctrl_send(self, timestamp, uElev, uThrot, uThrot2, uAilL, uAilR, uRud, obctrl_status, force_mavlink1=False): ''' Off-board controls/commands for ASLUAVs timestamp : Time since system start [us] (uint64_t) uElev : Elevator command [~] (float) uThrot : Throttle command [~] (float) uThrot2 : Throttle 2 command [~] (float) uAilL : Left aileron command [~] (float) uAilR : Right aileron command [~] (float) uRud : Rudder command [~] (float) obctrl_status : Off-board computer status (uint8_t) ''' return self.send(self.asl_obctrl_encode(timestamp, uElev, uThrot, uThrot2, uAilL, uAilR, uRud, obctrl_status), force_mavlink1=force_mavlink1)
Atmospheric sensors (temperature, humidity, ...) TempAmbient : Ambient temperature [degrees Celsius] (float) Humidity : Relative humidity [%] (float)
def sens_atmos_send(self, TempAmbient, Humidity, force_mavlink1=False): ''' Atmospheric sensors (temperature, humidity, ...) TempAmbient : Ambient temperature [degrees Celsius] (float) Humidity : Relative humidity [%] (float) ''' return self.send(self.sens_atmos_encode(TempAmbient, Humidity), force_mavlink1=force_mavlink1)
Battery pack monitoring data for Li-Ion batteries temperature : Battery pack temperature in [deg C] (float) voltage : Battery pack voltage in [mV] (uint16_t) current : Battery pack current in [mA] (int16_t) SoC : Battery pack state-of-charge (uint8_t) batterystatus : Battery monitor status report bits in Hex (uint16_t) serialnumber : Battery monitor serial number in Hex (uint16_t) hostfetcontrol : Battery monitor sensor host FET control in Hex (uint16_t) cellvoltage1 : Battery pack cell 1 voltage in [mV] (uint16_t) cellvoltage2 : Battery pack cell 2 voltage in [mV] (uint16_t) cellvoltage3 : Battery pack cell 3 voltage in [mV] (uint16_t) cellvoltage4 : Battery pack cell 4 voltage in [mV] (uint16_t) cellvoltage5 : Battery pack cell 5 voltage in [mV] (uint16_t) cellvoltage6 : Battery pack cell 6 voltage in [mV] (uint16_t)
def sens_batmon_encode(self, temperature, voltage, current, SoC, batterystatus, serialnumber, hostfetcontrol, cellvoltage1, cellvoltage2, cellvoltage3, cellvoltage4, cellvoltage5, cellvoltage6): ''' Battery pack monitoring data for Li-Ion batteries temperature : Battery pack temperature in [deg C] (float) voltage : Battery pack voltage in [mV] (uint16_t) current : Battery pack current in [mA] (int16_t) SoC : Battery pack state-of-charge (uint8_t) batterystatus : Battery monitor status report bits in Hex (uint16_t) serialnumber : Battery monitor serial number in Hex (uint16_t) hostfetcontrol : Battery monitor sensor host FET control in Hex (uint16_t) cellvoltage1 : Battery pack cell 1 voltage in [mV] (uint16_t) cellvoltage2 : Battery pack cell 2 voltage in [mV] (uint16_t) cellvoltage3 : Battery pack cell 3 voltage in [mV] (uint16_t) cellvoltage4 : Battery pack cell 4 voltage in [mV] (uint16_t) cellvoltage5 : Battery pack cell 5 voltage in [mV] (uint16_t) cellvoltage6 : Battery pack cell 6 voltage in [mV] (uint16_t) ''' return MAVLink_sens_batmon_message(temperature, voltage, current, SoC, batterystatus, serialnumber, hostfetcontrol, cellvoltage1, cellvoltage2, cellvoltage3, cellvoltage4, cellvoltage5, cellvoltage6)
Battery pack monitoring data for Li-Ion batteries temperature : Battery pack temperature in [deg C] (float) voltage : Battery pack voltage in [mV] (uint16_t) current : Battery pack current in [mA] (int16_t) SoC : Battery pack state-of-charge (uint8_t) batterystatus : Battery monitor status report bits in Hex (uint16_t) serialnumber : Battery monitor serial number in Hex (uint16_t) hostfetcontrol : Battery monitor sensor host FET control in Hex (uint16_t) cellvoltage1 : Battery pack cell 1 voltage in [mV] (uint16_t) cellvoltage2 : Battery pack cell 2 voltage in [mV] (uint16_t) cellvoltage3 : Battery pack cell 3 voltage in [mV] (uint16_t) cellvoltage4 : Battery pack cell 4 voltage in [mV] (uint16_t) cellvoltage5 : Battery pack cell 5 voltage in [mV] (uint16_t) cellvoltage6 : Battery pack cell 6 voltage in [mV] (uint16_t)
def sens_batmon_send(self, temperature, voltage, current, SoC, batterystatus, serialnumber, hostfetcontrol, cellvoltage1, cellvoltage2, cellvoltage3, cellvoltage4, cellvoltage5, cellvoltage6, force_mavlink1=False): ''' Battery pack monitoring data for Li-Ion batteries temperature : Battery pack temperature in [deg C] (float) voltage : Battery pack voltage in [mV] (uint16_t) current : Battery pack current in [mA] (int16_t) SoC : Battery pack state-of-charge (uint8_t) batterystatus : Battery monitor status report bits in Hex (uint16_t) serialnumber : Battery monitor serial number in Hex (uint16_t) hostfetcontrol : Battery monitor sensor host FET control in Hex (uint16_t) cellvoltage1 : Battery pack cell 1 voltage in [mV] (uint16_t) cellvoltage2 : Battery pack cell 2 voltage in [mV] (uint16_t) cellvoltage3 : Battery pack cell 3 voltage in [mV] (uint16_t) cellvoltage4 : Battery pack cell 4 voltage in [mV] (uint16_t) cellvoltage5 : Battery pack cell 5 voltage in [mV] (uint16_t) cellvoltage6 : Battery pack cell 6 voltage in [mV] (uint16_t) ''' return self.send(self.sens_batmon_encode(temperature, voltage, current, SoC, batterystatus, serialnumber, hostfetcontrol, cellvoltage1, cellvoltage2, cellvoltage3, cellvoltage4, cellvoltage5, cellvoltage6), force_mavlink1=force_mavlink1)
Fixed-wing soaring (i.e. thermal seeking) data timestamp : Timestamp [ms] (uint64_t) timestampModeChanged : Timestamp since last mode change[ms] (uint64_t) xW : Thermal core updraft strength [m/s] (float) xR : Thermal radius [m] (float) xLat : Thermal center latitude [deg] (float) xLon : Thermal center longitude [deg] (float) VarW : Variance W (float) VarR : Variance R (float) VarLat : Variance Lat (float) VarLon : Variance Lon (float) LoiterRadius : Suggested loiter radius [m] (float) LoiterDirection : Suggested loiter direction (float) DistToSoarPoint : Distance to soar point [m] (float) vSinkExp : Expected sink rate at current airspeed, roll and throttle [m/s] (float) z1_LocalUpdraftSpeed : Measurement / updraft speed at current/local airplane position [m/s] (float) z2_DeltaRoll : Measurement / roll angle tracking error [deg] (float) z1_exp : Expected measurement 1 (float) z2_exp : Expected measurement 2 (float) ThermalGSNorth : Thermal drift (from estimator prediction step only) [m/s] (float) ThermalGSEast : Thermal drift (from estimator prediction step only) [m/s] (float) TSE_dot : Total specific energy change (filtered) [m/s] (float) DebugVar1 : Debug variable 1 (float) DebugVar2 : Debug variable 2 (float) ControlMode : Control Mode [-] (uint8_t) valid : Data valid [-] (uint8_t)
def fw_soaring_data_encode(self, timestamp, timestampModeChanged, xW, xR, xLat, xLon, VarW, VarR, VarLat, VarLon, LoiterRadius, LoiterDirection, DistToSoarPoint, vSinkExp, z1_LocalUpdraftSpeed, z2_DeltaRoll, z1_exp, z2_exp, ThermalGSNorth, ThermalGSEast, TSE_dot, DebugVar1, DebugVar2, ControlMode, valid): ''' Fixed-wing soaring (i.e. thermal seeking) data timestamp : Timestamp [ms] (uint64_t) timestampModeChanged : Timestamp since last mode change[ms] (uint64_t) xW : Thermal core updraft strength [m/s] (float) xR : Thermal radius [m] (float) xLat : Thermal center latitude [deg] (float) xLon : Thermal center longitude [deg] (float) VarW : Variance W (float) VarR : Variance R (float) VarLat : Variance Lat (float) VarLon : Variance Lon (float) LoiterRadius : Suggested loiter radius [m] (float) LoiterDirection : Suggested loiter direction (float) DistToSoarPoint : Distance to soar point [m] (float) vSinkExp : Expected sink rate at current airspeed, roll and throttle [m/s] (float) z1_LocalUpdraftSpeed : Measurement / updraft speed at current/local airplane position [m/s] (float) z2_DeltaRoll : Measurement / roll angle tracking error [deg] (float) z1_exp : Expected measurement 1 (float) z2_exp : Expected measurement 2 (float) ThermalGSNorth : Thermal drift (from estimator prediction step only) [m/s] (float) ThermalGSEast : Thermal drift (from estimator prediction step only) [m/s] (float) TSE_dot : Total specific energy change (filtered) [m/s] (float) DebugVar1 : Debug variable 1 (float) DebugVar2 : Debug variable 2 (float) ControlMode : Control Mode [-] (uint8_t) valid : Data valid [-] (uint8_t) ''' return MAVLink_fw_soaring_data_message(timestamp, timestampModeChanged, xW, xR, xLat, xLon, VarW, VarR, VarLat, VarLon, LoiterRadius, LoiterDirection, DistToSoarPoint, vSinkExp, z1_LocalUpdraftSpeed, z2_DeltaRoll, z1_exp, z2_exp, ThermalGSNorth, ThermalGSEast, TSE_dot, DebugVar1, DebugVar2, ControlMode, valid)
Monitoring of sensorpod status timestamp : Timestamp in linuxtime [ms] (since 1.1.1970) (uint64_t) visensor_rate_1 : Rate of ROS topic 1 (uint8_t) visensor_rate_2 : Rate of ROS topic 2 (uint8_t) visensor_rate_3 : Rate of ROS topic 3 (uint8_t) visensor_rate_4 : Rate of ROS topic 4 (uint8_t) recording_nodes_count : Number of recording nodes (uint8_t) cpu_temp : Temperature of sensorpod CPU in [deg C] (uint8_t) free_space : Free space available in recordings directory in [Gb] * 1e2 (uint16_t)
def sensorpod_status_encode(self, timestamp, visensor_rate_1, visensor_rate_2, visensor_rate_3, visensor_rate_4, recording_nodes_count, cpu_temp, free_space): ''' Monitoring of sensorpod status timestamp : Timestamp in linuxtime [ms] (since 1.1.1970) (uint64_t) visensor_rate_1 : Rate of ROS topic 1 (uint8_t) visensor_rate_2 : Rate of ROS topic 2 (uint8_t) visensor_rate_3 : Rate of ROS topic 3 (uint8_t) visensor_rate_4 : Rate of ROS topic 4 (uint8_t) recording_nodes_count : Number of recording nodes (uint8_t) cpu_temp : Temperature of sensorpod CPU in [deg C] (uint8_t) free_space : Free space available in recordings directory in [Gb] * 1e2 (uint16_t) ''' return MAVLink_sensorpod_status_message(timestamp, visensor_rate_1, visensor_rate_2, visensor_rate_3, visensor_rate_4, recording_nodes_count, cpu_temp, free_space)
Monitoring of sensorpod status timestamp : Timestamp in linuxtime [ms] (since 1.1.1970) (uint64_t) visensor_rate_1 : Rate of ROS topic 1 (uint8_t) visensor_rate_2 : Rate of ROS topic 2 (uint8_t) visensor_rate_3 : Rate of ROS topic 3 (uint8_t) visensor_rate_4 : Rate of ROS topic 4 (uint8_t) recording_nodes_count : Number of recording nodes (uint8_t) cpu_temp : Temperature of sensorpod CPU in [deg C] (uint8_t) free_space : Free space available in recordings directory in [Gb] * 1e2 (uint16_t)
def sensorpod_status_send(self, timestamp, visensor_rate_1, visensor_rate_2, visensor_rate_3, visensor_rate_4, recording_nodes_count, cpu_temp, free_space, force_mavlink1=False): ''' Monitoring of sensorpod status timestamp : Timestamp in linuxtime [ms] (since 1.1.1970) (uint64_t) visensor_rate_1 : Rate of ROS topic 1 (uint8_t) visensor_rate_2 : Rate of ROS topic 2 (uint8_t) visensor_rate_3 : Rate of ROS topic 3 (uint8_t) visensor_rate_4 : Rate of ROS topic 4 (uint8_t) recording_nodes_count : Number of recording nodes (uint8_t) cpu_temp : Temperature of sensorpod CPU in [deg C] (uint8_t) free_space : Free space available in recordings directory in [Gb] * 1e2 (uint16_t) ''' return self.send(self.sensorpod_status_encode(timestamp, visensor_rate_1, visensor_rate_2, visensor_rate_3, visensor_rate_4, recording_nodes_count, cpu_temp, free_space), force_mavlink1=force_mavlink1)
Monitoring of power board status timestamp : Timestamp (uint64_t) pwr_brd_status : Power board status register (uint8_t) pwr_brd_led_status : Power board leds status (uint8_t) pwr_brd_system_volt : Power board system voltage (float) pwr_brd_servo_volt : Power board servo voltage (float) pwr_brd_mot_l_amp : Power board left motor current sensor (float) pwr_brd_mot_r_amp : Power board right motor current sensor (float) pwr_brd_servo_1_amp : Power board servo1 current sensor (float) pwr_brd_servo_2_amp : Power board servo1 current sensor (float) pwr_brd_servo_3_amp : Power board servo1 current sensor (float) pwr_brd_servo_4_amp : Power board servo1 current sensor (float) pwr_brd_aux_amp : Power board aux current sensor (float)
def sens_power_board_encode(self, timestamp, pwr_brd_status, pwr_brd_led_status, pwr_brd_system_volt, pwr_brd_servo_volt, pwr_brd_mot_l_amp, pwr_brd_mot_r_amp, pwr_brd_servo_1_amp, pwr_brd_servo_2_amp, pwr_brd_servo_3_amp, pwr_brd_servo_4_amp, pwr_brd_aux_amp): ''' Monitoring of power board status timestamp : Timestamp (uint64_t) pwr_brd_status : Power board status register (uint8_t) pwr_brd_led_status : Power board leds status (uint8_t) pwr_brd_system_volt : Power board system voltage (float) pwr_brd_servo_volt : Power board servo voltage (float) pwr_brd_mot_l_amp : Power board left motor current sensor (float) pwr_brd_mot_r_amp : Power board right motor current sensor (float) pwr_brd_servo_1_amp : Power board servo1 current sensor (float) pwr_brd_servo_2_amp : Power board servo1 current sensor (float) pwr_brd_servo_3_amp : Power board servo1 current sensor (float) pwr_brd_servo_4_amp : Power board servo1 current sensor (float) pwr_brd_aux_amp : Power board aux current sensor (float) ''' return MAVLink_sens_power_board_message(timestamp, pwr_brd_status, pwr_brd_led_status, pwr_brd_system_volt, pwr_brd_servo_volt, pwr_brd_mot_l_amp, pwr_brd_mot_r_amp, pwr_brd_servo_1_amp, pwr_brd_servo_2_amp, pwr_brd_servo_3_amp, pwr_brd_servo_4_amp, pwr_brd_aux_amp)
Monitoring of power board status timestamp : Timestamp (uint64_t) pwr_brd_status : Power board status register (uint8_t) pwr_brd_led_status : Power board leds status (uint8_t) pwr_brd_system_volt : Power board system voltage (float) pwr_brd_servo_volt : Power board servo voltage (float) pwr_brd_mot_l_amp : Power board left motor current sensor (float) pwr_brd_mot_r_amp : Power board right motor current sensor (float) pwr_brd_servo_1_amp : Power board servo1 current sensor (float) pwr_brd_servo_2_amp : Power board servo1 current sensor (float) pwr_brd_servo_3_amp : Power board servo1 current sensor (float) pwr_brd_servo_4_amp : Power board servo1 current sensor (float) pwr_brd_aux_amp : Power board aux current sensor (float)
def sens_power_board_send(self, timestamp, pwr_brd_status, pwr_brd_led_status, pwr_brd_system_volt, pwr_brd_servo_volt, pwr_brd_mot_l_amp, pwr_brd_mot_r_amp, pwr_brd_servo_1_amp, pwr_brd_servo_2_amp, pwr_brd_servo_3_amp, pwr_brd_servo_4_amp, pwr_brd_aux_amp, force_mavlink1=False): ''' Monitoring of power board status timestamp : Timestamp (uint64_t) pwr_brd_status : Power board status register (uint8_t) pwr_brd_led_status : Power board leds status (uint8_t) pwr_brd_system_volt : Power board system voltage (float) pwr_brd_servo_volt : Power board servo voltage (float) pwr_brd_mot_l_amp : Power board left motor current sensor (float) pwr_brd_mot_r_amp : Power board right motor current sensor (float) pwr_brd_servo_1_amp : Power board servo1 current sensor (float) pwr_brd_servo_2_amp : Power board servo1 current sensor (float) pwr_brd_servo_3_amp : Power board servo1 current sensor (float) pwr_brd_servo_4_amp : Power board servo1 current sensor (float) pwr_brd_aux_amp : Power board aux current sensor (float) ''' return self.send(self.sens_power_board_encode(timestamp, pwr_brd_status, pwr_brd_led_status, pwr_brd_system_volt, pwr_brd_servo_volt, pwr_brd_mot_l_amp, pwr_brd_mot_r_amp, pwr_brd_servo_1_amp, pwr_brd_servo_2_amp, pwr_brd_servo_3_amp, pwr_brd_servo_4_amp, pwr_brd_aux_amp), force_mavlink1=force_mavlink1)
calculate barometric altitude
def altitude(SCALED_PRESSURE, ground_pressure=None, ground_temp=None): '''calculate barometric altitude''' from . import mavutil self = mavutil.mavfile_global if ground_pressure is None: if self.param('GND_ABS_PRESS', None) is None: return 0 ground_pressure = self.param('GND_ABS_PRESS', 1) if ground_temp is None: ground_temp = self.param('GND_TEMP', 0) scaling = ground_pressure / (SCALED_PRESSURE.press_abs*100.0) temp = ground_temp + 273.15 return log(scaling) * temp * 29271.267 * 0.001
calculate barometric altitude
def altitude2(SCALED_PRESSURE, ground_pressure=None, ground_temp=None): '''calculate barometric altitude''' from . import mavutil self = mavutil.mavfile_global if ground_pressure is None: if self.param('GND_ABS_PRESS', None) is None: return 0 ground_pressure = self.param('GND_ABS_PRESS', 1) if ground_temp is None: ground_temp = self.param('GND_TEMP', 0) scaling = SCALED_PRESSURE.press_abs*100.0 / ground_pressure temp = ground_temp + 273.15 return 153.8462 * temp * (1.0 - exp(0.190259 * log(scaling)))
calculate heading from raw magnetometer
def mag_heading(RAW_IMU, ATTITUDE, declination=None, SENSOR_OFFSETS=None, ofs=None): '''calculate heading from raw magnetometer''' if declination is None: import mavutil declination = degrees(mavutil.mavfile_global.param('COMPASS_DEC', 0)) mag_x = RAW_IMU.xmag mag_y = RAW_IMU.ymag mag_z = RAW_IMU.zmag if SENSOR_OFFSETS is not None and ofs is not None: mag_x += ofs[0] - SENSOR_OFFSETS.mag_ofs_x mag_y += ofs[1] - SENSOR_OFFSETS.mag_ofs_y mag_z += ofs[2] - SENSOR_OFFSETS.mag_ofs_z # go via a DCM matrix to match the APM calculation dcm_matrix = rotation(ATTITUDE) cos_pitch_sq = 1.0-(dcm_matrix.c.x*dcm_matrix.c.x) headY = mag_y * dcm_matrix.c.z - mag_z * dcm_matrix.c.y headX = mag_x * cos_pitch_sq - dcm_matrix.c.x * (mag_y * dcm_matrix.c.y + mag_z * dcm_matrix.c.z) heading = degrees(atan2(-headY,headX)) + declination if heading < 0: heading += 360 return heading
calculate heading from raw magnetometer
def mag_heading_motors(RAW_IMU, ATTITUDE, declination, SENSOR_OFFSETS, ofs, SERVO_OUTPUT_RAW, motor_ofs): '''calculate heading from raw magnetometer''' ofs = get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs) if declination is None: import mavutil declination = degrees(mavutil.mavfile_global.param('COMPASS_DEC', 0)) mag_x = RAW_IMU.xmag mag_y = RAW_IMU.ymag mag_z = RAW_IMU.zmag if SENSOR_OFFSETS is not None and ofs is not None: mag_x += ofs[0] - SENSOR_OFFSETS.mag_ofs_x mag_y += ofs[1] - SENSOR_OFFSETS.mag_ofs_y mag_z += ofs[2] - SENSOR_OFFSETS.mag_ofs_z headX = mag_x*cos(ATTITUDE.pitch) + mag_y*sin(ATTITUDE.roll)*sin(ATTITUDE.pitch) + mag_z*cos(ATTITUDE.roll)*sin(ATTITUDE.pitch) headY = mag_y*cos(ATTITUDE.roll) - mag_z*sin(ATTITUDE.roll) heading = degrees(atan2(-headY,headX)) + declination if heading < 0: heading += 360 return heading
calculate magnetic field strength from raw magnetometer
def mag_field(RAW_IMU, SENSOR_OFFSETS=None, ofs=None): '''calculate magnetic field strength from raw magnetometer''' mag_x = RAW_IMU.xmag mag_y = RAW_IMU.ymag mag_z = RAW_IMU.zmag if SENSOR_OFFSETS is not None and ofs is not None: mag_x += ofs[0] - SENSOR_OFFSETS.mag_ofs_x mag_y += ofs[1] - SENSOR_OFFSETS.mag_ofs_y mag_z += ofs[2] - SENSOR_OFFSETS.mag_ofs_z return sqrt(mag_x**2 + mag_y**2 + mag_z**2)
calculate magnetic field strength from raw magnetometer (dataflash version)
def mag_field_df(MAG, ofs=None): '''calculate magnetic field strength from raw magnetometer (dataflash version)''' mag = Vector3(MAG.MagX, MAG.MagY, MAG.MagZ) offsets = Vector3(MAG.OfsX, MAG.OfsY, MAG.OfsZ) if ofs is not None: mag = (mag - offsets) + Vector3(ofs[0], ofs[1], ofs[2]) return mag.length()
calculate magnetic field strength from raw magnetometer
def get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs): '''calculate magnetic field strength from raw magnetometer''' import mavutil self = mavutil.mavfile_global m = SERVO_OUTPUT_RAW motor_pwm = m.servo1_raw + m.servo2_raw + m.servo3_raw + m.servo4_raw motor_pwm *= 0.25 rc3_min = self.param('RC3_MIN', 1100) rc3_max = self.param('RC3_MAX', 1900) motor = (motor_pwm - rc3_min) / (rc3_max - rc3_min) if motor > 1.0: motor = 1.0 if motor < 0.0: motor = 0.0 motor_offsets0 = motor_ofs[0] * motor motor_offsets1 = motor_ofs[1] * motor motor_offsets2 = motor_ofs[2] * motor ofs = (ofs[0] + motor_offsets0, ofs[1] + motor_offsets1, ofs[2] + motor_offsets2) return ofs
calculate magnetic field strength from raw magnetometer
def mag_field_motors(RAW_IMU, SENSOR_OFFSETS, ofs, SERVO_OUTPUT_RAW, motor_ofs): '''calculate magnetic field strength from raw magnetometer''' mag_x = RAW_IMU.xmag mag_y = RAW_IMU.ymag mag_z = RAW_IMU.zmag ofs = get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs) if SENSOR_OFFSETS is not None and ofs is not None: mag_x += ofs[0] - SENSOR_OFFSETS.mag_ofs_x mag_y += ofs[1] - SENSOR_OFFSETS.mag_ofs_y mag_z += ofs[2] - SENSOR_OFFSETS.mag_ofs_z return sqrt(mag_x**2 + mag_y**2 + mag_z**2)
average over N points
def average(var, key, N): '''average over N points''' global average_data if not key in average_data: average_data[key] = [var]*N return var average_data[key].pop(0) average_data[key].append(var) return sum(average_data[key])/N
5 point 2nd derivative
def second_derivative_5(var, key): '''5 point 2nd derivative''' global derivative_data import mavutil tnow = mavutil.mavfile_global.timestamp if not key in derivative_data: derivative_data[key] = (tnow, [var]*5) return 0 (last_time, data) = derivative_data[key] data.pop(0) data.append(var) derivative_data[key] = (tnow, data) h = (tnow - last_time) # N=5 2nd derivative from # http://www.holoborodko.com/pavel/numerical-methods/numerical-derivative/smooth-low-noise-differentiators/ ret = ((data[4] + data[0]) - 2*data[2]) / (4*h**2) return ret
a simple lowpass filter
def lowpass(var, key, factor): '''a simple lowpass filter''' global lowpass_data if not key in lowpass_data: lowpass_data[key] = var else: lowpass_data[key] = factor*lowpass_data[key] + (1.0 - factor)*var return lowpass_data[key]
calculate differences between values
def diff(var, key): '''calculate differences between values''' global last_diff ret = 0 if not key in last_diff: last_diff[key] = var return 0 ret = var - last_diff[key] last_diff[key] = var return ret
calculate slope
def delta(var, key, tusec=None): '''calculate slope''' global last_delta if tusec is not None: tnow = tusec * 1.0e-6 else: import mavutil tnow = mavutil.mavfile_global.timestamp dv = 0 ret = 0 if key in last_delta: (last_v, last_t, last_ret) = last_delta[key] if last_t == tnow: return last_ret if tnow == last_t: ret = 0 else: ret = (var - last_v) / (tnow - last_t) last_delta[key] = (var, tnow, ret) return ret
estimate roll from accelerometer
def roll_estimate(RAW_IMU,GPS_RAW_INT=None,ATTITUDE=None,SENSOR_OFFSETS=None, ofs=None, mul=None,smooth=0.7): '''estimate roll from accelerometer''' rx = RAW_IMU.xacc * 9.81 / 1000.0 ry = RAW_IMU.yacc * 9.81 / 1000.0 rz = RAW_IMU.zacc * 9.81 / 1000.0 if ATTITUDE is not None and GPS_RAW_INT is not None: ry -= ATTITUDE.yawspeed * GPS_RAW_INT.vel*0.01 rz += ATTITUDE.pitchspeed * GPS_RAW_INT.vel*0.01 if SENSOR_OFFSETS is not None and ofs is not None: rx += SENSOR_OFFSETS.accel_cal_x ry += SENSOR_OFFSETS.accel_cal_y rz += SENSOR_OFFSETS.accel_cal_z rx -= ofs[0] ry -= ofs[1] rz -= ofs[2] if mul is not None: rx *= mul[0] ry *= mul[1] rz *= mul[2] return lowpass(degrees(-asin(ry/sqrt(rx**2+ry**2+rz**2))),'_roll',smooth)
return the current DCM rotation matrix
def rotation(ATTITUDE): '''return the current DCM rotation matrix''' r = Matrix3() r.from_euler(ATTITUDE.roll, ATTITUDE.pitch, ATTITUDE.yaw) return r
return an attitude rotation matrix that is consistent with the current mag vector
def mag_rotation(RAW_IMU, inclination, declination): '''return an attitude rotation matrix that is consistent with the current mag vector''' m_body = Vector3(RAW_IMU.xmag, RAW_IMU.ymag, RAW_IMU.zmag) m_earth = Vector3(m_body.length(), 0, 0) r = Matrix3() r.from_euler(0, -radians(inclination), radians(declination)) m_earth = r * m_earth r.from_two_vectors(m_earth, m_body) return r
estimate yaw from mag
def mag_yaw(RAW_IMU, inclination, declination): '''estimate yaw from mag''' m = mag_rotation(RAW_IMU, inclination, declination) (r, p, y) = m.to_euler() y = degrees(y) if y < 0: y += 360 return y
estimate roll from mag
def mag_roll(RAW_IMU, inclination, declination): '''estimate roll from mag''' m = mag_rotation(RAW_IMU, inclination, declination) (r, p, y) = m.to_euler() return degrees(r)
give the magnitude of the discrepancy between observed and expected magnetic field
def mag_discrepancy(RAW_IMU, ATTITUDE, inclination, declination=None): '''give the magnitude of the discrepancy between observed and expected magnetic field''' if declination is None: import mavutil declination = degrees(mavutil.mavfile_global.param('COMPASS_DEC', 0)) expected = expected_mag(RAW_IMU, ATTITUDE, inclination, declination) mag = Vector3(RAW_IMU.xmag, RAW_IMU.ymag, RAW_IMU.zmag) return degrees(expected.angle(mag))
return expected mag vector
def expected_mag(RAW_IMU, ATTITUDE, inclination, declination): '''return expected mag vector''' m_body = Vector3(RAW_IMU.xmag, RAW_IMU.ymag, RAW_IMU.zmag) field_strength = m_body.length() m = rotation(ATTITUDE) r = Matrix3() r.from_euler(0, -radians(inclination), radians(declination)) m_earth = r * Vector3(field_strength, 0, 0) return m.transposed() * m_earth
give the magnitude of the discrepancy between observed and expected magnetic field
def mag_inclination(RAW_IMU, ATTITUDE, declination=None): '''give the magnitude of the discrepancy between observed and expected magnetic field''' if declination is None: import mavutil declination = degrees(mavutil.mavfile_global.param('COMPASS_DEC', 0)) r = rotation(ATTITUDE) mag1 = Vector3(RAW_IMU.xmag, RAW_IMU.ymag, RAW_IMU.zmag) mag1 = r * mag1 mag2 = Vector3(cos(radians(declination)), sin(radians(declination)), 0) inclination = degrees(mag1.angle(mag2)) if RAW_IMU.zmag < 0: inclination = -inclination return inclination
estimate from mag
def expected_magx(RAW_IMU, ATTITUDE, inclination, declination): '''estimate from mag''' v = expected_mag(RAW_IMU, ATTITUDE, inclination, declination) return v.x
estimate from mag
def expected_magy(RAW_IMU, ATTITUDE, inclination, declination): '''estimate from mag''' v = expected_mag(RAW_IMU, ATTITUDE, inclination, declination) return v.y
estimate from mag
def expected_magz(RAW_IMU, ATTITUDE, inclination, declination): '''estimate from mag''' v = expected_mag(RAW_IMU, ATTITUDE, inclination, declination) return v.z
estimate pitch from accelerometer
def gravity(RAW_IMU, SENSOR_OFFSETS=None, ofs=None, mul=None, smooth=0.7): '''estimate pitch from accelerometer''' if hasattr(RAW_IMU, 'xacc'): rx = RAW_IMU.xacc * 9.81 / 1000.0 ry = RAW_IMU.yacc * 9.81 / 1000.0 rz = RAW_IMU.zacc * 9.81 / 1000.0 else: rx = RAW_IMU.AccX ry = RAW_IMU.AccY rz = RAW_IMU.AccZ if SENSOR_OFFSETS is not None and ofs is not None: rx += SENSOR_OFFSETS.accel_cal_x ry += SENSOR_OFFSETS.accel_cal_y rz += SENSOR_OFFSETS.accel_cal_z rx -= ofs[0] ry -= ofs[1] rz -= ofs[2] if mul is not None: rx *= mul[0] ry *= mul[1] rz *= mul[2] return sqrt(rx**2+ry**2+rz**2)
estimate pitch from SIMSTATE accels
def pitch_sim(SIMSTATE, GPS_RAW): '''estimate pitch from SIMSTATE accels''' xacc = SIMSTATE.xacc - lowpass(delta(GPS_RAW.v,"v")*6.6, "v", 0.9) zacc = SIMSTATE.zacc zacc += SIMSTATE.ygyro * GPS_RAW.v; if xacc/zacc >= 1: return 0 if xacc/zacc <= -1: return -0 return degrees(-asin(xacc/zacc))
distance between two points
def distance_two(GPS_RAW1, GPS_RAW2, horizontal=True): '''distance between two points''' if hasattr(GPS_RAW1, 'Lat'): lat1 = radians(GPS_RAW1.Lat) lat2 = radians(GPS_RAW2.Lat) lon1 = radians(GPS_RAW1.Lng) lon2 = radians(GPS_RAW2.Lng) alt1 = GPS_RAW1.Alt alt2 = GPS_RAW2.Alt elif hasattr(GPS_RAW1, 'cog'): lat1 = radians(GPS_RAW1.lat)*1.0e-7 lat2 = radians(GPS_RAW2.lat)*1.0e-7 lon1 = radians(GPS_RAW1.lon)*1.0e-7 lon2 = radians(GPS_RAW2.lon)*1.0e-7 alt1 = GPS_RAW1.alt*0.001 alt2 = GPS_RAW2.alt*0.001 else: lat1 = radians(GPS_RAW1.lat) lat2 = radians(GPS_RAW2.lat) lon1 = radians(GPS_RAW1.lon) lon2 = radians(GPS_RAW2.lon) alt1 = GPS_RAW1.alt*0.001 alt2 = GPS_RAW2.alt*0.001 dLat = lat2 - lat1 dLon = lon2 - lon1 a = sin(0.5*dLat)**2 + sin(0.5*dLon)**2 * cos(lat1) * cos(lat2) c = 2.0 * atan2(sqrt(a), sqrt(1.0-a)) ground_dist = 6371 * 1000 * c if horizontal: return ground_dist return sqrt(ground_dist**2 + (alt2-alt1)**2)
distance from first fix point
def distance_home(GPS_RAW): '''distance from first fix point''' global first_fix if (hasattr(GPS_RAW, 'fix_type') and GPS_RAW.fix_type < 2) or \ (hasattr(GPS_RAW, 'Status') and GPS_RAW.Status < 2): return 0 if first_fix == None: first_fix = GPS_RAW return 0 return distance_two(GPS_RAW, first_fix)
sawtooth pattern based on uptime
def sawtooth(ATTITUDE, amplitude=2.0, period=5.0): '''sawtooth pattern based on uptime''' mins = (ATTITUDE.usec * 1.0e-6)/60 p = fmod(mins, period*2) if p < period: return amplitude * (p/period) return amplitude * (period - (p-period))/period
return expected rate of turn in degrees/s for given speed in m/s and bank angle in degrees
def rate_of_turn(speed, bank): '''return expected rate of turn in degrees/s for given speed in m/s and bank angle in degrees''' if abs(speed) < 2 or abs(bank) > 80: return 0 ret = degrees(9.81*tan(radians(bank))/speed) return ret
recompute airspeed with a different ARSPD_RATIO
def airspeed(VFR_HUD, ratio=None, used_ratio=None, offset=None): '''recompute airspeed with a different ARSPD_RATIO''' import mavutil mav = mavutil.mavfile_global if ratio is None: ratio = 1.9936 # APM default if used_ratio is None: if 'ARSPD_RATIO' in mav.params: used_ratio = mav.params['ARSPD_RATIO'] else: print("no ARSPD_RATIO in mav.params") used_ratio = ratio if hasattr(VFR_HUD,'airspeed'): airspeed = VFR_HUD.airspeed else: airspeed = VFR_HUD.Airspeed airspeed_pressure = (airspeed**2) / used_ratio if offset is not None: airspeed_pressure += offset if airspeed_pressure < 0: airspeed_pressure = 0 airspeed = sqrt(airspeed_pressure * ratio) return airspeed
EAS2TAS from ARSP.Temp
def EAS2TAS(ARSP,GPS,BARO,ground_temp=25): '''EAS2TAS from ARSP.Temp''' tempK = ground_temp + 273.15 - 0.0065 * GPS.Alt return sqrt(1.225 / (BARO.Press / (287.26 * tempK)))
recompute airspeed with a different ARSPD_RATIO
def airspeed_ratio(VFR_HUD): '''recompute airspeed with a different ARSPD_RATIO''' import mavutil mav = mavutil.mavfile_global airspeed_pressure = (VFR_HUD.airspeed**2) / ratio airspeed = sqrt(airspeed_pressure * ratio) return airspeed
back-calculate the voltage the airspeed sensor must have seen
def airspeed_voltage(VFR_HUD, ratio=None): '''back-calculate the voltage the airspeed sensor must have seen''' import mavutil mav = mavutil.mavfile_global if ratio is None: ratio = 1.9936 # APM default if 'ARSPD_RATIO' in mav.params: used_ratio = mav.params['ARSPD_RATIO'] else: used_ratio = ratio if 'ARSPD_OFFSET' in mav.params: offset = mav.params['ARSPD_OFFSET'] else: return -1 airspeed_pressure = (pow(VFR_HUD.airspeed,2)) / used_ratio raw = airspeed_pressure + offset SCALING_OLD_CALIBRATION = 204.8 voltage = 5.0 * raw / 4096 return voltage
return angular velocities in earth frame
def earth_rates(ATTITUDE): '''return angular velocities in earth frame''' from math import sin, cos, tan, fabs p = ATTITUDE.rollspeed q = ATTITUDE.pitchspeed r = ATTITUDE.yawspeed phi = ATTITUDE.roll theta = ATTITUDE.pitch psi = ATTITUDE.yaw phiDot = p + tan(theta)*(q*sin(phi) + r*cos(phi)) thetaDot = q*cos(phi) - r*sin(phi) if fabs(cos(theta)) < 1.0e-20: theta += 1.0e-10 psiDot = (q*sin(phi) + r*cos(phi))/cos(theta) return (phiDot, thetaDot, psiDot)
return GPS velocity vector
def gps_velocity_old(GPS_RAW_INT): '''return GPS velocity vector''' return Vector3(GPS_RAW_INT.vel*0.01*cos(radians(GPS_RAW_INT.cog*0.01)), GPS_RAW_INT.vel*0.01*sin(radians(GPS_RAW_INT.cog*0.01)), 0)
return GPS velocity vector in body frame
def gps_velocity_body(GPS_RAW_INT, ATTITUDE): '''return GPS velocity vector in body frame''' r = rotation(ATTITUDE) return r.transposed() * Vector3(GPS_RAW_INT.vel*0.01*cos(radians(GPS_RAW_INT.cog*0.01)), GPS_RAW_INT.vel*0.01*sin(radians(GPS_RAW_INT.cog*0.01)), -tan(ATTITUDE.pitch)*GPS_RAW_INT.vel*0.01)
return earth frame acceleration vector
def earth_accel(RAW_IMU,ATTITUDE): '''return earth frame acceleration vector''' r = rotation(ATTITUDE) accel = Vector3(RAW_IMU.xacc, RAW_IMU.yacc, RAW_IMU.zacc) * 9.81 * 0.001 return r * accel
return earth frame gyro vector
def earth_gyro(RAW_IMU,ATTITUDE): '''return earth frame gyro vector''' r = rotation(ATTITUDE) accel = Vector3(degrees(RAW_IMU.xgyro), degrees(RAW_IMU.ygyro), degrees(RAW_IMU.zgyro)) * 0.001 return r * accel
return airspeed energy error matching APM internals This is positive when we are going too slow
def airspeed_energy_error(NAV_CONTROLLER_OUTPUT, VFR_HUD): '''return airspeed energy error matching APM internals This is positive when we are going too slow ''' aspeed_cm = VFR_HUD.airspeed*100 target_airspeed = NAV_CONTROLLER_OUTPUT.aspd_error + aspeed_cm airspeed_energy_error = ((target_airspeed*target_airspeed) - (aspeed_cm*aspeed_cm))*0.00005 return airspeed_energy_error
return energy error matching APM internals This is positive when we are too low or going too slow
def energy_error(NAV_CONTROLLER_OUTPUT, VFR_HUD): '''return energy error matching APM internals This is positive when we are too low or going too slow ''' aspeed_energy_error = airspeed_energy_error(NAV_CONTROLLER_OUTPUT, VFR_HUD) alt_error = NAV_CONTROLLER_OUTPUT.alt_error*100 energy_error = aspeed_energy_error + alt_error*0.098 return energy_error
return yaw rate in degrees/second given steering_angle and speed
def rover_yaw_rate(VFR_HUD, SERVO_OUTPUT_RAW): '''return yaw rate in degrees/second given steering_angle and speed''' max_wheel_turn=35 speed = VFR_HUD.groundspeed # assume 1100 to 1900 PWM on steering steering_angle = max_wheel_turn * (SERVO_OUTPUT_RAW.servo1_raw - 1500) / 400.0 if abs(steering_angle) < 1.0e-6 or abs(speed) < 1.0e-6: return 0 d = rover_turn_circle(SERVO_OUTPUT_RAW) c = pi * d t = c / speed rate = 360.0 / t return rate
return turning circle (diameter) in meters for steering_angle in degrees
def rover_turn_circle(SERVO_OUTPUT_RAW): '''return turning circle (diameter) in meters for steering_angle in degrees ''' # this matches Toms slash max_wheel_turn = 35 wheelbase = 0.335 wheeltrack = 0.296 steering_angle = max_wheel_turn * (SERVO_OUTPUT_RAW.servo1_raw - 1500) / 400.0 theta = radians(steering_angle) return (wheeltrack/2) + (wheelbase/sin(theta))
return lateral acceleration in m/s/s
def rover_lat_accel(VFR_HUD, SERVO_OUTPUT_RAW): '''return lateral acceleration in m/s/s''' speed = VFR_HUD.groundspeed yaw_rate = rover_yaw_rate(VFR_HUD, SERVO_OUTPUT_RAW) accel = radians(yaw_rate) * speed return accel
de-mix a mixed servo output
def demix1(servo1, servo2, gain=0.5): '''de-mix a mixed servo output''' s1 = servo1 - 1500 s2 = servo2 - 1500 out1 = (s1+s2)*gain out2 = (s1-s2)*gain return out1+1500
de-mix a mixed servo output
def demix2(servo1, servo2, gain=0.5): '''de-mix a mixed servo output''' s1 = servo1 - 1500 s2 = servo2 - 1500 out1 = (s1+s2)*gain out2 = (s1-s2)*gain return out2+1500
mix two servos
def mixer(servo1, servo2, mixtype=1, gain=0.5): '''mix two servos''' s1 = servo1 - 1500 s2 = servo2 - 1500 v1 = (s1-s2)*gain v2 = (s1+s2)*gain if mixtype == 2: v2 = -v2 elif mixtype == 3: v1 = -v1 elif mixtype == 4: v1 = -v1 v2 = -v2 if v1 > 600: v1 = 600 elif v1 < -600: v1 = -600 if v2 > 600: v2 = 600 elif v2 < -600: v2 = -600 return (1500+v1,1500+v2)
de-mix a mixed servo output
def mix1(servo1, servo2, mixtype=1, gain=0.5): '''de-mix a mixed servo output''' (v1,v2) = mixer(servo1, servo2, mixtype=mixtype, gain=gain) return v1
de-mix a mixed servo output
def mix2(servo1, servo2, mixtype=1, gain=0.5): '''de-mix a mixed servo output''' (v1,v2) = mixer(servo1, servo2, mixtype=mixtype, gain=gain) return v2
implement full DCM system
def DCM_update(IMU, ATT, MAG, GPS): '''implement full DCM system''' global dcm_state if dcm_state is None: dcm_state = DCM_State(ATT.Roll, ATT.Pitch, ATT.Yaw) mag = Vector3(MAG.MagX, MAG.MagY, MAG.MagZ) gyro = Vector3(IMU.GyrX, IMU.GyrY, IMU.GyrZ) accel = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) accel2 = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) dcm_state.update(gyro, accel, mag, GPS) return dcm_state
implement full DCM using PX4 native SD log data
def PX4_update(IMU, ATT): '''implement full DCM using PX4 native SD log data''' global px4_state if px4_state is None: px4_state = PX4_State(degrees(ATT.Roll), degrees(ATT.Pitch), degrees(ATT.Yaw), IMU._timestamp) gyro = Vector3(IMU.GyroX, IMU.GyroY, IMU.GyroZ) accel = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) px4_state.update(gyro, accel, IMU._timestamp) return px4_state
return 1 if armed, 0 if not
def armed(HEARTBEAT): '''return 1 if armed, 0 if not''' from . import mavutil if HEARTBEAT.type == mavutil.mavlink.MAV_TYPE_GCS: self = mavutil.mavfile_global if self.motors_armed(): return 1 return 0 if HEARTBEAT.base_mode & mavutil.mavlink.MAV_MODE_FLAG_SAFETY_ARMED: return 1 return 0
return the current DCM rotation matrix
def rotation_df(ATT): '''return the current DCM rotation matrix''' r = Matrix3() r.from_euler(radians(ATT.Roll), radians(ATT.Pitch), radians(ATT.Yaw)) return r
return the current DCM rotation matrix
def rotation2(AHRS2): '''return the current DCM rotation matrix''' r = Matrix3() r.from_euler(AHRS2.roll, AHRS2.pitch, AHRS2.yaw) return r
return earth frame acceleration vector from AHRS2
def earth_accel2(RAW_IMU,ATTITUDE): '''return earth frame acceleration vector from AHRS2''' r = rotation2(ATTITUDE) accel = Vector3(RAW_IMU.xacc, RAW_IMU.yacc, RAW_IMU.zacc) * 9.81 * 0.001 return r * accel
return earth frame acceleration vector from df log
def earth_accel_df(IMU,ATT): '''return earth frame acceleration vector from df log''' r = rotation_df(ATT) accel = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) return r * accel
return earth frame acceleration vector from df log
def earth_accel2_df(IMU,IMU2,ATT): '''return earth frame acceleration vector from df log''' r = rotation_df(ATT) accel1 = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) accel2 = Vector3(IMU2.AccX, IMU2.AccY, IMU2.AccZ) accel = 0.5 * (accel1 + accel2) return r * accel
return GPS velocity vector
def gps_velocity_df(GPS): '''return GPS velocity vector''' vx = GPS.Spd * cos(radians(GPS.GCrs)) vy = GPS.Spd * sin(radians(GPS.GCrs)) return Vector3(vx, vy, GPS.VZ)
distance between two points
def distance_gps2(GPS, GPS2): '''distance between two points''' if GPS.TimeMS != GPS2.TimeMS: # reject messages not time aligned return None return distance_two(GPS, GPS2)
calculate EKF position when EKF disabled
def ekf1_pos(EKF1): '''calculate EKF position when EKF disabled''' global ekf_home from . import mavutil self = mavutil.mavfile_global if ekf_home is None: if not 'GPS' in self.messages or self.messages['GPS'].Status != 3: return None ekf_home = self.messages['GPS'] (ekf_home.Lat, ekf_home.Lng) = gps_offset(ekf_home.Lat, ekf_home.Lng, -EKF1.PE, -EKF1.PN) (lat,lon) = gps_offset(ekf_home.Lat, ekf_home.Lng, EKF1.PE, EKF1.PN) return (lat, lon)
Returns rotated quaternion :param attitude: quaternion [w, x, y , z] :param roll: rotation in rad :param pitch: rotation in rad :param yaw: rotation in rad :returns: quaternion [w, x, y , z]
def rotate_quat(attitude, roll, pitch, yaw): ''' Returns rotated quaternion :param attitude: quaternion [w, x, y , z] :param roll: rotation in rad :param pitch: rotation in rad :param yaw: rotation in rad :returns: quaternion [w, x, y , z] ''' quat = Quaternion(attitude) rotation = Quaternion([roll, pitch, yaw]) res = rotation * quat return res.q
take off
def cmd_takeoff(self, args): '''take off''' if ( len(args) != 1): print("Usage: takeoff ALTITUDE_IN_METERS") return if (len(args) == 1): altitude = float(args[0]) print("Take Off started") self.master.mav.command_long_send( self.settings.target_system, # target_system mavutil.mavlink.MAV_COMP_ID_SYSTEM_CONTROL, # target_component mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, # command 0, # confirmation 0, # param1 0, # param2 0, # param3 0, # param4 0, # param5 0, # param6 altitude)
parachute control
def cmd_parachute(self, args): '''parachute control''' usage = "Usage: parachute <enable|disable|release>" if len(args) != 1: print(usage) return cmds = { 'enable' : mavutil.mavlink.PARACHUTE_ENABLE, 'disable' : mavutil.mavlink.PARACHUTE_DISABLE, 'release' : mavutil.mavlink.PARACHUTE_RELEASE } if not args[0] in cmds: print(usage) return cmd = cmds[args[0]] self.master.mav.command_long_send( self.settings.target_system, # target_system 0, # target_component mavutil.mavlink.MAV_CMD_DO_PARACHUTE, 0, cmd, 0, 0, 0, 0, 0, 0)