INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
Send a block of log data to remote location
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seqno : log data block sequence number (uint32_t)
data : log data block (uint8_t)
|
def remote_log_data_block_encode(self, target_system, target_component, seqno, data):
'''
Send a block of log data to remote location
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seqno : log data block sequence number (uint32_t)
data : log data block (uint8_t)
'''
return MAVLink_remote_log_data_block_message(target_system, target_component, seqno, data)
|
Send a block of log data to remote location
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seqno : log data block sequence number (uint32_t)
data : log data block (uint8_t)
|
def remote_log_data_block_send(self, target_system, target_component, seqno, data, force_mavlink1=False):
'''
Send a block of log data to remote location
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seqno : log data block sequence number (uint32_t)
data : log data block (uint8_t)
'''
return self.send(self.remote_log_data_block_encode(target_system, target_component, seqno, data), force_mavlink1=force_mavlink1)
|
Send Status of each log block that autopilot board might have sent
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seqno : log data block sequence number (uint32_t)
status : log data block status (uint8_t)
|
def remote_log_block_status_encode(self, target_system, target_component, seqno, status):
'''
Send Status of each log block that autopilot board might have sent
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seqno : log data block sequence number (uint32_t)
status : log data block status (uint8_t)
'''
return MAVLink_remote_log_block_status_message(target_system, target_component, seqno, status)
|
Send Status of each log block that autopilot board might have sent
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seqno : log data block sequence number (uint32_t)
status : log data block status (uint8_t)
|
def remote_log_block_status_send(self, target_system, target_component, seqno, status, force_mavlink1=False):
'''
Send Status of each log block that autopilot board might have sent
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seqno : log data block sequence number (uint32_t)
status : log data block status (uint8_t)
'''
return self.send(self.remote_log_block_status_encode(target_system, target_component, seqno, status), force_mavlink1=force_mavlink1)
|
Control vehicle LEDs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
instance : Instance (LED instance to control or 255 for all LEDs) (uint8_t)
pattern : Pattern (see LED_PATTERN_ENUM) (uint8_t)
custom_len : Custom Byte Length (uint8_t)
custom_bytes : Custom Bytes (uint8_t)
|
def led_control_encode(self, target_system, target_component, instance, pattern, custom_len, custom_bytes):
'''
Control vehicle LEDs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
instance : Instance (LED instance to control or 255 for all LEDs) (uint8_t)
pattern : Pattern (see LED_PATTERN_ENUM) (uint8_t)
custom_len : Custom Byte Length (uint8_t)
custom_bytes : Custom Bytes (uint8_t)
'''
return MAVLink_led_control_message(target_system, target_component, instance, pattern, custom_len, custom_bytes)
|
Control vehicle LEDs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
instance : Instance (LED instance to control or 255 for all LEDs) (uint8_t)
pattern : Pattern (see LED_PATTERN_ENUM) (uint8_t)
custom_len : Custom Byte Length (uint8_t)
custom_bytes : Custom Bytes (uint8_t)
|
def led_control_send(self, target_system, target_component, instance, pattern, custom_len, custom_bytes, force_mavlink1=False):
'''
Control vehicle LEDs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
instance : Instance (LED instance to control or 255 for all LEDs) (uint8_t)
pattern : Pattern (see LED_PATTERN_ENUM) (uint8_t)
custom_len : Custom Byte Length (uint8_t)
custom_bytes : Custom Bytes (uint8_t)
'''
return self.send(self.led_control_encode(target_system, target_component, instance, pattern, custom_len, custom_bytes), force_mavlink1=force_mavlink1)
|
Reports progress of compass calibration.
compass_id : Compass being calibrated (uint8_t)
cal_mask : Bitmask of compasses being calibrated (uint8_t)
cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t)
attempt : Attempt number (uint8_t)
completion_pct : Completion percentage (uint8_t)
completion_mask : Bitmask of sphere sections (see http://en.wikipedia.org/wiki/Geodesic_grid) (uint8_t)
direction_x : Body frame direction vector for display (float)
direction_y : Body frame direction vector for display (float)
direction_z : Body frame direction vector for display (float)
|
def mag_cal_progress_encode(self, compass_id, cal_mask, cal_status, attempt, completion_pct, completion_mask, direction_x, direction_y, direction_z):
'''
Reports progress of compass calibration.
compass_id : Compass being calibrated (uint8_t)
cal_mask : Bitmask of compasses being calibrated (uint8_t)
cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t)
attempt : Attempt number (uint8_t)
completion_pct : Completion percentage (uint8_t)
completion_mask : Bitmask of sphere sections (see http://en.wikipedia.org/wiki/Geodesic_grid) (uint8_t)
direction_x : Body frame direction vector for display (float)
direction_y : Body frame direction vector for display (float)
direction_z : Body frame direction vector for display (float)
'''
return MAVLink_mag_cal_progress_message(compass_id, cal_mask, cal_status, attempt, completion_pct, completion_mask, direction_x, direction_y, direction_z)
|
Reports progress of compass calibration.
compass_id : Compass being calibrated (uint8_t)
cal_mask : Bitmask of compasses being calibrated (uint8_t)
cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t)
attempt : Attempt number (uint8_t)
completion_pct : Completion percentage (uint8_t)
completion_mask : Bitmask of sphere sections (see http://en.wikipedia.org/wiki/Geodesic_grid) (uint8_t)
direction_x : Body frame direction vector for display (float)
direction_y : Body frame direction vector for display (float)
direction_z : Body frame direction vector for display (float)
|
def mag_cal_progress_send(self, compass_id, cal_mask, cal_status, attempt, completion_pct, completion_mask, direction_x, direction_y, direction_z, force_mavlink1=False):
'''
Reports progress of compass calibration.
compass_id : Compass being calibrated (uint8_t)
cal_mask : Bitmask of compasses being calibrated (uint8_t)
cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t)
attempt : Attempt number (uint8_t)
completion_pct : Completion percentage (uint8_t)
completion_mask : Bitmask of sphere sections (see http://en.wikipedia.org/wiki/Geodesic_grid) (uint8_t)
direction_x : Body frame direction vector for display (float)
direction_y : Body frame direction vector for display (float)
direction_z : Body frame direction vector for display (float)
'''
return self.send(self.mag_cal_progress_encode(compass_id, cal_mask, cal_status, attempt, completion_pct, completion_mask, direction_x, direction_y, direction_z), force_mavlink1=force_mavlink1)
|
Reports results of completed compass calibration. Sent until
MAG_CAL_ACK received.
compass_id : Compass being calibrated (uint8_t)
cal_mask : Bitmask of compasses being calibrated (uint8_t)
cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t)
autosaved : 0=requires a MAV_CMD_DO_ACCEPT_MAG_CAL, 1=saved to parameters (uint8_t)
fitness : RMS milligauss residuals (float)
ofs_x : X offset (float)
ofs_y : Y offset (float)
ofs_z : Z offset (float)
diag_x : X diagonal (matrix 11) (float)
diag_y : Y diagonal (matrix 22) (float)
diag_z : Z diagonal (matrix 33) (float)
offdiag_x : X off-diagonal (matrix 12 and 21) (float)
offdiag_y : Y off-diagonal (matrix 13 and 31) (float)
offdiag_z : Z off-diagonal (matrix 32 and 23) (float)
|
def mag_cal_report_encode(self, compass_id, cal_mask, cal_status, autosaved, fitness, ofs_x, ofs_y, ofs_z, diag_x, diag_y, diag_z, offdiag_x, offdiag_y, offdiag_z):
'''
Reports results of completed compass calibration. Sent until
MAG_CAL_ACK received.
compass_id : Compass being calibrated (uint8_t)
cal_mask : Bitmask of compasses being calibrated (uint8_t)
cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t)
autosaved : 0=requires a MAV_CMD_DO_ACCEPT_MAG_CAL, 1=saved to parameters (uint8_t)
fitness : RMS milligauss residuals (float)
ofs_x : X offset (float)
ofs_y : Y offset (float)
ofs_z : Z offset (float)
diag_x : X diagonal (matrix 11) (float)
diag_y : Y diagonal (matrix 22) (float)
diag_z : Z diagonal (matrix 33) (float)
offdiag_x : X off-diagonal (matrix 12 and 21) (float)
offdiag_y : Y off-diagonal (matrix 13 and 31) (float)
offdiag_z : Z off-diagonal (matrix 32 and 23) (float)
'''
return MAVLink_mag_cal_report_message(compass_id, cal_mask, cal_status, autosaved, fitness, ofs_x, ofs_y, ofs_z, diag_x, diag_y, diag_z, offdiag_x, offdiag_y, offdiag_z)
|
Reports results of completed compass calibration. Sent until
MAG_CAL_ACK received.
compass_id : Compass being calibrated (uint8_t)
cal_mask : Bitmask of compasses being calibrated (uint8_t)
cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t)
autosaved : 0=requires a MAV_CMD_DO_ACCEPT_MAG_CAL, 1=saved to parameters (uint8_t)
fitness : RMS milligauss residuals (float)
ofs_x : X offset (float)
ofs_y : Y offset (float)
ofs_z : Z offset (float)
diag_x : X diagonal (matrix 11) (float)
diag_y : Y diagonal (matrix 22) (float)
diag_z : Z diagonal (matrix 33) (float)
offdiag_x : X off-diagonal (matrix 12 and 21) (float)
offdiag_y : Y off-diagonal (matrix 13 and 31) (float)
offdiag_z : Z off-diagonal (matrix 32 and 23) (float)
|
def mag_cal_report_send(self, compass_id, cal_mask, cal_status, autosaved, fitness, ofs_x, ofs_y, ofs_z, diag_x, diag_y, diag_z, offdiag_x, offdiag_y, offdiag_z, force_mavlink1=False):
'''
Reports results of completed compass calibration. Sent until
MAG_CAL_ACK received.
compass_id : Compass being calibrated (uint8_t)
cal_mask : Bitmask of compasses being calibrated (uint8_t)
cal_status : Status (see MAG_CAL_STATUS enum) (uint8_t)
autosaved : 0=requires a MAV_CMD_DO_ACCEPT_MAG_CAL, 1=saved to parameters (uint8_t)
fitness : RMS milligauss residuals (float)
ofs_x : X offset (float)
ofs_y : Y offset (float)
ofs_z : Z offset (float)
diag_x : X diagonal (matrix 11) (float)
diag_y : Y diagonal (matrix 22) (float)
diag_z : Z diagonal (matrix 33) (float)
offdiag_x : X off-diagonal (matrix 12 and 21) (float)
offdiag_y : Y off-diagonal (matrix 13 and 31) (float)
offdiag_z : Z off-diagonal (matrix 32 and 23) (float)
'''
return self.send(self.mag_cal_report_encode(compass_id, cal_mask, cal_status, autosaved, fitness, ofs_x, ofs_y, ofs_z, diag_x, diag_y, diag_z, offdiag_x, offdiag_y, offdiag_z), force_mavlink1=force_mavlink1)
|
EKF Status message including flags and variances
flags : Flags (uint16_t)
velocity_variance : Velocity variance (float)
pos_horiz_variance : Horizontal Position variance (float)
pos_vert_variance : Vertical Position variance (float)
compass_variance : Compass variance (float)
terrain_alt_variance : Terrain Altitude variance (float)
|
def ekf_status_report_encode(self, flags, velocity_variance, pos_horiz_variance, pos_vert_variance, compass_variance, terrain_alt_variance):
'''
EKF Status message including flags and variances
flags : Flags (uint16_t)
velocity_variance : Velocity variance (float)
pos_horiz_variance : Horizontal Position variance (float)
pos_vert_variance : Vertical Position variance (float)
compass_variance : Compass variance (float)
terrain_alt_variance : Terrain Altitude variance (float)
'''
return MAVLink_ekf_status_report_message(flags, velocity_variance, pos_horiz_variance, pos_vert_variance, compass_variance, terrain_alt_variance)
|
EKF Status message including flags and variances
flags : Flags (uint16_t)
velocity_variance : Velocity variance (float)
pos_horiz_variance : Horizontal Position variance (float)
pos_vert_variance : Vertical Position variance (float)
compass_variance : Compass variance (float)
terrain_alt_variance : Terrain Altitude variance (float)
|
def ekf_status_report_send(self, flags, velocity_variance, pos_horiz_variance, pos_vert_variance, compass_variance, terrain_alt_variance, force_mavlink1=False):
'''
EKF Status message including flags and variances
flags : Flags (uint16_t)
velocity_variance : Velocity variance (float)
pos_horiz_variance : Horizontal Position variance (float)
pos_vert_variance : Vertical Position variance (float)
compass_variance : Compass variance (float)
terrain_alt_variance : Terrain Altitude variance (float)
'''
return self.send(self.ekf_status_report_encode(flags, velocity_variance, pos_horiz_variance, pos_vert_variance, compass_variance, terrain_alt_variance), force_mavlink1=force_mavlink1)
|
PID tuning information
axis : axis (uint8_t)
desired : desired rate (degrees/s) (float)
achieved : achieved rate (degrees/s) (float)
FF : FF component (float)
P : P component (float)
I : I component (float)
D : D component (float)
|
def pid_tuning_encode(self, axis, desired, achieved, FF, P, I, D):
'''
PID tuning information
axis : axis (uint8_t)
desired : desired rate (degrees/s) (float)
achieved : achieved rate (degrees/s) (float)
FF : FF component (float)
P : P component (float)
I : I component (float)
D : D component (float)
'''
return MAVLink_pid_tuning_message(axis, desired, achieved, FF, P, I, D)
|
PID tuning information
axis : axis (uint8_t)
desired : desired rate (degrees/s) (float)
achieved : achieved rate (degrees/s) (float)
FF : FF component (float)
P : P component (float)
I : I component (float)
D : D component (float)
|
def pid_tuning_send(self, axis, desired, achieved, FF, P, I, D, force_mavlink1=False):
'''
PID tuning information
axis : axis (uint8_t)
desired : desired rate (degrees/s) (float)
achieved : achieved rate (degrees/s) (float)
FF : FF component (float)
P : P component (float)
I : I component (float)
D : D component (float)
'''
return self.send(self.pid_tuning_encode(axis, desired, achieved, FF, P, I, D), force_mavlink1=force_mavlink1)
|
3 axis gimbal mesuraments
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
delta_time : Time since last update (seconds) (float)
delta_angle_x : Delta angle X (radians) (float)
delta_angle_y : Delta angle Y (radians) (float)
delta_angle_z : Delta angle X (radians) (float)
delta_velocity_x : Delta velocity X (m/s) (float)
delta_velocity_y : Delta velocity Y (m/s) (float)
delta_velocity_z : Delta velocity Z (m/s) (float)
joint_roll : Joint ROLL (radians) (float)
joint_el : Joint EL (radians) (float)
joint_az : Joint AZ (radians) (float)
|
def gimbal_report_encode(self, target_system, target_component, delta_time, delta_angle_x, delta_angle_y, delta_angle_z, delta_velocity_x, delta_velocity_y, delta_velocity_z, joint_roll, joint_el, joint_az):
'''
3 axis gimbal mesuraments
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
delta_time : Time since last update (seconds) (float)
delta_angle_x : Delta angle X (radians) (float)
delta_angle_y : Delta angle Y (radians) (float)
delta_angle_z : Delta angle X (radians) (float)
delta_velocity_x : Delta velocity X (m/s) (float)
delta_velocity_y : Delta velocity Y (m/s) (float)
delta_velocity_z : Delta velocity Z (m/s) (float)
joint_roll : Joint ROLL (radians) (float)
joint_el : Joint EL (radians) (float)
joint_az : Joint AZ (radians) (float)
'''
return MAVLink_gimbal_report_message(target_system, target_component, delta_time, delta_angle_x, delta_angle_y, delta_angle_z, delta_velocity_x, delta_velocity_y, delta_velocity_z, joint_roll, joint_el, joint_az)
|
3 axis gimbal mesuraments
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
delta_time : Time since last update (seconds) (float)
delta_angle_x : Delta angle X (radians) (float)
delta_angle_y : Delta angle Y (radians) (float)
delta_angle_z : Delta angle X (radians) (float)
delta_velocity_x : Delta velocity X (m/s) (float)
delta_velocity_y : Delta velocity Y (m/s) (float)
delta_velocity_z : Delta velocity Z (m/s) (float)
joint_roll : Joint ROLL (radians) (float)
joint_el : Joint EL (radians) (float)
joint_az : Joint AZ (radians) (float)
|
def gimbal_report_send(self, target_system, target_component, delta_time, delta_angle_x, delta_angle_y, delta_angle_z, delta_velocity_x, delta_velocity_y, delta_velocity_z, joint_roll, joint_el, joint_az, force_mavlink1=False):
'''
3 axis gimbal mesuraments
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
delta_time : Time since last update (seconds) (float)
delta_angle_x : Delta angle X (radians) (float)
delta_angle_y : Delta angle Y (radians) (float)
delta_angle_z : Delta angle X (radians) (float)
delta_velocity_x : Delta velocity X (m/s) (float)
delta_velocity_y : Delta velocity Y (m/s) (float)
delta_velocity_z : Delta velocity Z (m/s) (float)
joint_roll : Joint ROLL (radians) (float)
joint_el : Joint EL (radians) (float)
joint_az : Joint AZ (radians) (float)
'''
return self.send(self.gimbal_report_encode(target_system, target_component, delta_time, delta_angle_x, delta_angle_y, delta_angle_z, delta_velocity_x, delta_velocity_y, delta_velocity_z, joint_roll, joint_el, joint_az), force_mavlink1=force_mavlink1)
|
Control message for rate gimbal
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
demanded_rate_x : Demanded angular rate X (rad/s) (float)
demanded_rate_y : Demanded angular rate Y (rad/s) (float)
demanded_rate_z : Demanded angular rate Z (rad/s) (float)
|
def gimbal_control_encode(self, target_system, target_component, demanded_rate_x, demanded_rate_y, demanded_rate_z):
'''
Control message for rate gimbal
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
demanded_rate_x : Demanded angular rate X (rad/s) (float)
demanded_rate_y : Demanded angular rate Y (rad/s) (float)
demanded_rate_z : Demanded angular rate Z (rad/s) (float)
'''
return MAVLink_gimbal_control_message(target_system, target_component, demanded_rate_x, demanded_rate_y, demanded_rate_z)
|
Control message for rate gimbal
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
demanded_rate_x : Demanded angular rate X (rad/s) (float)
demanded_rate_y : Demanded angular rate Y (rad/s) (float)
demanded_rate_z : Demanded angular rate Z (rad/s) (float)
|
def gimbal_control_send(self, target_system, target_component, demanded_rate_x, demanded_rate_y, demanded_rate_z, force_mavlink1=False):
'''
Control message for rate gimbal
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
demanded_rate_x : Demanded angular rate X (rad/s) (float)
demanded_rate_y : Demanded angular rate Y (rad/s) (float)
demanded_rate_z : Demanded angular rate Z (rad/s) (float)
'''
return self.send(self.gimbal_control_encode(target_system, target_component, demanded_rate_x, demanded_rate_y, demanded_rate_z), force_mavlink1=force_mavlink1)
|
100 Hz gimbal torque command telemetry
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
rl_torque_cmd : Roll Torque Command (int16_t)
el_torque_cmd : Elevation Torque Command (int16_t)
az_torque_cmd : Azimuth Torque Command (int16_t)
|
def gimbal_torque_cmd_report_encode(self, target_system, target_component, rl_torque_cmd, el_torque_cmd, az_torque_cmd):
'''
100 Hz gimbal torque command telemetry
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
rl_torque_cmd : Roll Torque Command (int16_t)
el_torque_cmd : Elevation Torque Command (int16_t)
az_torque_cmd : Azimuth Torque Command (int16_t)
'''
return MAVLink_gimbal_torque_cmd_report_message(target_system, target_component, rl_torque_cmd, el_torque_cmd, az_torque_cmd)
|
100 Hz gimbal torque command telemetry
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
rl_torque_cmd : Roll Torque Command (int16_t)
el_torque_cmd : Elevation Torque Command (int16_t)
az_torque_cmd : Azimuth Torque Command (int16_t)
|
def gimbal_torque_cmd_report_send(self, target_system, target_component, rl_torque_cmd, el_torque_cmd, az_torque_cmd, force_mavlink1=False):
'''
100 Hz gimbal torque command telemetry
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
rl_torque_cmd : Roll Torque Command (int16_t)
el_torque_cmd : Elevation Torque Command (int16_t)
az_torque_cmd : Azimuth Torque Command (int16_t)
'''
return self.send(self.gimbal_torque_cmd_report_encode(target_system, target_component, rl_torque_cmd, el_torque_cmd, az_torque_cmd), force_mavlink1=force_mavlink1)
|
Heartbeat from a HeroBus attached GoPro
status : Status (uint8_t)
capture_mode : Current capture mode (uint8_t)
flags : additional status bits (uint8_t)
|
def gopro_heartbeat_send(self, status, capture_mode, flags, force_mavlink1=False):
'''
Heartbeat from a HeroBus attached GoPro
status : Status (uint8_t)
capture_mode : Current capture mode (uint8_t)
flags : additional status bits (uint8_t)
'''
return self.send(self.gopro_heartbeat_encode(status, capture_mode, flags), force_mavlink1=force_mavlink1)
|
Request a GOPRO_COMMAND response from the GoPro
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
cmd_id : Command ID (uint8_t)
|
def gopro_get_request_send(self, target_system, target_component, cmd_id, force_mavlink1=False):
'''
Request a GOPRO_COMMAND response from the GoPro
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
cmd_id : Command ID (uint8_t)
'''
return self.send(self.gopro_get_request_encode(target_system, target_component, cmd_id), force_mavlink1=force_mavlink1)
|
Response from a GOPRO_COMMAND get request
cmd_id : Command ID (uint8_t)
status : Status (uint8_t)
value : Value (uint8_t)
|
def gopro_get_response_send(self, cmd_id, status, value, force_mavlink1=False):
'''
Response from a GOPRO_COMMAND get request
cmd_id : Command ID (uint8_t)
status : Status (uint8_t)
value : Value (uint8_t)
'''
return self.send(self.gopro_get_response_encode(cmd_id, status, value), force_mavlink1=force_mavlink1)
|
Request to set a GOPRO_COMMAND with a desired
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
cmd_id : Command ID (uint8_t)
value : Value (uint8_t)
|
def gopro_set_request_encode(self, target_system, target_component, cmd_id, value):
'''
Request to set a GOPRO_COMMAND with a desired
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
cmd_id : Command ID (uint8_t)
value : Value (uint8_t)
'''
return MAVLink_gopro_set_request_message(target_system, target_component, cmd_id, value)
|
Request to set a GOPRO_COMMAND with a desired
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
cmd_id : Command ID (uint8_t)
value : Value (uint8_t)
|
def gopro_set_request_send(self, target_system, target_component, cmd_id, value, force_mavlink1=False):
'''
Request to set a GOPRO_COMMAND with a desired
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
cmd_id : Command ID (uint8_t)
value : Value (uint8_t)
'''
return self.send(self.gopro_set_request_encode(target_system, target_component, cmd_id, value), force_mavlink1=force_mavlink1)
|
Response from a GOPRO_COMMAND set request
cmd_id : Command ID (uint8_t)
status : Status (uint8_t)
|
def gopro_set_response_send(self, cmd_id, status, force_mavlink1=False):
'''
Response from a GOPRO_COMMAND set request
cmd_id : Command ID (uint8_t)
status : Status (uint8_t)
'''
return self.send(self.gopro_set_response_encode(cmd_id, status), force_mavlink1=force_mavlink1)
|
RPM sensor output
rpm1 : RPM Sensor1 (float)
rpm2 : RPM Sensor2 (float)
|
def rpm_send(self, rpm1, rpm2, force_mavlink1=False):
'''
RPM sensor output
rpm1 : RPM Sensor1 (float)
rpm2 : RPM Sensor2 (float)
'''
return self.send(self.rpm_encode(rpm1, rpm2), force_mavlink1=force_mavlink1)
|
Static data to configure the ADS-B transponder (send within 10 sec of
a POR and every 10 sec thereafter)
ICAO : Vehicle address (24 bit) (uint32_t)
callsign : Vehicle identifier (8 characters, null terminated, valid characters are A-Z, 0-9, " " only) (char)
emitterType : Transmitting vehicle type. See ADSB_EMITTER_TYPE enum (uint8_t)
aircraftSize : Aircraft length and width encoding (table 2-35 of DO-282B) (uint8_t)
gpsOffsetLat : GPS antenna lateral offset (table 2-36 of DO-282B) (uint8_t)
gpsOffsetLon : GPS antenna longitudinal offset from nose [if non-zero, take position (in meters) divide by 2 and add one] (table 2-37 DO-282B) (uint8_t)
stallSpeed : Aircraft stall speed in cm/s (uint16_t)
rfSelect : ADS-B transponder reciever and transmit enable flags (uint8_t)
|
def uavionix_adsb_out_cfg_encode(self, ICAO, callsign, emitterType, aircraftSize, gpsOffsetLat, gpsOffsetLon, stallSpeed, rfSelect):
'''
Static data to configure the ADS-B transponder (send within 10 sec of
a POR and every 10 sec thereafter)
ICAO : Vehicle address (24 bit) (uint32_t)
callsign : Vehicle identifier (8 characters, null terminated, valid characters are A-Z, 0-9, " " only) (char)
emitterType : Transmitting vehicle type. See ADSB_EMITTER_TYPE enum (uint8_t)
aircraftSize : Aircraft length and width encoding (table 2-35 of DO-282B) (uint8_t)
gpsOffsetLat : GPS antenna lateral offset (table 2-36 of DO-282B) (uint8_t)
gpsOffsetLon : GPS antenna longitudinal offset from nose [if non-zero, take position (in meters) divide by 2 and add one] (table 2-37 DO-282B) (uint8_t)
stallSpeed : Aircraft stall speed in cm/s (uint16_t)
rfSelect : ADS-B transponder reciever and transmit enable flags (uint8_t)
'''
return MAVLink_uavionix_adsb_out_cfg_message(ICAO, callsign, emitterType, aircraftSize, gpsOffsetLat, gpsOffsetLon, stallSpeed, rfSelect)
|
Static data to configure the ADS-B transponder (send within 10 sec of
a POR and every 10 sec thereafter)
ICAO : Vehicle address (24 bit) (uint32_t)
callsign : Vehicle identifier (8 characters, null terminated, valid characters are A-Z, 0-9, " " only) (char)
emitterType : Transmitting vehicle type. See ADSB_EMITTER_TYPE enum (uint8_t)
aircraftSize : Aircraft length and width encoding (table 2-35 of DO-282B) (uint8_t)
gpsOffsetLat : GPS antenna lateral offset (table 2-36 of DO-282B) (uint8_t)
gpsOffsetLon : GPS antenna longitudinal offset from nose [if non-zero, take position (in meters) divide by 2 and add one] (table 2-37 DO-282B) (uint8_t)
stallSpeed : Aircraft stall speed in cm/s (uint16_t)
rfSelect : ADS-B transponder reciever and transmit enable flags (uint8_t)
|
def uavionix_adsb_out_cfg_send(self, ICAO, callsign, emitterType, aircraftSize, gpsOffsetLat, gpsOffsetLon, stallSpeed, rfSelect, force_mavlink1=False):
'''
Static data to configure the ADS-B transponder (send within 10 sec of
a POR and every 10 sec thereafter)
ICAO : Vehicle address (24 bit) (uint32_t)
callsign : Vehicle identifier (8 characters, null terminated, valid characters are A-Z, 0-9, " " only) (char)
emitterType : Transmitting vehicle type. See ADSB_EMITTER_TYPE enum (uint8_t)
aircraftSize : Aircraft length and width encoding (table 2-35 of DO-282B) (uint8_t)
gpsOffsetLat : GPS antenna lateral offset (table 2-36 of DO-282B) (uint8_t)
gpsOffsetLon : GPS antenna longitudinal offset from nose [if non-zero, take position (in meters) divide by 2 and add one] (table 2-37 DO-282B) (uint8_t)
stallSpeed : Aircraft stall speed in cm/s (uint16_t)
rfSelect : ADS-B transponder reciever and transmit enable flags (uint8_t)
'''
return self.send(self.uavionix_adsb_out_cfg_encode(ICAO, callsign, emitterType, aircraftSize, gpsOffsetLat, gpsOffsetLon, stallSpeed, rfSelect), force_mavlink1=force_mavlink1)
|
Dynamic data used to generate ADS-B out transponder data (send at 5Hz)
utcTime : UTC time in seconds since GPS epoch (Jan 6, 1980). If unknown set to UINT32_MAX (uint32_t)
gpsLat : Latitude WGS84 (deg * 1E7). If unknown set to INT32_MAX (int32_t)
gpsLon : Longitude WGS84 (deg * 1E7). If unknown set to INT32_MAX (int32_t)
gpsAlt : Altitude in mm (m * 1E-3) UP +ve. WGS84 altitude. If unknown set to INT32_MAX (int32_t)
gpsFix : 0-1: no fix, 2: 2D fix, 3: 3D fix, 4: DGPS, 5: RTK (uint8_t)
numSats : Number of satellites visible. If unknown set to UINT8_MAX (uint8_t)
baroAltMSL : Barometric pressure altitude relative to a standard atmosphere of 1013.2 mBar and NOT bar corrected altitude (m * 1E-3). (up +ve). If unknown set to INT32_MAX (int32_t)
accuracyHor : Horizontal accuracy in mm (m * 1E-3). If unknown set to UINT32_MAX (uint32_t)
accuracyVert : Vertical accuracy in cm. If unknown set to UINT16_MAX (uint16_t)
accuracyVel : Velocity accuracy in mm/s (m * 1E-3). If unknown set to UINT16_MAX (uint16_t)
velVert : GPS vertical speed in cm/s. If unknown set to INT16_MAX (int16_t)
velNS : North-South velocity over ground in cm/s North +ve. If unknown set to INT16_MAX (int16_t)
VelEW : East-West velocity over ground in cm/s East +ve. If unknown set to INT16_MAX (int16_t)
emergencyStatus : Emergency status (uint8_t)
state : ADS-B transponder dynamic input state flags (uint16_t)
squawk : Mode A code (typically 1200 [0x04B0] for VFR) (uint16_t)
|
def uavionix_adsb_out_dynamic_encode(self, utcTime, gpsLat, gpsLon, gpsAlt, gpsFix, numSats, baroAltMSL, accuracyHor, accuracyVert, accuracyVel, velVert, velNS, VelEW, emergencyStatus, state, squawk):
'''
Dynamic data used to generate ADS-B out transponder data (send at 5Hz)
utcTime : UTC time in seconds since GPS epoch (Jan 6, 1980). If unknown set to UINT32_MAX (uint32_t)
gpsLat : Latitude WGS84 (deg * 1E7). If unknown set to INT32_MAX (int32_t)
gpsLon : Longitude WGS84 (deg * 1E7). If unknown set to INT32_MAX (int32_t)
gpsAlt : Altitude in mm (m * 1E-3) UP +ve. WGS84 altitude. If unknown set to INT32_MAX (int32_t)
gpsFix : 0-1: no fix, 2: 2D fix, 3: 3D fix, 4: DGPS, 5: RTK (uint8_t)
numSats : Number of satellites visible. If unknown set to UINT8_MAX (uint8_t)
baroAltMSL : Barometric pressure altitude relative to a standard atmosphere of 1013.2 mBar and NOT bar corrected altitude (m * 1E-3). (up +ve). If unknown set to INT32_MAX (int32_t)
accuracyHor : Horizontal accuracy in mm (m * 1E-3). If unknown set to UINT32_MAX (uint32_t)
accuracyVert : Vertical accuracy in cm. If unknown set to UINT16_MAX (uint16_t)
accuracyVel : Velocity accuracy in mm/s (m * 1E-3). If unknown set to UINT16_MAX (uint16_t)
velVert : GPS vertical speed in cm/s. If unknown set to INT16_MAX (int16_t)
velNS : North-South velocity over ground in cm/s North +ve. If unknown set to INT16_MAX (int16_t)
VelEW : East-West velocity over ground in cm/s East +ve. If unknown set to INT16_MAX (int16_t)
emergencyStatus : Emergency status (uint8_t)
state : ADS-B transponder dynamic input state flags (uint16_t)
squawk : Mode A code (typically 1200 [0x04B0] for VFR) (uint16_t)
'''
return MAVLink_uavionix_adsb_out_dynamic_message(utcTime, gpsLat, gpsLon, gpsAlt, gpsFix, numSats, baroAltMSL, accuracyHor, accuracyVert, accuracyVel, velVert, velNS, VelEW, emergencyStatus, state, squawk)
|
Dynamic data used to generate ADS-B out transponder data (send at 5Hz)
utcTime : UTC time in seconds since GPS epoch (Jan 6, 1980). If unknown set to UINT32_MAX (uint32_t)
gpsLat : Latitude WGS84 (deg * 1E7). If unknown set to INT32_MAX (int32_t)
gpsLon : Longitude WGS84 (deg * 1E7). If unknown set to INT32_MAX (int32_t)
gpsAlt : Altitude in mm (m * 1E-3) UP +ve. WGS84 altitude. If unknown set to INT32_MAX (int32_t)
gpsFix : 0-1: no fix, 2: 2D fix, 3: 3D fix, 4: DGPS, 5: RTK (uint8_t)
numSats : Number of satellites visible. If unknown set to UINT8_MAX (uint8_t)
baroAltMSL : Barometric pressure altitude relative to a standard atmosphere of 1013.2 mBar and NOT bar corrected altitude (m * 1E-3). (up +ve). If unknown set to INT32_MAX (int32_t)
accuracyHor : Horizontal accuracy in mm (m * 1E-3). If unknown set to UINT32_MAX (uint32_t)
accuracyVert : Vertical accuracy in cm. If unknown set to UINT16_MAX (uint16_t)
accuracyVel : Velocity accuracy in mm/s (m * 1E-3). If unknown set to UINT16_MAX (uint16_t)
velVert : GPS vertical speed in cm/s. If unknown set to INT16_MAX (int16_t)
velNS : North-South velocity over ground in cm/s North +ve. If unknown set to INT16_MAX (int16_t)
VelEW : East-West velocity over ground in cm/s East +ve. If unknown set to INT16_MAX (int16_t)
emergencyStatus : Emergency status (uint8_t)
state : ADS-B transponder dynamic input state flags (uint16_t)
squawk : Mode A code (typically 1200 [0x04B0] for VFR) (uint16_t)
|
def uavionix_adsb_out_dynamic_send(self, utcTime, gpsLat, gpsLon, gpsAlt, gpsFix, numSats, baroAltMSL, accuracyHor, accuracyVert, accuracyVel, velVert, velNS, VelEW, emergencyStatus, state, squawk, force_mavlink1=False):
'''
Dynamic data used to generate ADS-B out transponder data (send at 5Hz)
utcTime : UTC time in seconds since GPS epoch (Jan 6, 1980). If unknown set to UINT32_MAX (uint32_t)
gpsLat : Latitude WGS84 (deg * 1E7). If unknown set to INT32_MAX (int32_t)
gpsLon : Longitude WGS84 (deg * 1E7). If unknown set to INT32_MAX (int32_t)
gpsAlt : Altitude in mm (m * 1E-3) UP +ve. WGS84 altitude. If unknown set to INT32_MAX (int32_t)
gpsFix : 0-1: no fix, 2: 2D fix, 3: 3D fix, 4: DGPS, 5: RTK (uint8_t)
numSats : Number of satellites visible. If unknown set to UINT8_MAX (uint8_t)
baroAltMSL : Barometric pressure altitude relative to a standard atmosphere of 1013.2 mBar and NOT bar corrected altitude (m * 1E-3). (up +ve). If unknown set to INT32_MAX (int32_t)
accuracyHor : Horizontal accuracy in mm (m * 1E-3). If unknown set to UINT32_MAX (uint32_t)
accuracyVert : Vertical accuracy in cm. If unknown set to UINT16_MAX (uint16_t)
accuracyVel : Velocity accuracy in mm/s (m * 1E-3). If unknown set to UINT16_MAX (uint16_t)
velVert : GPS vertical speed in cm/s. If unknown set to INT16_MAX (int16_t)
velNS : North-South velocity over ground in cm/s North +ve. If unknown set to INT16_MAX (int16_t)
VelEW : East-West velocity over ground in cm/s East +ve. If unknown set to INT16_MAX (int16_t)
emergencyStatus : Emergency status (uint8_t)
state : ADS-B transponder dynamic input state flags (uint16_t)
squawk : Mode A code (typically 1200 [0x04B0] for VFR) (uint16_t)
'''
return self.send(self.uavionix_adsb_out_dynamic_encode(utcTime, gpsLat, gpsLon, gpsAlt, gpsFix, numSats, baroAltMSL, accuracyHor, accuracyVert, accuracyVel, velVert, velNS, VelEW, emergencyStatus, state, squawk), force_mavlink1=force_mavlink1)
|
Transceiver heartbeat with health report (updated every 10s)
rfHealth : ADS-B transponder messages (uint8_t)
|
def uavionix_adsb_transceiver_health_report_send(self, rfHealth, force_mavlink1=False):
'''
Transceiver heartbeat with health report (updated every 10s)
rfHealth : ADS-B transponder messages (uint8_t)
'''
return self.send(self.uavionix_adsb_transceiver_health_report_encode(rfHealth), force_mavlink1=force_mavlink1)
|
convert a value from one set of units to another
|
def convert(self, value, fromunits, tounits):
'''convert a value from one set of units to another'''
if fromunits == tounits:
return value
if (fromunits,tounits) in self.unitmap:
return value * self.unitmap[(fromunits,tounits)]
if (tounits,fromunits) in self.unitmap:
return value / self.unitmap[(tounits,fromunits)]
raise fgFDMError("unknown unit mapping (%s,%s)" % (fromunits, tounits))
|
return the default units of a variable
|
def units(self, varname):
'''return the default units of a variable'''
if not varname in self.mapping.vars:
raise fgFDMError('Unknown variable %s' % varname)
return self.mapping.vars[varname].units
|
return a list of available variables
|
def variables(self):
'''return a list of available variables'''
return sorted(list(self.mapping.vars.keys()),
key = lambda v : self.mapping.vars[v].index)
|
get a variable value
|
def get(self, varname, idx=0, units=None):
'''get a variable value'''
if not varname in self.mapping.vars:
raise fgFDMError('Unknown variable %s' % varname)
if idx >= self.mapping.vars[varname].arraylength:
raise fgFDMError('index of %s beyond end of array idx=%u arraylength=%u' % (
varname, idx, self.mapping.vars[varname].arraylength))
value = self.values[self.mapping.vars[varname].index + idx]
if units:
value = self.convert(value, self.mapping.vars[varname].units, units)
return value
|
set a variable value
|
def set(self, varname, value, idx=0, units=None):
'''set a variable value'''
if not varname in self.mapping.vars:
raise fgFDMError('Unknown variable %s' % varname)
if idx >= self.mapping.vars[varname].arraylength:
raise fgFDMError('index of %s beyond end of array idx=%u arraylength=%u' % (
varname, idx, self.mapping.vars[varname].arraylength))
if units:
value = self.convert(value, units, self.mapping.vars[varname].units)
# avoid range errors when packing into 4 byte floats
if math.isinf(value) or math.isnan(value) or math.fabs(value) > 3.4e38:
value = 0
self.values[self.mapping.vars[varname].index + idx] = value
|
parse a FD FDM buffer
|
def parse(self, buf):
'''parse a FD FDM buffer'''
try:
t = struct.unpack(self.pack_string, buf)
except struct.error as msg:
raise fgFDMError('unable to parse - %s' % msg)
self.values = list(t)
|
pack a FD FDM buffer from current values
|
def pack(self):
'''pack a FD FDM buffer from current values'''
for i in range(len(self.values)):
if math.isnan(self.values[i]):
self.values[i] = 0
return struct.pack(self.pack_string, *self.values)
|
Translates from Quaternion to Yaw.
@param qw,qx,qy,qz: Quaternion values
@type qw,qx,qy,qz: float
@return Yaw value translated from Quaternion
|
def quat2Yaw(qw, qx, qy, qz):
'''
Translates from Quaternion to Yaw.
@param qw,qx,qy,qz: Quaternion values
@type qw,qx,qy,qz: float
@return Yaw value translated from Quaternion
'''
rotateZa0=2.0*(qx*qy + qw*qz)
rotateZa1=qw*qw + qx*qx - qy*qy - qz*qz
rotateZ=0.0
if(rotateZa0 != 0.0 and rotateZa1 != 0.0):
rotateZ=atan2(rotateZa0,rotateZa1)
return rotateZ
|
Translates from Quaternion to Pitch.
@param qw,qx,qy,qz: Quaternion values
@type qw,qx,qy,qz: float
@return Pitch value translated from Quaternion
|
def quat2Pitch(qw, qx, qy, qz):
'''
Translates from Quaternion to Pitch.
@param qw,qx,qy,qz: Quaternion values
@type qw,qx,qy,qz: float
@return Pitch value translated from Quaternion
'''
rotateYa0=-2.0*(qx*qz - qw*qy)
rotateY=0.0
if(rotateYa0 >= 1.0):
rotateY = pi/2.0
elif(rotateYa0 <= -1.0):
rotateY = -pi/2.0
else:
rotateY = asin(rotateYa0)
return rotateY
|
Translates from ROS Odometry to JderobotTypes Pose3d.
@param odom: ROS Odometry to translate
@type odom: Odometry
@return a Pose3d translated from odom
|
def odometry2Pose3D(odom):
'''
Translates from ROS Odometry to JderobotTypes Pose3d.
@param odom: ROS Odometry to translate
@type odom: Odometry
@return a Pose3d translated from odom
'''
pose = Pose3d()
ori = odom.pose.pose.orientation
pose.x = odom.pose.pose.position.x
pose.y = odom.pose.pose.position.y
pose.z = odom.pose.pose.position.z
#pose.h = odom.pose.pose.position.h
pose.yaw = quat2Yaw(ori.w, ori.x, ori.y, ori.z)
pose.pitch = quat2Pitch(ori.w, ori.x, ori.y, ori.z)
pose.roll = quat2Roll(ori.w, ori.x, ori.y, ori.z)
pose.q = [ori.w, ori.x, ori.y, ori.z]
pose.timeStamp = odom.header.stamp.secs + (odom.header.stamp.nsecs *1e-9)
return pose
|
Callback function to receive and save Pose3d.
@param odom: ROS Odometry received
@type odom: Odometry
|
def __callback (self, odom):
'''
Callback function to receive and save Pose3d.
@param odom: ROS Odometry received
@type odom: Odometry
'''
pose = odometry2Pose3D(odom)
self.lock.acquire()
self.data = pose
self.lock.release()
|
Starts (Subscribes) the client.
|
def start (self):
'''
Starts (Subscribes) the client.
'''
self.sub = rospy.Subscriber(self.topic, Odometry, self.__callback)
|
clip an area for display on the map
|
def clip(self, px, py, w, h, img):
'''clip an area for display on the map'''
sx = 0
sy = 0
if px < 0:
sx = -px
w += px
px = 0
if py < 0:
sy = -py
h += py
py = 0
if px+w > img.width:
w = img.width - px
if py+h > img.height:
h = img.height - py
return (px, py, sx, sy, w, h)
|
update object position
|
def update_position(self, newpos):
'''update object position'''
if getattr(self, 'trail', None) is not None:
self.trail.update_position(newpos)
self.latlon = newpos.latlon
if hasattr(self, 'rotation'):
self.rotation = newpos.rotation
|
draw a line on the image
|
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
'''draw a line on the image'''
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
clipped = cv.ClipLine((img.width, img.height), pix1, pix2)
if clipped is None:
if len(self._pix_points) == 0:
self._pix_points.append(None)
self._pix_points.append(None)
return
(pix1, pix2) = clipped
cv.Line(img, pix1, pix2, colour, linewidth)
cv.Circle(img, pix2, linewidth*2, colour)
if len(self._pix_points) == 0:
self._pix_points.append(pix1)
self._pix_points.append(pix2)
|
draw a polygon on the image
|
def draw(self, img, pixmapper, bounds):
'''draw a polygon on the image'''
if self.hidden:
return
self._pix_points = []
for i in range(len(self.points)-1):
if len(self.points[i]) > 2:
colour = self.points[i][2]
else:
colour = self.colour
self.draw_line(img, pixmapper, self.points[i], self.points[i+1],
colour, self.linewidth)
|
see if the polygon has been clicked on.
Consider it clicked if the pixel is within 6 of the point
|
def clicked(self, px, py):
'''see if the polygon has been clicked on.
Consider it clicked if the pixel is within 6 of the point
'''
if self.hidden:
return None
for i in range(len(self._pix_points)):
if self._pix_points[i] is None:
continue
(pixx,pixy) = self._pix_points[i]
if abs(px - pixx) < 6 and abs(py - pixy) < 6:
self._selected_vertex = i
return math.sqrt((px - pixx)**2 + (py - pixy)**2)
return None
|
draw a line on the image
|
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
'''draw a line on the image'''
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
clipped = cv.ClipLine((img.width, img.height), pix1, pix2)
if clipped is None:
return
(pix1, pix2) = clipped
cv.Line(img, pix1, pix2, colour, linewidth)
cv.Circle(img, pix2, linewidth*2, colour)
|
draw a polygon on the image
|
def draw(self, img, pixmapper, bounds):
'''draw a polygon on the image'''
if self.hidden:
return
(x,y,w,h) = bounds
spacing = 1000
while True:
start = mp_util.latlon_round((x,y), spacing)
dist = mp_util.gps_distance(x,y,x+w,y+h)
count = int(dist / spacing)
if count < 2:
spacing /= 10
elif count > 50:
spacing *= 10
else:
break
for i in range(count*2+2):
pos1 = mp_util.gps_newpos(start[0], start[1], 90, i*spacing)
pos3 = mp_util.gps_newpos(pos1[0], pos1[1], 0, 3*count*spacing)
self.draw_line(img, pixmapper, pos1, pos3, self.colour, self.linewidth)
pos1 = mp_util.gps_newpos(start[0], start[1], 0, i*spacing)
pos3 = mp_util.gps_newpos(pos1[0], pos1[1], 90, 3*count*spacing)
self.draw_line(img, pixmapper, pos1, pos3, self.colour, self.linewidth)
|
return a cv image for the thumbnail
|
def img(self):
'''return a cv image for the thumbnail'''
if self._img is not None:
return self._img
self._img = cv.CreateImage((self.width, self.height), 8, 3)
cv.SetData(self._img, self.imgstr)
cv.CvtColor(self._img, self._img, cv.CV_BGR2RGB)
if self.border_width and self.border_colour is not None:
cv.Rectangle(self._img, (0, 0), (self.width-1, self.height-1),
self.border_colour, self.border_width)
return self._img
|
see if the image has been clicked on
|
def clicked(self, px, py):
'''see if the image has been clicked on'''
if self.hidden:
return None
if (abs(px - self.posx) > self.width/2 or
abs(py - self.posy) > self.height/2):
return None
return math.sqrt((px-self.posx)**2 + (py-self.posy)**2)
|
update trail
|
def update_position(self, newpos):
'''update trail'''
tnow = time.time()
if tnow >= self.last_time + self.timestep:
self.points.append(newpos.latlon)
self.last_time = tnow
while len(self.points) > self.count:
self.points.pop(0)
|
draw the trail
|
def draw(self, img, pixmapper, bounds):
'''draw the trail'''
for p in self.points:
(px,py) = pixmapper(p)
if px >= 0 and py >= 0 and px < img.width and py < img.height:
cv.Circle(img, (px,py), 1, self.colour)
|
return a cv image for the icon
|
def img(self):
'''return a cv image for the icon'''
SlipThumbnail.img(self)
if self.rotation:
# rotate the image
mat = cv.CreateMat(2, 3, cv.CV_32FC1)
cv.GetRotationMatrix2D((self.width/2,self.height/2),
-self.rotation, 1.0, mat)
self._rotated = cv.CloneImage(self._img)
cv.WarpAffine(self._img, self._rotated, mat)
else:
self._rotated = self._img
return self._rotated
|
draw the icon on the image
|
def draw(self, img, pixmapper, bounds):
'''draw the icon on the image'''
if self.hidden:
return
if self.trail is not None:
self.trail.draw(img, pixmapper, bounds)
icon = self.img()
(px,py) = pixmapper(self.latlon)
# find top left
px -= icon.width/2
py -= icon.height/2
w = icon.width
h = icon.height
(px, py, sx, sy, w, h) = self.clip(px, py, w, h, img)
cv.SetImageROI(icon, (sx, sy, w, h))
cv.SetImageROI(img, (px, py, w, h))
cv.Add(icon, img, img)
cv.ResetImageROI(img)
cv.ResetImageROI(icon)
# remember where we placed it for clicked()
self.posx = px+w/2
self.posy = py+h/2
|
return a wx image
|
def img(self):
'''return a wx image'''
import wx
img = wx.EmptyImage(self.width, self.height)
img.SetData(self.imgstr)
return img
|
redraw the image
|
def draw(self, parent, box):
'''redraw the image'''
import wx
from MAVProxy.modules.lib import mp_widgets
if self.imgpanel is None:
self.imgpanel = mp_widgets.ImagePanel(parent, self.img())
box.Add(self.imgpanel, flag=wx.LEFT, border=0)
box.Layout()
|
update the image
|
def update(self, newinfo):
'''update the image'''
self.imgstr = newinfo.imgstr
self.width = newinfo.width
self.height = newinfo.height
if self.imgpanel is not None:
self.imgpanel.set_image(self.img())
|
calculate and set text size, handling multi-line
|
def _resize(self):
'''calculate and set text size, handling multi-line'''
lines = self.text.split('\n')
xsize, ysize = 0, 0
for line in lines:
size = self.textctrl.GetTextExtent(line)
xsize = max(xsize, size[0])
ysize = ysize + size[1]
xsize = int(xsize*1.2)
self.textctrl.SetSize((xsize, ysize))
self.textctrl.SetMinSize((xsize, ysize))
|
redraw the text
|
def draw(self, parent, box):
'''redraw the text'''
import wx
if self.textctrl is None:
self.textctrl = wx.TextCtrl(parent, style=wx.TE_MULTILINE|wx.TE_READONLY)
self.textctrl.WriteText(self.text)
self._resize()
box.Add(self.textctrl, flag=wx.LEFT, border=0)
box.Layout()
|
update the image
|
def update(self, newinfo):
'''update the image'''
self.text = newinfo.text
if self.textctrl is not None:
self.textctrl.Clear()
self.textctrl.WriteText(self.text)
self._resize()
|
Application entry point
|
def main():
"""
Application entry point
"""
logging.basicConfig(level=logging.DEBUG)
# create the application and the main window
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QMainWindow()
# setup ui
ui = example_ui.Ui_MainWindow()
ui.setupUi(window)
ui.bt_delay_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
ui.bt_instant_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
ui.bt_menu_button_popup.addActions([
ui.actionAction,
ui.actionAction_C
])
item = QtWidgets.QTableWidgetItem("Test")
item.setCheckState(QtCore.Qt.Checked)
ui.tableWidget.setItem(0, 0, item)
window.setWindowTitle("QDarkStyle example")
# tabify dock widgets to show bug #6
window.tabifyDockWidget(ui.dockWidget1, ui.dockWidget2)
# setup stylesheet
app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
# auto quit after 2s when testing on travis-ci
if "--travis" in sys.argv:
QtCore.QTimer.singleShot(2000, app.exit)
# run
window.show()
app.exec_()
|
return pixel coordinates in the map image for a (lat,lon)
|
def pixel_coords(latlon, ground_width=0, mt=None, topleft=None, width=None):
'''return pixel coordinates in the map image for a (lat,lon)'''
(lat,lon) = (latlon[0], latlon[1])
return mt.coord_to_pixel(topleft[0], topleft[1], width, ground_width, lat, lon)
|
create path and mission as an image file
|
def create_imagefile(options, filename, latlon, ground_width, path_objs, mission_obj, fence_obj, width=600, height=600):
'''create path and mission as an image file'''
mt = mp_tile.MPTile(service=options.service)
map_img = mt.area_to_image(latlon[0], latlon[1],
width, height, ground_width)
while mt.tiles_pending() > 0:
print("Waiting on %u tiles" % mt.tiles_pending())
time.sleep(1)
map_img = mt.area_to_image(latlon[0], latlon[1],
width, height, ground_width)
# a function to convert from (lat,lon) to (px,py) on the map
pixmapper = functools.partial(pixel_coords, ground_width=ground_width, mt=mt, topleft=latlon, width=width)
for path_obj in path_objs:
path_obj.draw(map_img, pixmapper, None)
if mission_obj is not None:
for m in mission_obj:
m.draw(map_img, pixmapper, None)
if fence_obj is not None:
fence_obj.draw(map_img, pixmapper, None)
cv.CvtColor(map_img, map_img, cv.CV_BGR2RGB)
cv.SaveImage(filename, map_img)
|
display the waypoints
|
def display_waypoints(wploader, map):
'''display the waypoints'''
mission_list = wploader.view_list()
polygons = wploader.polygon_list()
map.add_object(mp_slipmap.SlipClearLayer('Mission'))
for i in range(len(polygons)):
p = polygons[i]
if len(p) > 1:
map.add_object(mp_slipmap.SlipPolygon('mission %u' % i, p,
layer='Mission', linewidth=2, colour=(255,255,255)))
labeled_wps = {}
for i in range(len(mission_list)):
next_list = mission_list[i]
for j in range(len(next_list)):
#label already printed for this wp?
if (next_list[j] not in labeled_wps):
map.add_object(mp_slipmap.SlipLabel(
'miss_cmd %u/%u' % (i,j), polygons[i][j], str(next_list[j]), 'Mission', colour=(0,255,255)))
labeled_wps[next_list[j]] = (i,j)
|
create a map for a log file
|
def mavflightview_mav(mlog, options=None, title=None):
'''create a map for a log file'''
if not title:
title='MAVFlightView'
wp = mavwp.MAVWPLoader()
if options.mission is not None:
wp.load(options.mission)
fen = mavwp.MAVFenceLoader()
if options.fence is not None:
fen.load(options.fence)
path = [[]]
instances = {}
ekf_counter = 0
types = ['MISSION_ITEM','CMD']
if options.types is not None:
types.extend(options.types.split(','))
else:
types.extend(['GPS','GLOBAL_POSITION_INT'])
if options.rawgps or options.dualgps:
types.extend(['GPS', 'GPS_RAW_INT'])
if options.rawgps2 or options.dualgps:
types.extend(['GPS2_RAW','GPS2'])
if options.ekf:
types.extend(['EKF1', 'GPS'])
if options.ahr2:
types.extend(['AHR2', 'AHRS2', 'GPS'])
print("Looking for types %s" % str(types))
last_timestamps = {}
while True:
try:
m = mlog.recv_match(type=types)
if m is None:
break
except Exception:
break
type = m.get_type()
if type == 'MISSION_ITEM':
try:
while m.seq > wp.count():
print("Adding dummy WP %u" % wp.count())
wp.set(m, wp.count())
wp.set(m, m.seq)
except Exception:
pass
continue
if type == 'CMD':
m = mavutil.mavlink.MAVLink_mission_item_message(0,
0,
m.CNum,
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
m.CId,
0, 1,
m.Prm1, m.Prm2, m.Prm3, m.Prm4,
m.Lat, m.Lng, m.Alt)
try:
while m.seq > wp.count():
print("Adding dummy WP %u" % wp.count())
wp.set(m, wp.count())
wp.set(m, m.seq)
except Exception:
pass
continue
if not mlog.check_condition(options.condition):
continue
if options.mode is not None and mlog.flightmode.lower() != options.mode.lower():
continue
if type in ['GPS','GPS2']:
status = getattr(m, 'Status', None)
if status is None:
status = getattr(m, 'FixType', None)
if status is None:
print("Can't find status on GPS message")
print(m)
break
if status < 2:
continue
# flash log
lat = m.Lat
lng = getattr(m, 'Lng', None)
if lng is None:
lng = getattr(m, 'Lon', None)
if lng is None:
print("Can't find longitude on GPS message")
print(m)
break
elif type in ['EKF1', 'ANU1']:
pos = mavextra.ekf1_pos(m)
if pos is None:
continue
ekf_counter += 1
if ekf_counter % options.ekf_sample != 0:
continue
(lat, lng) = pos
elif type in ['ANU5']:
(lat, lng) = (m.Alat*1.0e-7, m.Alng*1.0e-7)
elif type in ['AHR2', 'POS', 'CHEK']:
(lat, lng) = (m.Lat, m.Lng)
elif type == 'AHRS2':
(lat, lng) = (m.lat*1.0e-7, m.lng*1.0e-7)
else:
lat = m.lat * 1.0e-7
lng = m.lon * 1.0e-7
# automatically add new types to instances
if type not in instances:
instances[type] = len(instances)
while len(instances) >= len(path):
path.append([])
instance = instances[type]
if abs(lat)>0.01 or abs(lng)>0.01:
fmode = getattr(mlog, 'flightmode','')
if fmode in colourmap:
colour = colourmap[fmode]
else:
colour = colourmap['UNKNOWN']
(r,g,b) = colour
(r,g,b) = (r+instance*80,g+instance*50,b+instance*70)
if r > 255:
r = 205
if g > 255:
g = 205
if g < 0:
g = 0
if b > 255:
b = 205
colour = (r,g,b)
point = (lat, lng, colour)
if options.rate == 0 or not type in last_timestamps or m._timestamp - last_timestamps[type] > 1.0/options.rate:
last_timestamps[type] = m._timestamp
path[instance].append(point)
if len(path[0]) == 0:
print("No points to plot")
return
bounds = mp_util.polygon_bounds(path[0])
(lat, lon) = (bounds[0]+bounds[2], bounds[1])
(lat, lon) = mp_util.gps_newpos(lat, lon, -45, 50)
ground_width = mp_util.gps_distance(lat, lon, lat-bounds[2], lon+bounds[3])
while (mp_util.gps_distance(lat, lon, bounds[0], bounds[1]) >= ground_width-20 or
mp_util.gps_distance(lat, lon, lat, bounds[1]+bounds[3]) >= ground_width-20):
ground_width += 10
path_objs = []
for i in range(len(path)):
if len(path[i]) != 0:
path_objs.append(mp_slipmap.SlipPolygon('FlightPath[%u]-%s' % (i,title), path[i], layer='FlightPath',
linewidth=2, colour=(255,0,180)))
plist = wp.polygon_list()
mission_obj = None
if len(plist) > 0:
mission_obj = []
for i in range(len(plist)):
mission_obj.append(mp_slipmap.SlipPolygon('Mission-%s-%u' % (title,i), plist[i], layer='Mission',
linewidth=2, colour=(255,255,255)))
else:
mission_obj = None
fence = fen.polygon()
if len(fence) > 1:
fence_obj = mp_slipmap.SlipPolygon('Fence-%s' % title, fen.polygon(), layer='Fence',
linewidth=2, colour=(0,255,0))
else:
fence_obj = None
if options.imagefile:
create_imagefile(options, options.imagefile, (lat,lon), ground_width, path_objs, mission_obj, fence_obj)
else:
global multi_map
if options.multi and multi_map is not None:
map = multi_map
else:
map = mp_slipmap.MPSlipMap(title=title,
service=options.service,
elevation=True,
width=600,
height=600,
ground_width=ground_width,
lat=lat, lon=lon,
debug=options.debug)
if options.multi:
multi_map = map
for path_obj in path_objs:
map.add_object(path_obj)
if mission_obj is not None:
display_waypoints(wp, map)
if fence_obj is not None:
map.add_object(fence_obj)
for flag in options.flag:
a = flag.split(',')
lat = a[0]
lon = a[1]
icon = 'flag.png'
if len(a) > 2:
icon = a[2] + '.png'
icon = map.icon(icon)
map.add_object(mp_slipmap.SlipIcon('icon - %s' % str(flag), (float(lat),float(lon)), icon, layer=3, rotation=0, follow=False))
|
return an image from the images/ directory
|
def LoadImage(filename):
'''return an image from the images/ directory'''
app_dir = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(app_dir, 'images', filename)
return Tkinter.PhotoImage(file=path)
|
add a button
|
def button(self, name, filename, command):
'''add a button'''
try:
img = LoadImage(filename)
b = Tkinter.Button(self.frame, image=img, command=command)
b.image = img
except Exception:
b = Tkinter.Button(self.frame, text=filename, command=command)
b.pack(side=Tkinter.LEFT)
self.buttons[name] = b
|
rewind 10%
|
def rewind(self):
'''rewind 10%'''
pos = int(self.mlog.f.tell() - 0.1*self.filesize)
if pos < 0:
pos = 0
self.mlog.f.seek(pos)
self.find_message()
|
show status
|
def status(self):
'''show status'''
for m in sorted(self.mlog.messages.keys()):
print(str(self.mlog.messages[m]))
|
find the next valid message
|
def find_message(self):
'''find the next valid message'''
while True:
self.msg = self.mlog.recv_match(condition=args.condition)
if self.msg is not None and self.msg.get_type() != 'BAD_DATA':
break
if self.mlog.f.tell() > self.filesize - 10:
self.paused = True
break
self.last_timestamp = getattr(self.msg, '_timestamp')
|
move to a given position in the file
|
def slew(self, value):
'''move to a given position in the file'''
if float(value) != self.filepos:
pos = float(value) * self.filesize
self.mlog.f.seek(int(pos))
self.find_message()
|
called as each msg is ready
|
def next_message(self):
'''called as each msg is ready'''
msg = self.msg
if msg is None:
self.paused = True
if self.paused:
self.root.after(100, self.next_message)
return
try:
speed = float(self.playback.get())
except:
speed = 0.0
timestamp = getattr(msg, '_timestamp')
now = time.strftime("%H:%M:%S", time.localtime(timestamp))
self.clock.configure(text=now)
if speed == 0.0:
self.root.after(200, self.next_message)
else:
self.root.after(int(1000*(timestamp - self.last_timestamp) / speed), self.next_message)
self.last_timestamp = timestamp
while True:
self.msg = self.mlog.recv_match(condition=args.condition)
if self.msg is None and self.mlog.f.tell() > self.filesize - 10:
self.paused = True
return
if self.msg is not None and self.msg.get_type() != "BAD_DATA":
break
pos = float(self.mlog.f.tell()) / self.filesize
self.slider.set(pos)
self.filepos = self.slider.get()
if msg.get_type() != "BAD_DATA":
for m in self.mout:
m.write(msg.get_msgbuf())
if msg.get_type() == "GPS_RAW":
self.fdm.set('latitude', msg.lat, units='degrees')
self.fdm.set('longitude', msg.lon, units='degrees')
if args.gpsalt:
self.fdm.set('altitude', msg.alt, units='meters')
if msg.get_type() == "GPS_RAW_INT":
self.fdm.set('latitude', msg.lat/1.0e7, units='degrees')
self.fdm.set('longitude', msg.lon/1.0e7, units='degrees')
if args.gpsalt:
self.fdm.set('altitude', msg.alt/1.0e3, units='meters')
if msg.get_type() == "VFR_HUD":
if not args.gpsalt:
self.fdm.set('altitude', msg.alt, units='meters')
self.fdm.set('num_engines', 1)
self.fdm.set('vcas', msg.airspeed, units='mps')
if msg.get_type() == "ATTITUDE":
self.fdm.set('phi', msg.roll, units='radians')
self.fdm.set('theta', msg.pitch, units='radians')
self.fdm.set('psi', msg.yaw, units='radians')
self.fdm.set('phidot', msg.rollspeed, units='rps')
self.fdm.set('thetadot', msg.pitchspeed, units='rps')
self.fdm.set('psidot', msg.yawspeed, units='rps')
if msg.get_type() == "RC_CHANNELS_SCALED":
self.fdm.set("right_aileron", msg.chan1_scaled*0.0001)
self.fdm.set("left_aileron", -msg.chan1_scaled*0.0001)
self.fdm.set("rudder", msg.chan4_scaled*0.0001)
self.fdm.set("elevator", msg.chan2_scaled*0.0001)
self.fdm.set('rpm', msg.chan3_scaled*0.01)
if msg.get_type() == 'STATUSTEXT':
print("APM: %s" % msg.text)
if msg.get_type() == 'SYS_STATUS':
self.flightmode.configure(text=self.mlog.flightmode)
if msg.get_type() == "BAD_DATA":
if mavutil.all_printable(msg.data):
sys.stdout.write(msg.data)
sys.stdout.flush()
if self.fdm.get('latitude') != 0:
for f in self.fgout:
f.write(self.fdm.pack())
|
Redraws the plot
|
def draw_plot(self):
""" Redraws the plot
"""
import numpy, pylab
state = self.state
if len(self.data[0]) == 0:
print("no data to plot")
return
vhigh = max(self.data[0])
vlow = min(self.data[0])
for i in range(1,len(self.plot_data)):
vhigh = max(vhigh, max(self.data[i]))
vlow = min(vlow, min(self.data[i]))
ymin = vlow - 0.05*(vhigh-vlow)
ymax = vhigh + 0.05*(vhigh-vlow)
if ymin == ymax:
ymax = ymin + 0.1
ymin = ymin - 0.1
self.axes.set_ybound(lower=ymin, upper=ymax)
self.axes.grid(True, color='gray')
pylab.setp(self.axes.get_xticklabels(), visible=True)
pylab.setp(self.axes.get_legend().get_texts(), fontsize='small')
for i in range(len(self.plot_data)):
ydata = numpy.array(self.data[i])
xdata = self.xdata
if len(ydata) < len(self.xdata):
xdata = xdata[-len(ydata):]
self.plot_data[i].set_xdata(xdata)
self.plot_data[i].set_ydata(ydata)
self.canvas.draw()
|
evaluation a conditional (boolean) statement
|
def evaluate_condition(condition, vars):
'''evaluation a conditional (boolean) statement'''
if condition is None:
return True
v = evaluate_expression(condition, vars)
if v is None:
return False
return v
|
set the MAVLink dialect to work with.
For example, set_dialect("ardupilotmega")
|
def set_dialect(dialect):
'''set the MAVLink dialect to work with.
For example, set_dialect("ardupilotmega")
'''
global mavlink, current_dialect
from .generator import mavparse
if 'MAVLINK20' in os.environ:
wire_protocol = mavparse.PROTOCOL_2_0
modname = "pymavlink.dialects.v20." + dialect
elif mavlink is None or mavlink.WIRE_PROTOCOL_VERSION == "1.0" or not 'MAVLINK09' in os.environ:
wire_protocol = mavparse.PROTOCOL_1_0
modname = "pymavlink.dialects.v10." + dialect
else:
wire_protocol = mavparse.PROTOCOL_0_9
modname = "pymavlink.dialects.v09." + dialect
try:
mod = __import__(modname)
except Exception:
# auto-generate the dialect module
from .generator.mavgen import mavgen_python_dialect
mavgen_python_dialect(dialect, wire_protocol)
mod = __import__(modname)
components = modname.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
current_dialect = dialect
mavlink = mod
|
set the clone on exec flag on a file descriptor. Ignore exceptions
|
def set_close_on_exec(fd):
'''set the clone on exec flag on a file descriptor. Ignore exceptions'''
try:
import fcntl
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(fd, fcntl.F_SETFD, flags)
except Exception:
pass
|
open a serial, UDP, TCP or file mavlink connection
|
def mavlink_connection(device, baud=115200, source_system=255,
planner_format=None, write=False, append=False,
robust_parsing=True, notimestamps=False, input=True,
dialect=None, autoreconnect=False, zero_time_base=False,
retries=3, use_native=default_native):
'''open a serial, UDP, TCP or file mavlink connection'''
global mavfile_global
if dialect is not None:
set_dialect(dialect)
if device.startswith('tcp:'):
return mavtcp(device[4:], source_system=source_system, retries=retries, use_native=use_native)
if device.startswith('tcpin:'):
return mavtcpin(device[6:], source_system=source_system, retries=retries, use_native=use_native)
if device.startswith('udpin:'):
return mavudp(device[6:], input=True, source_system=source_system, use_native=use_native)
if device.startswith('udpout:'):
return mavudp(device[7:], input=False, source_system=source_system, use_native=use_native)
if device.startswith('udpbcast:'):
return mavudp(device[9:], input=False, source_system=source_system, use_native=use_native, broadcast=True)
# For legacy purposes we accept the following syntax and let the caller to specify direction
if device.startswith('udp:'):
return mavudp(device[4:], input=input, source_system=source_system, use_native=use_native)
if device.lower().endswith('.bin') or device.lower().endswith('.px4log'):
# support dataflash logs
from pymavlink import DFReader
m = DFReader.DFReader_binary(device, zero_time_base=zero_time_base)
mavfile_global = m
return m
if device.endswith('.log'):
# support dataflash text logs
from pymavlink import DFReader
if DFReader.DFReader_is_text_log(device):
m = DFReader.DFReader_text(device, zero_time_base=zero_time_base)
mavfile_global = m
return m
# list of suffixes to prevent setting DOS paths as UDP sockets
logsuffixes = ['mavlink', 'log', 'raw', 'tlog' ]
suffix = device.split('.')[-1].lower()
if device.find(':') != -1 and not suffix in logsuffixes:
return mavudp(device, source_system=source_system, input=input, use_native=use_native)
if os.path.isfile(device):
if device.endswith(".elf") or device.find("/bin/") != -1:
print("executing '%s'" % device)
return mavchildexec(device, source_system=source_system, use_native=use_native)
else:
return mavlogfile(device, planner_format=planner_format, write=write,
append=append, robust_parsing=robust_parsing, notimestamps=notimestamps,
source_system=source_system, use_native=use_native)
return mavserial(device, baud=baud, source_system=source_system, autoreconnect=autoreconnect, use_native=use_native)
|
see if a character is printable
|
def is_printable(c):
'''see if a character is printable'''
global have_ascii
if have_ascii:
return ascii.isprint(c)
if isinstance(c, int):
ic = c
else:
ic = ord(c)
return ic >= 32 and ic <= 126
|
try to auto-detect serial ports on win32
|
def auto_detect_serial_win32(preferred_list=['*']):
'''try to auto-detect serial ports on win32'''
try:
from serial.tools.list_ports_windows import comports
list = sorted(comports())
except:
return []
ret = []
others = []
for port, description, hwid in list:
matches = False
p = SerialPort(port, description=description, hwid=hwid)
for preferred in preferred_list:
if fnmatch.fnmatch(description, preferred) or fnmatch.fnmatch(hwid, preferred):
matches = True
if matches:
ret.append(p)
else:
others.append(p)
if len(ret) > 0:
return ret
# now the rest
ret.extend(others)
return ret
|
try to auto-detect serial ports on unix
|
def auto_detect_serial_unix(preferred_list=['*']):
'''try to auto-detect serial ports on unix'''
import glob
glist = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') + glob.glob('/dev/serial/by-id/*')
ret = []
others = []
# try preferred ones first
for d in glist:
matches = False
for preferred in preferred_list:
if fnmatch.fnmatch(d, preferred):
matches = True
if matches:
ret.append(SerialPort(d))
else:
others.append(SerialPort(d))
if len(ret) > 0:
return ret
ret.extend(others)
return ret
|
try to auto-detect serial port
|
def auto_detect_serial(preferred_list=['*']):
'''try to auto-detect serial port'''
# see if
if os.name == 'nt':
return auto_detect_serial_win32(preferred_list=preferred_list)
return auto_detect_serial_unix(preferred_list=preferred_list)
|
mode string for 0.9 protocol
|
def mode_string_v09(msg):
'''mode string for 0.9 protocol'''
mode = msg.mode
nav_mode = msg.nav_mode
MAV_MODE_UNINIT = 0
MAV_MODE_MANUAL = 2
MAV_MODE_GUIDED = 3
MAV_MODE_AUTO = 4
MAV_MODE_TEST1 = 5
MAV_MODE_TEST2 = 6
MAV_MODE_TEST3 = 7
MAV_NAV_GROUNDED = 0
MAV_NAV_LIFTOFF = 1
MAV_NAV_HOLD = 2
MAV_NAV_WAYPOINT = 3
MAV_NAV_VECTOR = 4
MAV_NAV_RETURNING = 5
MAV_NAV_LANDING = 6
MAV_NAV_LOST = 7
MAV_NAV_LOITER = 8
cmode = (mode, nav_mode)
mapping = {
(MAV_MODE_UNINIT, MAV_NAV_GROUNDED) : "INITIALISING",
(MAV_MODE_MANUAL, MAV_NAV_VECTOR) : "MANUAL",
(MAV_MODE_TEST3, MAV_NAV_VECTOR) : "CIRCLE",
(MAV_MODE_GUIDED, MAV_NAV_VECTOR) : "GUIDED",
(MAV_MODE_TEST1, MAV_NAV_VECTOR) : "STABILIZE",
(MAV_MODE_TEST2, MAV_NAV_LIFTOFF) : "FBWA",
(MAV_MODE_AUTO, MAV_NAV_WAYPOINT) : "AUTO",
(MAV_MODE_AUTO, MAV_NAV_RETURNING) : "RTL",
(MAV_MODE_AUTO, MAV_NAV_LOITER) : "LOITER",
(MAV_MODE_AUTO, MAV_NAV_LIFTOFF) : "TAKEOFF",
(MAV_MODE_AUTO, MAV_NAV_LANDING) : "LANDING",
(MAV_MODE_AUTO, MAV_NAV_HOLD) : "LOITER",
(MAV_MODE_GUIDED, MAV_NAV_VECTOR) : "GUIDED",
(MAV_MODE_GUIDED, MAV_NAV_WAYPOINT) : "GUIDED",
(100, MAV_NAV_VECTOR) : "STABILIZE",
(101, MAV_NAV_VECTOR) : "ACRO",
(102, MAV_NAV_VECTOR) : "ALT_HOLD",
(107, MAV_NAV_VECTOR) : "CIRCLE",
(109, MAV_NAV_VECTOR) : "LAND",
}
if cmode in mapping:
return mapping[cmode]
return "Mode(%s,%s)" % cmode
|
return dictionary mapping mode names to numbers, or None if unknown
|
def mode_mapping_byname(mav_type):
'''return dictionary mapping mode names to numbers, or None if unknown'''
map = None
if mav_type in [mavlink.MAV_TYPE_QUADROTOR,
mavlink.MAV_TYPE_HELICOPTER,
mavlink.MAV_TYPE_HEXAROTOR,
mavlink.MAV_TYPE_OCTOROTOR,
mavlink.MAV_TYPE_COAXIAL,
mavlink.MAV_TYPE_TRICOPTER]:
map = mode_mapping_acm
if mav_type == mavlink.MAV_TYPE_FIXED_WING:
map = mode_mapping_apm
if mav_type == mavlink.MAV_TYPE_GROUND_ROVER:
map = mode_mapping_rover
if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER:
map = mode_mapping_tracker
if map is None:
return None
inv_map = dict((a, b) for (b, a) in map.items())
return inv_map
|
return dictionary mapping mode numbers to name, or None if unknown
|
def mode_mapping_bynumber(mav_type):
'''return dictionary mapping mode numbers to name, or None if unknown'''
map = None
if mav_type in [mavlink.MAV_TYPE_QUADROTOR,
mavlink.MAV_TYPE_HELICOPTER,
mavlink.MAV_TYPE_HEXAROTOR,
mavlink.MAV_TYPE_OCTOROTOR,
mavlink.MAV_TYPE_COAXIAL,
mavlink.MAV_TYPE_TRICOPTER]:
map = mode_mapping_acm
if mav_type == mavlink.MAV_TYPE_FIXED_WING:
map = mode_mapping_apm
if mav_type == mavlink.MAV_TYPE_GROUND_ROVER:
map = mode_mapping_rover
if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER:
map = mode_mapping_tracker
if map is None:
return None
return map
|
mode string for 1.0 protocol, from heartbeat
|
def mode_string_v10(msg):
'''mode string for 1.0 protocol, from heartbeat'''
if msg.autopilot == mavlink.MAV_AUTOPILOT_PX4:
return interpret_px4_mode(msg.base_mode, msg.custom_mode)
if not msg.base_mode & mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED:
return "Mode(0x%08x)" % msg.base_mode
if msg.type in [ mavlink.MAV_TYPE_QUADROTOR, mavlink.MAV_TYPE_HEXAROTOR,
mavlink.MAV_TYPE_OCTOROTOR, mavlink.MAV_TYPE_TRICOPTER,
mavlink.MAV_TYPE_COAXIAL,
mavlink.MAV_TYPE_HELICOPTER ]:
if msg.custom_mode in mode_mapping_acm:
return mode_mapping_acm[msg.custom_mode]
if msg.type == mavlink.MAV_TYPE_FIXED_WING:
if msg.custom_mode in mode_mapping_apm:
return mode_mapping_apm[msg.custom_mode]
if msg.type == mavlink.MAV_TYPE_GROUND_ROVER:
if msg.custom_mode in mode_mapping_rover:
return mode_mapping_rover[msg.custom_mode]
if msg.type == mavlink.MAV_TYPE_ANTENNA_TRACKER:
if msg.custom_mode in mode_mapping_tracker:
return mode_mapping_tracker[msg.custom_mode]
return "Mode(%u)" % msg.custom_mode
|
auto-switch mavlink protocol version
|
def auto_mavlink_version(self, buf):
'''auto-switch mavlink protocol version'''
global mavlink
if len(buf) == 0:
return
try:
magic = ord(buf[0])
except:
magic = buf[0]
if not magic in [ 85, 254, 253 ]:
return
self.first_byte = False
if self.WIRE_PROTOCOL_VERSION == "0.9" and magic == 254:
self.WIRE_PROTOCOL_VERSION = "1.0"
set_dialect(current_dialect)
elif self.WIRE_PROTOCOL_VERSION == "1.0" and magic == 85:
self.WIRE_PROTOCOL_VERSION = "0.9"
os.environ['MAVLINK09'] = '1'
set_dialect(current_dialect)
elif self.WIRE_PROTOCOL_VERSION != "2.0" and magic == 253:
self.WIRE_PROTOCOL_VERSION = "2.0"
os.environ['MAVLINK20'] = '1'
set_dialect(current_dialect)
else:
return
# switch protocol
(callback, callback_args, callback_kwargs) = (self.mav.callback,
self.mav.callback_args,
self.mav.callback_kwargs)
self.mav = mavlink.MAVLink(self, srcSystem=self.source_system)
self.mav.robust_parsing = self.robust_parsing
self.WIRE_PROTOCOL_VERSION = mavlink.WIRE_PROTOCOL_VERSION
(self.mav.callback, self.mav.callback_args, self.mav.callback_kwargs) = (callback,
callback_args,
callback_kwargs)
|
wait for up to timeout seconds for more data
|
def select(self, timeout):
'''wait for up to timeout seconds for more data'''
if self.fd is None:
time.sleep(min(timeout,0.5))
return True
try:
(rin, win, xin) = select.select([self.fd], [], [], timeout)
except select.error:
return False
return len(rin) == 1
|
default post message call
|
def post_message(self, msg):
'''default post message call'''
if '_posted' in msg.__dict__:
return
msg._posted = True
msg._timestamp = time.time()
type = msg.get_type()
if type != 'HEARTBEAT' or (msg.type != mavlink.MAV_TYPE_GCS and msg.type != mavlink.MAV_TYPE_GIMBAL):
self.messages[type] = msg
if 'usec' in msg.__dict__:
self.uptime = msg.usec * 1.0e-6
if 'time_boot_ms' in msg.__dict__:
self.uptime = msg.time_boot_ms * 1.0e-3
if self._timestamp is not None:
if self.notimestamps:
msg._timestamp = self.uptime
else:
msg._timestamp = self._timestamp
src_system = msg.get_srcSystem()
src_component = msg.get_srcComponent()
src_tuple = (src_system, src_component)
radio_tuple = (ord('3'), ord('D'))
if not (src_tuple == radio_tuple or msg.get_type() == 'BAD_DATA'):
if not src_tuple in self.last_seq:
last_seq = -1
else:
last_seq = self.last_seq[src_tuple]
seq = (last_seq+1) % 256
seq2 = msg.get_seq()
if seq != seq2 and last_seq != -1:
diff = (seq2 - seq) % 256
self.mav_loss += diff
#print("lost %u seq=%u seq2=%u last_seq=%u src_system=%u %s" % (diff, seq, seq2, last_seq, src_system, msg.get_type()))
self.last_seq[src_tuple] = seq2
self.mav_count += 1
self.timestamp = msg._timestamp
if type == 'HEARTBEAT' and msg.get_srcComponent() != mavlink.MAV_COMP_ID_GIMBAL:
self.target_system = msg.get_srcSystem()
self.target_component = msg.get_srcComponent()
if float(mavlink.WIRE_PROTOCOL_VERSION) >= 1 and msg.type != mavlink.MAV_TYPE_GCS:
self.flightmode = mode_string_v10(msg)
self.mav_type = msg.type
self.base_mode = msg.base_mode
elif type == 'PARAM_VALUE':
s = str(msg.param_id)
self.params[str(msg.param_id)] = msg.param_value
if msg.param_index+1 == msg.param_count:
self.param_fetch_in_progress = False
self.param_fetch_complete = True
elif type == 'SYS_STATUS' and mavlink.WIRE_PROTOCOL_VERSION == '0.9':
self.flightmode = mode_string_v09(msg)
elif type == 'GPS_RAW':
if self.messages['HOME'].fix_type < 2:
self.messages['HOME'] = msg
elif type == 'GPS_RAW_INT':
if self.messages['HOME'].fix_type < 3:
self.messages['HOME'] = msg
for hook in self.message_hooks:
hook(self, msg)
if (msg.get_signed() and
self.mav.signing.link_id == 0 and
msg.get_link_id() != 0 and
self.target_system == msg.get_srcSystem() and
self.target_component == msg.get_srcComponent()):
# change to link_id from incoming packet
self.mav.signing.link_id = msg.get_link_id()
|
packet loss as a percentage
|
def packet_loss(self):
'''packet loss as a percentage'''
if self.mav_count == 0:
return 0
return (100.0*self.mav_loss)/(self.mav_count+self.mav_loss)
|
message receive routine
|
def recv_msg(self):
'''message receive routine'''
self.pre_message()
while True:
n = self.mav.bytes_needed()
s = self.recv(n)
numnew = len(s)
if numnew != 0:
if self.logfile_raw:
self.logfile_raw.write(str(s))
if self.first_byte:
self.auto_mavlink_version(s)
# We always call parse_char even if the new string is empty, because the existing message buf might already have some valid packet
# we can extract
msg = self.mav.parse_char(s)
if msg:
if self.logfile and msg.get_type() != 'BAD_DATA' :
usec = int(time.time() * 1.0e6) & ~3
self.logfile.write(str(struct.pack('>Q', usec) + msg.get_msgbuf()))
self.post_message(msg)
return msg
else:
# if we failed to parse any messages _and_ no new bytes arrived, return immediately so the client has the option to
# timeout
if numnew == 0:
return None
|
recv the next MAVLink message that matches the given condition
type can be a string or a list of strings
|
def recv_match(self, condition=None, type=None, blocking=False, timeout=None):
'''recv the next MAVLink message that matches the given condition
type can be a string or a list of strings'''
if type is not None and not isinstance(type, list):
type = [type]
start_time = time.time()
while True:
if timeout is not None:
now = time.time()
if now < start_time:
start_time = now # If an external process rolls back system time, we should not spin forever.
if start_time + timeout < time.time():
return None
m = self.recv_msg()
if m is None:
if blocking:
for hook in self.idle_hooks:
hook(self)
if timeout is None:
self.select(0.05)
else:
self.select(timeout/2)
continue
return None
if type is not None and not m.get_type() in type:
continue
if not evaluate_condition(condition, self.messages):
continue
return m
|
start logging to the given logfile, with timestamps
|
def setup_logfile(self, logfile, mode='w'):
'''start logging to the given logfile, with timestamps'''
self.logfile = open(logfile, mode=mode)
|
start logging raw bytes to the given logfile, without timestamps
|
def setup_logfile_raw(self, logfile, mode='w'):
'''start logging raw bytes to the given logfile, without timestamps'''
self.logfile_raw = open(logfile, mode=mode)
|
initiate fetch of all parameters
|
def param_fetch_all(self):
'''initiate fetch of all parameters'''
if time.time() - getattr(self, 'param_fetch_start', 0) < 2.0:
# don't fetch too often
return
self.param_fetch_start = time.time()
self.param_fetch_in_progress = True
self.mav.param_request_list_send(self.target_system, self.target_component)
|
initiate fetch of one parameter
|
def param_fetch_one(self, name):
'''initiate fetch of one parameter'''
try:
idx = int(name)
self.mav.param_request_read_send(self.target_system, self.target_component, "", idx)
except Exception:
self.mav.param_request_read_send(self.target_system, self.target_component, name, -1)
|
return the time since the last message of type mtype was received
|
def time_since(self, mtype):
'''return the time since the last message of type mtype was received'''
if not mtype in self.messages:
return time.time() - self.start_time
return time.time() - self.messages[mtype]._timestamp
|
wrapper for parameter set
|
def param_set_send(self, parm_name, parm_value, parm_type=None):
'''wrapper for parameter set'''
if self.mavlink10():
if parm_type == None:
parm_type = mavlink.MAVLINK_TYPE_FLOAT
self.mav.param_set_send(self.target_system, self.target_component,
parm_name, parm_value, parm_type)
else:
self.mav.param_set_send(self.target_system, self.target_component,
parm_name, parm_value)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.