blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
adc306eabb7dbc0bfdb65f42a941a06a2541d9b8
fbdd18eac2c5a3163f0a4154daf3e89ddef0507d
/day3/start/12_random.py
703da11b1752801f5ef6c90fd8594635d546c62e
[]
no_license
techsharif/python_training_2021
562d891e40fe2410cebcdad841eb407fb40b7871
246dddc1c4dae683df4b006fe96a5a117d1aeaf6
refs/heads/master
2023-02-27T12:11:23.541408
2021-02-10T10:03:48
2021-02-10T10:03:48
333,330,902
0
0
null
null
null
null
UTF-8
Python
false
false
77
py
import random print(random.random()) # 0.125 print(random.randint(0,9)) # 5
[ "sharif.cse.hstu@gmail.com" ]
sharif.cse.hstu@gmail.com
570bc08e2531a3c60bc6778ff86427b795d3d936
9e610e88158b973a2129cb794176dc1a9b0b6bfd
/juicer/util/jinja2_custom.py
535940968e98e01641d04d94dbc96fd93dc925e3
[]
no_license
eubr-bigsea/juicer
8735b3aefcf66a5207364270e7ee9ec809b94ad4
4714187a6cb8ca7d1e09d8eae4cf4898ae7dcc58
refs/heads/master
2023-08-31T07:01:52.091443
2023-08-14T21:45:03
2023-08-14T21:56:48
68,124,762
6
8
null
2023-08-01T01:21:18
2016-09-13T16:09:11
Python
UTF-8
Python
false
false
903
py
# -*- coding: utf-8 -*- from jinja2 import nodes from jinja2.ext import Extension import autopep8 class AutoPep8Extension(Extension): # a set of names that trigger the extension. tags = {'autopep8'} def __init__(self, environment): super(AutoPep8Extension, self).__init__(environment) # add the defaults to the environment environment.extend() def parse(self, parser): lineno = next(parser.stream).lineno body = parser.parse_statements(['name:endautopep8'], drop_needle=True) args = [] result = nodes.CallBlock(self.call_method('_format_support', args), [], [], body).set_lineno(lineno) return result @staticmethod def _format_support(caller): options = autopep8.parse_args(['--max-line-length', '81', '-']) return autopep8.fix_code(caller(), options=options)
[ "waltersf@gmail.com" ]
waltersf@gmail.com
7d6112f173be2b434f9779490f1979f1d893a056
01d92ca39cd4836aaef67e2efcf88a44671c7213
/code_pack_19/basic_logger_2.py
360836d78049880cad49c8acca8c494b507ccf7d
[]
no_license
manuelpereira292/py3_bootcamp
247f411b80f09c46aeeba90a96e6a5d3fd329f2c
1988553394cb993db82c39993ed397e497bd5ae8
refs/heads/master
2022-08-20T02:25:51.265204
2020-05-15T22:26:27
2020-05-15T22:26:27
263,367,513
1
0
null
null
null
null
UTF-8
Python
false
false
383
py
import logging logging.basicConfig(filename="code_pack_19/sample1.log", level=logging.INFO) log = logging.getLogger("ex") try: raise RuntimeError except RuntimeError: log.exception("Error!") # Let's use our file reading knowledge to # read the log file with open("code_pack_19/sample1.log") as file_handler: for line in file_handler: print(line)
[ "manuelpereira292@gmail.com" ]
manuelpereira292@gmail.com
98697225e835037618221274549d17e44739d9f0
b31e7898aa5131125f243eaff973049b17e08512
/.venv/lib/python3.10/site-packages/anyio/_core/_signals.py
8ea54af86c4be12340de02dc2a6f7eba387e0d98
[]
no_license
ramsred/MyProjects
f2978eeda3d73421daf0da9f2d012caef6c3ccda
a7f90ef1ecfbc7517be61e71286bd14405985de5
refs/heads/master
2023-07-09T03:19:17.683705
2023-07-02T19:30:19
2023-07-02T19:30:19
71,980,729
0
0
null
null
null
null
UTF-8
Python
false
false
863
py
from __future__ import annotations from typing import AsyncIterator from ._compat import DeprecatedAsyncContextManager from ._eventloop import get_asynclib def open_signal_receiver( *signals: int, ) -> DeprecatedAsyncContextManager[AsyncIterator[int]]: """ Start receiving operating system signals. :param signals: signals to receive (e.g. ``signal.SIGINT``) :return: an asynchronous context manager for an asynchronous iterator which yields signal numbers .. warning:: Windows does not support signals natively so it is best to avoid relying on this in cross-platform applications. .. warning:: On asyncio, this permanently replaces any previous signal handler for the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`. """ return get_asynclib().open_signal_receiver(*signals)
[ "venkataramireddy534@gmail.com" ]
venkataramireddy534@gmail.com
5a58a787ab85afbf656093287cdf31bb5fd3798e
a6e4a6f0a73d24a6ba957277899adbd9b84bd594
/sdk/python/pulumi_azure_native/network/get_hub_virtual_network_connection.py
a68415eeb18718c1b8b9c127daf3badcdf55b420
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
MisinformedDNA/pulumi-azure-native
9cbd75306e9c8f92abc25be3f73c113cb93865e9
de974fd984f7e98649951dbe80b4fc0603d03356
refs/heads/master
2023-03-24T22:02:03.842935
2021-03-08T21:16:19
2021-03-08T21:16:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,803
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from . import outputs __all__ = [ 'GetHubVirtualNetworkConnectionResult', 'AwaitableGetHubVirtualNetworkConnectionResult', 'get_hub_virtual_network_connection', ] @pulumi.output_type class GetHubVirtualNetworkConnectionResult: """ HubVirtualNetworkConnection Resource. """ def __init__(__self__, allow_hub_to_remote_vnet_transit=None, allow_remote_vnet_to_use_hub_vnet_gateways=None, enable_internet_security=None, etag=None, id=None, name=None, provisioning_state=None, remote_virtual_network=None, routing_configuration=None): if allow_hub_to_remote_vnet_transit and not isinstance(allow_hub_to_remote_vnet_transit, bool): raise TypeError("Expected argument 'allow_hub_to_remote_vnet_transit' to be a bool") pulumi.set(__self__, "allow_hub_to_remote_vnet_transit", allow_hub_to_remote_vnet_transit) if allow_remote_vnet_to_use_hub_vnet_gateways and not isinstance(allow_remote_vnet_to_use_hub_vnet_gateways, bool): raise TypeError("Expected argument 'allow_remote_vnet_to_use_hub_vnet_gateways' to be a bool") pulumi.set(__self__, "allow_remote_vnet_to_use_hub_vnet_gateways", allow_remote_vnet_to_use_hub_vnet_gateways) if enable_internet_security and not isinstance(enable_internet_security, bool): raise TypeError("Expected argument 'enable_internet_security' to be a bool") pulumi.set(__self__, "enable_internet_security", enable_internet_security) if etag and not isinstance(etag, str): raise TypeError("Expected argument 'etag' to be a str") pulumi.set(__self__, "etag", etag) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if remote_virtual_network and not isinstance(remote_virtual_network, dict): raise TypeError("Expected argument 'remote_virtual_network' to be a dict") pulumi.set(__self__, "remote_virtual_network", remote_virtual_network) if routing_configuration and not isinstance(routing_configuration, dict): raise TypeError("Expected argument 'routing_configuration' to be a dict") pulumi.set(__self__, "routing_configuration", routing_configuration) @property @pulumi.getter(name="allowHubToRemoteVnetTransit") def allow_hub_to_remote_vnet_transit(self) -> Optional[bool]: """ Deprecated: VirtualHub to RemoteVnet transit to enabled or not. """ return pulumi.get(self, "allow_hub_to_remote_vnet_transit") @property @pulumi.getter(name="allowRemoteVnetToUseHubVnetGateways") def allow_remote_vnet_to_use_hub_vnet_gateways(self) -> Optional[bool]: """ Deprecated: Allow RemoteVnet to use Virtual Hub's gateways. """ return pulumi.get(self, "allow_remote_vnet_to_use_hub_vnet_gateways") @property @pulumi.getter(name="enableInternetSecurity") def enable_internet_security(self) -> Optional[bool]: """ Enable internet security. """ return pulumi.get(self, "enable_internet_security") @property @pulumi.getter def etag(self) -> str: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the hub virtual network connection resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="remoteVirtualNetwork") def remote_virtual_network(self) -> Optional['outputs.SubResourceResponse']: """ Reference to the remote virtual network. """ return pulumi.get(self, "remote_virtual_network") @property @pulumi.getter(name="routingConfiguration") def routing_configuration(self) -> Optional['outputs.RoutingConfigurationResponse']: """ The Routing Configuration indicating the associated and propagated route tables on this connection. """ return pulumi.get(self, "routing_configuration") class AwaitableGetHubVirtualNetworkConnectionResult(GetHubVirtualNetworkConnectionResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetHubVirtualNetworkConnectionResult( allow_hub_to_remote_vnet_transit=self.allow_hub_to_remote_vnet_transit, allow_remote_vnet_to_use_hub_vnet_gateways=self.allow_remote_vnet_to_use_hub_vnet_gateways, enable_internet_security=self.enable_internet_security, etag=self.etag, id=self.id, name=self.name, provisioning_state=self.provisioning_state, remote_virtual_network=self.remote_virtual_network, routing_configuration=self.routing_configuration) def get_hub_virtual_network_connection(connection_name: Optional[str] = None, resource_group_name: Optional[str] = None, virtual_hub_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetHubVirtualNetworkConnectionResult: """ HubVirtualNetworkConnection Resource. API Version: 2020-11-01. :param str connection_name: The name of the vpn connection. :param str resource_group_name: The resource group name of the VirtualHub. :param str virtual_hub_name: The name of the VirtualHub. """ __args__ = dict() __args__['connectionName'] = connection_name __args__['resourceGroupName'] = resource_group_name __args__['virtualHubName'] = virtual_hub_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:network:getHubVirtualNetworkConnection', __args__, opts=opts, typ=GetHubVirtualNetworkConnectionResult).value return AwaitableGetHubVirtualNetworkConnectionResult( allow_hub_to_remote_vnet_transit=__ret__.allow_hub_to_remote_vnet_transit, allow_remote_vnet_to_use_hub_vnet_gateways=__ret__.allow_remote_vnet_to_use_hub_vnet_gateways, enable_internet_security=__ret__.enable_internet_security, etag=__ret__.etag, id=__ret__.id, name=__ret__.name, provisioning_state=__ret__.provisioning_state, remote_virtual_network=__ret__.remote_virtual_network, routing_configuration=__ret__.routing_configuration)
[ "noreply@github.com" ]
MisinformedDNA.noreply@github.com
e78649e5c08756d7f0bd2c588219d7302dd0f4e2
df716b2868b289a7e264f8d2b0ded52fff38d7fc
/plaso/parsers/sqlite_plugins/safari.py
22bb6098cb41d93825e091cb3aafa5f5caee31fd
[ "Apache-2.0" ]
permissive
ir4n6/plaso
7dd3cebb92de53cc4866ae650d41c255027cf80a
010f9cbdfc82e21ed6658657fd09a7b44115c464
refs/heads/master
2021-04-25T05:50:45.963652
2018-03-08T15:11:58
2018-03-08T15:11:58
122,255,666
0
0
Apache-2.0
2018-02-20T21:00:50
2018-02-20T21:00:50
null
UTF-8
Python
false
false
5,409
py
# -*- coding: utf-8 -*- """Parser for the Safari History files. The Safari History is stored in SQLite database files named History.db """ from __future__ import unicode_literals from dfdatetime import cocoa_time as dfdatetime_cocoa_time from plaso.containers import events from plaso.containers import time_events from plaso.lib import definitions from plaso.parsers import sqlite from plaso.parsers.sqlite_plugins import interface class SafariHistoryPageVisitedEventData(events.EventData): """Safari history event data. Attributes: title (str): title of the webpage visited. url (str): URL visited. host(str): hostname of the server. visit_count (int): number of times the website was visited. was_http_non_get (bool): True if the webpage was visited using a non-GET HTTP request. """ DATA_TYPE = 'safari:history:visit_sqlite' def __init__(self): """Initializes event data.""" super(SafariHistoryPageVisitedEventData, self).__init__(data_type=self.DATA_TYPE) self.title = None self.url = None self.visit_count = None self.host = None self.was_http_non_get = None self.visit_redirect_source = None class SafariHistoryPluginSqlite(interface.SQLitePlugin): """Parse Safari History Files. Safari history file is stored in a SQLite database file named History.db """ NAME = 'safari_history' DESCRIPTION = 'Parser for Safari history SQLite database files.' QUERIES = [ (('SELECT history_items.id, history_items.url, history_items.visit' '_count, history_visits.id AS visit_id, history_visits.history_item,' 'history_visits.visit_time, history_visits.redirect_destination, ' 'history_visits.title, history_visits.http_non_get, ' 'history_visits.redirect_source ' 'FROM history_items, history_visits ' 'WHERE history_items.id = history_visits.history_item ' 'ORDER BY history_visits.visit_time'), 'ParsePageVisitRow') ] REQUIRED_TABLES = frozenset(['history_items', 'history_visits']) SCHEMAS = [{ 'history_client_versions': ( 'CREATE TABLE history_client_versions (client_version INTEGER ' 'PRIMARY KEY,last_seen REAL NOT NULL)'), 'history_event_listeners': ( 'CREATE TABLE history_event_listeners (listener_name TEXT PRIMARY ' 'KEY NOT NULL UNIQUE,last_seen REAL NOT NULL)'), 'history_events': ( 'CREATE TABLE history_events (id INTEGER PRIMARY KEY ' 'AUTOINCREMENT,event_type TEXT NOT NULL,event_time REAL NOT ' 'NULL,pending_listeners TEXT NOT NULL,value BLOB)'), 'history_items': ( 'CREATE TABLE history_items (id INTEGER PRIMARY KEY ' 'AUTOINCREMENT,url TEXT NOT NULL UNIQUE,domain_expansion TEXT ' 'NULL,visit_count INTEGER NOT NULL,daily_visit_counts BLOB NOT ' 'NULL,weekly_visit_counts BLOB NULL,autocomplete_triggers BLOB ' 'NULL,should_recompute_derived_visit_counts INTEGER NOT ' 'NULL,visit_count_score INTEGER NOT NULL)'), 'history_tombstones': ( 'CREATE TABLE history_tombstones (id INTEGER PRIMARY KEY ' 'AUTOINCREMENT,start_time REAL NOT NULL,end_time REAL NOT NULL,url ' 'TEXT,generation INTEGER NOT NULL DEFAULT 0)'), 'history_visits': ( 'CREATE TABLE history_visits (id INTEGER PRIMARY KEY ' 'AUTOINCREMENT,history_item INTEGER NOT NULL REFERENCES ' 'history_items(id) ON DELETE CASCADE,visit_time REAL NOT NULL,title ' 'TEXT NULL,load_successful BOOLEAN NOT NULL DEFAULT 1,http_non_get ' 'BOOLEAN NOT NULL DEFAULT 0,synthesized BOOLEAN NOT NULL DEFAULT ' '0,redirect_source INTEGER NULL UNIQUE REFERENCES ' 'history_visits(id) ON DELETE CASCADE,redirect_destination INTEGER ' 'NULL UNIQUE REFERENCES history_visits(id) ON DELETE CASCADE,origin ' 'INTEGER NOT NULL DEFAULT 0,generation INTEGER NOT NULL DEFAULT ' '0,attributes INTEGER NOT NULL DEFAULT 0,score INTEGER NOT NULL ' 'DEFAULT 0)'), 'metadata': ( 'CREATE TABLE metadata (key TEXT NOT NULL UNIQUE, value)')}] def ParsePageVisitRow(self, parser_mediator, query, row, **unused_kwargs): """Parses a visited row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row. """ query_hash = hash(query) was_http_non_get = self._GetRowValue(query_hash, row, 'http_non_get') event_data = SafariHistoryPageVisitedEventData() event_data.offset = self._GetRowValue(query_hash, row, 'id') event_data.query = query event_data.title = self._GetRowValue(query_hash, row, 'title') event_data.url = self._GetRowValue(query_hash, row, 'url') event_data.visit_count = self._GetRowValue(query_hash, row, 'visit_count') event_data.was_http_non_get = bool(was_http_non_get) timestamp = self._GetRowValue(query_hash, row, 'visit_time') date_time = dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp) event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_LAST_VISITED) parser_mediator.ProduceEventWithEventData(event, event_data) sqlite.SQLiteParser.RegisterPlugin(SafariHistoryPluginSqlite)
[ "onager@deerpie.com" ]
onager@deerpie.com
04c13e2c86dc8ea3c26a9f4c6c9286fc9ec47a0e
7eb3009e95a15a992c0c21afe0884008ba10544d
/game/src/leveleditor/objectproperties/ColorEditor.py
6262d9c64458825c0e02be2bb60267cca144a4fc
[]
no_license
tsp-team/ttsp-src
be391ebc44f01463ff2e802ab039438e07a645f3
9bf1869adbc4f0c1dff69095c04f4604a515c4e4
refs/heads/master
2022-12-04T09:50:36.944988
2020-08-23T21:01:32
2020-08-23T21:01:32
263,228,539
0
0
null
null
null
null
UTF-8
Python
false
false
2,649
py
from .BaseEditor import BaseEditor from src.leveleditor import LEUtils from PyQt5 import QtWidgets, QtCore class ColorEditor(BaseEditor): def __init__(self, parent, item, model): BaseEditor.__init__(self, parent, item, model) self.lineEdit = QtWidgets.QLineEdit("", self) self.lineEdit.returnPressed.connect(self.__confirmColorText) self.layout().addWidget(self.lineEdit) self.colorLbl = QtWidgets.QLabel("", self) self.colorLbl.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) self.layout().addWidget(self.colorLbl) self.editButton = QtWidgets.QPushButton("Pick Color", self) self.editButton.clicked.connect(self.__pickColor) self.layout().addWidget(self.editButton) self.colorDlg = None self.adjustToColor(LEUtils.strToQColor(self.getItemData())) def __confirmColorText(self): self.setModelData(self.model, self.item.index()) self.adjustToColor(LEUtils.strToQColor(self.lineEdit.text())) def __pickColor(self): self.origColor = LEUtils.strToQColor(self.getItemData()) color = LEUtils.strToQColor(self.getItemData()) colorDlg = QtWidgets.QColorDialog(color, self) colorDlg.setOptions(QtWidgets.QColorDialog.DontUseNativeDialog) colorDlg.setModal(True) colorDlg.currentColorChanged.connect(self.adjustToColorAndSetData) colorDlg.finished.connect(self.__colorDlgFinished) colorDlg.open() colorDlg.blockSignals(True) colorDlg.setCurrentColor(color) colorDlg.blockSignals(False) self.colorDlg = colorDlg def __colorDlgFinished(self, ret): if ret: color = self.colorDlg.currentColor() self.adjustToColorAndSetData(color) else: self.adjustToColorAndSetData(self.origColor) self.colorDlg = None def adjustToColorAndSetData(self, color): if not color.isValid(): return self.adjustToColor(color) self.setModelData(self.model, self.item.index()) def adjustToColor(self, color): self.colorLbl.setStyleSheet("border: 1px solid black; background-color: rgb(%i, %i, %i);" % (color.red(), color.green(), color.blue())) vals = self.getItemData().split(' ') alpha = vals[3] self.lineEdit.setText("%i %i %i %s" % (color.red(), color.green(), color.blue(), alpha)) def setEditorData(self, index): self.lineEdit.setText(self.getItemData()) def setModelData(self, model, index): model.setData(index, self.lineEdit.text(), QtCore.Qt.EditRole)
[ "brianlach72@gmail.com" ]
brianlach72@gmail.com
2ba8af9a37d1b2976828cea090385da648a31a6a
45cb74f15ebf96b431e5689e554fcdc42062ee08
/4-magnet_particles/solution.py
2c864f0e918fe8e2abfb2ca11901b3067432a85e
[]
no_license
acu192/codewars
d296bc95fd067f0059045494fc445f62f95c060a
905c5397461976335dbcf6a5bb0ffb6b359a29c0
refs/heads/master
2021-01-23T03:52:58.009582
2017-08-04T05:03:06
2017-08-04T05:03:06
86,128,943
0
0
null
null
null
null
UTF-8
Python
false
false
746
py
""" https://www.codewars.com/kata/magnet-particules-in-boxes """ from math import pow def doubles(maxk, maxn): return sum(sum(pow(n+1, -2*k) for n in range(1, maxn+1))/k for k in range(1, maxk+1)) def assertFuzzyEquals(actual, expected, msg=""): merr = 1e-6 inrange = abs(actual - expected) <= merr if (inrange == False): msg = "At 1e-6: Expected value must be {:0.6f} but got {:0.6f}" msg = msg.format(expected, actual) return msg return True print assertFuzzyEquals(doubles(1, 10), 0.5580321939764581) print assertFuzzyEquals(doubles(10, 1000), 0.6921486500921933) print assertFuzzyEquals(doubles(10, 10000), 0.6930471674194457) print assertFuzzyEquals(doubles(20, 10000), 0.6930471955575918)
[ "ryan@rhobota.com" ]
ryan@rhobota.com
e6c86286a352b6e8be637ea94f7acb30ed3348f1
854d0673d18cf1db557d2b9b27c248dd879ba28a
/venv/Lib/site-packages/pymavlink/dialects/v20/paparazzi.py
930bc5ac439eecddc6e991a9774529639ab527a7
[]
no_license
Miao1127/code-charpter3
51e141c0e463f1ea63f371a498d967b520f59853
313dae0b53f1f68fb7ce713ac3eab7e1a2d1b001
refs/heads/master
2023-07-15T21:27:22.688910
2021-08-23T01:13:59
2021-08-23T01:13:59
398,937,184
0
0
null
null
null
null
UTF-8
Python
false
false
1,161,977
py
''' MAVLink protocol implementation (auto-generated by mavgen.py) Generated from: paparazzi.xml,common.xml Note: this file has been auto-generated. DO NOT EDIT ''' from __future__ import print_function from builtins import range from builtins import object import struct, array, time, json, os, sys, platform from ...generator.mavcrc import x25crc import hashlib WIRE_PROTOCOL_VERSION = '2.0' DIALECT = 'paparazzi' PROTOCOL_MARKER_V1 = 0xFE PROTOCOL_MARKER_V2 = 0xFD HEADER_LEN_V1 = 6 HEADER_LEN_V2 = 10 MAVLINK_SIGNATURE_BLOCK_LEN = 13 MAVLINK_IFLAG_SIGNED = 0x01 native_supported = platform.system() != 'Windows' # Not yet supported on other dialects native_force = 'MAVNATIVE_FORCE' in os.environ # Will force use of native code regardless of what client app wants native_testing = 'MAVNATIVE_TESTING' in os.environ # Will force both native and legacy code to be used and their results compared if native_supported and float(WIRE_PROTOCOL_VERSION) <= 1: try: import mavnative except ImportError: print('ERROR LOADING MAVNATIVE - falling back to python implementation') native_supported = False else: # mavnative isn't supported for MAVLink2 yet native_supported = False # some base types from mavlink_types.h MAVLINK_TYPE_CHAR = 0 MAVLINK_TYPE_UINT8_T = 1 MAVLINK_TYPE_INT8_T = 2 MAVLINK_TYPE_UINT16_T = 3 MAVLINK_TYPE_INT16_T = 4 MAVLINK_TYPE_UINT32_T = 5 MAVLINK_TYPE_INT32_T = 6 MAVLINK_TYPE_UINT64_T = 7 MAVLINK_TYPE_INT64_T = 8 MAVLINK_TYPE_FLOAT = 9 MAVLINK_TYPE_DOUBLE = 10 class MAVLink_header(object): '''MAVLink message header''' def __init__(self, msgId, incompat_flags=0, compat_flags=0, mlen=0, seq=0, srcSystem=0, srcComponent=0): self.mlen = mlen self.seq = seq self.srcSystem = srcSystem self.srcComponent = srcComponent self.msgId = msgId self.incompat_flags = incompat_flags self.compat_flags = compat_flags def pack(self, force_mavlink1=False): if WIRE_PROTOCOL_VERSION == '2.0' and not force_mavlink1: return struct.pack('<BBBBBBBHB', 253, self.mlen, self.incompat_flags, self.compat_flags, self.seq, self.srcSystem, self.srcComponent, self.msgId&0xFFFF, self.msgId>>16) return struct.pack('<BBBBBB', PROTOCOL_MARKER_V1, self.mlen, self.seq, self.srcSystem, self.srcComponent, self.msgId) class MAVLink_message(object): '''base MAVLink message class''' def __init__(self, msgId, name): self._header = MAVLink_header(msgId) self._payload = None self._msgbuf = None self._crc = None self._fieldnames = [] self._type = name self._signed = False self._link_id = None def format_attr(self, field): '''override field getter''' raw_attr = getattr(self,field) if isinstance(raw_attr, bytes): raw_attr = raw_attr.decode("utf-8").rstrip("\00") return raw_attr def get_msgbuf(self): if isinstance(self._msgbuf, bytearray): return self._msgbuf return bytearray(self._msgbuf) def get_header(self): return self._header def get_payload(self): return self._payload def get_crc(self): return self._crc def get_fieldnames(self): return self._fieldnames def get_type(self): return self._type def get_msgId(self): return self._header.msgId def get_srcSystem(self): return self._header.srcSystem def get_srcComponent(self): return self._header.srcComponent def get_seq(self): return self._header.seq def get_signed(self): return self._signed def get_link_id(self): return self._link_id def __str__(self): ret = '%s {' % self._type for a in self._fieldnames: v = self.format_attr(a) ret += '%s : %s, ' % (a, v) ret = ret[0:-2] + '}' return ret def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): if other is None: return False if self.get_type() != other.get_type(): return False # We do not compare CRC because native code doesn't provide it #if self.get_crc() != other.get_crc(): # return False if self.get_seq() != other.get_seq(): return False if self.get_srcSystem() != other.get_srcSystem(): return False if self.get_srcComponent() != other.get_srcComponent(): return False for a in self._fieldnames: if self.format_attr(a) != other.format_attr(a): return False return True def to_dict(self): d = dict({}) d['mavpackettype'] = self._type for a in self._fieldnames: d[a] = self.format_attr(a) return d def to_json(self): return json.dumps(self.to_dict()) def sign_packet(self, mav): h = hashlib.new('sha256') self._msgbuf += struct.pack('<BQ', mav.signing.link_id, mav.signing.timestamp)[:7] h.update(mav.signing.secret_key) h.update(self._msgbuf) sig = h.digest()[:6] self._msgbuf += sig mav.signing.timestamp += 1 def pack(self, mav, crc_extra, payload, force_mavlink1=False): plen = len(payload) if WIRE_PROTOCOL_VERSION != '1.0' and not force_mavlink1: # in MAVLink2 we can strip trailing zeros off payloads. This allows for simple # variable length arrays and smaller packets nullbyte = chr(0) # in Python2, type("fred') is str but also type("fred")==bytes if str(type(payload)) == "<class 'bytes'>": nullbyte = 0 while plen > 1 and payload[plen-1] == nullbyte: plen -= 1 self._payload = payload[:plen] incompat_flags = 0 if mav.signing.sign_outgoing: incompat_flags |= MAVLINK_IFLAG_SIGNED self._header = MAVLink_header(self._header.msgId, incompat_flags=incompat_flags, compat_flags=0, mlen=len(self._payload), seq=mav.seq, srcSystem=mav.srcSystem, srcComponent=mav.srcComponent) self._msgbuf = self._header.pack(force_mavlink1=force_mavlink1) + self._payload crc = x25crc(self._msgbuf[1:]) if True: # using CRC extra crc.accumulate_str(struct.pack('B', crc_extra)) self._crc = crc.crc self._msgbuf += struct.pack('<H', self._crc) if mav.signing.sign_outgoing and not force_mavlink1: self.sign_packet(mav) return self._msgbuf # enums class EnumEntry(object): def __init__(self, name, description): self.name = name self.description = description self.param = {} enums = {} # MAV_AUTOPILOT enums['MAV_AUTOPILOT'] = {} MAV_AUTOPILOT_GENERIC = 0 # Generic autopilot, full support for everything enums['MAV_AUTOPILOT'][0] = EnumEntry('MAV_AUTOPILOT_GENERIC', '''Generic autopilot, full support for everything''') MAV_AUTOPILOT_RESERVED = 1 # Reserved for future use. enums['MAV_AUTOPILOT'][1] = EnumEntry('MAV_AUTOPILOT_RESERVED', '''Reserved for future use.''') MAV_AUTOPILOT_SLUGS = 2 # SLUGS autopilot, http://slugsuav.soe.ucsc.edu enums['MAV_AUTOPILOT'][2] = EnumEntry('MAV_AUTOPILOT_SLUGS', '''SLUGS autopilot, http://slugsuav.soe.ucsc.edu''') MAV_AUTOPILOT_ARDUPILOTMEGA = 3 # ArduPilot - Plane/Copter/Rover/Sub/Tracker, http://ardupilot.org enums['MAV_AUTOPILOT'][3] = EnumEntry('MAV_AUTOPILOT_ARDUPILOTMEGA', '''ArduPilot - Plane/Copter/Rover/Sub/Tracker, http://ardupilot.org''') MAV_AUTOPILOT_OPENPILOT = 4 # OpenPilot, http://openpilot.org enums['MAV_AUTOPILOT'][4] = EnumEntry('MAV_AUTOPILOT_OPENPILOT', '''OpenPilot, http://openpilot.org''') MAV_AUTOPILOT_GENERIC_WAYPOINTS_ONLY = 5 # Generic autopilot only supporting simple waypoints enums['MAV_AUTOPILOT'][5] = EnumEntry('MAV_AUTOPILOT_GENERIC_WAYPOINTS_ONLY', '''Generic autopilot only supporting simple waypoints''') MAV_AUTOPILOT_GENERIC_WAYPOINTS_AND_SIMPLE_NAVIGATION_ONLY = 6 # Generic autopilot supporting waypoints and other simple navigation # commands enums['MAV_AUTOPILOT'][6] = EnumEntry('MAV_AUTOPILOT_GENERIC_WAYPOINTS_AND_SIMPLE_NAVIGATION_ONLY', '''Generic autopilot supporting waypoints and other simple navigation commands''') MAV_AUTOPILOT_GENERIC_MISSION_FULL = 7 # Generic autopilot supporting the full mission command set enums['MAV_AUTOPILOT'][7] = EnumEntry('MAV_AUTOPILOT_GENERIC_MISSION_FULL', '''Generic autopilot supporting the full mission command set''') MAV_AUTOPILOT_INVALID = 8 # No valid autopilot, e.g. a GCS or other MAVLink component enums['MAV_AUTOPILOT'][8] = EnumEntry('MAV_AUTOPILOT_INVALID', '''No valid autopilot, e.g. a GCS or other MAVLink component''') MAV_AUTOPILOT_PPZ = 9 # PPZ UAV - http://nongnu.org/paparazzi enums['MAV_AUTOPILOT'][9] = EnumEntry('MAV_AUTOPILOT_PPZ', '''PPZ UAV - http://nongnu.org/paparazzi''') MAV_AUTOPILOT_UDB = 10 # UAV Dev Board enums['MAV_AUTOPILOT'][10] = EnumEntry('MAV_AUTOPILOT_UDB', '''UAV Dev Board''') MAV_AUTOPILOT_FP = 11 # FlexiPilot enums['MAV_AUTOPILOT'][11] = EnumEntry('MAV_AUTOPILOT_FP', '''FlexiPilot''') MAV_AUTOPILOT_PX4 = 12 # PX4 Autopilot - http://px4.io/ enums['MAV_AUTOPILOT'][12] = EnumEntry('MAV_AUTOPILOT_PX4', '''PX4 Autopilot - http://px4.io/''') MAV_AUTOPILOT_SMACCMPILOT = 13 # SMACCMPilot - http://smaccmpilot.org enums['MAV_AUTOPILOT'][13] = EnumEntry('MAV_AUTOPILOT_SMACCMPILOT', '''SMACCMPilot - http://smaccmpilot.org''') MAV_AUTOPILOT_AUTOQUAD = 14 # AutoQuad -- http://autoquad.org enums['MAV_AUTOPILOT'][14] = EnumEntry('MAV_AUTOPILOT_AUTOQUAD', '''AutoQuad -- http://autoquad.org''') MAV_AUTOPILOT_ARMAZILA = 15 # Armazila -- http://armazila.com enums['MAV_AUTOPILOT'][15] = EnumEntry('MAV_AUTOPILOT_ARMAZILA', '''Armazila -- http://armazila.com''') MAV_AUTOPILOT_AEROB = 16 # Aerob -- http://aerob.ru enums['MAV_AUTOPILOT'][16] = EnumEntry('MAV_AUTOPILOT_AEROB', '''Aerob -- http://aerob.ru''') MAV_AUTOPILOT_ASLUAV = 17 # ASLUAV autopilot -- http://www.asl.ethz.ch enums['MAV_AUTOPILOT'][17] = EnumEntry('MAV_AUTOPILOT_ASLUAV', '''ASLUAV autopilot -- http://www.asl.ethz.ch''') MAV_AUTOPILOT_SMARTAP = 18 # SmartAP Autopilot - http://sky-drones.com enums['MAV_AUTOPILOT'][18] = EnumEntry('MAV_AUTOPILOT_SMARTAP', '''SmartAP Autopilot - http://sky-drones.com''') MAV_AUTOPILOT_AIRRAILS = 19 # AirRails - http://uaventure.com enums['MAV_AUTOPILOT'][19] = EnumEntry('MAV_AUTOPILOT_AIRRAILS', '''AirRails - http://uaventure.com''') MAV_AUTOPILOT_ENUM_END = 20 # enums['MAV_AUTOPILOT'][20] = EnumEntry('MAV_AUTOPILOT_ENUM_END', '''''') # MAV_TYPE enums['MAV_TYPE'] = {} MAV_TYPE_GENERIC = 0 # Generic micro air vehicle enums['MAV_TYPE'][0] = EnumEntry('MAV_TYPE_GENERIC', '''Generic micro air vehicle''') MAV_TYPE_FIXED_WING = 1 # Fixed wing aircraft. enums['MAV_TYPE'][1] = EnumEntry('MAV_TYPE_FIXED_WING', '''Fixed wing aircraft.''') MAV_TYPE_QUADROTOR = 2 # Quadrotor enums['MAV_TYPE'][2] = EnumEntry('MAV_TYPE_QUADROTOR', '''Quadrotor''') MAV_TYPE_COAXIAL = 3 # Coaxial helicopter enums['MAV_TYPE'][3] = EnumEntry('MAV_TYPE_COAXIAL', '''Coaxial helicopter''') MAV_TYPE_HELICOPTER = 4 # Normal helicopter with tail rotor. enums['MAV_TYPE'][4] = EnumEntry('MAV_TYPE_HELICOPTER', '''Normal helicopter with tail rotor.''') MAV_TYPE_ANTENNA_TRACKER = 5 # Ground installation enums['MAV_TYPE'][5] = EnumEntry('MAV_TYPE_ANTENNA_TRACKER', '''Ground installation''') MAV_TYPE_GCS = 6 # Operator control unit / ground control station enums['MAV_TYPE'][6] = EnumEntry('MAV_TYPE_GCS', '''Operator control unit / ground control station''') MAV_TYPE_AIRSHIP = 7 # Airship, controlled enums['MAV_TYPE'][7] = EnumEntry('MAV_TYPE_AIRSHIP', '''Airship, controlled''') MAV_TYPE_FREE_BALLOON = 8 # Free balloon, uncontrolled enums['MAV_TYPE'][8] = EnumEntry('MAV_TYPE_FREE_BALLOON', '''Free balloon, uncontrolled''') MAV_TYPE_ROCKET = 9 # Rocket enums['MAV_TYPE'][9] = EnumEntry('MAV_TYPE_ROCKET', '''Rocket''') MAV_TYPE_GROUND_ROVER = 10 # Ground rover enums['MAV_TYPE'][10] = EnumEntry('MAV_TYPE_GROUND_ROVER', '''Ground rover''') MAV_TYPE_SURFACE_BOAT = 11 # Surface vessel, boat, ship enums['MAV_TYPE'][11] = EnumEntry('MAV_TYPE_SURFACE_BOAT', '''Surface vessel, boat, ship''') MAV_TYPE_SUBMARINE = 12 # Submarine enums['MAV_TYPE'][12] = EnumEntry('MAV_TYPE_SUBMARINE', '''Submarine''') MAV_TYPE_HEXAROTOR = 13 # Hexarotor enums['MAV_TYPE'][13] = EnumEntry('MAV_TYPE_HEXAROTOR', '''Hexarotor''') MAV_TYPE_OCTOROTOR = 14 # Octorotor enums['MAV_TYPE'][14] = EnumEntry('MAV_TYPE_OCTOROTOR', '''Octorotor''') MAV_TYPE_TRICOPTER = 15 # Tricopter enums['MAV_TYPE'][15] = EnumEntry('MAV_TYPE_TRICOPTER', '''Tricopter''') MAV_TYPE_FLAPPING_WING = 16 # Flapping wing enums['MAV_TYPE'][16] = EnumEntry('MAV_TYPE_FLAPPING_WING', '''Flapping wing''') MAV_TYPE_KITE = 17 # Kite enums['MAV_TYPE'][17] = EnumEntry('MAV_TYPE_KITE', '''Kite''') MAV_TYPE_ONBOARD_CONTROLLER = 18 # Onboard companion controller enums['MAV_TYPE'][18] = EnumEntry('MAV_TYPE_ONBOARD_CONTROLLER', '''Onboard companion controller''') MAV_TYPE_VTOL_DUOROTOR = 19 # Two-rotor VTOL using control surfaces in vertical operation in # addition. Tailsitter. enums['MAV_TYPE'][19] = EnumEntry('MAV_TYPE_VTOL_DUOROTOR', '''Two-rotor VTOL using control surfaces in vertical operation in addition. Tailsitter.''') MAV_TYPE_VTOL_QUADROTOR = 20 # Quad-rotor VTOL using a V-shaped quad config in vertical operation. # Tailsitter. enums['MAV_TYPE'][20] = EnumEntry('MAV_TYPE_VTOL_QUADROTOR', '''Quad-rotor VTOL using a V-shaped quad config in vertical operation. Tailsitter.''') MAV_TYPE_VTOL_TILTROTOR = 21 # Tiltrotor VTOL enums['MAV_TYPE'][21] = EnumEntry('MAV_TYPE_VTOL_TILTROTOR', '''Tiltrotor VTOL''') MAV_TYPE_VTOL_RESERVED2 = 22 # VTOL reserved 2 enums['MAV_TYPE'][22] = EnumEntry('MAV_TYPE_VTOL_RESERVED2', '''VTOL reserved 2''') MAV_TYPE_VTOL_RESERVED3 = 23 # VTOL reserved 3 enums['MAV_TYPE'][23] = EnumEntry('MAV_TYPE_VTOL_RESERVED3', '''VTOL reserved 3''') MAV_TYPE_VTOL_RESERVED4 = 24 # VTOL reserved 4 enums['MAV_TYPE'][24] = EnumEntry('MAV_TYPE_VTOL_RESERVED4', '''VTOL reserved 4''') MAV_TYPE_VTOL_RESERVED5 = 25 # VTOL reserved 5 enums['MAV_TYPE'][25] = EnumEntry('MAV_TYPE_VTOL_RESERVED5', '''VTOL reserved 5''') MAV_TYPE_GIMBAL = 26 # Gimbal enums['MAV_TYPE'][26] = EnumEntry('MAV_TYPE_GIMBAL', '''Gimbal''') MAV_TYPE_ADSB = 27 # ADSB system enums['MAV_TYPE'][27] = EnumEntry('MAV_TYPE_ADSB', '''ADSB system''') MAV_TYPE_PARAFOIL = 28 # Steerable, nonrigid airfoil enums['MAV_TYPE'][28] = EnumEntry('MAV_TYPE_PARAFOIL', '''Steerable, nonrigid airfoil''') MAV_TYPE_DODECAROTOR = 29 # Dodecarotor enums['MAV_TYPE'][29] = EnumEntry('MAV_TYPE_DODECAROTOR', '''Dodecarotor''') MAV_TYPE_CAMERA = 30 # Camera enums['MAV_TYPE'][30] = EnumEntry('MAV_TYPE_CAMERA', '''Camera''') MAV_TYPE_CHARGING_STATION = 31 # Charging station enums['MAV_TYPE'][31] = EnumEntry('MAV_TYPE_CHARGING_STATION', '''Charging station''') MAV_TYPE_FLARM = 32 # FLARM collision avoidance system enums['MAV_TYPE'][32] = EnumEntry('MAV_TYPE_FLARM', '''FLARM collision avoidance system''') MAV_TYPE_SERVO = 33 # Servo enums['MAV_TYPE'][33] = EnumEntry('MAV_TYPE_SERVO', '''Servo''') MAV_TYPE_ENUM_END = 34 # enums['MAV_TYPE'][34] = EnumEntry('MAV_TYPE_ENUM_END', '''''') # FIRMWARE_VERSION_TYPE enums['FIRMWARE_VERSION_TYPE'] = {} FIRMWARE_VERSION_TYPE_DEV = 0 # development release enums['FIRMWARE_VERSION_TYPE'][0] = EnumEntry('FIRMWARE_VERSION_TYPE_DEV', '''development release''') FIRMWARE_VERSION_TYPE_ALPHA = 64 # alpha release enums['FIRMWARE_VERSION_TYPE'][64] = EnumEntry('FIRMWARE_VERSION_TYPE_ALPHA', '''alpha release''') FIRMWARE_VERSION_TYPE_BETA = 128 # beta release enums['FIRMWARE_VERSION_TYPE'][128] = EnumEntry('FIRMWARE_VERSION_TYPE_BETA', '''beta release''') FIRMWARE_VERSION_TYPE_RC = 192 # release candidate enums['FIRMWARE_VERSION_TYPE'][192] = EnumEntry('FIRMWARE_VERSION_TYPE_RC', '''release candidate''') FIRMWARE_VERSION_TYPE_OFFICIAL = 255 # official stable release enums['FIRMWARE_VERSION_TYPE'][255] = EnumEntry('FIRMWARE_VERSION_TYPE_OFFICIAL', '''official stable release''') FIRMWARE_VERSION_TYPE_ENUM_END = 256 # enums['FIRMWARE_VERSION_TYPE'][256] = EnumEntry('FIRMWARE_VERSION_TYPE_ENUM_END', '''''') # MAV_MODE_FLAG enums['MAV_MODE_FLAG'] = {} MAV_MODE_FLAG_CUSTOM_MODE_ENABLED = 1 # 0b00000001 Reserved for future use. enums['MAV_MODE_FLAG'][1] = EnumEntry('MAV_MODE_FLAG_CUSTOM_MODE_ENABLED', '''0b00000001 Reserved for future use.''') MAV_MODE_FLAG_TEST_ENABLED = 2 # 0b00000010 system has a test mode enabled. This flag is intended for # temporary system tests and should not be # used for stable implementations. enums['MAV_MODE_FLAG'][2] = EnumEntry('MAV_MODE_FLAG_TEST_ENABLED', '''0b00000010 system has a test mode enabled. This flag is intended for temporary system tests and should not be used for stable implementations.''') MAV_MODE_FLAG_AUTO_ENABLED = 4 # 0b00000100 autonomous mode enabled, system finds its own goal # positions. Guided flag can be set or not, # depends on the actual implementation. enums['MAV_MODE_FLAG'][4] = EnumEntry('MAV_MODE_FLAG_AUTO_ENABLED', '''0b00000100 autonomous mode enabled, system finds its own goal positions. Guided flag can be set or not, depends on the actual implementation.''') MAV_MODE_FLAG_GUIDED_ENABLED = 8 # 0b00001000 guided mode enabled, system flies waypoints / mission # items. enums['MAV_MODE_FLAG'][8] = EnumEntry('MAV_MODE_FLAG_GUIDED_ENABLED', '''0b00001000 guided mode enabled, system flies waypoints / mission items.''') MAV_MODE_FLAG_STABILIZE_ENABLED = 16 # 0b00010000 system stabilizes electronically its attitude (and # optionally position). It needs however # further control inputs to move around. enums['MAV_MODE_FLAG'][16] = EnumEntry('MAV_MODE_FLAG_STABILIZE_ENABLED', '''0b00010000 system stabilizes electronically its attitude (and optionally position). It needs however further control inputs to move around.''') MAV_MODE_FLAG_HIL_ENABLED = 32 # 0b00100000 hardware in the loop simulation. All motors / actuators are # blocked, but internal software is full # operational. enums['MAV_MODE_FLAG'][32] = EnumEntry('MAV_MODE_FLAG_HIL_ENABLED', '''0b00100000 hardware in the loop simulation. All motors / actuators are blocked, but internal software is full operational.''') MAV_MODE_FLAG_MANUAL_INPUT_ENABLED = 64 # 0b01000000 remote control input is enabled. enums['MAV_MODE_FLAG'][64] = EnumEntry('MAV_MODE_FLAG_MANUAL_INPUT_ENABLED', '''0b01000000 remote control input is enabled.''') MAV_MODE_FLAG_SAFETY_ARMED = 128 # 0b10000000 MAV safety set to armed. Motors are enabled / running / can # start. Ready to fly. Additional note: this # flag is to be ignore when sent in the # command MAV_CMD_DO_SET_MODE and # MAV_CMD_COMPONENT_ARM_DISARM shall be used # instead. The flag can still be used to # report the armed state. enums['MAV_MODE_FLAG'][128] = EnumEntry('MAV_MODE_FLAG_SAFETY_ARMED', '''0b10000000 MAV safety set to armed. Motors are enabled / running / can start. Ready to fly. Additional note: this flag is to be ignore when sent in the command MAV_CMD_DO_SET_MODE and MAV_CMD_COMPONENT_ARM_DISARM shall be used instead. The flag can still be used to report the armed state.''') MAV_MODE_FLAG_ENUM_END = 129 # enums['MAV_MODE_FLAG'][129] = EnumEntry('MAV_MODE_FLAG_ENUM_END', '''''') # MAV_MODE_FLAG_DECODE_POSITION enums['MAV_MODE_FLAG_DECODE_POSITION'] = {} MAV_MODE_FLAG_DECODE_POSITION_CUSTOM_MODE = 1 # Eighth bit: 00000001 enums['MAV_MODE_FLAG_DECODE_POSITION'][1] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_CUSTOM_MODE', '''Eighth bit: 00000001''') MAV_MODE_FLAG_DECODE_POSITION_TEST = 2 # Seventh bit: 00000010 enums['MAV_MODE_FLAG_DECODE_POSITION'][2] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_TEST', '''Seventh bit: 00000010''') MAV_MODE_FLAG_DECODE_POSITION_AUTO = 4 # Sixth bit: 00000100 enums['MAV_MODE_FLAG_DECODE_POSITION'][4] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_AUTO', '''Sixth bit: 00000100''') MAV_MODE_FLAG_DECODE_POSITION_GUIDED = 8 # Fifth bit: 00001000 enums['MAV_MODE_FLAG_DECODE_POSITION'][8] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_GUIDED', '''Fifth bit: 00001000''') MAV_MODE_FLAG_DECODE_POSITION_STABILIZE = 16 # Fourth bit: 00010000 enums['MAV_MODE_FLAG_DECODE_POSITION'][16] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_STABILIZE', '''Fourth bit: 00010000''') MAV_MODE_FLAG_DECODE_POSITION_HIL = 32 # Third bit: 00100000 enums['MAV_MODE_FLAG_DECODE_POSITION'][32] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_HIL', '''Third bit: 00100000''') MAV_MODE_FLAG_DECODE_POSITION_MANUAL = 64 # Second bit: 01000000 enums['MAV_MODE_FLAG_DECODE_POSITION'][64] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_MANUAL', '''Second bit: 01000000''') MAV_MODE_FLAG_DECODE_POSITION_SAFETY = 128 # First bit: 10000000 enums['MAV_MODE_FLAG_DECODE_POSITION'][128] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_SAFETY', '''First bit: 10000000''') MAV_MODE_FLAG_DECODE_POSITION_ENUM_END = 129 # enums['MAV_MODE_FLAG_DECODE_POSITION'][129] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_ENUM_END', '''''') # MAV_GOTO enums['MAV_GOTO'] = {} MAV_GOTO_DO_HOLD = 0 # Hold at the current position. enums['MAV_GOTO'][0] = EnumEntry('MAV_GOTO_DO_HOLD', '''Hold at the current position.''') MAV_GOTO_DO_CONTINUE = 1 # Continue with the next item in mission execution. enums['MAV_GOTO'][1] = EnumEntry('MAV_GOTO_DO_CONTINUE', '''Continue with the next item in mission execution.''') MAV_GOTO_HOLD_AT_CURRENT_POSITION = 2 # Hold at the current position of the system enums['MAV_GOTO'][2] = EnumEntry('MAV_GOTO_HOLD_AT_CURRENT_POSITION', '''Hold at the current position of the system''') MAV_GOTO_HOLD_AT_SPECIFIED_POSITION = 3 # Hold at the position specified in the parameters of the DO_HOLD action enums['MAV_GOTO'][3] = EnumEntry('MAV_GOTO_HOLD_AT_SPECIFIED_POSITION', '''Hold at the position specified in the parameters of the DO_HOLD action''') MAV_GOTO_ENUM_END = 4 # enums['MAV_GOTO'][4] = EnumEntry('MAV_GOTO_ENUM_END', '''''') # MAV_MODE enums['MAV_MODE'] = {} MAV_MODE_PREFLIGHT = 0 # System is not ready to fly, booting, calibrating, etc. No flag is set. enums['MAV_MODE'][0] = EnumEntry('MAV_MODE_PREFLIGHT', '''System is not ready to fly, booting, calibrating, etc. No flag is set.''') MAV_MODE_MANUAL_DISARMED = 64 # System is allowed to be active, under manual (RC) control, no # stabilization enums['MAV_MODE'][64] = EnumEntry('MAV_MODE_MANUAL_DISARMED', '''System is allowed to be active, under manual (RC) control, no stabilization''') MAV_MODE_TEST_DISARMED = 66 # UNDEFINED mode. This solely depends on the autopilot - use with # caution, intended for developers only. enums['MAV_MODE'][66] = EnumEntry('MAV_MODE_TEST_DISARMED', '''UNDEFINED mode. This solely depends on the autopilot - use with caution, intended for developers only.''') MAV_MODE_STABILIZE_DISARMED = 80 # System is allowed to be active, under assisted RC control. enums['MAV_MODE'][80] = EnumEntry('MAV_MODE_STABILIZE_DISARMED', '''System is allowed to be active, under assisted RC control.''') MAV_MODE_GUIDED_DISARMED = 88 # System is allowed to be active, under autonomous control, manual # setpoint enums['MAV_MODE'][88] = EnumEntry('MAV_MODE_GUIDED_DISARMED', '''System is allowed to be active, under autonomous control, manual setpoint''') MAV_MODE_AUTO_DISARMED = 92 # System is allowed to be active, under autonomous control and # navigation (the trajectory is decided # onboard and not pre-programmed by waypoints) enums['MAV_MODE'][92] = EnumEntry('MAV_MODE_AUTO_DISARMED', '''System is allowed to be active, under autonomous control and navigation (the trajectory is decided onboard and not pre-programmed by waypoints)''') MAV_MODE_MANUAL_ARMED = 192 # System is allowed to be active, under manual (RC) control, no # stabilization enums['MAV_MODE'][192] = EnumEntry('MAV_MODE_MANUAL_ARMED', '''System is allowed to be active, under manual (RC) control, no stabilization''') MAV_MODE_TEST_ARMED = 194 # UNDEFINED mode. This solely depends on the autopilot - use with # caution, intended for developers only. enums['MAV_MODE'][194] = EnumEntry('MAV_MODE_TEST_ARMED', '''UNDEFINED mode. This solely depends on the autopilot - use with caution, intended for developers only.''') MAV_MODE_STABILIZE_ARMED = 208 # System is allowed to be active, under assisted RC control. enums['MAV_MODE'][208] = EnumEntry('MAV_MODE_STABILIZE_ARMED', '''System is allowed to be active, under assisted RC control.''') MAV_MODE_GUIDED_ARMED = 216 # System is allowed to be active, under autonomous control, manual # setpoint enums['MAV_MODE'][216] = EnumEntry('MAV_MODE_GUIDED_ARMED', '''System is allowed to be active, under autonomous control, manual setpoint''') MAV_MODE_AUTO_ARMED = 220 # System is allowed to be active, under autonomous control and # navigation (the trajectory is decided # onboard and not pre-programmed by waypoints) enums['MAV_MODE'][220] = EnumEntry('MAV_MODE_AUTO_ARMED', '''System is allowed to be active, under autonomous control and navigation (the trajectory is decided onboard and not pre-programmed by waypoints)''') MAV_MODE_ENUM_END = 221 # enums['MAV_MODE'][221] = EnumEntry('MAV_MODE_ENUM_END', '''''') # MAV_STATE enums['MAV_STATE'] = {} MAV_STATE_UNINIT = 0 # Uninitialized system, state is unknown. enums['MAV_STATE'][0] = EnumEntry('MAV_STATE_UNINIT', '''Uninitialized system, state is unknown.''') MAV_STATE_BOOT = 1 # System is booting up. enums['MAV_STATE'][1] = EnumEntry('MAV_STATE_BOOT', '''System is booting up.''') MAV_STATE_CALIBRATING = 2 # System is calibrating and not flight-ready. enums['MAV_STATE'][2] = EnumEntry('MAV_STATE_CALIBRATING', '''System is calibrating and not flight-ready.''') MAV_STATE_STANDBY = 3 # System is grounded and on standby. It can be launched any time. enums['MAV_STATE'][3] = EnumEntry('MAV_STATE_STANDBY', '''System is grounded and on standby. It can be launched any time.''') MAV_STATE_ACTIVE = 4 # System is active and might be already airborne. Motors are engaged. enums['MAV_STATE'][4] = EnumEntry('MAV_STATE_ACTIVE', '''System is active and might be already airborne. Motors are engaged.''') MAV_STATE_CRITICAL = 5 # System is in a non-normal flight mode. It can however still navigate. enums['MAV_STATE'][5] = EnumEntry('MAV_STATE_CRITICAL', '''System is in a non-normal flight mode. It can however still navigate.''') MAV_STATE_EMERGENCY = 6 # System is in a non-normal flight mode. It lost control over parts or # over the whole airframe. It is in mayday and # going down. enums['MAV_STATE'][6] = EnumEntry('MAV_STATE_EMERGENCY', '''System is in a non-normal flight mode. It lost control over parts or over the whole airframe. It is in mayday and going down.''') MAV_STATE_POWEROFF = 7 # System just initialized its power-down sequence, will shut down now. enums['MAV_STATE'][7] = EnumEntry('MAV_STATE_POWEROFF', '''System just initialized its power-down sequence, will shut down now.''') MAV_STATE_FLIGHT_TERMINATION = 8 # System is terminating itself. enums['MAV_STATE'][8] = EnumEntry('MAV_STATE_FLIGHT_TERMINATION', '''System is terminating itself.''') MAV_STATE_ENUM_END = 9 # enums['MAV_STATE'][9] = EnumEntry('MAV_STATE_ENUM_END', '''''') # MAV_COMPONENT enums['MAV_COMPONENT'] = {} MAV_COMP_ID_ALL = 0 # Used to broadcast messages to all components of the receiving system. # Components should attempt to process # messages with this component ID and forward # to components on any other interfaces. enums['MAV_COMPONENT'][0] = EnumEntry('MAV_COMP_ID_ALL', '''Used to broadcast messages to all components of the receiving system. Components should attempt to process messages with this component ID and forward to components on any other interfaces.''') MAV_COMP_ID_AUTOPILOT1 = 1 # System flight controller component ("autopilot"). Only one autopilot # is expected in a particular system. enums['MAV_COMPONENT'][1] = EnumEntry('MAV_COMP_ID_AUTOPILOT1', '''System flight controller component ("autopilot"). Only one autopilot is expected in a particular system.''') MAV_COMP_ID_USER1 = 25 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][25] = EnumEntry('MAV_COMP_ID_USER1', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER2 = 26 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][26] = EnumEntry('MAV_COMP_ID_USER2', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER3 = 27 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][27] = EnumEntry('MAV_COMP_ID_USER3', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER4 = 28 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][28] = EnumEntry('MAV_COMP_ID_USER4', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER5 = 29 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][29] = EnumEntry('MAV_COMP_ID_USER5', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER6 = 30 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][30] = EnumEntry('MAV_COMP_ID_USER6', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER7 = 31 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][31] = EnumEntry('MAV_COMP_ID_USER7', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER8 = 32 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][32] = EnumEntry('MAV_COMP_ID_USER8', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER9 = 33 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][33] = EnumEntry('MAV_COMP_ID_USER9', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER10 = 34 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][34] = EnumEntry('MAV_COMP_ID_USER10', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER11 = 35 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][35] = EnumEntry('MAV_COMP_ID_USER11', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER12 = 36 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][36] = EnumEntry('MAV_COMP_ID_USER12', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER13 = 37 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][37] = EnumEntry('MAV_COMP_ID_USER13', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER14 = 38 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][38] = EnumEntry('MAV_COMP_ID_USER14', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER15 = 39 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][39] = EnumEntry('MAV_COMP_ID_USER15', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USE16 = 40 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][40] = EnumEntry('MAV_COMP_ID_USE16', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER17 = 41 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][41] = EnumEntry('MAV_COMP_ID_USER17', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER18 = 42 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][42] = EnumEntry('MAV_COMP_ID_USER18', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER19 = 43 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][43] = EnumEntry('MAV_COMP_ID_USER19', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER20 = 44 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][44] = EnumEntry('MAV_COMP_ID_USER20', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER21 = 45 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][45] = EnumEntry('MAV_COMP_ID_USER21', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER22 = 46 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][46] = EnumEntry('MAV_COMP_ID_USER22', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER23 = 47 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][47] = EnumEntry('MAV_COMP_ID_USER23', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER24 = 48 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][48] = EnumEntry('MAV_COMP_ID_USER24', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER25 = 49 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][49] = EnumEntry('MAV_COMP_ID_USER25', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER26 = 50 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][50] = EnumEntry('MAV_COMP_ID_USER26', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER27 = 51 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][51] = EnumEntry('MAV_COMP_ID_USER27', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER28 = 52 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][52] = EnumEntry('MAV_COMP_ID_USER28', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER29 = 53 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][53] = EnumEntry('MAV_COMP_ID_USER29', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER30 = 54 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][54] = EnumEntry('MAV_COMP_ID_USER30', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER31 = 55 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][55] = EnumEntry('MAV_COMP_ID_USER31', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER32 = 56 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][56] = EnumEntry('MAV_COMP_ID_USER32', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER33 = 57 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][57] = EnumEntry('MAV_COMP_ID_USER33', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER34 = 58 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][58] = EnumEntry('MAV_COMP_ID_USER34', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER35 = 59 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][59] = EnumEntry('MAV_COMP_ID_USER35', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER36 = 60 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][60] = EnumEntry('MAV_COMP_ID_USER36', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER37 = 61 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][61] = EnumEntry('MAV_COMP_ID_USER37', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER38 = 62 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][62] = EnumEntry('MAV_COMP_ID_USER38', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER39 = 63 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][63] = EnumEntry('MAV_COMP_ID_USER39', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER40 = 64 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][64] = EnumEntry('MAV_COMP_ID_USER40', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER41 = 65 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][65] = EnumEntry('MAV_COMP_ID_USER41', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER42 = 66 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][66] = EnumEntry('MAV_COMP_ID_USER42', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER43 = 67 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][67] = EnumEntry('MAV_COMP_ID_USER43', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER44 = 68 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][68] = EnumEntry('MAV_COMP_ID_USER44', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER45 = 69 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][69] = EnumEntry('MAV_COMP_ID_USER45', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER46 = 70 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][70] = EnumEntry('MAV_COMP_ID_USER46', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER47 = 71 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][71] = EnumEntry('MAV_COMP_ID_USER47', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER48 = 72 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][72] = EnumEntry('MAV_COMP_ID_USER48', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER49 = 73 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][73] = EnumEntry('MAV_COMP_ID_USER49', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER50 = 74 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][74] = EnumEntry('MAV_COMP_ID_USER50', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER51 = 75 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][75] = EnumEntry('MAV_COMP_ID_USER51', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER52 = 76 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][76] = EnumEntry('MAV_COMP_ID_USER52', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER53 = 77 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][77] = EnumEntry('MAV_COMP_ID_USER53', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER54 = 78 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][78] = EnumEntry('MAV_COMP_ID_USER54', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER55 = 79 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][79] = EnumEntry('MAV_COMP_ID_USER55', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER56 = 80 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][80] = EnumEntry('MAV_COMP_ID_USER56', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER57 = 81 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][81] = EnumEntry('MAV_COMP_ID_USER57', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER58 = 82 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][82] = EnumEntry('MAV_COMP_ID_USER58', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER59 = 83 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][83] = EnumEntry('MAV_COMP_ID_USER59', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER60 = 84 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][84] = EnumEntry('MAV_COMP_ID_USER60', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER61 = 85 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][85] = EnumEntry('MAV_COMP_ID_USER61', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER62 = 86 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][86] = EnumEntry('MAV_COMP_ID_USER62', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER63 = 87 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][87] = EnumEntry('MAV_COMP_ID_USER63', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER64 = 88 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][88] = EnumEntry('MAV_COMP_ID_USER64', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER65 = 89 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][89] = EnumEntry('MAV_COMP_ID_USER65', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER66 = 90 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][90] = EnumEntry('MAV_COMP_ID_USER66', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER67 = 91 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][91] = EnumEntry('MAV_COMP_ID_USER67', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER68 = 92 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][92] = EnumEntry('MAV_COMP_ID_USER68', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER69 = 93 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][93] = EnumEntry('MAV_COMP_ID_USER69', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER70 = 94 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][94] = EnumEntry('MAV_COMP_ID_USER70', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER71 = 95 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][95] = EnumEntry('MAV_COMP_ID_USER71', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER72 = 96 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][96] = EnumEntry('MAV_COMP_ID_USER72', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER73 = 97 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][97] = EnumEntry('MAV_COMP_ID_USER73', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER74 = 98 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][98] = EnumEntry('MAV_COMP_ID_USER74', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_USER75 = 99 # Id for a component on privately managed MAVLink network. Can be used # for any purpose but may not be published by # components outside of the private network. enums['MAV_COMPONENT'][99] = EnumEntry('MAV_COMP_ID_USER75', '''Id for a component on privately managed MAVLink network. Can be used for any purpose but may not be published by components outside of the private network.''') MAV_COMP_ID_CAMERA = 100 # Camera #1. enums['MAV_COMPONENT'][100] = EnumEntry('MAV_COMP_ID_CAMERA', '''Camera #1.''') MAV_COMP_ID_CAMERA2 = 101 # Camera #2. enums['MAV_COMPONENT'][101] = EnumEntry('MAV_COMP_ID_CAMERA2', '''Camera #2.''') MAV_COMP_ID_CAMERA3 = 102 # Camera #3. enums['MAV_COMPONENT'][102] = EnumEntry('MAV_COMP_ID_CAMERA3', '''Camera #3.''') MAV_COMP_ID_CAMERA4 = 103 # Camera #4. enums['MAV_COMPONENT'][103] = EnumEntry('MAV_COMP_ID_CAMERA4', '''Camera #4.''') MAV_COMP_ID_CAMERA5 = 104 # Camera #5. enums['MAV_COMPONENT'][104] = EnumEntry('MAV_COMP_ID_CAMERA5', '''Camera #5.''') MAV_COMP_ID_CAMERA6 = 105 # Camera #6. enums['MAV_COMPONENT'][105] = EnumEntry('MAV_COMP_ID_CAMERA6', '''Camera #6.''') MAV_COMP_ID_SERVO1 = 140 # Servo #1. enums['MAV_COMPONENT'][140] = EnumEntry('MAV_COMP_ID_SERVO1', '''Servo #1.''') MAV_COMP_ID_SERVO2 = 141 # Servo #2. enums['MAV_COMPONENT'][141] = EnumEntry('MAV_COMP_ID_SERVO2', '''Servo #2.''') MAV_COMP_ID_SERVO3 = 142 # Servo #3. enums['MAV_COMPONENT'][142] = EnumEntry('MAV_COMP_ID_SERVO3', '''Servo #3.''') MAV_COMP_ID_SERVO4 = 143 # Servo #4. enums['MAV_COMPONENT'][143] = EnumEntry('MAV_COMP_ID_SERVO4', '''Servo #4.''') MAV_COMP_ID_SERVO5 = 144 # Servo #5. enums['MAV_COMPONENT'][144] = EnumEntry('MAV_COMP_ID_SERVO5', '''Servo #5.''') MAV_COMP_ID_SERVO6 = 145 # Servo #6. enums['MAV_COMPONENT'][145] = EnumEntry('MAV_COMP_ID_SERVO6', '''Servo #6.''') MAV_COMP_ID_SERVO7 = 146 # Servo #7. enums['MAV_COMPONENT'][146] = EnumEntry('MAV_COMP_ID_SERVO7', '''Servo #7.''') MAV_COMP_ID_SERVO8 = 147 # Servo #8. enums['MAV_COMPONENT'][147] = EnumEntry('MAV_COMP_ID_SERVO8', '''Servo #8.''') MAV_COMP_ID_SERVO9 = 148 # Servo #9. enums['MAV_COMPONENT'][148] = EnumEntry('MAV_COMP_ID_SERVO9', '''Servo #9.''') MAV_COMP_ID_SERVO10 = 149 # Servo #10. enums['MAV_COMPONENT'][149] = EnumEntry('MAV_COMP_ID_SERVO10', '''Servo #10.''') MAV_COMP_ID_SERVO11 = 150 # Servo #11. enums['MAV_COMPONENT'][150] = EnumEntry('MAV_COMP_ID_SERVO11', '''Servo #11.''') MAV_COMP_ID_SERVO12 = 151 # Servo #12. enums['MAV_COMPONENT'][151] = EnumEntry('MAV_COMP_ID_SERVO12', '''Servo #12.''') MAV_COMP_ID_SERVO13 = 152 # Servo #13. enums['MAV_COMPONENT'][152] = EnumEntry('MAV_COMP_ID_SERVO13', '''Servo #13.''') MAV_COMP_ID_SERVO14 = 153 # Servo #14. enums['MAV_COMPONENT'][153] = EnumEntry('MAV_COMP_ID_SERVO14', '''Servo #14.''') MAV_COMP_ID_GIMBAL = 154 # Gimbal #1. enums['MAV_COMPONENT'][154] = EnumEntry('MAV_COMP_ID_GIMBAL', '''Gimbal #1.''') MAV_COMP_ID_LOG = 155 # Logging component. enums['MAV_COMPONENT'][155] = EnumEntry('MAV_COMP_ID_LOG', '''Logging component.''') MAV_COMP_ID_ADSB = 156 # Automatic Dependent Surveillance-Broadcast (ADS-B) component. enums['MAV_COMPONENT'][156] = EnumEntry('MAV_COMP_ID_ADSB', '''Automatic Dependent Surveillance-Broadcast (ADS-B) component.''') MAV_COMP_ID_OSD = 157 # On Screen Display (OSD) devices for video links. enums['MAV_COMPONENT'][157] = EnumEntry('MAV_COMP_ID_OSD', '''On Screen Display (OSD) devices for video links.''') MAV_COMP_ID_PERIPHERAL = 158 # Generic autopilot peripheral component ID. Meant for devices that do # not implement the parameter microservice. enums['MAV_COMPONENT'][158] = EnumEntry('MAV_COMP_ID_PERIPHERAL', '''Generic autopilot peripheral component ID. Meant for devices that do not implement the parameter microservice.''') MAV_COMP_ID_QX1_GIMBAL = 159 # Gimbal ID for QX1. enums['MAV_COMPONENT'][159] = EnumEntry('MAV_COMP_ID_QX1_GIMBAL', '''Gimbal ID for QX1.''') MAV_COMP_ID_FLARM = 160 # FLARM collision alert component. enums['MAV_COMPONENT'][160] = EnumEntry('MAV_COMP_ID_FLARM', '''FLARM collision alert component.''') MAV_COMP_ID_GIMBAL2 = 171 # Gimbal #2. enums['MAV_COMPONENT'][171] = EnumEntry('MAV_COMP_ID_GIMBAL2', '''Gimbal #2.''') MAV_COMP_ID_GIMBAL3 = 172 # Gimbal #3. enums['MAV_COMPONENT'][172] = EnumEntry('MAV_COMP_ID_GIMBAL3', '''Gimbal #3.''') MAV_COMP_ID_GIMBAL4 = 173 # Gimbal #4 enums['MAV_COMPONENT'][173] = EnumEntry('MAV_COMP_ID_GIMBAL4', '''Gimbal #4''') MAV_COMP_ID_GIMBAL5 = 174 # Gimbal #5. enums['MAV_COMPONENT'][174] = EnumEntry('MAV_COMP_ID_GIMBAL5', '''Gimbal #5.''') MAV_COMP_ID_GIMBAL6 = 175 # Gimbal #6. enums['MAV_COMPONENT'][175] = EnumEntry('MAV_COMP_ID_GIMBAL6', '''Gimbal #6.''') MAV_COMP_ID_MISSIONPLANNER = 190 # Component that can generate/supply a mission flight plan (e.g. GCS or # developer API). enums['MAV_COMPONENT'][190] = EnumEntry('MAV_COMP_ID_MISSIONPLANNER', '''Component that can generate/supply a mission flight plan (e.g. GCS or developer API).''') MAV_COMP_ID_PATHPLANNER = 195 # Component that finds an optimal path between points based on a certain # constraint (e.g. minimum snap, shortest # path, cost, etc.). enums['MAV_COMPONENT'][195] = EnumEntry('MAV_COMP_ID_PATHPLANNER', '''Component that finds an optimal path between points based on a certain constraint (e.g. minimum snap, shortest path, cost, etc.).''') MAV_COMP_ID_OBSTACLE_AVOIDANCE = 196 # Component that plans a collision free path between two points. enums['MAV_COMPONENT'][196] = EnumEntry('MAV_COMP_ID_OBSTACLE_AVOIDANCE', '''Component that plans a collision free path between two points.''') MAV_COMP_ID_VISUAL_INERTIAL_ODOMETRY = 197 # Component that provides position estimates using VIO techniques. enums['MAV_COMPONENT'][197] = EnumEntry('MAV_COMP_ID_VISUAL_INERTIAL_ODOMETRY', '''Component that provides position estimates using VIO techniques.''') MAV_COMP_ID_IMU = 200 # Inertial Measurement Unit (IMU) #1. enums['MAV_COMPONENT'][200] = EnumEntry('MAV_COMP_ID_IMU', '''Inertial Measurement Unit (IMU) #1.''') MAV_COMP_ID_IMU_2 = 201 # Inertial Measurement Unit (IMU) #2. enums['MAV_COMPONENT'][201] = EnumEntry('MAV_COMP_ID_IMU_2', '''Inertial Measurement Unit (IMU) #2.''') MAV_COMP_ID_IMU_3 = 202 # Inertial Measurement Unit (IMU) #3. enums['MAV_COMPONENT'][202] = EnumEntry('MAV_COMP_ID_IMU_3', '''Inertial Measurement Unit (IMU) #3.''') MAV_COMP_ID_GPS = 220 # GPS #1. enums['MAV_COMPONENT'][220] = EnumEntry('MAV_COMP_ID_GPS', '''GPS #1.''') MAV_COMP_ID_GPS2 = 221 # GPS #2. enums['MAV_COMPONENT'][221] = EnumEntry('MAV_COMP_ID_GPS2', '''GPS #2.''') MAV_COMP_ID_UDP_BRIDGE = 240 # Component to bridge MAVLink to UDP (i.e. from a UART). enums['MAV_COMPONENT'][240] = EnumEntry('MAV_COMP_ID_UDP_BRIDGE', '''Component to bridge MAVLink to UDP (i.e. from a UART).''') MAV_COMP_ID_UART_BRIDGE = 241 # Component to bridge to UART (i.e. from UDP). enums['MAV_COMPONENT'][241] = EnumEntry('MAV_COMP_ID_UART_BRIDGE', '''Component to bridge to UART (i.e. from UDP).''') MAV_COMP_ID_SYSTEM_CONTROL = 250 # Component for handling system messages (e.g. to ARM, takeoff, etc.). enums['MAV_COMPONENT'][250] = EnumEntry('MAV_COMP_ID_SYSTEM_CONTROL', '''Component for handling system messages (e.g. to ARM, takeoff, etc.).''') MAV_COMPONENT_ENUM_END = 251 # enums['MAV_COMPONENT'][251] = EnumEntry('MAV_COMPONENT_ENUM_END', '''''') # MAV_SYS_STATUS_SENSOR enums['MAV_SYS_STATUS_SENSOR'] = {} MAV_SYS_STATUS_SENSOR_3D_GYRO = 1 # 0x01 3D gyro enums['MAV_SYS_STATUS_SENSOR'][1] = EnumEntry('MAV_SYS_STATUS_SENSOR_3D_GYRO', '''0x01 3D gyro''') MAV_SYS_STATUS_SENSOR_3D_ACCEL = 2 # 0x02 3D accelerometer enums['MAV_SYS_STATUS_SENSOR'][2] = EnumEntry('MAV_SYS_STATUS_SENSOR_3D_ACCEL', '''0x02 3D accelerometer''') MAV_SYS_STATUS_SENSOR_3D_MAG = 4 # 0x04 3D magnetometer enums['MAV_SYS_STATUS_SENSOR'][4] = EnumEntry('MAV_SYS_STATUS_SENSOR_3D_MAG', '''0x04 3D magnetometer''') MAV_SYS_STATUS_SENSOR_ABSOLUTE_PRESSURE = 8 # 0x08 absolute pressure enums['MAV_SYS_STATUS_SENSOR'][8] = EnumEntry('MAV_SYS_STATUS_SENSOR_ABSOLUTE_PRESSURE', '''0x08 absolute pressure''') MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE = 16 # 0x10 differential pressure enums['MAV_SYS_STATUS_SENSOR'][16] = EnumEntry('MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE', '''0x10 differential pressure''') MAV_SYS_STATUS_SENSOR_GPS = 32 # 0x20 GPS enums['MAV_SYS_STATUS_SENSOR'][32] = EnumEntry('MAV_SYS_STATUS_SENSOR_GPS', '''0x20 GPS''') MAV_SYS_STATUS_SENSOR_OPTICAL_FLOW = 64 # 0x40 optical flow enums['MAV_SYS_STATUS_SENSOR'][64] = EnumEntry('MAV_SYS_STATUS_SENSOR_OPTICAL_FLOW', '''0x40 optical flow''') MAV_SYS_STATUS_SENSOR_VISION_POSITION = 128 # 0x80 computer vision position enums['MAV_SYS_STATUS_SENSOR'][128] = EnumEntry('MAV_SYS_STATUS_SENSOR_VISION_POSITION', '''0x80 computer vision position''') MAV_SYS_STATUS_SENSOR_LASER_POSITION = 256 # 0x100 laser based position enums['MAV_SYS_STATUS_SENSOR'][256] = EnumEntry('MAV_SYS_STATUS_SENSOR_LASER_POSITION', '''0x100 laser based position''') MAV_SYS_STATUS_SENSOR_EXTERNAL_GROUND_TRUTH = 512 # 0x200 external ground truth (Vicon or Leica) enums['MAV_SYS_STATUS_SENSOR'][512] = EnumEntry('MAV_SYS_STATUS_SENSOR_EXTERNAL_GROUND_TRUTH', '''0x200 external ground truth (Vicon or Leica)''') MAV_SYS_STATUS_SENSOR_ANGULAR_RATE_CONTROL = 1024 # 0x400 3D angular rate control enums['MAV_SYS_STATUS_SENSOR'][1024] = EnumEntry('MAV_SYS_STATUS_SENSOR_ANGULAR_RATE_CONTROL', '''0x400 3D angular rate control''') MAV_SYS_STATUS_SENSOR_ATTITUDE_STABILIZATION = 2048 # 0x800 attitude stabilization enums['MAV_SYS_STATUS_SENSOR'][2048] = EnumEntry('MAV_SYS_STATUS_SENSOR_ATTITUDE_STABILIZATION', '''0x800 attitude stabilization''') MAV_SYS_STATUS_SENSOR_YAW_POSITION = 4096 # 0x1000 yaw position enums['MAV_SYS_STATUS_SENSOR'][4096] = EnumEntry('MAV_SYS_STATUS_SENSOR_YAW_POSITION', '''0x1000 yaw position''') MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL = 8192 # 0x2000 z/altitude control enums['MAV_SYS_STATUS_SENSOR'][8192] = EnumEntry('MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL', '''0x2000 z/altitude control''') MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL = 16384 # 0x4000 x/y position control enums['MAV_SYS_STATUS_SENSOR'][16384] = EnumEntry('MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL', '''0x4000 x/y position control''') MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS = 32768 # 0x8000 motor outputs / control enums['MAV_SYS_STATUS_SENSOR'][32768] = EnumEntry('MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS', '''0x8000 motor outputs / control''') MAV_SYS_STATUS_SENSOR_RC_RECEIVER = 65536 # 0x10000 rc receiver enums['MAV_SYS_STATUS_SENSOR'][65536] = EnumEntry('MAV_SYS_STATUS_SENSOR_RC_RECEIVER', '''0x10000 rc receiver''') MAV_SYS_STATUS_SENSOR_3D_GYRO2 = 131072 # 0x20000 2nd 3D gyro enums['MAV_SYS_STATUS_SENSOR'][131072] = EnumEntry('MAV_SYS_STATUS_SENSOR_3D_GYRO2', '''0x20000 2nd 3D gyro''') MAV_SYS_STATUS_SENSOR_3D_ACCEL2 = 262144 # 0x40000 2nd 3D accelerometer enums['MAV_SYS_STATUS_SENSOR'][262144] = EnumEntry('MAV_SYS_STATUS_SENSOR_3D_ACCEL2', '''0x40000 2nd 3D accelerometer''') MAV_SYS_STATUS_SENSOR_3D_MAG2 = 524288 # 0x80000 2nd 3D magnetometer enums['MAV_SYS_STATUS_SENSOR'][524288] = EnumEntry('MAV_SYS_STATUS_SENSOR_3D_MAG2', '''0x80000 2nd 3D magnetometer''') MAV_SYS_STATUS_GEOFENCE = 1048576 # 0x100000 geofence enums['MAV_SYS_STATUS_SENSOR'][1048576] = EnumEntry('MAV_SYS_STATUS_GEOFENCE', '''0x100000 geofence''') MAV_SYS_STATUS_AHRS = 2097152 # 0x200000 AHRS subsystem health enums['MAV_SYS_STATUS_SENSOR'][2097152] = EnumEntry('MAV_SYS_STATUS_AHRS', '''0x200000 AHRS subsystem health''') MAV_SYS_STATUS_TERRAIN = 4194304 # 0x400000 Terrain subsystem health enums['MAV_SYS_STATUS_SENSOR'][4194304] = EnumEntry('MAV_SYS_STATUS_TERRAIN', '''0x400000 Terrain subsystem health''') MAV_SYS_STATUS_REVERSE_MOTOR = 8388608 # 0x800000 Motors are reversed enums['MAV_SYS_STATUS_SENSOR'][8388608] = EnumEntry('MAV_SYS_STATUS_REVERSE_MOTOR', '''0x800000 Motors are reversed''') MAV_SYS_STATUS_LOGGING = 16777216 # 0x1000000 Logging enums['MAV_SYS_STATUS_SENSOR'][16777216] = EnumEntry('MAV_SYS_STATUS_LOGGING', '''0x1000000 Logging''') MAV_SYS_STATUS_SENSOR_BATTERY = 33554432 # 0x2000000 Battery enums['MAV_SYS_STATUS_SENSOR'][33554432] = EnumEntry('MAV_SYS_STATUS_SENSOR_BATTERY', '''0x2000000 Battery''') MAV_SYS_STATUS_SENSOR_PROXIMITY = 67108864 # 0x4000000 Proximity enums['MAV_SYS_STATUS_SENSOR'][67108864] = EnumEntry('MAV_SYS_STATUS_SENSOR_PROXIMITY', '''0x4000000 Proximity''') MAV_SYS_STATUS_SENSOR_SATCOM = 134217728 # 0x8000000 Satellite Communication enums['MAV_SYS_STATUS_SENSOR'][134217728] = EnumEntry('MAV_SYS_STATUS_SENSOR_SATCOM', '''0x8000000 Satellite Communication ''') MAV_SYS_STATUS_SENSOR_ENUM_END = 134217729 # enums['MAV_SYS_STATUS_SENSOR'][134217729] = EnumEntry('MAV_SYS_STATUS_SENSOR_ENUM_END', '''''') # MAV_FRAME enums['MAV_FRAME'] = {} MAV_FRAME_GLOBAL = 0 # Global (WGS84) coordinate frame + MSL altitude. First value / x: # latitude, second value / y: longitude, third # value / z: positive altitude over mean sea # level (MSL). enums['MAV_FRAME'][0] = EnumEntry('MAV_FRAME_GLOBAL', '''Global (WGS84) coordinate frame + MSL altitude. First value / x: latitude, second value / y: longitude, third value / z: positive altitude over mean sea level (MSL).''') MAV_FRAME_LOCAL_NED = 1 # Local coordinate frame, Z-down (x: north, y: east, z: down). enums['MAV_FRAME'][1] = EnumEntry('MAV_FRAME_LOCAL_NED', '''Local coordinate frame, Z-down (x: north, y: east, z: down).''') MAV_FRAME_MISSION = 2 # NOT a coordinate frame, indicates a mission command. enums['MAV_FRAME'][2] = EnumEntry('MAV_FRAME_MISSION', '''NOT a coordinate frame, indicates a mission command.''') MAV_FRAME_GLOBAL_RELATIVE_ALT = 3 # Global (WGS84) coordinate frame + altitude relative to the home # position. First value / x: latitude, second # value / y: longitude, third value / z: # positive altitude with 0 being at the # altitude of the home location. enums['MAV_FRAME'][3] = EnumEntry('MAV_FRAME_GLOBAL_RELATIVE_ALT', '''Global (WGS84) coordinate frame + altitude relative to the home position. First value / x: latitude, second value / y: longitude, third value / z: positive altitude with 0 being at the altitude of the home location.''') MAV_FRAME_LOCAL_ENU = 4 # Local coordinate frame, Z-up (x: east, y: north, z: up). enums['MAV_FRAME'][4] = EnumEntry('MAV_FRAME_LOCAL_ENU', '''Local coordinate frame, Z-up (x: east, y: north, z: up).''') MAV_FRAME_GLOBAL_INT = 5 # Global (WGS84) coordinate frame (scaled) + MSL altitude. First value / # x: latitude in degrees*1.0e-7, second value # / y: longitude in degrees*1.0e-7, third # value / z: positive altitude over mean sea # level (MSL). enums['MAV_FRAME'][5] = EnumEntry('MAV_FRAME_GLOBAL_INT', '''Global (WGS84) coordinate frame (scaled) + MSL altitude. First value / x: latitude in degrees*1.0e-7, second value / y: longitude in degrees*1.0e-7, third value / z: positive altitude over mean sea level (MSL).''') MAV_FRAME_GLOBAL_RELATIVE_ALT_INT = 6 # Global (WGS84) coordinate frame (scaled) + altitude relative to the # home position. First value / x: latitude in # degrees*10e-7, second value / y: longitude # in degrees*10e-7, third value / z: positive # altitude with 0 being at the altitude of the # home location. enums['MAV_FRAME'][6] = EnumEntry('MAV_FRAME_GLOBAL_RELATIVE_ALT_INT', '''Global (WGS84) coordinate frame (scaled) + altitude relative to the home position. First value / x: latitude in degrees*10e-7, second value / y: longitude in degrees*10e-7, third value / z: positive altitude with 0 being at the altitude of the home location.''') MAV_FRAME_LOCAL_OFFSET_NED = 7 # Offset to the current local frame. Anything expressed in this frame # should be added to the current local frame # position. enums['MAV_FRAME'][7] = EnumEntry('MAV_FRAME_LOCAL_OFFSET_NED', '''Offset to the current local frame. Anything expressed in this frame should be added to the current local frame position.''') MAV_FRAME_BODY_NED = 8 # Setpoint in body NED frame. This makes sense if all position control # is externalized - e.g. useful to command 2 # m/s^2 acceleration to the right. enums['MAV_FRAME'][8] = EnumEntry('MAV_FRAME_BODY_NED', '''Setpoint in body NED frame. This makes sense if all position control is externalized - e.g. useful to command 2 m/s^2 acceleration to the right.''') MAV_FRAME_BODY_OFFSET_NED = 9 # Offset in body NED frame. This makes sense if adding setpoints to the # current flight path, to avoid an obstacle - # e.g. useful to command 2 m/s^2 acceleration # to the east. enums['MAV_FRAME'][9] = EnumEntry('MAV_FRAME_BODY_OFFSET_NED', '''Offset in body NED frame. This makes sense if adding setpoints to the current flight path, to avoid an obstacle - e.g. useful to command 2 m/s^2 acceleration to the east.''') MAV_FRAME_GLOBAL_TERRAIN_ALT = 10 # Global (WGS84) coordinate frame with AGL altitude (at the waypoint # coordinate). First value / x: latitude in # degrees, second value / y: longitude in # degrees, third value / z: positive altitude # in meters with 0 being at ground level in # terrain model. enums['MAV_FRAME'][10] = EnumEntry('MAV_FRAME_GLOBAL_TERRAIN_ALT', '''Global (WGS84) coordinate frame with AGL altitude (at the waypoint coordinate). First value / x: latitude in degrees, second value / y: longitude in degrees, third value / z: positive altitude in meters with 0 being at ground level in terrain model.''') MAV_FRAME_GLOBAL_TERRAIN_ALT_INT = 11 # Global (WGS84) coordinate frame (scaled) with AGL altitude (at the # waypoint coordinate). First value / x: # latitude in degrees*10e-7, second value / y: # longitude in degrees*10e-7, third value / z: # positive altitude in meters with 0 being at # ground level in terrain model. enums['MAV_FRAME'][11] = EnumEntry('MAV_FRAME_GLOBAL_TERRAIN_ALT_INT', '''Global (WGS84) coordinate frame (scaled) with AGL altitude (at the waypoint coordinate). First value / x: latitude in degrees*10e-7, second value / y: longitude in degrees*10e-7, third value / z: positive altitude in meters with 0 being at ground level in terrain model.''') MAV_FRAME_BODY_FRD = 12 # Body fixed frame of reference, Z-down (x: forward, y: right, z: down). enums['MAV_FRAME'][12] = EnumEntry('MAV_FRAME_BODY_FRD', '''Body fixed frame of reference, Z-down (x: forward, y: right, z: down).''') MAV_FRAME_BODY_FLU = 13 # Body fixed frame of reference, Z-up (x: forward, y: left, z: up). enums['MAV_FRAME'][13] = EnumEntry('MAV_FRAME_BODY_FLU', '''Body fixed frame of reference, Z-up (x: forward, y: left, z: up).''') MAV_FRAME_MOCAP_NED = 14 # Odometry local coordinate frame of data given by a motion capture # system, Z-down (x: north, y: east, z: down). enums['MAV_FRAME'][14] = EnumEntry('MAV_FRAME_MOCAP_NED', '''Odometry local coordinate frame of data given by a motion capture system, Z-down (x: north, y: east, z: down).''') MAV_FRAME_MOCAP_ENU = 15 # Odometry local coordinate frame of data given by a motion capture # system, Z-up (x: east, y: north, z: up). enums['MAV_FRAME'][15] = EnumEntry('MAV_FRAME_MOCAP_ENU', '''Odometry local coordinate frame of data given by a motion capture system, Z-up (x: east, y: north, z: up).''') MAV_FRAME_VISION_NED = 16 # Odometry local coordinate frame of data given by a vision estimation # system, Z-down (x: north, y: east, z: down). enums['MAV_FRAME'][16] = EnumEntry('MAV_FRAME_VISION_NED', '''Odometry local coordinate frame of data given by a vision estimation system, Z-down (x: north, y: east, z: down).''') MAV_FRAME_VISION_ENU = 17 # Odometry local coordinate frame of data given by a vision estimation # system, Z-up (x: east, y: north, z: up). enums['MAV_FRAME'][17] = EnumEntry('MAV_FRAME_VISION_ENU', '''Odometry local coordinate frame of data given by a vision estimation system, Z-up (x: east, y: north, z: up).''') MAV_FRAME_ESTIM_NED = 18 # Odometry local coordinate frame of data given by an estimator running # onboard the vehicle, Z-down (x: north, y: # east, z: down). enums['MAV_FRAME'][18] = EnumEntry('MAV_FRAME_ESTIM_NED', '''Odometry local coordinate frame of data given by an estimator running onboard the vehicle, Z-down (x: north, y: east, z: down).''') MAV_FRAME_ESTIM_ENU = 19 # Odometry local coordinate frame of data given by an estimator running # onboard the vehicle, Z-up (x: east, y: noth, # z: up). enums['MAV_FRAME'][19] = EnumEntry('MAV_FRAME_ESTIM_ENU', '''Odometry local coordinate frame of data given by an estimator running onboard the vehicle, Z-up (x: east, y: noth, z: up).''') MAV_FRAME_LOCAL_FRD = 20 # Forward, Right, Down coordinate frame. This is a local frame with # Z-down and arbitrary F/R alignment (i.e. not # aligned with NED/earth frame). enums['MAV_FRAME'][20] = EnumEntry('MAV_FRAME_LOCAL_FRD', '''Forward, Right, Down coordinate frame. This is a local frame with Z-down and arbitrary F/R alignment (i.e. not aligned with NED/earth frame).''') MAV_FRAME_LOCAL_FLU = 21 # Forward, Left, Up coordinate frame. This is a local frame with Z-up # and arbitrary F/L alignment (i.e. not # aligned with ENU/earth frame). enums['MAV_FRAME'][21] = EnumEntry('MAV_FRAME_LOCAL_FLU', '''Forward, Left, Up coordinate frame. This is a local frame with Z-up and arbitrary F/L alignment (i.e. not aligned with ENU/earth frame).''') MAV_FRAME_ENUM_END = 22 # enums['MAV_FRAME'][22] = EnumEntry('MAV_FRAME_ENUM_END', '''''') # MAVLINK_DATA_STREAM_TYPE enums['MAVLINK_DATA_STREAM_TYPE'] = {} MAVLINK_DATA_STREAM_IMG_JPEG = 1 # enums['MAVLINK_DATA_STREAM_TYPE'][1] = EnumEntry('MAVLINK_DATA_STREAM_IMG_JPEG', '''''') MAVLINK_DATA_STREAM_IMG_BMP = 2 # enums['MAVLINK_DATA_STREAM_TYPE'][2] = EnumEntry('MAVLINK_DATA_STREAM_IMG_BMP', '''''') MAVLINK_DATA_STREAM_IMG_RAW8U = 3 # enums['MAVLINK_DATA_STREAM_TYPE'][3] = EnumEntry('MAVLINK_DATA_STREAM_IMG_RAW8U', '''''') MAVLINK_DATA_STREAM_IMG_RAW32U = 4 # enums['MAVLINK_DATA_STREAM_TYPE'][4] = EnumEntry('MAVLINK_DATA_STREAM_IMG_RAW32U', '''''') MAVLINK_DATA_STREAM_IMG_PGM = 5 # enums['MAVLINK_DATA_STREAM_TYPE'][5] = EnumEntry('MAVLINK_DATA_STREAM_IMG_PGM', '''''') MAVLINK_DATA_STREAM_IMG_PNG = 6 # enums['MAVLINK_DATA_STREAM_TYPE'][6] = EnumEntry('MAVLINK_DATA_STREAM_IMG_PNG', '''''') MAVLINK_DATA_STREAM_TYPE_ENUM_END = 7 # enums['MAVLINK_DATA_STREAM_TYPE'][7] = EnumEntry('MAVLINK_DATA_STREAM_TYPE_ENUM_END', '''''') # FENCE_ACTION enums['FENCE_ACTION'] = {} FENCE_ACTION_NONE = 0 # Disable fenced mode enums['FENCE_ACTION'][0] = EnumEntry('FENCE_ACTION_NONE', '''Disable fenced mode''') FENCE_ACTION_GUIDED = 1 # Switched to guided mode to return point (fence point 0) enums['FENCE_ACTION'][1] = EnumEntry('FENCE_ACTION_GUIDED', '''Switched to guided mode to return point (fence point 0)''') FENCE_ACTION_REPORT = 2 # Report fence breach, but don't take action enums['FENCE_ACTION'][2] = EnumEntry('FENCE_ACTION_REPORT', '''Report fence breach, but don't take action''') FENCE_ACTION_GUIDED_THR_PASS = 3 # Switched to guided mode to return point (fence point 0) with manual # throttle control enums['FENCE_ACTION'][3] = EnumEntry('FENCE_ACTION_GUIDED_THR_PASS', '''Switched to guided mode to return point (fence point 0) with manual throttle control''') FENCE_ACTION_RTL = 4 # Switch to RTL (return to launch) mode and head for the return point. enums['FENCE_ACTION'][4] = EnumEntry('FENCE_ACTION_RTL', '''Switch to RTL (return to launch) mode and head for the return point.''') FENCE_ACTION_ENUM_END = 5 # enums['FENCE_ACTION'][5] = EnumEntry('FENCE_ACTION_ENUM_END', '''''') # FENCE_BREACH enums['FENCE_BREACH'] = {} FENCE_BREACH_NONE = 0 # No last fence breach enums['FENCE_BREACH'][0] = EnumEntry('FENCE_BREACH_NONE', '''No last fence breach''') FENCE_BREACH_MINALT = 1 # Breached minimum altitude enums['FENCE_BREACH'][1] = EnumEntry('FENCE_BREACH_MINALT', '''Breached minimum altitude''') FENCE_BREACH_MAXALT = 2 # Breached maximum altitude enums['FENCE_BREACH'][2] = EnumEntry('FENCE_BREACH_MAXALT', '''Breached maximum altitude''') FENCE_BREACH_BOUNDARY = 3 # Breached fence boundary enums['FENCE_BREACH'][3] = EnumEntry('FENCE_BREACH_BOUNDARY', '''Breached fence boundary''') FENCE_BREACH_ENUM_END = 4 # enums['FENCE_BREACH'][4] = EnumEntry('FENCE_BREACH_ENUM_END', '''''') # MAV_MOUNT_MODE enums['MAV_MOUNT_MODE'] = {} MAV_MOUNT_MODE_RETRACT = 0 # Load and keep safe position (Roll,Pitch,Yaw) from permant memory and # stop stabilization enums['MAV_MOUNT_MODE'][0] = EnumEntry('MAV_MOUNT_MODE_RETRACT', '''Load and keep safe position (Roll,Pitch,Yaw) from permant memory and stop stabilization''') MAV_MOUNT_MODE_NEUTRAL = 1 # Load and keep neutral position (Roll,Pitch,Yaw) from permanent memory. enums['MAV_MOUNT_MODE'][1] = EnumEntry('MAV_MOUNT_MODE_NEUTRAL', '''Load and keep neutral position (Roll,Pitch,Yaw) from permanent memory.''') MAV_MOUNT_MODE_MAVLINK_TARGETING = 2 # Load neutral position and start MAVLink Roll,Pitch,Yaw control with # stabilization enums['MAV_MOUNT_MODE'][2] = EnumEntry('MAV_MOUNT_MODE_MAVLINK_TARGETING', '''Load neutral position and start MAVLink Roll,Pitch,Yaw control with stabilization''') MAV_MOUNT_MODE_RC_TARGETING = 3 # Load neutral position and start RC Roll,Pitch,Yaw control with # stabilization enums['MAV_MOUNT_MODE'][3] = EnumEntry('MAV_MOUNT_MODE_RC_TARGETING', '''Load neutral position and start RC Roll,Pitch,Yaw control with stabilization''') MAV_MOUNT_MODE_GPS_POINT = 4 # Load neutral position and start to point to Lat,Lon,Alt enums['MAV_MOUNT_MODE'][4] = EnumEntry('MAV_MOUNT_MODE_GPS_POINT', '''Load neutral position and start to point to Lat,Lon,Alt''') MAV_MOUNT_MODE_SYSID_TARGET = 5 # Follow system ID enums['MAV_MOUNT_MODE'][5] = EnumEntry('MAV_MOUNT_MODE_SYSID_TARGET', '''Follow system ID''') MAV_MOUNT_MODE_ENUM_END = 6 # enums['MAV_MOUNT_MODE'][6] = EnumEntry('MAV_MOUNT_MODE_ENUM_END', '''''') # UAVCAN_NODE_HEALTH enums['UAVCAN_NODE_HEALTH'] = {} UAVCAN_NODE_HEALTH_OK = 0 # The node is functioning properly. enums['UAVCAN_NODE_HEALTH'][0] = EnumEntry('UAVCAN_NODE_HEALTH_OK', '''The node is functioning properly.''') UAVCAN_NODE_HEALTH_WARNING = 1 # A critical parameter went out of range or the node has encountered a # minor failure. enums['UAVCAN_NODE_HEALTH'][1] = EnumEntry('UAVCAN_NODE_HEALTH_WARNING', '''A critical parameter went out of range or the node has encountered a minor failure.''') UAVCAN_NODE_HEALTH_ERROR = 2 # The node has encountered a major failure. enums['UAVCAN_NODE_HEALTH'][2] = EnumEntry('UAVCAN_NODE_HEALTH_ERROR', '''The node has encountered a major failure.''') UAVCAN_NODE_HEALTH_CRITICAL = 3 # The node has suffered a fatal malfunction. enums['UAVCAN_NODE_HEALTH'][3] = EnumEntry('UAVCAN_NODE_HEALTH_CRITICAL', '''The node has suffered a fatal malfunction.''') UAVCAN_NODE_HEALTH_ENUM_END = 4 # enums['UAVCAN_NODE_HEALTH'][4] = EnumEntry('UAVCAN_NODE_HEALTH_ENUM_END', '''''') # UAVCAN_NODE_MODE enums['UAVCAN_NODE_MODE'] = {} UAVCAN_NODE_MODE_OPERATIONAL = 0 # The node is performing its primary functions. enums['UAVCAN_NODE_MODE'][0] = EnumEntry('UAVCAN_NODE_MODE_OPERATIONAL', '''The node is performing its primary functions.''') UAVCAN_NODE_MODE_INITIALIZATION = 1 # The node is initializing; this mode is entered immediately after # startup. enums['UAVCAN_NODE_MODE'][1] = EnumEntry('UAVCAN_NODE_MODE_INITIALIZATION', '''The node is initializing; this mode is entered immediately after startup.''') UAVCAN_NODE_MODE_MAINTENANCE = 2 # The node is under maintenance. enums['UAVCAN_NODE_MODE'][2] = EnumEntry('UAVCAN_NODE_MODE_MAINTENANCE', '''The node is under maintenance.''') UAVCAN_NODE_MODE_SOFTWARE_UPDATE = 3 # The node is in the process of updating its software. enums['UAVCAN_NODE_MODE'][3] = EnumEntry('UAVCAN_NODE_MODE_SOFTWARE_UPDATE', '''The node is in the process of updating its software.''') UAVCAN_NODE_MODE_OFFLINE = 7 # The node is no longer available online. enums['UAVCAN_NODE_MODE'][7] = EnumEntry('UAVCAN_NODE_MODE_OFFLINE', '''The node is no longer available online.''') UAVCAN_NODE_MODE_ENUM_END = 8 # enums['UAVCAN_NODE_MODE'][8] = EnumEntry('UAVCAN_NODE_MODE_ENUM_END', '''''') # STORAGE_STATUS enums['STORAGE_STATUS'] = {} STORAGE_STATUS_EMPTY = 0 # Storage is missing (no microSD card loaded for example.) enums['STORAGE_STATUS'][0] = EnumEntry('STORAGE_STATUS_EMPTY', '''Storage is missing (no microSD card loaded for example.)''') STORAGE_STATUS_UNFORMATTED = 1 # Storage present but unformatted. enums['STORAGE_STATUS'][1] = EnumEntry('STORAGE_STATUS_UNFORMATTED', '''Storage present but unformatted.''') STORAGE_STATUS_READY = 2 # Storage present and ready. enums['STORAGE_STATUS'][2] = EnumEntry('STORAGE_STATUS_READY', '''Storage present and ready.''') STORAGE_STATUS_NOT_SUPPORTED = 3 # Camera does not supply storage status information. Capacity # information in STORAGE_INFORMATION fields # will be ignored. enums['STORAGE_STATUS'][3] = EnumEntry('STORAGE_STATUS_NOT_SUPPORTED', '''Camera does not supply storage status information. Capacity information in STORAGE_INFORMATION fields will be ignored.''') STORAGE_STATUS_ENUM_END = 4 # enums['STORAGE_STATUS'][4] = EnumEntry('STORAGE_STATUS_ENUM_END', '''''') # MAV_CMD enums['MAV_CMD'] = {} MAV_CMD_NAV_WAYPOINT = 16 # Navigate to waypoint. enums['MAV_CMD'][16] = EnumEntry('MAV_CMD_NAV_WAYPOINT', '''Navigate to waypoint.''') enums['MAV_CMD'][16].param[1] = '''Hold time. (ignored by fixed wing, time to stay at waypoint for rotary wing)''' enums['MAV_CMD'][16].param[2] = '''Acceptance radius (if the sphere with this radius is hit, the waypoint counts as reached)''' enums['MAV_CMD'][16].param[3] = '''0 to pass through the WP, if > 0 radius to pass by WP. Positive value for clockwise orbit, negative value for counter-clockwise orbit. Allows trajectory control.''' enums['MAV_CMD'][16].param[4] = '''Desired yaw angle at waypoint (rotary wing). NaN for unchanged.''' enums['MAV_CMD'][16].param[5] = '''Latitude''' enums['MAV_CMD'][16].param[6] = '''Longitude''' enums['MAV_CMD'][16].param[7] = '''Altitude''' MAV_CMD_NAV_LOITER_UNLIM = 17 # Loiter around this waypoint an unlimited amount of time enums['MAV_CMD'][17] = EnumEntry('MAV_CMD_NAV_LOITER_UNLIM', '''Loiter around this waypoint an unlimited amount of time''') enums['MAV_CMD'][17].param[1] = '''Empty''' enums['MAV_CMD'][17].param[2] = '''Empty''' enums['MAV_CMD'][17].param[3] = '''Radius around waypoint. If positive loiter clockwise, else counter-clockwise''' enums['MAV_CMD'][17].param[4] = '''Desired yaw angle. NaN for unchanged.''' enums['MAV_CMD'][17].param[5] = '''Latitude''' enums['MAV_CMD'][17].param[6] = '''Longitude''' enums['MAV_CMD'][17].param[7] = '''Altitude''' MAV_CMD_NAV_LOITER_TURNS = 18 # Loiter around this waypoint for X turns enums['MAV_CMD'][18] = EnumEntry('MAV_CMD_NAV_LOITER_TURNS', '''Loiter around this waypoint for X turns''') enums['MAV_CMD'][18].param[1] = '''Number of turns.''' enums['MAV_CMD'][18].param[2] = '''Empty''' enums['MAV_CMD'][18].param[3] = '''Radius around waypoint. If positive loiter clockwise, else counter-clockwise''' enums['MAV_CMD'][18].param[4] = '''Forward moving aircraft this sets exit xtrack location: 0 for center of loiter wp, 1 for exit location. Else, this is desired yaw angle. NaN for unchanged.''' enums['MAV_CMD'][18].param[5] = '''Latitude''' enums['MAV_CMD'][18].param[6] = '''Longitude''' enums['MAV_CMD'][18].param[7] = '''Altitude''' MAV_CMD_NAV_LOITER_TIME = 19 # Loiter around this waypoint for X seconds enums['MAV_CMD'][19] = EnumEntry('MAV_CMD_NAV_LOITER_TIME', '''Loiter around this waypoint for X seconds''') enums['MAV_CMD'][19].param[1] = '''Loiter time.''' enums['MAV_CMD'][19].param[2] = '''Empty''' enums['MAV_CMD'][19].param[3] = '''Radius around waypoint. If positive loiter clockwise, else counter-clockwise.''' enums['MAV_CMD'][19].param[4] = '''Forward moving aircraft this sets exit xtrack location: 0 for center of loiter wp, 1 for exit location. Else, this is desired yaw angle. NaN for unchanged.''' enums['MAV_CMD'][19].param[5] = '''Latitude''' enums['MAV_CMD'][19].param[6] = '''Longitude''' enums['MAV_CMD'][19].param[7] = '''Altitude''' MAV_CMD_NAV_RETURN_TO_LAUNCH = 20 # Return to launch location enums['MAV_CMD'][20] = EnumEntry('MAV_CMD_NAV_RETURN_TO_LAUNCH', '''Return to launch location''') enums['MAV_CMD'][20].param[1] = '''Empty''' enums['MAV_CMD'][20].param[2] = '''Empty''' enums['MAV_CMD'][20].param[3] = '''Empty''' enums['MAV_CMD'][20].param[4] = '''Empty''' enums['MAV_CMD'][20].param[5] = '''Empty''' enums['MAV_CMD'][20].param[6] = '''Empty''' enums['MAV_CMD'][20].param[7] = '''Empty''' MAV_CMD_NAV_LAND = 21 # Land at location. enums['MAV_CMD'][21] = EnumEntry('MAV_CMD_NAV_LAND', '''Land at location.''') enums['MAV_CMD'][21].param[1] = '''Minimum target altitude if landing is aborted (0 = undefined/use system default).''' enums['MAV_CMD'][21].param[2] = '''Precision land mode.''' enums['MAV_CMD'][21].param[3] = '''Empty.''' enums['MAV_CMD'][21].param[4] = '''Desired yaw angle. NaN for unchanged.''' enums['MAV_CMD'][21].param[5] = '''Latitude.''' enums['MAV_CMD'][21].param[6] = '''Longitude.''' enums['MAV_CMD'][21].param[7] = '''Landing altitude (ground level in current frame).''' MAV_CMD_NAV_TAKEOFF = 22 # Takeoff from ground / hand enums['MAV_CMD'][22] = EnumEntry('MAV_CMD_NAV_TAKEOFF', '''Takeoff from ground / hand''') enums['MAV_CMD'][22].param[1] = '''Minimum pitch (if airspeed sensor present), desired pitch without sensor''' enums['MAV_CMD'][22].param[2] = '''Empty''' enums['MAV_CMD'][22].param[3] = '''Empty''' enums['MAV_CMD'][22].param[4] = '''Yaw angle (if magnetometer present), ignored without magnetometer. NaN for unchanged.''' enums['MAV_CMD'][22].param[5] = '''Latitude''' enums['MAV_CMD'][22].param[6] = '''Longitude''' enums['MAV_CMD'][22].param[7] = '''Altitude''' MAV_CMD_NAV_LAND_LOCAL = 23 # Land at local position (local frame only) enums['MAV_CMD'][23] = EnumEntry('MAV_CMD_NAV_LAND_LOCAL', '''Land at local position (local frame only)''') enums['MAV_CMD'][23].param[1] = '''Landing target number (if available)''' enums['MAV_CMD'][23].param[2] = '''Maximum accepted offset from desired landing position - computed magnitude from spherical coordinates: d = sqrt(x^2 + y^2 + z^2), which gives the maximum accepted distance between the desired landing position and the position where the vehicle is about to land''' enums['MAV_CMD'][23].param[3] = '''Landing descend rate''' enums['MAV_CMD'][23].param[4] = '''Desired yaw angle''' enums['MAV_CMD'][23].param[5] = '''Y-axis position''' enums['MAV_CMD'][23].param[6] = '''X-axis position''' enums['MAV_CMD'][23].param[7] = '''Z-axis / ground level position''' MAV_CMD_NAV_TAKEOFF_LOCAL = 24 # Takeoff from local position (local frame only) enums['MAV_CMD'][24] = EnumEntry('MAV_CMD_NAV_TAKEOFF_LOCAL', '''Takeoff from local position (local frame only)''') enums['MAV_CMD'][24].param[1] = '''Minimum pitch (if airspeed sensor present), desired pitch without sensor''' enums['MAV_CMD'][24].param[2] = '''Empty''' enums['MAV_CMD'][24].param[3] = '''Takeoff ascend rate''' enums['MAV_CMD'][24].param[4] = '''Yaw angle (if magnetometer or another yaw estimation source present), ignored without one of these''' enums['MAV_CMD'][24].param[5] = '''Y-axis position''' enums['MAV_CMD'][24].param[6] = '''X-axis position''' enums['MAV_CMD'][24].param[7] = '''Z-axis position''' MAV_CMD_NAV_FOLLOW = 25 # Vehicle following, i.e. this waypoint represents the position of a # moving vehicle enums['MAV_CMD'][25] = EnumEntry('MAV_CMD_NAV_FOLLOW', '''Vehicle following, i.e. this waypoint represents the position of a moving vehicle''') enums['MAV_CMD'][25].param[1] = '''Following logic to use (e.g. loitering or sinusoidal following) - depends on specific autopilot implementation''' enums['MAV_CMD'][25].param[2] = '''Ground speed of vehicle to be followed''' enums['MAV_CMD'][25].param[3] = '''Radius around waypoint. If positive loiter clockwise, else counter-clockwise''' enums['MAV_CMD'][25].param[4] = '''Desired yaw angle.''' enums['MAV_CMD'][25].param[5] = '''Latitude''' enums['MAV_CMD'][25].param[6] = '''Longitude''' enums['MAV_CMD'][25].param[7] = '''Altitude''' MAV_CMD_NAV_CONTINUE_AND_CHANGE_ALT = 30 # Continue on the current course and climb/descend to specified # altitude. When the altitude is reached # continue to the next command (i.e., don't # proceed to the next command until the # desired altitude is reached. enums['MAV_CMD'][30] = EnumEntry('MAV_CMD_NAV_CONTINUE_AND_CHANGE_ALT', '''Continue on the current course and climb/descend to specified altitude. When the altitude is reached continue to the next command (i.e., don't proceed to the next command until the desired altitude is reached.''') enums['MAV_CMD'][30].param[1] = '''Climb or Descend (0 = Neutral, command completes when within 5m of this command's altitude, 1 = Climbing, command completes when at or above this command's altitude, 2 = Descending, command completes when at or below this command's altitude.''' enums['MAV_CMD'][30].param[2] = '''Empty''' enums['MAV_CMD'][30].param[3] = '''Empty''' enums['MAV_CMD'][30].param[4] = '''Empty''' enums['MAV_CMD'][30].param[5] = '''Empty''' enums['MAV_CMD'][30].param[6] = '''Empty''' enums['MAV_CMD'][30].param[7] = '''Desired altitude''' MAV_CMD_NAV_LOITER_TO_ALT = 31 # Begin loiter at the specified Latitude and Longitude. If Lat=Lon=0, # then loiter at the current position. Don't # consider the navigation command complete # (don't leave loiter) until the altitude has # been reached. Additionally, if the Heading # Required parameter is non-zero the aircraft # will not leave the loiter until heading # toward the next waypoint. enums['MAV_CMD'][31] = EnumEntry('MAV_CMD_NAV_LOITER_TO_ALT', '''Begin loiter at the specified Latitude and Longitude. If Lat=Lon=0, then loiter at the current position. Don't consider the navigation command complete (don't leave loiter) until the altitude has been reached. Additionally, if the Heading Required parameter is non-zero the aircraft will not leave the loiter until heading toward the next waypoint.''') enums['MAV_CMD'][31].param[1] = '''Heading Required (0 = False)''' enums['MAV_CMD'][31].param[2] = '''Radius. If positive loiter clockwise, negative counter-clockwise, 0 means no change to standard loiter.''' enums['MAV_CMD'][31].param[3] = '''Empty''' enums['MAV_CMD'][31].param[4] = '''Forward moving aircraft this sets exit xtrack location: 0 for center of loiter wp, 1 for exit location''' enums['MAV_CMD'][31].param[5] = '''Latitude''' enums['MAV_CMD'][31].param[6] = '''Longitude''' enums['MAV_CMD'][31].param[7] = '''Altitude''' MAV_CMD_DO_FOLLOW = 32 # Begin following a target enums['MAV_CMD'][32] = EnumEntry('MAV_CMD_DO_FOLLOW', '''Begin following a target''') enums['MAV_CMD'][32].param[1] = '''System ID (of the FOLLOW_TARGET beacon). Send 0 to disable follow-me and return to the default position hold mode.''' enums['MAV_CMD'][32].param[2] = '''RESERVED''' enums['MAV_CMD'][32].param[3] = '''RESERVED''' enums['MAV_CMD'][32].param[4] = '''Altitude mode: 0: Keep current altitude, 1: keep altitude difference to target, 2: go to a fixed altitude above home.''' enums['MAV_CMD'][32].param[5] = '''Altitude above home. (used if mode=2)''' enums['MAV_CMD'][32].param[6] = '''RESERVED''' enums['MAV_CMD'][32].param[7] = '''Time to land in which the MAV should go to the default position hold mode after a message RX timeout.''' MAV_CMD_DO_FOLLOW_REPOSITION = 33 # Reposition the MAV after a follow target command has been sent enums['MAV_CMD'][33] = EnumEntry('MAV_CMD_DO_FOLLOW_REPOSITION', '''Reposition the MAV after a follow target command has been sent''') enums['MAV_CMD'][33].param[1] = '''Camera q1 (where 0 is on the ray from the camera to the tracking device)''' enums['MAV_CMD'][33].param[2] = '''Camera q2''' enums['MAV_CMD'][33].param[3] = '''Camera q3''' enums['MAV_CMD'][33].param[4] = '''Camera q4''' enums['MAV_CMD'][33].param[5] = '''altitude offset from target''' enums['MAV_CMD'][33].param[6] = '''X offset from target''' enums['MAV_CMD'][33].param[7] = '''Y offset from target''' MAV_CMD_NAV_ROI = 80 # Sets the region of interest (ROI) for a sensor set or the vehicle # itself. This can then be used by the # vehicles control system to control the # vehicle attitude and the attitude of various # sensors such as cameras. enums['MAV_CMD'][80] = EnumEntry('MAV_CMD_NAV_ROI', '''Sets the region of interest (ROI) for a sensor set or the vehicle itself. This can then be used by the vehicles control system to control the vehicle attitude and the attitude of various sensors such as cameras.''') enums['MAV_CMD'][80].param[1] = '''Region of interest mode.''' enums['MAV_CMD'][80].param[2] = '''Waypoint index/ target ID. (see MAV_ROI enum)''' enums['MAV_CMD'][80].param[3] = '''ROI index (allows a vehicle to manage multiple ROI's)''' enums['MAV_CMD'][80].param[4] = '''Empty''' enums['MAV_CMD'][80].param[5] = '''x the location of the fixed ROI (see MAV_FRAME)''' enums['MAV_CMD'][80].param[6] = '''y''' enums['MAV_CMD'][80].param[7] = '''z''' MAV_CMD_NAV_PATHPLANNING = 81 # Control autonomous path planning on the MAV. enums['MAV_CMD'][81] = EnumEntry('MAV_CMD_NAV_PATHPLANNING', '''Control autonomous path planning on the MAV.''') enums['MAV_CMD'][81].param[1] = '''0: Disable local obstacle avoidance / local path planning (without resetting map), 1: Enable local path planning, 2: Enable and reset local path planning''' enums['MAV_CMD'][81].param[2] = '''0: Disable full path planning (without resetting map), 1: Enable, 2: Enable and reset map/occupancy grid, 3: Enable and reset planned route, but not occupancy grid''' enums['MAV_CMD'][81].param[3] = '''Empty''' enums['MAV_CMD'][81].param[4] = '''Yaw angle at goal''' enums['MAV_CMD'][81].param[5] = '''Latitude/X of goal''' enums['MAV_CMD'][81].param[6] = '''Longitude/Y of goal''' enums['MAV_CMD'][81].param[7] = '''Altitude/Z of goal''' MAV_CMD_NAV_SPLINE_WAYPOINT = 82 # Navigate to waypoint using a spline path. enums['MAV_CMD'][82] = EnumEntry('MAV_CMD_NAV_SPLINE_WAYPOINT', '''Navigate to waypoint using a spline path.''') enums['MAV_CMD'][82].param[1] = '''Hold time. (ignored by fixed wing, time to stay at waypoint for rotary wing)''' enums['MAV_CMD'][82].param[2] = '''Empty''' enums['MAV_CMD'][82].param[3] = '''Empty''' enums['MAV_CMD'][82].param[4] = '''Empty''' enums['MAV_CMD'][82].param[5] = '''Latitude/X of goal''' enums['MAV_CMD'][82].param[6] = '''Longitude/Y of goal''' enums['MAV_CMD'][82].param[7] = '''Altitude/Z of goal''' MAV_CMD_NAV_VTOL_TAKEOFF = 84 # Takeoff from ground using VTOL mode, and transition to forward flight # with specified heading. enums['MAV_CMD'][84] = EnumEntry('MAV_CMD_NAV_VTOL_TAKEOFF', '''Takeoff from ground using VTOL mode, and transition to forward flight with specified heading.''') enums['MAV_CMD'][84].param[1] = '''Empty''' enums['MAV_CMD'][84].param[2] = '''Front transition heading.''' enums['MAV_CMD'][84].param[3] = '''Empty''' enums['MAV_CMD'][84].param[4] = '''Yaw angle. NaN for unchanged.''' enums['MAV_CMD'][84].param[5] = '''Latitude''' enums['MAV_CMD'][84].param[6] = '''Longitude''' enums['MAV_CMD'][84].param[7] = '''Altitude''' MAV_CMD_NAV_VTOL_LAND = 85 # Land using VTOL mode enums['MAV_CMD'][85] = EnumEntry('MAV_CMD_NAV_VTOL_LAND', '''Land using VTOL mode''') enums['MAV_CMD'][85].param[1] = '''Empty''' enums['MAV_CMD'][85].param[2] = '''Empty''' enums['MAV_CMD'][85].param[3] = '''Approach altitude (with the same reference as the Altitude field). NaN if unspecified.''' enums['MAV_CMD'][85].param[4] = '''Yaw angle. NaN for unchanged.''' enums['MAV_CMD'][85].param[5] = '''Latitude''' enums['MAV_CMD'][85].param[6] = '''Longitude''' enums['MAV_CMD'][85].param[7] = '''Altitude (ground level)''' MAV_CMD_NAV_GUIDED_ENABLE = 92 # hand control over to an external controller enums['MAV_CMD'][92] = EnumEntry('MAV_CMD_NAV_GUIDED_ENABLE', '''hand control over to an external controller''') enums['MAV_CMD'][92].param[1] = '''On / Off (> 0.5f on)''' enums['MAV_CMD'][92].param[2] = '''Empty''' enums['MAV_CMD'][92].param[3] = '''Empty''' enums['MAV_CMD'][92].param[4] = '''Empty''' enums['MAV_CMD'][92].param[5] = '''Empty''' enums['MAV_CMD'][92].param[6] = '''Empty''' enums['MAV_CMD'][92].param[7] = '''Empty''' MAV_CMD_NAV_DELAY = 93 # Delay the next navigation command a number of seconds or until a # specified time enums['MAV_CMD'][93] = EnumEntry('MAV_CMD_NAV_DELAY', '''Delay the next navigation command a number of seconds or until a specified time''') enums['MAV_CMD'][93].param[1] = '''Delay (-1 to enable time-of-day fields)''' enums['MAV_CMD'][93].param[2] = '''hour (24h format, UTC, -1 to ignore)''' enums['MAV_CMD'][93].param[3] = '''minute (24h format, UTC, -1 to ignore)''' enums['MAV_CMD'][93].param[4] = '''second (24h format, UTC)''' enums['MAV_CMD'][93].param[5] = '''Empty''' enums['MAV_CMD'][93].param[6] = '''Empty''' enums['MAV_CMD'][93].param[7] = '''Empty''' MAV_CMD_NAV_PAYLOAD_PLACE = 94 # Descend and place payload. Vehicle moves to specified location, # descends until it detects a hanging payload # has reached the ground, and then releases # the payload. If ground is not detected # before the reaching the maximum descent # value (param1), the command will complete # without releasing the payload. enums['MAV_CMD'][94] = EnumEntry('MAV_CMD_NAV_PAYLOAD_PLACE', '''Descend and place payload. Vehicle moves to specified location, descends until it detects a hanging payload has reached the ground, and then releases the payload. If ground is not detected before the reaching the maximum descent value (param1), the command will complete without releasing the payload.''') enums['MAV_CMD'][94].param[1] = '''Maximum distance to descend.''' enums['MAV_CMD'][94].param[2] = '''Empty''' enums['MAV_CMD'][94].param[3] = '''Empty''' enums['MAV_CMD'][94].param[4] = '''Empty''' enums['MAV_CMD'][94].param[5] = '''Latitude''' enums['MAV_CMD'][94].param[6] = '''Longitude''' enums['MAV_CMD'][94].param[7] = '''Altitude''' MAV_CMD_NAV_LAST = 95 # NOP - This command is only used to mark the upper limit of the # NAV/ACTION commands in the enumeration enums['MAV_CMD'][95] = EnumEntry('MAV_CMD_NAV_LAST', '''NOP - This command is only used to mark the upper limit of the NAV/ACTION commands in the enumeration''') enums['MAV_CMD'][95].param[1] = '''Empty''' enums['MAV_CMD'][95].param[2] = '''Empty''' enums['MAV_CMD'][95].param[3] = '''Empty''' enums['MAV_CMD'][95].param[4] = '''Empty''' enums['MAV_CMD'][95].param[5] = '''Empty''' enums['MAV_CMD'][95].param[6] = '''Empty''' enums['MAV_CMD'][95].param[7] = '''Empty''' MAV_CMD_CONDITION_DELAY = 112 # Delay mission state machine. enums['MAV_CMD'][112] = EnumEntry('MAV_CMD_CONDITION_DELAY', '''Delay mission state machine.''') enums['MAV_CMD'][112].param[1] = '''Delay''' enums['MAV_CMD'][112].param[2] = '''Empty''' enums['MAV_CMD'][112].param[3] = '''Empty''' enums['MAV_CMD'][112].param[4] = '''Empty''' enums['MAV_CMD'][112].param[5] = '''Empty''' enums['MAV_CMD'][112].param[6] = '''Empty''' enums['MAV_CMD'][112].param[7] = '''Empty''' MAV_CMD_CONDITION_CHANGE_ALT = 113 # Ascend/descend at rate. Delay mission state machine until desired # altitude reached. enums['MAV_CMD'][113] = EnumEntry('MAV_CMD_CONDITION_CHANGE_ALT', '''Ascend/descend at rate. Delay mission state machine until desired altitude reached.''') enums['MAV_CMD'][113].param[1] = '''Descent / Ascend rate.''' enums['MAV_CMD'][113].param[2] = '''Empty''' enums['MAV_CMD'][113].param[3] = '''Empty''' enums['MAV_CMD'][113].param[4] = '''Empty''' enums['MAV_CMD'][113].param[5] = '''Empty''' enums['MAV_CMD'][113].param[6] = '''Empty''' enums['MAV_CMD'][113].param[7] = '''Finish Altitude''' MAV_CMD_CONDITION_DISTANCE = 114 # Delay mission state machine until within desired distance of next NAV # point. enums['MAV_CMD'][114] = EnumEntry('MAV_CMD_CONDITION_DISTANCE', '''Delay mission state machine until within desired distance of next NAV point.''') enums['MAV_CMD'][114].param[1] = '''Distance.''' enums['MAV_CMD'][114].param[2] = '''Empty''' enums['MAV_CMD'][114].param[3] = '''Empty''' enums['MAV_CMD'][114].param[4] = '''Empty''' enums['MAV_CMD'][114].param[5] = '''Empty''' enums['MAV_CMD'][114].param[6] = '''Empty''' enums['MAV_CMD'][114].param[7] = '''Empty''' MAV_CMD_CONDITION_YAW = 115 # Reach a certain target angle. enums['MAV_CMD'][115] = EnumEntry('MAV_CMD_CONDITION_YAW', '''Reach a certain target angle.''') enums['MAV_CMD'][115].param[1] = '''target angle, 0 is north''' enums['MAV_CMD'][115].param[2] = '''angular speed''' enums['MAV_CMD'][115].param[3] = '''direction: -1: counter clockwise, 1: clockwise''' enums['MAV_CMD'][115].param[4] = '''0: absolute angle, 1: relative offset''' enums['MAV_CMD'][115].param[5] = '''Empty''' enums['MAV_CMD'][115].param[6] = '''Empty''' enums['MAV_CMD'][115].param[7] = '''Empty''' MAV_CMD_CONDITION_LAST = 159 # NOP - This command is only used to mark the upper limit of the # CONDITION commands in the enumeration enums['MAV_CMD'][159] = EnumEntry('MAV_CMD_CONDITION_LAST', '''NOP - This command is only used to mark the upper limit of the CONDITION commands in the enumeration''') enums['MAV_CMD'][159].param[1] = '''Empty''' enums['MAV_CMD'][159].param[2] = '''Empty''' enums['MAV_CMD'][159].param[3] = '''Empty''' enums['MAV_CMD'][159].param[4] = '''Empty''' enums['MAV_CMD'][159].param[5] = '''Empty''' enums['MAV_CMD'][159].param[6] = '''Empty''' enums['MAV_CMD'][159].param[7] = '''Empty''' MAV_CMD_DO_SET_MODE = 176 # Set system mode. enums['MAV_CMD'][176] = EnumEntry('MAV_CMD_DO_SET_MODE', '''Set system mode.''') enums['MAV_CMD'][176].param[1] = '''Mode''' enums['MAV_CMD'][176].param[2] = '''Custom mode - this is system specific, please refer to the individual autopilot specifications for details.''' enums['MAV_CMD'][176].param[3] = '''Custom sub mode - this is system specific, please refer to the individual autopilot specifications for details.''' enums['MAV_CMD'][176].param[4] = '''Empty''' enums['MAV_CMD'][176].param[5] = '''Empty''' enums['MAV_CMD'][176].param[6] = '''Empty''' enums['MAV_CMD'][176].param[7] = '''Empty''' MAV_CMD_DO_JUMP = 177 # Jump to the desired command in the mission list. Repeat this action # only the specified number of times enums['MAV_CMD'][177] = EnumEntry('MAV_CMD_DO_JUMP', '''Jump to the desired command in the mission list. Repeat this action only the specified number of times''') enums['MAV_CMD'][177].param[1] = '''Sequence number''' enums['MAV_CMD'][177].param[2] = '''Repeat count''' enums['MAV_CMD'][177].param[3] = '''Empty''' enums['MAV_CMD'][177].param[4] = '''Empty''' enums['MAV_CMD'][177].param[5] = '''Empty''' enums['MAV_CMD'][177].param[6] = '''Empty''' enums['MAV_CMD'][177].param[7] = '''Empty''' MAV_CMD_DO_CHANGE_SPEED = 178 # Change speed and/or throttle set points. enums['MAV_CMD'][178] = EnumEntry('MAV_CMD_DO_CHANGE_SPEED', '''Change speed and/or throttle set points.''') enums['MAV_CMD'][178].param[1] = '''Speed type (0=Airspeed, 1=Ground Speed, 2=Climb Speed, 3=Descent Speed)''' enums['MAV_CMD'][178].param[2] = '''Speed (-1 indicates no change)''' enums['MAV_CMD'][178].param[3] = '''Throttle (-1 indicates no change)''' enums['MAV_CMD'][178].param[4] = '''0: absolute, 1: relative''' enums['MAV_CMD'][178].param[5] = '''Empty''' enums['MAV_CMD'][178].param[6] = '''Empty''' enums['MAV_CMD'][178].param[7] = '''Empty''' MAV_CMD_DO_SET_HOME = 179 # Changes the home location either to the current location or a # specified location. enums['MAV_CMD'][179] = EnumEntry('MAV_CMD_DO_SET_HOME', '''Changes the home location either to the current location or a specified location.''') enums['MAV_CMD'][179].param[1] = '''Use current (1=use current location, 0=use specified location)''' enums['MAV_CMD'][179].param[2] = '''Empty''' enums['MAV_CMD'][179].param[3] = '''Empty''' enums['MAV_CMD'][179].param[4] = '''Empty''' enums['MAV_CMD'][179].param[5] = '''Latitude''' enums['MAV_CMD'][179].param[6] = '''Longitude''' enums['MAV_CMD'][179].param[7] = '''Altitude''' MAV_CMD_DO_SET_PARAMETER = 180 # Set a system parameter. Caution! Use of this command requires # knowledge of the numeric enumeration value # of the parameter. enums['MAV_CMD'][180] = EnumEntry('MAV_CMD_DO_SET_PARAMETER', '''Set a system parameter. Caution! Use of this command requires knowledge of the numeric enumeration value of the parameter.''') enums['MAV_CMD'][180].param[1] = '''Parameter number''' enums['MAV_CMD'][180].param[2] = '''Parameter value''' enums['MAV_CMD'][180].param[3] = '''Empty''' enums['MAV_CMD'][180].param[4] = '''Empty''' enums['MAV_CMD'][180].param[5] = '''Empty''' enums['MAV_CMD'][180].param[6] = '''Empty''' enums['MAV_CMD'][180].param[7] = '''Empty''' MAV_CMD_DO_SET_RELAY = 181 # Set a relay to a condition. enums['MAV_CMD'][181] = EnumEntry('MAV_CMD_DO_SET_RELAY', '''Set a relay to a condition.''') enums['MAV_CMD'][181].param[1] = '''Relay instance number.''' enums['MAV_CMD'][181].param[2] = '''Setting. (1=on, 0=off, others possible depending on system hardware)''' enums['MAV_CMD'][181].param[3] = '''Empty''' enums['MAV_CMD'][181].param[4] = '''Empty''' enums['MAV_CMD'][181].param[5] = '''Empty''' enums['MAV_CMD'][181].param[6] = '''Empty''' enums['MAV_CMD'][181].param[7] = '''Empty''' MAV_CMD_DO_REPEAT_RELAY = 182 # Cycle a relay on and off for a desired number of cycles with a desired # period. enums['MAV_CMD'][182] = EnumEntry('MAV_CMD_DO_REPEAT_RELAY', '''Cycle a relay on and off for a desired number of cycles with a desired period.''') enums['MAV_CMD'][182].param[1] = '''Relay instance number.''' enums['MAV_CMD'][182].param[2] = '''Cycle count.''' enums['MAV_CMD'][182].param[3] = '''Cycle time.''' enums['MAV_CMD'][182].param[4] = '''Empty''' enums['MAV_CMD'][182].param[5] = '''Empty''' enums['MAV_CMD'][182].param[6] = '''Empty''' enums['MAV_CMD'][182].param[7] = '''Empty''' MAV_CMD_DO_SET_SERVO = 183 # Set a servo to a desired PWM value. enums['MAV_CMD'][183] = EnumEntry('MAV_CMD_DO_SET_SERVO', '''Set a servo to a desired PWM value.''') enums['MAV_CMD'][183].param[1] = '''Servo instance number.''' enums['MAV_CMD'][183].param[2] = '''Pulse Width Modulation.''' enums['MAV_CMD'][183].param[3] = '''Empty''' enums['MAV_CMD'][183].param[4] = '''Empty''' enums['MAV_CMD'][183].param[5] = '''Empty''' enums['MAV_CMD'][183].param[6] = '''Empty''' enums['MAV_CMD'][183].param[7] = '''Empty''' MAV_CMD_DO_REPEAT_SERVO = 184 # Cycle a between its nominal setting and a desired PWM for a desired # number of cycles with a desired period. enums['MAV_CMD'][184] = EnumEntry('MAV_CMD_DO_REPEAT_SERVO', '''Cycle a between its nominal setting and a desired PWM for a desired number of cycles with a desired period.''') enums['MAV_CMD'][184].param[1] = '''Servo instance number.''' enums['MAV_CMD'][184].param[2] = '''Pulse Width Modulation.''' enums['MAV_CMD'][184].param[3] = '''Cycle count.''' enums['MAV_CMD'][184].param[4] = '''Cycle time.''' enums['MAV_CMD'][184].param[5] = '''Empty''' enums['MAV_CMD'][184].param[6] = '''Empty''' enums['MAV_CMD'][184].param[7] = '''Empty''' MAV_CMD_DO_FLIGHTTERMINATION = 185 # Terminate flight immediately enums['MAV_CMD'][185] = EnumEntry('MAV_CMD_DO_FLIGHTTERMINATION', '''Terminate flight immediately''') enums['MAV_CMD'][185].param[1] = '''Flight termination activated if > 0.5''' enums['MAV_CMD'][185].param[2] = '''Empty''' enums['MAV_CMD'][185].param[3] = '''Empty''' enums['MAV_CMD'][185].param[4] = '''Empty''' enums['MAV_CMD'][185].param[5] = '''Empty''' enums['MAV_CMD'][185].param[6] = '''Empty''' enums['MAV_CMD'][185].param[7] = '''Empty''' MAV_CMD_DO_CHANGE_ALTITUDE = 186 # Change altitude set point. enums['MAV_CMD'][186] = EnumEntry('MAV_CMD_DO_CHANGE_ALTITUDE', '''Change altitude set point.''') enums['MAV_CMD'][186].param[1] = '''Altitude.''' enums['MAV_CMD'][186].param[2] = '''Frame of new altitude.''' enums['MAV_CMD'][186].param[3] = '''Empty''' enums['MAV_CMD'][186].param[4] = '''Empty''' enums['MAV_CMD'][186].param[5] = '''Empty''' enums['MAV_CMD'][186].param[6] = '''Empty''' enums['MAV_CMD'][186].param[7] = '''Empty''' MAV_CMD_DO_LAND_START = 189 # Mission command to perform a landing. This is used as a marker in a # mission to tell the autopilot where a # sequence of mission items that represents a # landing starts. It may also be sent via a # COMMAND_LONG to trigger a landing, in which # case the nearest (geographically) landing # sequence in the mission will be used. The # Latitude/Longitude is optional, and may be # set to 0 if not needed. If specified then it # will be used to help find the closest # landing sequence. enums['MAV_CMD'][189] = EnumEntry('MAV_CMD_DO_LAND_START', '''Mission command to perform a landing. This is used as a marker in a mission to tell the autopilot where a sequence of mission items that represents a landing starts. It may also be sent via a COMMAND_LONG to trigger a landing, in which case the nearest (geographically) landing sequence in the mission will be used. The Latitude/Longitude is optional, and may be set to 0 if not needed. If specified then it will be used to help find the closest landing sequence.''') enums['MAV_CMD'][189].param[1] = '''Empty''' enums['MAV_CMD'][189].param[2] = '''Empty''' enums['MAV_CMD'][189].param[3] = '''Empty''' enums['MAV_CMD'][189].param[4] = '''Empty''' enums['MAV_CMD'][189].param[5] = '''Latitude''' enums['MAV_CMD'][189].param[6] = '''Longitude''' enums['MAV_CMD'][189].param[7] = '''Empty''' MAV_CMD_DO_RALLY_LAND = 190 # Mission command to perform a landing from a rally point. enums['MAV_CMD'][190] = EnumEntry('MAV_CMD_DO_RALLY_LAND', '''Mission command to perform a landing from a rally point.''') enums['MAV_CMD'][190].param[1] = '''Break altitude''' enums['MAV_CMD'][190].param[2] = '''Landing speed''' enums['MAV_CMD'][190].param[3] = '''Empty''' enums['MAV_CMD'][190].param[4] = '''Empty''' enums['MAV_CMD'][190].param[5] = '''Empty''' enums['MAV_CMD'][190].param[6] = '''Empty''' enums['MAV_CMD'][190].param[7] = '''Empty''' MAV_CMD_DO_GO_AROUND = 191 # Mission command to safely abort an autonomous landing. enums['MAV_CMD'][191] = EnumEntry('MAV_CMD_DO_GO_AROUND', '''Mission command to safely abort an autonomous landing.''') enums['MAV_CMD'][191].param[1] = '''Altitude''' enums['MAV_CMD'][191].param[2] = '''Empty''' enums['MAV_CMD'][191].param[3] = '''Empty''' enums['MAV_CMD'][191].param[4] = '''Empty''' enums['MAV_CMD'][191].param[5] = '''Empty''' enums['MAV_CMD'][191].param[6] = '''Empty''' enums['MAV_CMD'][191].param[7] = '''Empty''' MAV_CMD_DO_REPOSITION = 192 # Reposition the vehicle to a specific WGS84 global position. enums['MAV_CMD'][192] = EnumEntry('MAV_CMD_DO_REPOSITION', '''Reposition the vehicle to a specific WGS84 global position.''') enums['MAV_CMD'][192].param[1] = '''Ground speed, less than 0 (-1) for default''' enums['MAV_CMD'][192].param[2] = '''Bitmask of option flags.''' enums['MAV_CMD'][192].param[3] = '''Reserved''' enums['MAV_CMD'][192].param[4] = '''Yaw heading, NaN for unchanged. For planes indicates loiter direction (0: clockwise, 1: counter clockwise)''' enums['MAV_CMD'][192].param[5] = '''Latitude (deg * 1E7)''' enums['MAV_CMD'][192].param[6] = '''Longitude (deg * 1E7)''' enums['MAV_CMD'][192].param[7] = '''Altitude (meters)''' MAV_CMD_DO_PAUSE_CONTINUE = 193 # If in a GPS controlled position mode, hold the current position or # continue. enums['MAV_CMD'][193] = EnumEntry('MAV_CMD_DO_PAUSE_CONTINUE', '''If in a GPS controlled position mode, hold the current position or continue.''') enums['MAV_CMD'][193].param[1] = '''0: Pause current mission or reposition command, hold current position. 1: Continue mission. A VTOL capable vehicle should enter hover mode (multicopter and VTOL planes). A plane should loiter with the default loiter radius.''' enums['MAV_CMD'][193].param[2] = '''Reserved''' enums['MAV_CMD'][193].param[3] = '''Reserved''' enums['MAV_CMD'][193].param[4] = '''Reserved''' enums['MAV_CMD'][193].param[5] = '''Reserved''' enums['MAV_CMD'][193].param[6] = '''Reserved''' enums['MAV_CMD'][193].param[7] = '''Reserved''' MAV_CMD_DO_SET_REVERSE = 194 # Set moving direction to forward or reverse. enums['MAV_CMD'][194] = EnumEntry('MAV_CMD_DO_SET_REVERSE', '''Set moving direction to forward or reverse.''') enums['MAV_CMD'][194].param[1] = '''Direction (0=Forward, 1=Reverse)''' enums['MAV_CMD'][194].param[2] = '''Empty''' enums['MAV_CMD'][194].param[3] = '''Empty''' enums['MAV_CMD'][194].param[4] = '''Empty''' enums['MAV_CMD'][194].param[5] = '''Empty''' enums['MAV_CMD'][194].param[6] = '''Empty''' enums['MAV_CMD'][194].param[7] = '''Empty''' MAV_CMD_DO_SET_ROI_LOCATION = 195 # Sets the region of interest (ROI) to a location. This can then be used # by the vehicles control system to control # the vehicle attitude and the attitude of # various sensors such as cameras. enums['MAV_CMD'][195] = EnumEntry('MAV_CMD_DO_SET_ROI_LOCATION', '''Sets the region of interest (ROI) to a location. This can then be used by the vehicles control system to control the vehicle attitude and the attitude of various sensors such as cameras.''') enums['MAV_CMD'][195].param[1] = '''Empty''' enums['MAV_CMD'][195].param[2] = '''Empty''' enums['MAV_CMD'][195].param[3] = '''Empty''' enums['MAV_CMD'][195].param[4] = '''Empty''' enums['MAV_CMD'][195].param[5] = '''Latitude''' enums['MAV_CMD'][195].param[6] = '''Longitude''' enums['MAV_CMD'][195].param[7] = '''Altitude''' MAV_CMD_DO_SET_ROI_WPNEXT_OFFSET = 196 # Sets the region of interest (ROI) to be toward next waypoint, with # optional pitch/roll/yaw offset. This can # then be used by the vehicles control system # to control the vehicle attitude and the # attitude of various sensors such as cameras. enums['MAV_CMD'][196] = EnumEntry('MAV_CMD_DO_SET_ROI_WPNEXT_OFFSET', '''Sets the region of interest (ROI) to be toward next waypoint, with optional pitch/roll/yaw offset. This can then be used by the vehicles control system to control the vehicle attitude and the attitude of various sensors such as cameras.''') enums['MAV_CMD'][196].param[1] = '''Empty''' enums['MAV_CMD'][196].param[2] = '''Empty''' enums['MAV_CMD'][196].param[3] = '''Empty''' enums['MAV_CMD'][196].param[4] = '''Empty''' enums['MAV_CMD'][196].param[5] = '''pitch offset from next waypoint''' enums['MAV_CMD'][196].param[6] = '''roll offset from next waypoint''' enums['MAV_CMD'][196].param[7] = '''yaw offset from next waypoint''' MAV_CMD_DO_SET_ROI_NONE = 197 # Cancels any previous ROI command returning the vehicle/sensors to # default flight characteristics. This can # then be used by the vehicles control system # to control the vehicle attitude and the # attitude of various sensors such as cameras. enums['MAV_CMD'][197] = EnumEntry('MAV_CMD_DO_SET_ROI_NONE', '''Cancels any previous ROI command returning the vehicle/sensors to default flight characteristics. This can then be used by the vehicles control system to control the vehicle attitude and the attitude of various sensors such as cameras.''') enums['MAV_CMD'][197].param[1] = '''Empty''' enums['MAV_CMD'][197].param[2] = '''Empty''' enums['MAV_CMD'][197].param[3] = '''Empty''' enums['MAV_CMD'][197].param[4] = '''Empty''' enums['MAV_CMD'][197].param[5] = '''Empty''' enums['MAV_CMD'][197].param[6] = '''Empty''' enums['MAV_CMD'][197].param[7] = '''Empty''' MAV_CMD_DO_SET_ROI_SYSID = 198 # Camera ROI is vehicle with specified SysID. enums['MAV_CMD'][198] = EnumEntry('MAV_CMD_DO_SET_ROI_SYSID', '''Camera ROI is vehicle with specified SysID.''') enums['MAV_CMD'][198].param[1] = '''sysid''' enums['MAV_CMD'][198].param[2] = '''Reserved (default:0)''' enums['MAV_CMD'][198].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][198].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][198].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][198].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][198].param[7] = '''Reserved (default:0)''' MAV_CMD_DO_CONTROL_VIDEO = 200 # Control onboard camera system. enums['MAV_CMD'][200] = EnumEntry('MAV_CMD_DO_CONTROL_VIDEO', '''Control onboard camera system.''') enums['MAV_CMD'][200].param[1] = '''Camera ID (-1 for all)''' enums['MAV_CMD'][200].param[2] = '''Transmission: 0: disabled, 1: enabled compressed, 2: enabled raw''' enums['MAV_CMD'][200].param[3] = '''Transmission mode: 0: video stream, >0: single images every n seconds''' enums['MAV_CMD'][200].param[4] = '''Recording: 0: disabled, 1: enabled compressed, 2: enabled raw''' enums['MAV_CMD'][200].param[5] = '''Empty''' enums['MAV_CMD'][200].param[6] = '''Empty''' enums['MAV_CMD'][200].param[7] = '''Empty''' MAV_CMD_DO_SET_ROI = 201 # Sets the region of interest (ROI) for a sensor set or the vehicle # itself. This can then be used by the # vehicles control system to control the # vehicle attitude and the attitude of various # sensors such as cameras. enums['MAV_CMD'][201] = EnumEntry('MAV_CMD_DO_SET_ROI', '''Sets the region of interest (ROI) for a sensor set or the vehicle itself. This can then be used by the vehicles control system to control the vehicle attitude and the attitude of various sensors such as cameras.''') enums['MAV_CMD'][201].param[1] = '''Region of interest mode.''' enums['MAV_CMD'][201].param[2] = '''Waypoint index/ target ID (depends on param 1).''' enums['MAV_CMD'][201].param[3] = '''Region of interest index. (allows a vehicle to manage multiple ROI's)''' enums['MAV_CMD'][201].param[4] = '''Empty''' enums['MAV_CMD'][201].param[5] = '''x the location of the fixed ROI (see MAV_FRAME)''' enums['MAV_CMD'][201].param[6] = '''y''' enums['MAV_CMD'][201].param[7] = '''z''' MAV_CMD_DO_DIGICAM_CONFIGURE = 202 # Configure digital camera. This is a fallback message for systems that # have not yet implemented PARAM_EXT_XXX # messages and camera definition files (see ht # tps://mavlink.io/en/services/camera_def.html # ). enums['MAV_CMD'][202] = EnumEntry('MAV_CMD_DO_DIGICAM_CONFIGURE', '''Configure digital camera. This is a fallback message for systems that have not yet implemented PARAM_EXT_XXX messages and camera definition files (see https://mavlink.io/en/services/camera_def.html ).''') enums['MAV_CMD'][202].param[1] = '''Modes: P, TV, AV, M, Etc.''' enums['MAV_CMD'][202].param[2] = '''Shutter speed: Divisor number for one second.''' enums['MAV_CMD'][202].param[3] = '''Aperture: F stop number.''' enums['MAV_CMD'][202].param[4] = '''ISO number e.g. 80, 100, 200, Etc.''' enums['MAV_CMD'][202].param[5] = '''Exposure type enumerator.''' enums['MAV_CMD'][202].param[6] = '''Command Identity.''' enums['MAV_CMD'][202].param[7] = '''Main engine cut-off time before camera trigger. (0 means no cut-off)''' MAV_CMD_DO_DIGICAM_CONTROL = 203 # Control digital camera. This is a fallback message for systems that # have not yet implemented PARAM_EXT_XXX # messages and camera definition files (see ht # tps://mavlink.io/en/services/camera_def.html # ). enums['MAV_CMD'][203] = EnumEntry('MAV_CMD_DO_DIGICAM_CONTROL', '''Control digital camera. This is a fallback message for systems that have not yet implemented PARAM_EXT_XXX messages and camera definition files (see https://mavlink.io/en/services/camera_def.html ).''') enums['MAV_CMD'][203].param[1] = '''Session control e.g. show/hide lens''' enums['MAV_CMD'][203].param[2] = '''Zoom's absolute position''' enums['MAV_CMD'][203].param[3] = '''Zooming step value to offset zoom from the current position''' enums['MAV_CMD'][203].param[4] = '''Focus Locking, Unlocking or Re-locking''' enums['MAV_CMD'][203].param[5] = '''Shooting Command''' enums['MAV_CMD'][203].param[6] = '''Command Identity''' enums['MAV_CMD'][203].param[7] = '''Test shot identifier. If set to 1, image will only be captured, but not counted towards internal frame count.''' MAV_CMD_DO_MOUNT_CONFIGURE = 204 # Mission command to configure a camera or antenna mount enums['MAV_CMD'][204] = EnumEntry('MAV_CMD_DO_MOUNT_CONFIGURE', '''Mission command to configure a camera or antenna mount''') enums['MAV_CMD'][204].param[1] = '''Mount operation mode''' enums['MAV_CMD'][204].param[2] = '''stabilize roll? (1 = yes, 0 = no)''' enums['MAV_CMD'][204].param[3] = '''stabilize pitch? (1 = yes, 0 = no)''' enums['MAV_CMD'][204].param[4] = '''stabilize yaw? (1 = yes, 0 = no)''' enums['MAV_CMD'][204].param[5] = '''Empty''' enums['MAV_CMD'][204].param[6] = '''Empty''' enums['MAV_CMD'][204].param[7] = '''Empty''' MAV_CMD_DO_MOUNT_CONTROL = 205 # Mission command to control a camera or antenna mount enums['MAV_CMD'][205] = EnumEntry('MAV_CMD_DO_MOUNT_CONTROL', '''Mission command to control a camera or antenna mount''') enums['MAV_CMD'][205].param[1] = '''pitch (WIP: DEPRECATED: or lat in degrees) depending on mount mode.''' enums['MAV_CMD'][205].param[2] = '''roll (WIP: DEPRECATED: or lon in degrees) depending on mount mode.''' enums['MAV_CMD'][205].param[3] = '''yaw (WIP: DEPRECATED: or alt in meters) depending on mount mode.''' enums['MAV_CMD'][205].param[4] = '''WIP: alt in meters depending on mount mode.''' enums['MAV_CMD'][205].param[5] = '''WIP: latitude in degrees * 1E7, set if appropriate mount mode.''' enums['MAV_CMD'][205].param[6] = '''WIP: longitude in degrees * 1E7, set if appropriate mount mode.''' enums['MAV_CMD'][205].param[7] = '''Mount mode.''' MAV_CMD_DO_SET_CAM_TRIGG_DIST = 206 # Mission command to set camera trigger distance for this flight. The # camera is triggered each time this distance # is exceeded. This command can also be used # to set the shutter integration time for the # camera. enums['MAV_CMD'][206] = EnumEntry('MAV_CMD_DO_SET_CAM_TRIGG_DIST', '''Mission command to set camera trigger distance for this flight. The camera is triggered each time this distance is exceeded. This command can also be used to set the shutter integration time for the camera.''') enums['MAV_CMD'][206].param[1] = '''Camera trigger distance. 0 to stop triggering.''' enums['MAV_CMD'][206].param[2] = '''Camera shutter integration time. -1 or 0 to ignore''' enums['MAV_CMD'][206].param[3] = '''Trigger camera once immediately. (0 = no trigger, 1 = trigger)''' enums['MAV_CMD'][206].param[4] = '''Empty''' enums['MAV_CMD'][206].param[5] = '''Empty''' enums['MAV_CMD'][206].param[6] = '''Empty''' enums['MAV_CMD'][206].param[7] = '''Empty''' MAV_CMD_DO_FENCE_ENABLE = 207 # Mission command to enable the geofence enums['MAV_CMD'][207] = EnumEntry('MAV_CMD_DO_FENCE_ENABLE', '''Mission command to enable the geofence''') enums['MAV_CMD'][207].param[1] = '''enable? (0=disable, 1=enable, 2=disable_floor_only)''' enums['MAV_CMD'][207].param[2] = '''Empty''' enums['MAV_CMD'][207].param[3] = '''Empty''' enums['MAV_CMD'][207].param[4] = '''Empty''' enums['MAV_CMD'][207].param[5] = '''Empty''' enums['MAV_CMD'][207].param[6] = '''Empty''' enums['MAV_CMD'][207].param[7] = '''Empty''' MAV_CMD_DO_PARACHUTE = 208 # Mission command to trigger a parachute enums['MAV_CMD'][208] = EnumEntry('MAV_CMD_DO_PARACHUTE', '''Mission command to trigger a parachute''') enums['MAV_CMD'][208].param[1] = '''action''' enums['MAV_CMD'][208].param[2] = '''Empty''' enums['MAV_CMD'][208].param[3] = '''Empty''' enums['MAV_CMD'][208].param[4] = '''Empty''' enums['MAV_CMD'][208].param[5] = '''Empty''' enums['MAV_CMD'][208].param[6] = '''Empty''' enums['MAV_CMD'][208].param[7] = '''Empty''' MAV_CMD_DO_MOTOR_TEST = 209 # Mission command to perform motor test. enums['MAV_CMD'][209] = EnumEntry('MAV_CMD_DO_MOTOR_TEST', '''Mission command to perform motor test.''') enums['MAV_CMD'][209].param[1] = '''Motor instance number. (from 1 to max number of motors on the vehicle)''' enums['MAV_CMD'][209].param[2] = '''Throttle type.''' enums['MAV_CMD'][209].param[3] = '''Throttle.''' enums['MAV_CMD'][209].param[4] = '''Timeout.''' enums['MAV_CMD'][209].param[5] = '''Motor count. (number of motors to test to test in sequence, waiting for the timeout above between them; 0=1 motor, 1=1 motor, 2=2 motors...)''' enums['MAV_CMD'][209].param[6] = '''Motor test order.''' enums['MAV_CMD'][209].param[7] = '''Empty''' MAV_CMD_DO_INVERTED_FLIGHT = 210 # Change to/from inverted flight. enums['MAV_CMD'][210] = EnumEntry('MAV_CMD_DO_INVERTED_FLIGHT', '''Change to/from inverted flight.''') enums['MAV_CMD'][210].param[1] = '''Inverted flight. (0=normal, 1=inverted)''' enums['MAV_CMD'][210].param[2] = '''Empty''' enums['MAV_CMD'][210].param[3] = '''Empty''' enums['MAV_CMD'][210].param[4] = '''Empty''' enums['MAV_CMD'][210].param[5] = '''Empty''' enums['MAV_CMD'][210].param[6] = '''Empty''' enums['MAV_CMD'][210].param[7] = '''Empty''' MAV_CMD_NAV_SET_YAW_SPEED = 213 # Sets a desired vehicle turn angle and speed change. enums['MAV_CMD'][213] = EnumEntry('MAV_CMD_NAV_SET_YAW_SPEED', '''Sets a desired vehicle turn angle and speed change.''') enums['MAV_CMD'][213].param[1] = '''Yaw angle to adjust steering by.''' enums['MAV_CMD'][213].param[2] = '''Speed.''' enums['MAV_CMD'][213].param[3] = '''Final angle. (0=absolute, 1=relative)''' enums['MAV_CMD'][213].param[4] = '''Empty''' enums['MAV_CMD'][213].param[5] = '''Empty''' enums['MAV_CMD'][213].param[6] = '''Empty''' enums['MAV_CMD'][213].param[7] = '''Empty''' MAV_CMD_DO_SET_CAM_TRIGG_INTERVAL = 214 # Mission command to set camera trigger interval for this flight. If # triggering is enabled, the camera is # triggered each time this interval expires. # This command can also be used to set the # shutter integration time for the camera. enums['MAV_CMD'][214] = EnumEntry('MAV_CMD_DO_SET_CAM_TRIGG_INTERVAL', '''Mission command to set camera trigger interval for this flight. If triggering is enabled, the camera is triggered each time this interval expires. This command can also be used to set the shutter integration time for the camera.''') enums['MAV_CMD'][214].param[1] = '''Camera trigger cycle time. -1 or 0 to ignore.''' enums['MAV_CMD'][214].param[2] = '''Camera shutter integration time. Should be less than trigger cycle time. -1 or 0 to ignore.''' enums['MAV_CMD'][214].param[3] = '''Empty''' enums['MAV_CMD'][214].param[4] = '''Empty''' enums['MAV_CMD'][214].param[5] = '''Empty''' enums['MAV_CMD'][214].param[6] = '''Empty''' enums['MAV_CMD'][214].param[7] = '''Empty''' MAV_CMD_DO_MOUNT_CONTROL_QUAT = 220 # Mission command to control a camera or antenna mount, using a # quaternion as reference. enums['MAV_CMD'][220] = EnumEntry('MAV_CMD_DO_MOUNT_CONTROL_QUAT', '''Mission command to control a camera or antenna mount, using a quaternion as reference.''') enums['MAV_CMD'][220].param[1] = '''quaternion param q1, w (1 in null-rotation)''' enums['MAV_CMD'][220].param[2] = '''quaternion param q2, x (0 in null-rotation)''' enums['MAV_CMD'][220].param[3] = '''quaternion param q3, y (0 in null-rotation)''' enums['MAV_CMD'][220].param[4] = '''quaternion param q4, z (0 in null-rotation)''' enums['MAV_CMD'][220].param[5] = '''Empty''' enums['MAV_CMD'][220].param[6] = '''Empty''' enums['MAV_CMD'][220].param[7] = '''Empty''' MAV_CMD_DO_GUIDED_MASTER = 221 # set id of master controller enums['MAV_CMD'][221] = EnumEntry('MAV_CMD_DO_GUIDED_MASTER', '''set id of master controller''') enums['MAV_CMD'][221].param[1] = '''System ID''' enums['MAV_CMD'][221].param[2] = '''Component ID''' enums['MAV_CMD'][221].param[3] = '''Empty''' enums['MAV_CMD'][221].param[4] = '''Empty''' enums['MAV_CMD'][221].param[5] = '''Empty''' enums['MAV_CMD'][221].param[6] = '''Empty''' enums['MAV_CMD'][221].param[7] = '''Empty''' MAV_CMD_DO_GUIDED_LIMITS = 222 # Set limits for external control enums['MAV_CMD'][222] = EnumEntry('MAV_CMD_DO_GUIDED_LIMITS', '''Set limits for external control''') enums['MAV_CMD'][222].param[1] = '''Timeout - maximum time that external controller will be allowed to control vehicle. 0 means no timeout.''' enums['MAV_CMD'][222].param[2] = '''Altitude (MSL) min - if vehicle moves below this alt, the command will be aborted and the mission will continue. 0 means no lower altitude limit.''' enums['MAV_CMD'][222].param[3] = '''Altitude (MSL) max - if vehicle moves above this alt, the command will be aborted and the mission will continue. 0 means no upper altitude limit.''' enums['MAV_CMD'][222].param[4] = '''Horizontal move limit - if vehicle moves more than this distance from its location at the moment the command was executed, the command will be aborted and the mission will continue. 0 means no horizontal move limit.''' enums['MAV_CMD'][222].param[5] = '''Empty''' enums['MAV_CMD'][222].param[6] = '''Empty''' enums['MAV_CMD'][222].param[7] = '''Empty''' MAV_CMD_DO_ENGINE_CONTROL = 223 # Control vehicle engine. This is interpreted by the vehicles engine # controller to change the target engine # state. It is intended for vehicles with # internal combustion engines enums['MAV_CMD'][223] = EnumEntry('MAV_CMD_DO_ENGINE_CONTROL', '''Control vehicle engine. This is interpreted by the vehicles engine controller to change the target engine state. It is intended for vehicles with internal combustion engines''') enums['MAV_CMD'][223].param[1] = '''0: Stop engine, 1:Start Engine''' enums['MAV_CMD'][223].param[2] = '''0: Warm start, 1:Cold start. Controls use of choke where applicable''' enums['MAV_CMD'][223].param[3] = '''Height delay. This is for commanding engine start only after the vehicle has gained the specified height. Used in VTOL vehicles during takeoff to start engine after the aircraft is off the ground. Zero for no delay.''' enums['MAV_CMD'][223].param[4] = '''Empty''' enums['MAV_CMD'][223].param[5] = '''Empty''' enums['MAV_CMD'][223].param[6] = '''Empty''' enums['MAV_CMD'][223].param[7] = '''Empty''' MAV_CMD_DO_SET_MISSION_CURRENT = 224 # Set the mission item with sequence number seq as current item. This # means that the MAV will continue to this # mission item on the shortest path (not # following the mission items in-between). enums['MAV_CMD'][224] = EnumEntry('MAV_CMD_DO_SET_MISSION_CURRENT', '''Set the mission item with sequence number seq as current item. This means that the MAV will continue to this mission item on the shortest path (not following the mission items in-between).''') enums['MAV_CMD'][224].param[1] = '''Mission sequence value to set''' enums['MAV_CMD'][224].param[2] = '''Empty''' enums['MAV_CMD'][224].param[3] = '''Empty''' enums['MAV_CMD'][224].param[4] = '''Empty''' enums['MAV_CMD'][224].param[5] = '''Empty''' enums['MAV_CMD'][224].param[6] = '''Empty''' enums['MAV_CMD'][224].param[7] = '''Empty''' MAV_CMD_DO_LAST = 240 # NOP - This command is only used to mark the upper limit of the DO # commands in the enumeration enums['MAV_CMD'][240] = EnumEntry('MAV_CMD_DO_LAST', '''NOP - This command is only used to mark the upper limit of the DO commands in the enumeration''') enums['MAV_CMD'][240].param[1] = '''Empty''' enums['MAV_CMD'][240].param[2] = '''Empty''' enums['MAV_CMD'][240].param[3] = '''Empty''' enums['MAV_CMD'][240].param[4] = '''Empty''' enums['MAV_CMD'][240].param[5] = '''Empty''' enums['MAV_CMD'][240].param[6] = '''Empty''' enums['MAV_CMD'][240].param[7] = '''Empty''' MAV_CMD_PREFLIGHT_CALIBRATION = 241 # Trigger calibration. This command will be only accepted if in pre- # flight mode. Except for Temperature # Calibration, only one sensor should be set # in a single message and all others should be # zero. enums['MAV_CMD'][241] = EnumEntry('MAV_CMD_PREFLIGHT_CALIBRATION', '''Trigger calibration. This command will be only accepted if in pre-flight mode. Except for Temperature Calibration, only one sensor should be set in a single message and all others should be zero.''') enums['MAV_CMD'][241].param[1] = '''1: gyro calibration, 3: gyro temperature calibration''' enums['MAV_CMD'][241].param[2] = '''1: magnetometer calibration''' enums['MAV_CMD'][241].param[3] = '''1: ground pressure calibration''' enums['MAV_CMD'][241].param[4] = '''1: radio RC calibration, 2: RC trim calibration''' enums['MAV_CMD'][241].param[5] = '''1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration''' enums['MAV_CMD'][241].param[6] = '''1: APM: compass/motor interference calibration (PX4: airspeed calibration, deprecated), 2: airspeed calibration''' enums['MAV_CMD'][241].param[7] = '''1: ESC calibration, 3: barometer temperature calibration''' MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS = 242 # Set sensor offsets. This command will be only accepted if in pre- # flight mode. enums['MAV_CMD'][242] = EnumEntry('MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS', '''Set sensor offsets. This command will be only accepted if in pre-flight mode.''') enums['MAV_CMD'][242].param[1] = '''Sensor to adjust the offsets for: 0: gyros, 1: accelerometer, 2: magnetometer, 3: barometer, 4: optical flow, 5: second magnetometer, 6: third magnetometer''' enums['MAV_CMD'][242].param[2] = '''X axis offset (or generic dimension 1), in the sensor's raw units''' enums['MAV_CMD'][242].param[3] = '''Y axis offset (or generic dimension 2), in the sensor's raw units''' enums['MAV_CMD'][242].param[4] = '''Z axis offset (or generic dimension 3), in the sensor's raw units''' enums['MAV_CMD'][242].param[5] = '''Generic dimension 4, in the sensor's raw units''' enums['MAV_CMD'][242].param[6] = '''Generic dimension 5, in the sensor's raw units''' enums['MAV_CMD'][242].param[7] = '''Generic dimension 6, in the sensor's raw units''' MAV_CMD_PREFLIGHT_UAVCAN = 243 # Trigger UAVCAN config. This command will be only accepted if in pre- # flight mode. enums['MAV_CMD'][243] = EnumEntry('MAV_CMD_PREFLIGHT_UAVCAN', '''Trigger UAVCAN config. This command will be only accepted if in pre-flight mode.''') enums['MAV_CMD'][243].param[1] = '''1: Trigger actuator ID assignment and direction mapping.''' enums['MAV_CMD'][243].param[2] = '''Reserved''' enums['MAV_CMD'][243].param[3] = '''Reserved''' enums['MAV_CMD'][243].param[4] = '''Reserved''' enums['MAV_CMD'][243].param[5] = '''Reserved''' enums['MAV_CMD'][243].param[6] = '''Reserved''' enums['MAV_CMD'][243].param[7] = '''Reserved''' MAV_CMD_PREFLIGHT_STORAGE = 245 # Request storage of different parameter values and logs. This command # will be only accepted if in pre-flight mode. enums['MAV_CMD'][245] = EnumEntry('MAV_CMD_PREFLIGHT_STORAGE', '''Request storage of different parameter values and logs. This command will be only accepted if in pre-flight mode.''') enums['MAV_CMD'][245].param[1] = '''Parameter storage: 0: READ FROM FLASH/EEPROM, 1: WRITE CURRENT TO FLASH/EEPROM, 2: Reset to defaults''' enums['MAV_CMD'][245].param[2] = '''Mission storage: 0: READ FROM FLASH/EEPROM, 1: WRITE CURRENT TO FLASH/EEPROM, 2: Reset to defaults''' enums['MAV_CMD'][245].param[3] = '''Onboard logging: 0: Ignore, 1: Start default rate logging, -1: Stop logging, > 1: logging rate (e.g. set to 1000 for 1000 Hz logging)''' enums['MAV_CMD'][245].param[4] = '''Reserved''' enums['MAV_CMD'][245].param[5] = '''Empty''' enums['MAV_CMD'][245].param[6] = '''Empty''' enums['MAV_CMD'][245].param[7] = '''Empty''' MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN = 246 # Request the reboot or shutdown of system components. enums['MAV_CMD'][246] = EnumEntry('MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN', '''Request the reboot or shutdown of system components.''') enums['MAV_CMD'][246].param[1] = '''0: Do nothing for autopilot, 1: Reboot autopilot, 2: Shutdown autopilot, 3: Reboot autopilot and keep it in the bootloader until upgraded.''' enums['MAV_CMD'][246].param[2] = '''0: Do nothing for onboard computer, 1: Reboot onboard computer, 2: Shutdown onboard computer, 3: Reboot onboard computer and keep it in the bootloader until upgraded.''' enums['MAV_CMD'][246].param[3] = '''WIP: 0: Do nothing for camera, 1: Reboot onboard camera, 2: Shutdown onboard camera, 3: Reboot onboard camera and keep it in the bootloader until upgraded''' enums['MAV_CMD'][246].param[4] = '''WIP: 0: Do nothing for mount (e.g. gimbal), 1: Reboot mount, 2: Shutdown mount, 3: Reboot mount and keep it in the bootloader until upgraded''' enums['MAV_CMD'][246].param[5] = '''Reserved, send 0''' enums['MAV_CMD'][246].param[6] = '''Reserved, send 0''' enums['MAV_CMD'][246].param[7] = '''WIP: ID (e.g. camera ID -1 for all IDs)''' MAV_CMD_OVERRIDE_GOTO = 252 # Override current mission with command to pause mission, pause mission # and move to position, continue/resume # mission. When param 1 indicates that the # mission is paused (MAV_GOTO_DO_HOLD), param # 2 defines whether it holds in place or moves # to another position. enums['MAV_CMD'][252] = EnumEntry('MAV_CMD_OVERRIDE_GOTO', '''Override current mission with command to pause mission, pause mission and move to position, continue/resume mission. When param 1 indicates that the mission is paused (MAV_GOTO_DO_HOLD), param 2 defines whether it holds in place or moves to another position.''') enums['MAV_CMD'][252].param[1] = '''MAV_GOTO_DO_HOLD: pause mission and either hold or move to specified position (depending on param2), MAV_GOTO_DO_CONTINUE: resume mission.''' enums['MAV_CMD'][252].param[2] = '''MAV_GOTO_HOLD_AT_CURRENT_POSITION: hold at current position, MAV_GOTO_HOLD_AT_SPECIFIED_POSITION: hold at specified position.''' enums['MAV_CMD'][252].param[3] = '''Coordinate frame of hold point.''' enums['MAV_CMD'][252].param[4] = '''Desired yaw angle.''' enums['MAV_CMD'][252].param[5] = '''Latitude / X position.''' enums['MAV_CMD'][252].param[6] = '''Longitude / Y position.''' enums['MAV_CMD'][252].param[7] = '''Altitude / Z position.''' MAV_CMD_MISSION_START = 300 # start running a mission enums['MAV_CMD'][300] = EnumEntry('MAV_CMD_MISSION_START', '''start running a mission''') enums['MAV_CMD'][300].param[1] = '''first_item: the first mission item to run''' enums['MAV_CMD'][300].param[2] = '''last_item: the last mission item to run (after this item is run, the mission ends)''' enums['MAV_CMD'][300].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][300].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][300].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][300].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][300].param[7] = '''Reserved (default:0)''' MAV_CMD_COMPONENT_ARM_DISARM = 400 # Arms / Disarms a component enums['MAV_CMD'][400] = EnumEntry('MAV_CMD_COMPONENT_ARM_DISARM', '''Arms / Disarms a component''') enums['MAV_CMD'][400].param[1] = '''0: disarm, 1: arm''' enums['MAV_CMD'][400].param[2] = '''0: arm-disarm unless prevented by safety checks (i.e. when landed), 21196: force arming/disarming (e.g. allow arming to override preflight checks and disarming in flight)''' enums['MAV_CMD'][400].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][400].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][400].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][400].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][400].param[7] = '''Reserved (default:0)''' MAV_CMD_GET_HOME_POSITION = 410 # Request the home position from the vehicle. enums['MAV_CMD'][410] = EnumEntry('MAV_CMD_GET_HOME_POSITION', '''Request the home position from the vehicle.''') enums['MAV_CMD'][410].param[1] = '''Reserved''' enums['MAV_CMD'][410].param[2] = '''Reserved''' enums['MAV_CMD'][410].param[3] = '''Reserved''' enums['MAV_CMD'][410].param[4] = '''Reserved''' enums['MAV_CMD'][410].param[5] = '''Reserved''' enums['MAV_CMD'][410].param[6] = '''Reserved''' enums['MAV_CMD'][410].param[7] = '''Reserved''' MAV_CMD_START_RX_PAIR = 500 # Starts receiver pairing. enums['MAV_CMD'][500] = EnumEntry('MAV_CMD_START_RX_PAIR', '''Starts receiver pairing.''') enums['MAV_CMD'][500].param[1] = '''0:Spektrum.''' enums['MAV_CMD'][500].param[2] = '''RC type.''' enums['MAV_CMD'][500].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][500].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][500].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][500].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][500].param[7] = '''Reserved (default:0)''' MAV_CMD_GET_MESSAGE_INTERVAL = 510 # Request the interval between messages for a particular MAVLink message # ID. The receiver should ACK the command and # then emit its response in a MESSAGE_INTERVAL # message. enums['MAV_CMD'][510] = EnumEntry('MAV_CMD_GET_MESSAGE_INTERVAL', '''Request the interval between messages for a particular MAVLink message ID. The receiver should ACK the command and then emit its response in a MESSAGE_INTERVAL message.''') enums['MAV_CMD'][510].param[1] = '''The MAVLink message ID''' enums['MAV_CMD'][510].param[2] = '''Reserved (default:0)''' enums['MAV_CMD'][510].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][510].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][510].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][510].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][510].param[7] = '''Reserved (default:0)''' MAV_CMD_SET_MESSAGE_INTERVAL = 511 # Set the interval between messages for a particular MAVLink message ID. # This interface replaces REQUEST_DATA_STREAM. enums['MAV_CMD'][511] = EnumEntry('MAV_CMD_SET_MESSAGE_INTERVAL', '''Set the interval between messages for a particular MAVLink message ID. This interface replaces REQUEST_DATA_STREAM.''') enums['MAV_CMD'][511].param[1] = '''The MAVLink message ID''' enums['MAV_CMD'][511].param[2] = '''The interval between two messages. Set to -1 to disable and 0 to request default rate.''' enums['MAV_CMD'][511].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][511].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][511].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][511].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][511].param[7] = '''Reserved (default:0)''' MAV_CMD_REQUEST_MESSAGE = 512 # Request the target system(s) emit a single instance of a specified # message (i.e. a "one-shot" version of # MAV_CMD_SET_MESSAGE_INTERVAL). enums['MAV_CMD'][512] = EnumEntry('MAV_CMD_REQUEST_MESSAGE', '''Request the target system(s) emit a single instance of a specified message (i.e. a "one-shot" version of MAV_CMD_SET_MESSAGE_INTERVAL).''') enums['MAV_CMD'][512].param[1] = '''The MAVLink message ID of the requested message.''' enums['MAV_CMD'][512].param[2] = '''Index id (if appropriate). The use of this parameter (if any), must be defined in the requested message.''' enums['MAV_CMD'][512].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][512].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][512].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][512].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][512].param[7] = '''Reserved (default:0)''' MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES = 520 # Request autopilot capabilities. The receiver should ACK the command # and then emit its capabilities in an # AUTOPILOT_VERSION message enums['MAV_CMD'][520] = EnumEntry('MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES', '''Request autopilot capabilities. The receiver should ACK the command and then emit its capabilities in an AUTOPILOT_VERSION message''') enums['MAV_CMD'][520].param[1] = '''1: Request autopilot version''' enums['MAV_CMD'][520].param[2] = '''Reserved (all remaining params)''' enums['MAV_CMD'][520].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][520].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][520].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][520].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][520].param[7] = '''Reserved (default:0)''' MAV_CMD_REQUEST_CAMERA_INFORMATION = 521 # Request camera information (CAMERA_INFORMATION). enums['MAV_CMD'][521] = EnumEntry('MAV_CMD_REQUEST_CAMERA_INFORMATION', '''Request camera information (CAMERA_INFORMATION).''') enums['MAV_CMD'][521].param[1] = '''0: No action 1: Request camera capabilities''' enums['MAV_CMD'][521].param[2] = '''Reserved (all remaining params)''' enums['MAV_CMD'][521].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][521].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][521].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][521].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][521].param[7] = '''Reserved (default:0)''' MAV_CMD_REQUEST_CAMERA_SETTINGS = 522 # Request camera settings (CAMERA_SETTINGS). enums['MAV_CMD'][522] = EnumEntry('MAV_CMD_REQUEST_CAMERA_SETTINGS', '''Request camera settings (CAMERA_SETTINGS).''') enums['MAV_CMD'][522].param[1] = '''0: No Action 1: Request camera settings''' enums['MAV_CMD'][522].param[2] = '''Reserved (all remaining params)''' enums['MAV_CMD'][522].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][522].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][522].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][522].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][522].param[7] = '''Reserved (default:0)''' MAV_CMD_REQUEST_STORAGE_INFORMATION = 525 # Request storage information (STORAGE_INFORMATION). Use the command's # target_component to target a specific # component's storage. enums['MAV_CMD'][525] = EnumEntry('MAV_CMD_REQUEST_STORAGE_INFORMATION', '''Request storage information (STORAGE_INFORMATION). Use the command's target_component to target a specific component's storage.''') enums['MAV_CMD'][525].param[1] = '''Storage ID (0 for all, 1 for first, 2 for second, etc.)''' enums['MAV_CMD'][525].param[2] = '''0: No Action 1: Request storage information''' enums['MAV_CMD'][525].param[3] = '''Reserved (all remaining params)''' enums['MAV_CMD'][525].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][525].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][525].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][525].param[7] = '''Reserved (default:0)''' MAV_CMD_STORAGE_FORMAT = 526 # Format a storage medium. Once format is complete, a # STORAGE_INFORMATION message is sent. Use the # command's target_component to target a # specific component's storage. enums['MAV_CMD'][526] = EnumEntry('MAV_CMD_STORAGE_FORMAT', '''Format a storage medium. Once format is complete, a STORAGE_INFORMATION message is sent. Use the command's target_component to target a specific component's storage.''') enums['MAV_CMD'][526].param[1] = '''Storage ID (1 for first, 2 for second, etc.)''' enums['MAV_CMD'][526].param[2] = '''0: No action 1: Format storage''' enums['MAV_CMD'][526].param[3] = '''Reserved (all remaining params)''' enums['MAV_CMD'][526].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][526].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][526].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][526].param[7] = '''Reserved (default:0)''' MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS = 527 # Request camera capture status (CAMERA_CAPTURE_STATUS) enums['MAV_CMD'][527] = EnumEntry('MAV_CMD_REQUEST_CAMERA_CAPTURE_STATUS', '''Request camera capture status (CAMERA_CAPTURE_STATUS)''') enums['MAV_CMD'][527].param[1] = '''0: No Action 1: Request camera capture status''' enums['MAV_CMD'][527].param[2] = '''Reserved (all remaining params)''' enums['MAV_CMD'][527].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][527].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][527].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][527].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][527].param[7] = '''Reserved (default:0)''' MAV_CMD_REQUEST_FLIGHT_INFORMATION = 528 # Request flight information (FLIGHT_INFORMATION) enums['MAV_CMD'][528] = EnumEntry('MAV_CMD_REQUEST_FLIGHT_INFORMATION', '''Request flight information (FLIGHT_INFORMATION)''') enums['MAV_CMD'][528].param[1] = '''1: Request flight information''' enums['MAV_CMD'][528].param[2] = '''Reserved (all remaining params)''' enums['MAV_CMD'][528].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][528].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][528].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][528].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][528].param[7] = '''Reserved (default:0)''' MAV_CMD_RESET_CAMERA_SETTINGS = 529 # Reset all camera settings to Factory Default enums['MAV_CMD'][529] = EnumEntry('MAV_CMD_RESET_CAMERA_SETTINGS', '''Reset all camera settings to Factory Default''') enums['MAV_CMD'][529].param[1] = '''0: No Action 1: Reset all settings''' enums['MAV_CMD'][529].param[2] = '''Reserved (all remaining params)''' enums['MAV_CMD'][529].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][529].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][529].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][529].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][529].param[7] = '''Reserved (default:0)''' MAV_CMD_SET_CAMERA_MODE = 530 # Set camera running mode. Use NaN for reserved values. GCS will send a # MAV_CMD_REQUEST_VIDEO_STREAM_STATUS command # after a mode change if the camera supports # video streaming. enums['MAV_CMD'][530] = EnumEntry('MAV_CMD_SET_CAMERA_MODE', '''Set camera running mode. Use NaN for reserved values. GCS will send a MAV_CMD_REQUEST_VIDEO_STREAM_STATUS command after a mode change if the camera supports video streaming.''') enums['MAV_CMD'][530].param[1] = '''Reserved (Set to 0)''' enums['MAV_CMD'][530].param[2] = '''Camera mode''' enums['MAV_CMD'][530].param[3] = '''Reserved (all remaining params)''' enums['MAV_CMD'][530].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][530].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][530].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][530].param[7] = '''Reserved (default:0)''' MAV_CMD_JUMP_TAG = 600 # Tagged jump target. Can be jumped to with MAV_CMD_DO_JUMP_TAG. enums['MAV_CMD'][600] = EnumEntry('MAV_CMD_JUMP_TAG', '''Tagged jump target. Can be jumped to with MAV_CMD_DO_JUMP_TAG.''') enums['MAV_CMD'][600].param[1] = '''Tag.''' enums['MAV_CMD'][600].param[2] = '''Reserved (default:0)''' enums['MAV_CMD'][600].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][600].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][600].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][600].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][600].param[7] = '''Reserved (default:0)''' MAV_CMD_DO_JUMP_TAG = 601 # Jump to the matching tag in the mission list. Repeat this action for # the specified number of times. A mission # should contain a single matching tag for # each jump. If this is not the case then a # jump to a missing tag should complete the # mission, and a jump where there are multiple # matching tags should always select the one # with the lowest mission sequence number. enums['MAV_CMD'][601] = EnumEntry('MAV_CMD_DO_JUMP_TAG', '''Jump to the matching tag in the mission list. Repeat this action for the specified number of times. A mission should contain a single matching tag for each jump. If this is not the case then a jump to a missing tag should complete the mission, and a jump where there are multiple matching tags should always select the one with the lowest mission sequence number.''') enums['MAV_CMD'][601].param[1] = '''Target tag to jump to.''' enums['MAV_CMD'][601].param[2] = '''Repeat count.''' enums['MAV_CMD'][601].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][601].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][601].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][601].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][601].param[7] = '''Reserved (default:0)''' MAV_CMD_IMAGE_START_CAPTURE = 2000 # Start image capture sequence. Sends CAMERA_IMAGE_CAPTURED after each # capture. Use NaN for reserved values. enums['MAV_CMD'][2000] = EnumEntry('MAV_CMD_IMAGE_START_CAPTURE', '''Start image capture sequence. Sends CAMERA_IMAGE_CAPTURED after each capture. Use NaN for reserved values.''') enums['MAV_CMD'][2000].param[1] = '''Reserved (Set to 0)''' enums['MAV_CMD'][2000].param[2] = '''Desired elapsed time between two consecutive pictures (in seconds). Minimum values depend on hardware (typically greater than 2 seconds).''' enums['MAV_CMD'][2000].param[3] = '''Total number of images to capture. 0 to capture forever/until MAV_CMD_IMAGE_STOP_CAPTURE.''' enums['MAV_CMD'][2000].param[4] = '''Capture sequence number starting from 1. This is only valid for single-capture (param3 == 1). Increment the capture ID for each capture command to prevent double captures when a command is re-transmitted. Use 0 to ignore it.''' enums['MAV_CMD'][2000].param[5] = '''Reserved (all remaining params)''' enums['MAV_CMD'][2000].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][2000].param[7] = '''Reserved (default:0)''' MAV_CMD_IMAGE_STOP_CAPTURE = 2001 # Stop image capture sequence Use NaN for reserved values. enums['MAV_CMD'][2001] = EnumEntry('MAV_CMD_IMAGE_STOP_CAPTURE', '''Stop image capture sequence Use NaN for reserved values.''') enums['MAV_CMD'][2001].param[1] = '''Reserved (Set to 0)''' enums['MAV_CMD'][2001].param[2] = '''Reserved (all remaining params)''' enums['MAV_CMD'][2001].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][2001].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][2001].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][2001].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][2001].param[7] = '''Reserved (default:0)''' MAV_CMD_DO_TRIGGER_CONTROL = 2003 # Enable or disable on-board camera triggering system. enums['MAV_CMD'][2003] = EnumEntry('MAV_CMD_DO_TRIGGER_CONTROL', '''Enable or disable on-board camera triggering system.''') enums['MAV_CMD'][2003].param[1] = '''Trigger enable/disable (0 for disable, 1 for start), -1 to ignore''' enums['MAV_CMD'][2003].param[2] = '''1 to reset the trigger sequence, -1 or 0 to ignore''' enums['MAV_CMD'][2003].param[3] = '''1 to pause triggering, but without switching the camera off or retracting it. -1 to ignore''' enums['MAV_CMD'][2003].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][2003].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][2003].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][2003].param[7] = '''Reserved (default:0)''' MAV_CMD_VIDEO_START_CAPTURE = 2500 # Starts video capture (recording). Use NaN for reserved values. enums['MAV_CMD'][2500] = EnumEntry('MAV_CMD_VIDEO_START_CAPTURE', '''Starts video capture (recording). Use NaN for reserved values.''') enums['MAV_CMD'][2500].param[1] = '''Video Stream ID (0 for all streams)''' enums['MAV_CMD'][2500].param[2] = '''Frequency CAMERA_CAPTURE_STATUS messages should be sent while recording (0 for no messages, otherwise frequency)''' enums['MAV_CMD'][2500].param[3] = '''Reserved (all remaining params)''' enums['MAV_CMD'][2500].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][2500].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][2500].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][2500].param[7] = '''Reserved (default:0)''' MAV_CMD_VIDEO_STOP_CAPTURE = 2501 # Stop the current video capture (recording). Use NaN for reserved # values. enums['MAV_CMD'][2501] = EnumEntry('MAV_CMD_VIDEO_STOP_CAPTURE', '''Stop the current video capture (recording). Use NaN for reserved values.''') enums['MAV_CMD'][2501].param[1] = '''Video Stream ID (0 for all streams)''' enums['MAV_CMD'][2501].param[2] = '''Reserved (all remaining params)''' enums['MAV_CMD'][2501].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][2501].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][2501].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][2501].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][2501].param[7] = '''Reserved (default:0)''' MAV_CMD_LOGGING_START = 2510 # Request to start streaming logging data over MAVLink (see also # LOGGING_DATA message) enums['MAV_CMD'][2510] = EnumEntry('MAV_CMD_LOGGING_START', '''Request to start streaming logging data over MAVLink (see also LOGGING_DATA message)''') enums['MAV_CMD'][2510].param[1] = '''Format: 0: ULog''' enums['MAV_CMD'][2510].param[2] = '''Reserved (set to 0)''' enums['MAV_CMD'][2510].param[3] = '''Reserved (set to 0)''' enums['MAV_CMD'][2510].param[4] = '''Reserved (set to 0)''' enums['MAV_CMD'][2510].param[5] = '''Reserved (set to 0)''' enums['MAV_CMD'][2510].param[6] = '''Reserved (set to 0)''' enums['MAV_CMD'][2510].param[7] = '''Reserved (set to 0)''' MAV_CMD_LOGGING_STOP = 2511 # Request to stop streaming log data over MAVLink enums['MAV_CMD'][2511] = EnumEntry('MAV_CMD_LOGGING_STOP', '''Request to stop streaming log data over MAVLink''') enums['MAV_CMD'][2511].param[1] = '''Reserved (set to 0)''' enums['MAV_CMD'][2511].param[2] = '''Reserved (set to 0)''' enums['MAV_CMD'][2511].param[3] = '''Reserved (set to 0)''' enums['MAV_CMD'][2511].param[4] = '''Reserved (set to 0)''' enums['MAV_CMD'][2511].param[5] = '''Reserved (set to 0)''' enums['MAV_CMD'][2511].param[6] = '''Reserved (set to 0)''' enums['MAV_CMD'][2511].param[7] = '''Reserved (set to 0)''' MAV_CMD_AIRFRAME_CONFIGURATION = 2520 # enums['MAV_CMD'][2520] = EnumEntry('MAV_CMD_AIRFRAME_CONFIGURATION', '''''') enums['MAV_CMD'][2520].param[1] = '''Landing gear ID (default: 0, -1 for all)''' enums['MAV_CMD'][2520].param[2] = '''Landing gear position (Down: 0, Up: 1, NaN for no change)''' enums['MAV_CMD'][2520].param[3] = '''Reserved, set to NaN''' enums['MAV_CMD'][2520].param[4] = '''Reserved, set to NaN''' enums['MAV_CMD'][2520].param[5] = '''Reserved, set to NaN''' enums['MAV_CMD'][2520].param[6] = '''Reserved, set to NaN''' enums['MAV_CMD'][2520].param[7] = '''Reserved, set to NaN''' MAV_CMD_CONTROL_HIGH_LATENCY = 2600 # Request to start/stop transmitting over the high latency telemetry enums['MAV_CMD'][2600] = EnumEntry('MAV_CMD_CONTROL_HIGH_LATENCY', '''Request to start/stop transmitting over the high latency telemetry''') enums['MAV_CMD'][2600].param[1] = '''Control transmission over high latency telemetry (0: stop, 1: start)''' enums['MAV_CMD'][2600].param[2] = '''Empty''' enums['MAV_CMD'][2600].param[3] = '''Empty''' enums['MAV_CMD'][2600].param[4] = '''Empty''' enums['MAV_CMD'][2600].param[5] = '''Empty''' enums['MAV_CMD'][2600].param[6] = '''Empty''' enums['MAV_CMD'][2600].param[7] = '''Empty''' MAV_CMD_PANORAMA_CREATE = 2800 # Create a panorama at the current position enums['MAV_CMD'][2800] = EnumEntry('MAV_CMD_PANORAMA_CREATE', '''Create a panorama at the current position''') enums['MAV_CMD'][2800].param[1] = '''Viewing angle horizontal of the panorama (+- 0.5 the total angle)''' enums['MAV_CMD'][2800].param[2] = '''Viewing angle vertical of panorama.''' enums['MAV_CMD'][2800].param[3] = '''Speed of the horizontal rotation.''' enums['MAV_CMD'][2800].param[4] = '''Speed of the vertical rotation.''' enums['MAV_CMD'][2800].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][2800].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][2800].param[7] = '''Reserved (default:0)''' MAV_CMD_DO_VTOL_TRANSITION = 3000 # Request VTOL transition enums['MAV_CMD'][3000] = EnumEntry('MAV_CMD_DO_VTOL_TRANSITION', '''Request VTOL transition''') enums['MAV_CMD'][3000].param[1] = '''The target VTOL state. Only MAV_VTOL_STATE_MC and MAV_VTOL_STATE_FW can be used.''' enums['MAV_CMD'][3000].param[2] = '''Reserved (default:0)''' enums['MAV_CMD'][3000].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][3000].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][3000].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][3000].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][3000].param[7] = '''Reserved (default:0)''' MAV_CMD_ARM_AUTHORIZATION_REQUEST = 3001 # Request authorization to arm the vehicle to a external entity, the arm # authorizer is responsible to request all # data that is needs from the vehicle before # authorize or deny the request. If approved # the progress of command_ack message should # be set with period of time that this # authorization is valid in seconds or in case # it was denied it should be set with one of # the reasons in ARM_AUTH_DENIED_REASON. enums['MAV_CMD'][3001] = EnumEntry('MAV_CMD_ARM_AUTHORIZATION_REQUEST', '''Request authorization to arm the vehicle to a external entity, the arm authorizer is responsible to request all data that is needs from the vehicle before authorize or deny the request. If approved the progress of command_ack message should be set with period of time that this authorization is valid in seconds or in case it was denied it should be set with one of the reasons in ARM_AUTH_DENIED_REASON. ''') enums['MAV_CMD'][3001].param[1] = '''Vehicle system id, this way ground station can request arm authorization on behalf of any vehicle''' enums['MAV_CMD'][3001].param[2] = '''Reserved (default:0)''' enums['MAV_CMD'][3001].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][3001].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][3001].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][3001].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][3001].param[7] = '''Reserved (default:0)''' MAV_CMD_SET_GUIDED_SUBMODE_STANDARD = 4000 # This command sets the submode to standard guided when vehicle is in # guided mode. The vehicle holds position and # altitude and the user can input the desired # velocities along all three axes. enums['MAV_CMD'][4000] = EnumEntry('MAV_CMD_SET_GUIDED_SUBMODE_STANDARD', '''This command sets the submode to standard guided when vehicle is in guided mode. The vehicle holds position and altitude and the user can input the desired velocities along all three axes. ''') enums['MAV_CMD'][4000].param[1] = '''Reserved (default:0)''' enums['MAV_CMD'][4000].param[2] = '''Reserved (default:0)''' enums['MAV_CMD'][4000].param[3] = '''Reserved (default:0)''' enums['MAV_CMD'][4000].param[4] = '''Reserved (default:0)''' enums['MAV_CMD'][4000].param[5] = '''Reserved (default:0)''' enums['MAV_CMD'][4000].param[6] = '''Reserved (default:0)''' enums['MAV_CMD'][4000].param[7] = '''Reserved (default:0)''' MAV_CMD_SET_GUIDED_SUBMODE_CIRCLE = 4001 # This command sets submode circle when vehicle is in guided mode. # Vehicle flies along a circle facing the # center of the circle. The user can input the # velocity along the circle and change the # radius. If no input is given the vehicle # will hold position. enums['MAV_CMD'][4001] = EnumEntry('MAV_CMD_SET_GUIDED_SUBMODE_CIRCLE', '''This command sets submode circle when vehicle is in guided mode. Vehicle flies along a circle facing the center of the circle. The user can input the velocity along the circle and change the radius. If no input is given the vehicle will hold position. ''') enums['MAV_CMD'][4001].param[1] = '''Radius of desired circle in CIRCLE_MODE''' enums['MAV_CMD'][4001].param[2] = '''User defined''' enums['MAV_CMD'][4001].param[3] = '''User defined''' enums['MAV_CMD'][4001].param[4] = '''User defined''' enums['MAV_CMD'][4001].param[5] = '''Unscaled target latitude of center of circle in CIRCLE_MODE''' enums['MAV_CMD'][4001].param[6] = '''Unscaled target longitude of center of circle in CIRCLE_MODE''' enums['MAV_CMD'][4001].param[7] = '''Reserved (default:0)''' MAV_CMD_NAV_FENCE_RETURN_POINT = 5000 # Fence return point. There can only be one fence return point. enums['MAV_CMD'][5000] = EnumEntry('MAV_CMD_NAV_FENCE_RETURN_POINT', '''Fence return point. There can only be one fence return point. ''') enums['MAV_CMD'][5000].param[1] = '''Reserved''' enums['MAV_CMD'][5000].param[2] = '''Reserved''' enums['MAV_CMD'][5000].param[3] = '''Reserved''' enums['MAV_CMD'][5000].param[4] = '''Reserved''' enums['MAV_CMD'][5000].param[5] = '''Latitude''' enums['MAV_CMD'][5000].param[6] = '''Longitude''' enums['MAV_CMD'][5000].param[7] = '''Altitude''' MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION = 5001 # Fence vertex for an inclusion polygon (the polygon must not be self- # intersecting). The vehicle must stay within # this area. Minimum of 3 vertices required. enums['MAV_CMD'][5001] = EnumEntry('MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION', '''Fence vertex for an inclusion polygon (the polygon must not be self-intersecting). The vehicle must stay within this area. Minimum of 3 vertices required. ''') enums['MAV_CMD'][5001].param[1] = '''Polygon vertex count''' enums['MAV_CMD'][5001].param[2] = '''Reserved''' enums['MAV_CMD'][5001].param[3] = '''Reserved''' enums['MAV_CMD'][5001].param[4] = '''Reserved''' enums['MAV_CMD'][5001].param[5] = '''Latitude''' enums['MAV_CMD'][5001].param[6] = '''Longitude''' enums['MAV_CMD'][5001].param[7] = '''Reserved''' MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION = 5002 # Fence vertex for an exclusion polygon (the polygon must not be self- # intersecting). The vehicle must stay outside # this area. Minimum of 3 vertices required. enums['MAV_CMD'][5002] = EnumEntry('MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION', '''Fence vertex for an exclusion polygon (the polygon must not be self-intersecting). The vehicle must stay outside this area. Minimum of 3 vertices required. ''') enums['MAV_CMD'][5002].param[1] = '''Polygon vertex count''' enums['MAV_CMD'][5002].param[2] = '''Reserved''' enums['MAV_CMD'][5002].param[3] = '''Reserved''' enums['MAV_CMD'][5002].param[4] = '''Reserved''' enums['MAV_CMD'][5002].param[5] = '''Latitude''' enums['MAV_CMD'][5002].param[6] = '''Longitude''' enums['MAV_CMD'][5002].param[7] = '''Reserved''' MAV_CMD_NAV_FENCE_CIRCLE_INCLUSION = 5003 # Circular fence area. The vehicle must stay inside this area. enums['MAV_CMD'][5003] = EnumEntry('MAV_CMD_NAV_FENCE_CIRCLE_INCLUSION', '''Circular fence area. The vehicle must stay inside this area. ''') enums['MAV_CMD'][5003].param[1] = '''Radius.''' enums['MAV_CMD'][5003].param[2] = '''Reserved''' enums['MAV_CMD'][5003].param[3] = '''Reserved''' enums['MAV_CMD'][5003].param[4] = '''Reserved''' enums['MAV_CMD'][5003].param[5] = '''Latitude''' enums['MAV_CMD'][5003].param[6] = '''Longitude''' enums['MAV_CMD'][5003].param[7] = '''Reserved''' MAV_CMD_NAV_FENCE_CIRCLE_EXCLUSION = 5004 # Circular fence area. The vehicle must stay outside this area. enums['MAV_CMD'][5004] = EnumEntry('MAV_CMD_NAV_FENCE_CIRCLE_EXCLUSION', '''Circular fence area. The vehicle must stay outside this area. ''') enums['MAV_CMD'][5004].param[1] = '''Radius.''' enums['MAV_CMD'][5004].param[2] = '''Reserved''' enums['MAV_CMD'][5004].param[3] = '''Reserved''' enums['MAV_CMD'][5004].param[4] = '''Reserved''' enums['MAV_CMD'][5004].param[5] = '''Latitude''' enums['MAV_CMD'][5004].param[6] = '''Longitude''' enums['MAV_CMD'][5004].param[7] = '''Reserved''' MAV_CMD_NAV_RALLY_POINT = 5100 # Rally point. You can have multiple rally points defined. enums['MAV_CMD'][5100] = EnumEntry('MAV_CMD_NAV_RALLY_POINT', '''Rally point. You can have multiple rally points defined. ''') enums['MAV_CMD'][5100].param[1] = '''Reserved''' enums['MAV_CMD'][5100].param[2] = '''Reserved''' enums['MAV_CMD'][5100].param[3] = '''Reserved''' enums['MAV_CMD'][5100].param[4] = '''Reserved''' enums['MAV_CMD'][5100].param[5] = '''Latitude''' enums['MAV_CMD'][5100].param[6] = '''Longitude''' enums['MAV_CMD'][5100].param[7] = '''Altitude''' MAV_CMD_UAVCAN_GET_NODE_INFO = 5200 # Commands the vehicle to respond with a sequence of messages # UAVCAN_NODE_INFO, one message per every # UAVCAN node that is online. Note that some # of the response messages can be lost, which # the receiver can detect easily by checking # whether every received UAVCAN_NODE_STATUS # has a matching message UAVCAN_NODE_INFO # received earlier; if not, this command # should be sent again in order to request re- # transmission of the node information # messages. enums['MAV_CMD'][5200] = EnumEntry('MAV_CMD_UAVCAN_GET_NODE_INFO', '''Commands the vehicle to respond with a sequence of messages UAVCAN_NODE_INFO, one message per every UAVCAN node that is online. Note that some of the response messages can be lost, which the receiver can detect easily by checking whether every received UAVCAN_NODE_STATUS has a matching message UAVCAN_NODE_INFO received earlier; if not, this command should be sent again in order to request re-transmission of the node information messages.''') enums['MAV_CMD'][5200].param[1] = '''Reserved (set to 0)''' enums['MAV_CMD'][5200].param[2] = '''Reserved (set to 0)''' enums['MAV_CMD'][5200].param[3] = '''Reserved (set to 0)''' enums['MAV_CMD'][5200].param[4] = '''Reserved (set to 0)''' enums['MAV_CMD'][5200].param[5] = '''Reserved (set to 0)''' enums['MAV_CMD'][5200].param[6] = '''Reserved (set to 0)''' enums['MAV_CMD'][5200].param[7] = '''Reserved (set to 0)''' MAV_CMD_PAYLOAD_PREPARE_DEPLOY = 30001 # Deploy payload on a Lat / Lon / Alt position. This includes the # navigation to reach the required release # position and velocity. enums['MAV_CMD'][30001] = EnumEntry('MAV_CMD_PAYLOAD_PREPARE_DEPLOY', '''Deploy payload on a Lat / Lon / Alt position. This includes the navigation to reach the required release position and velocity.''') enums['MAV_CMD'][30001].param[1] = '''Operation mode. 0: prepare single payload deploy (overwriting previous requests), but do not execute it. 1: execute payload deploy immediately (rejecting further deploy commands during execution, but allowing abort). 2: add payload deploy to existing deployment list.''' enums['MAV_CMD'][30001].param[2] = '''Desired approach vector in compass heading. A negative value indicates the system can define the approach vector at will.''' enums['MAV_CMD'][30001].param[3] = '''Desired ground speed at release time. This can be overridden by the airframe in case it needs to meet minimum airspeed. A negative value indicates the system can define the ground speed at will.''' enums['MAV_CMD'][30001].param[4] = '''Minimum altitude clearance to the release position. A negative value indicates the system can define the clearance at will.''' enums['MAV_CMD'][30001].param[5] = '''Latitude unscaled for MISSION_ITEM or in 1e7 degrees for MISSION_ITEM_INT''' enums['MAV_CMD'][30001].param[6] = '''Longitude unscaled for MISSION_ITEM or in 1e7 degrees for MISSION_ITEM_INT''' enums['MAV_CMD'][30001].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_PAYLOAD_CONTROL_DEPLOY = 30002 # Control the payload deployment. enums['MAV_CMD'][30002] = EnumEntry('MAV_CMD_PAYLOAD_CONTROL_DEPLOY', '''Control the payload deployment.''') enums['MAV_CMD'][30002].param[1] = '''Operation mode. 0: Abort deployment, continue normal mission. 1: switch to payload deployment mode. 100: delete first payload deployment request. 101: delete all payload deployment requests.''' enums['MAV_CMD'][30002].param[2] = '''Reserved''' enums['MAV_CMD'][30002].param[3] = '''Reserved''' enums['MAV_CMD'][30002].param[4] = '''Reserved''' enums['MAV_CMD'][30002].param[5] = '''Reserved''' enums['MAV_CMD'][30002].param[6] = '''Reserved''' enums['MAV_CMD'][30002].param[7] = '''Reserved''' MAV_CMD_WAYPOINT_USER_1 = 31000 # User defined waypoint item. Ground Station will show the Vehicle as # flying through this item. enums['MAV_CMD'][31000] = EnumEntry('MAV_CMD_WAYPOINT_USER_1', '''User defined waypoint item. Ground Station will show the Vehicle as flying through this item.''') enums['MAV_CMD'][31000].param[1] = '''User defined''' enums['MAV_CMD'][31000].param[2] = '''User defined''' enums['MAV_CMD'][31000].param[3] = '''User defined''' enums['MAV_CMD'][31000].param[4] = '''User defined''' enums['MAV_CMD'][31000].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31000].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31000].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_WAYPOINT_USER_2 = 31001 # User defined waypoint item. Ground Station will show the Vehicle as # flying through this item. enums['MAV_CMD'][31001] = EnumEntry('MAV_CMD_WAYPOINT_USER_2', '''User defined waypoint item. Ground Station will show the Vehicle as flying through this item.''') enums['MAV_CMD'][31001].param[1] = '''User defined''' enums['MAV_CMD'][31001].param[2] = '''User defined''' enums['MAV_CMD'][31001].param[3] = '''User defined''' enums['MAV_CMD'][31001].param[4] = '''User defined''' enums['MAV_CMD'][31001].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31001].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31001].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_WAYPOINT_USER_3 = 31002 # User defined waypoint item. Ground Station will show the Vehicle as # flying through this item. enums['MAV_CMD'][31002] = EnumEntry('MAV_CMD_WAYPOINT_USER_3', '''User defined waypoint item. Ground Station will show the Vehicle as flying through this item.''') enums['MAV_CMD'][31002].param[1] = '''User defined''' enums['MAV_CMD'][31002].param[2] = '''User defined''' enums['MAV_CMD'][31002].param[3] = '''User defined''' enums['MAV_CMD'][31002].param[4] = '''User defined''' enums['MAV_CMD'][31002].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31002].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31002].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_WAYPOINT_USER_4 = 31003 # User defined waypoint item. Ground Station will show the Vehicle as # flying through this item. enums['MAV_CMD'][31003] = EnumEntry('MAV_CMD_WAYPOINT_USER_4', '''User defined waypoint item. Ground Station will show the Vehicle as flying through this item.''') enums['MAV_CMD'][31003].param[1] = '''User defined''' enums['MAV_CMD'][31003].param[2] = '''User defined''' enums['MAV_CMD'][31003].param[3] = '''User defined''' enums['MAV_CMD'][31003].param[4] = '''User defined''' enums['MAV_CMD'][31003].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31003].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31003].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_WAYPOINT_USER_5 = 31004 # User defined waypoint item. Ground Station will show the Vehicle as # flying through this item. enums['MAV_CMD'][31004] = EnumEntry('MAV_CMD_WAYPOINT_USER_5', '''User defined waypoint item. Ground Station will show the Vehicle as flying through this item.''') enums['MAV_CMD'][31004].param[1] = '''User defined''' enums['MAV_CMD'][31004].param[2] = '''User defined''' enums['MAV_CMD'][31004].param[3] = '''User defined''' enums['MAV_CMD'][31004].param[4] = '''User defined''' enums['MAV_CMD'][31004].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31004].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31004].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_SPATIAL_USER_1 = 31005 # User defined spatial item. Ground Station will not show the Vehicle as # flying through this item. Example: ROI item. enums['MAV_CMD'][31005] = EnumEntry('MAV_CMD_SPATIAL_USER_1', '''User defined spatial item. Ground Station will not show the Vehicle as flying through this item. Example: ROI item.''') enums['MAV_CMD'][31005].param[1] = '''User defined''' enums['MAV_CMD'][31005].param[2] = '''User defined''' enums['MAV_CMD'][31005].param[3] = '''User defined''' enums['MAV_CMD'][31005].param[4] = '''User defined''' enums['MAV_CMD'][31005].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31005].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31005].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_SPATIAL_USER_2 = 31006 # User defined spatial item. Ground Station will not show the Vehicle as # flying through this item. Example: ROI item. enums['MAV_CMD'][31006] = EnumEntry('MAV_CMD_SPATIAL_USER_2', '''User defined spatial item. Ground Station will not show the Vehicle as flying through this item. Example: ROI item.''') enums['MAV_CMD'][31006].param[1] = '''User defined''' enums['MAV_CMD'][31006].param[2] = '''User defined''' enums['MAV_CMD'][31006].param[3] = '''User defined''' enums['MAV_CMD'][31006].param[4] = '''User defined''' enums['MAV_CMD'][31006].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31006].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31006].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_SPATIAL_USER_3 = 31007 # User defined spatial item. Ground Station will not show the Vehicle as # flying through this item. Example: ROI item. enums['MAV_CMD'][31007] = EnumEntry('MAV_CMD_SPATIAL_USER_3', '''User defined spatial item. Ground Station will not show the Vehicle as flying through this item. Example: ROI item.''') enums['MAV_CMD'][31007].param[1] = '''User defined''' enums['MAV_CMD'][31007].param[2] = '''User defined''' enums['MAV_CMD'][31007].param[3] = '''User defined''' enums['MAV_CMD'][31007].param[4] = '''User defined''' enums['MAV_CMD'][31007].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31007].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31007].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_SPATIAL_USER_4 = 31008 # User defined spatial item. Ground Station will not show the Vehicle as # flying through this item. Example: ROI item. enums['MAV_CMD'][31008] = EnumEntry('MAV_CMD_SPATIAL_USER_4', '''User defined spatial item. Ground Station will not show the Vehicle as flying through this item. Example: ROI item.''') enums['MAV_CMD'][31008].param[1] = '''User defined''' enums['MAV_CMD'][31008].param[2] = '''User defined''' enums['MAV_CMD'][31008].param[3] = '''User defined''' enums['MAV_CMD'][31008].param[4] = '''User defined''' enums['MAV_CMD'][31008].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31008].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31008].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_SPATIAL_USER_5 = 31009 # User defined spatial item. Ground Station will not show the Vehicle as # flying through this item. Example: ROI item. enums['MAV_CMD'][31009] = EnumEntry('MAV_CMD_SPATIAL_USER_5', '''User defined spatial item. Ground Station will not show the Vehicle as flying through this item. Example: ROI item.''') enums['MAV_CMD'][31009].param[1] = '''User defined''' enums['MAV_CMD'][31009].param[2] = '''User defined''' enums['MAV_CMD'][31009].param[3] = '''User defined''' enums['MAV_CMD'][31009].param[4] = '''User defined''' enums['MAV_CMD'][31009].param[5] = '''Latitude unscaled''' enums['MAV_CMD'][31009].param[6] = '''Longitude unscaled''' enums['MAV_CMD'][31009].param[7] = '''Altitude (MSL), in meters''' MAV_CMD_USER_1 = 31010 # User defined command. Ground Station will not show the Vehicle as # flying through this item. Example: # MAV_CMD_DO_SET_PARAMETER item. enums['MAV_CMD'][31010] = EnumEntry('MAV_CMD_USER_1', '''User defined command. Ground Station will not show the Vehicle as flying through this item. Example: MAV_CMD_DO_SET_PARAMETER item.''') enums['MAV_CMD'][31010].param[1] = '''User defined''' enums['MAV_CMD'][31010].param[2] = '''User defined''' enums['MAV_CMD'][31010].param[3] = '''User defined''' enums['MAV_CMD'][31010].param[4] = '''User defined''' enums['MAV_CMD'][31010].param[5] = '''User defined''' enums['MAV_CMD'][31010].param[6] = '''User defined''' enums['MAV_CMD'][31010].param[7] = '''User defined''' MAV_CMD_USER_2 = 31011 # User defined command. Ground Station will not show the Vehicle as # flying through this item. Example: # MAV_CMD_DO_SET_PARAMETER item. enums['MAV_CMD'][31011] = EnumEntry('MAV_CMD_USER_2', '''User defined command. Ground Station will not show the Vehicle as flying through this item. Example: MAV_CMD_DO_SET_PARAMETER item.''') enums['MAV_CMD'][31011].param[1] = '''User defined''' enums['MAV_CMD'][31011].param[2] = '''User defined''' enums['MAV_CMD'][31011].param[3] = '''User defined''' enums['MAV_CMD'][31011].param[4] = '''User defined''' enums['MAV_CMD'][31011].param[5] = '''User defined''' enums['MAV_CMD'][31011].param[6] = '''User defined''' enums['MAV_CMD'][31011].param[7] = '''User defined''' MAV_CMD_USER_3 = 31012 # User defined command. Ground Station will not show the Vehicle as # flying through this item. Example: # MAV_CMD_DO_SET_PARAMETER item. enums['MAV_CMD'][31012] = EnumEntry('MAV_CMD_USER_3', '''User defined command. Ground Station will not show the Vehicle as flying through this item. Example: MAV_CMD_DO_SET_PARAMETER item.''') enums['MAV_CMD'][31012].param[1] = '''User defined''' enums['MAV_CMD'][31012].param[2] = '''User defined''' enums['MAV_CMD'][31012].param[3] = '''User defined''' enums['MAV_CMD'][31012].param[4] = '''User defined''' enums['MAV_CMD'][31012].param[5] = '''User defined''' enums['MAV_CMD'][31012].param[6] = '''User defined''' enums['MAV_CMD'][31012].param[7] = '''User defined''' MAV_CMD_USER_4 = 31013 # User defined command. Ground Station will not show the Vehicle as # flying through this item. Example: # MAV_CMD_DO_SET_PARAMETER item. enums['MAV_CMD'][31013] = EnumEntry('MAV_CMD_USER_4', '''User defined command. Ground Station will not show the Vehicle as flying through this item. Example: MAV_CMD_DO_SET_PARAMETER item.''') enums['MAV_CMD'][31013].param[1] = '''User defined''' enums['MAV_CMD'][31013].param[2] = '''User defined''' enums['MAV_CMD'][31013].param[3] = '''User defined''' enums['MAV_CMD'][31013].param[4] = '''User defined''' enums['MAV_CMD'][31013].param[5] = '''User defined''' enums['MAV_CMD'][31013].param[6] = '''User defined''' enums['MAV_CMD'][31013].param[7] = '''User defined''' MAV_CMD_USER_5 = 31014 # User defined command. Ground Station will not show the Vehicle as # flying through this item. Example: # MAV_CMD_DO_SET_PARAMETER item. enums['MAV_CMD'][31014] = EnumEntry('MAV_CMD_USER_5', '''User defined command. Ground Station will not show the Vehicle as flying through this item. Example: MAV_CMD_DO_SET_PARAMETER item.''') enums['MAV_CMD'][31014].param[1] = '''User defined''' enums['MAV_CMD'][31014].param[2] = '''User defined''' enums['MAV_CMD'][31014].param[3] = '''User defined''' enums['MAV_CMD'][31014].param[4] = '''User defined''' enums['MAV_CMD'][31014].param[5] = '''User defined''' enums['MAV_CMD'][31014].param[6] = '''User defined''' enums['MAV_CMD'][31014].param[7] = '''User defined''' MAV_CMD_ENUM_END = 31015 # enums['MAV_CMD'][31015] = EnumEntry('MAV_CMD_ENUM_END', '''''') # MAV_DATA_STREAM enums['MAV_DATA_STREAM'] = {} MAV_DATA_STREAM_ALL = 0 # Enable all data streams enums['MAV_DATA_STREAM'][0] = EnumEntry('MAV_DATA_STREAM_ALL', '''Enable all data streams''') MAV_DATA_STREAM_RAW_SENSORS = 1 # Enable IMU_RAW, GPS_RAW, GPS_STATUS packets. enums['MAV_DATA_STREAM'][1] = EnumEntry('MAV_DATA_STREAM_RAW_SENSORS', '''Enable IMU_RAW, GPS_RAW, GPS_STATUS packets.''') MAV_DATA_STREAM_EXTENDED_STATUS = 2 # Enable GPS_STATUS, CONTROL_STATUS, AUX_STATUS enums['MAV_DATA_STREAM'][2] = EnumEntry('MAV_DATA_STREAM_EXTENDED_STATUS', '''Enable GPS_STATUS, CONTROL_STATUS, AUX_STATUS''') MAV_DATA_STREAM_RC_CHANNELS = 3 # Enable RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW enums['MAV_DATA_STREAM'][3] = EnumEntry('MAV_DATA_STREAM_RC_CHANNELS', '''Enable RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW''') MAV_DATA_STREAM_RAW_CONTROLLER = 4 # Enable ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, # NAV_CONTROLLER_OUTPUT. enums['MAV_DATA_STREAM'][4] = EnumEntry('MAV_DATA_STREAM_RAW_CONTROLLER', '''Enable ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, NAV_CONTROLLER_OUTPUT.''') MAV_DATA_STREAM_POSITION = 6 # Enable LOCAL_POSITION, GLOBAL_POSITION/GLOBAL_POSITION_INT messages. enums['MAV_DATA_STREAM'][6] = EnumEntry('MAV_DATA_STREAM_POSITION', '''Enable LOCAL_POSITION, GLOBAL_POSITION/GLOBAL_POSITION_INT messages.''') MAV_DATA_STREAM_EXTRA1 = 10 # Dependent on the autopilot enums['MAV_DATA_STREAM'][10] = EnumEntry('MAV_DATA_STREAM_EXTRA1', '''Dependent on the autopilot''') MAV_DATA_STREAM_EXTRA2 = 11 # Dependent on the autopilot enums['MAV_DATA_STREAM'][11] = EnumEntry('MAV_DATA_STREAM_EXTRA2', '''Dependent on the autopilot''') MAV_DATA_STREAM_EXTRA3 = 12 # Dependent on the autopilot enums['MAV_DATA_STREAM'][12] = EnumEntry('MAV_DATA_STREAM_EXTRA3', '''Dependent on the autopilot''') MAV_DATA_STREAM_ENUM_END = 13 # enums['MAV_DATA_STREAM'][13] = EnumEntry('MAV_DATA_STREAM_ENUM_END', '''''') # MAV_ROI enums['MAV_ROI'] = {} MAV_ROI_NONE = 0 # No region of interest. enums['MAV_ROI'][0] = EnumEntry('MAV_ROI_NONE', '''No region of interest.''') MAV_ROI_WPNEXT = 1 # Point toward next waypoint, with optional pitch/roll/yaw offset. enums['MAV_ROI'][1] = EnumEntry('MAV_ROI_WPNEXT', '''Point toward next waypoint, with optional pitch/roll/yaw offset.''') MAV_ROI_WPINDEX = 2 # Point toward given waypoint. enums['MAV_ROI'][2] = EnumEntry('MAV_ROI_WPINDEX', '''Point toward given waypoint.''') MAV_ROI_LOCATION = 3 # Point toward fixed location. enums['MAV_ROI'][3] = EnumEntry('MAV_ROI_LOCATION', '''Point toward fixed location.''') MAV_ROI_TARGET = 4 # Point toward of given id. enums['MAV_ROI'][4] = EnumEntry('MAV_ROI_TARGET', '''Point toward of given id.''') MAV_ROI_ENUM_END = 5 # enums['MAV_ROI'][5] = EnumEntry('MAV_ROI_ENUM_END', '''''') # MAV_CMD_ACK enums['MAV_CMD_ACK'] = {} MAV_CMD_ACK_OK = 1 # Command / mission item is ok. enums['MAV_CMD_ACK'][1] = EnumEntry('MAV_CMD_ACK_OK', '''Command / mission item is ok.''') enums['MAV_CMD_ACK'][1].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][1].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][1].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][1].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][1].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][1].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][1].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ERR_FAIL = 2 # Generic error message if none of the other reasons fails or if no # detailed error reporting is implemented. enums['MAV_CMD_ACK'][2] = EnumEntry('MAV_CMD_ACK_ERR_FAIL', '''Generic error message if none of the other reasons fails or if no detailed error reporting is implemented.''') enums['MAV_CMD_ACK'][2].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][2].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][2].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][2].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][2].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][2].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][2].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ERR_ACCESS_DENIED = 3 # The system is refusing to accept this command from this source / # communication partner. enums['MAV_CMD_ACK'][3] = EnumEntry('MAV_CMD_ACK_ERR_ACCESS_DENIED', '''The system is refusing to accept this command from this source / communication partner.''') enums['MAV_CMD_ACK'][3].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][3].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][3].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][3].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][3].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][3].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][3].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ERR_NOT_SUPPORTED = 4 # Command or mission item is not supported, other commands would be # accepted. enums['MAV_CMD_ACK'][4] = EnumEntry('MAV_CMD_ACK_ERR_NOT_SUPPORTED', '''Command or mission item is not supported, other commands would be accepted.''') enums['MAV_CMD_ACK'][4].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][4].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][4].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][4].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][4].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][4].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][4].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ERR_COORDINATE_FRAME_NOT_SUPPORTED = 5 # The coordinate frame of this command / mission item is not supported. enums['MAV_CMD_ACK'][5] = EnumEntry('MAV_CMD_ACK_ERR_COORDINATE_FRAME_NOT_SUPPORTED', '''The coordinate frame of this command / mission item is not supported.''') enums['MAV_CMD_ACK'][5].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][5].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][5].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][5].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][5].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][5].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][5].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ERR_COORDINATES_OUT_OF_RANGE = 6 # The coordinate frame of this command is ok, but he coordinate values # exceed the safety limits of this system. # This is a generic error, please use the more # specific error messages below if possible. enums['MAV_CMD_ACK'][6] = EnumEntry('MAV_CMD_ACK_ERR_COORDINATES_OUT_OF_RANGE', '''The coordinate frame of this command is ok, but he coordinate values exceed the safety limits of this system. This is a generic error, please use the more specific error messages below if possible.''') enums['MAV_CMD_ACK'][6].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][6].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][6].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][6].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][6].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][6].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][6].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ERR_X_LAT_OUT_OF_RANGE = 7 # The X or latitude value is out of range. enums['MAV_CMD_ACK'][7] = EnumEntry('MAV_CMD_ACK_ERR_X_LAT_OUT_OF_RANGE', '''The X or latitude value is out of range.''') enums['MAV_CMD_ACK'][7].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][7].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][7].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][7].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][7].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][7].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][7].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ERR_Y_LON_OUT_OF_RANGE = 8 # The Y or longitude value is out of range. enums['MAV_CMD_ACK'][8] = EnumEntry('MAV_CMD_ACK_ERR_Y_LON_OUT_OF_RANGE', '''The Y or longitude value is out of range.''') enums['MAV_CMD_ACK'][8].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][8].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][8].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][8].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][8].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][8].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][8].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ERR_Z_ALT_OUT_OF_RANGE = 9 # The Z or altitude value is out of range. enums['MAV_CMD_ACK'][9] = EnumEntry('MAV_CMD_ACK_ERR_Z_ALT_OUT_OF_RANGE', '''The Z or altitude value is out of range.''') enums['MAV_CMD_ACK'][9].param[1] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][9].param[2] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][9].param[3] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][9].param[4] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][9].param[5] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][9].param[6] = '''Reserved (default:0)''' enums['MAV_CMD_ACK'][9].param[7] = '''Reserved (default:0)''' MAV_CMD_ACK_ENUM_END = 10 # enums['MAV_CMD_ACK'][10] = EnumEntry('MAV_CMD_ACK_ENUM_END', '''''') # MAV_PARAM_TYPE enums['MAV_PARAM_TYPE'] = {} MAV_PARAM_TYPE_UINT8 = 1 # 8-bit unsigned integer enums['MAV_PARAM_TYPE'][1] = EnumEntry('MAV_PARAM_TYPE_UINT8', '''8-bit unsigned integer''') MAV_PARAM_TYPE_INT8 = 2 # 8-bit signed integer enums['MAV_PARAM_TYPE'][2] = EnumEntry('MAV_PARAM_TYPE_INT8', '''8-bit signed integer''') MAV_PARAM_TYPE_UINT16 = 3 # 16-bit unsigned integer enums['MAV_PARAM_TYPE'][3] = EnumEntry('MAV_PARAM_TYPE_UINT16', '''16-bit unsigned integer''') MAV_PARAM_TYPE_INT16 = 4 # 16-bit signed integer enums['MAV_PARAM_TYPE'][4] = EnumEntry('MAV_PARAM_TYPE_INT16', '''16-bit signed integer''') MAV_PARAM_TYPE_UINT32 = 5 # 32-bit unsigned integer enums['MAV_PARAM_TYPE'][5] = EnumEntry('MAV_PARAM_TYPE_UINT32', '''32-bit unsigned integer''') MAV_PARAM_TYPE_INT32 = 6 # 32-bit signed integer enums['MAV_PARAM_TYPE'][6] = EnumEntry('MAV_PARAM_TYPE_INT32', '''32-bit signed integer''') MAV_PARAM_TYPE_UINT64 = 7 # 64-bit unsigned integer enums['MAV_PARAM_TYPE'][7] = EnumEntry('MAV_PARAM_TYPE_UINT64', '''64-bit unsigned integer''') MAV_PARAM_TYPE_INT64 = 8 # 64-bit signed integer enums['MAV_PARAM_TYPE'][8] = EnumEntry('MAV_PARAM_TYPE_INT64', '''64-bit signed integer''') MAV_PARAM_TYPE_REAL32 = 9 # 32-bit floating-point enums['MAV_PARAM_TYPE'][9] = EnumEntry('MAV_PARAM_TYPE_REAL32', '''32-bit floating-point''') MAV_PARAM_TYPE_REAL64 = 10 # 64-bit floating-point enums['MAV_PARAM_TYPE'][10] = EnumEntry('MAV_PARAM_TYPE_REAL64', '''64-bit floating-point''') MAV_PARAM_TYPE_ENUM_END = 11 # enums['MAV_PARAM_TYPE'][11] = EnumEntry('MAV_PARAM_TYPE_ENUM_END', '''''') # MAV_RESULT enums['MAV_RESULT'] = {} MAV_RESULT_ACCEPTED = 0 # Command ACCEPTED and EXECUTED enums['MAV_RESULT'][0] = EnumEntry('MAV_RESULT_ACCEPTED', '''Command ACCEPTED and EXECUTED''') MAV_RESULT_TEMPORARILY_REJECTED = 1 # Command TEMPORARY REJECTED/DENIED enums['MAV_RESULT'][1] = EnumEntry('MAV_RESULT_TEMPORARILY_REJECTED', '''Command TEMPORARY REJECTED/DENIED''') MAV_RESULT_DENIED = 2 # Command PERMANENTLY DENIED enums['MAV_RESULT'][2] = EnumEntry('MAV_RESULT_DENIED', '''Command PERMANENTLY DENIED''') MAV_RESULT_UNSUPPORTED = 3 # Command UNKNOWN/UNSUPPORTED enums['MAV_RESULT'][3] = EnumEntry('MAV_RESULT_UNSUPPORTED', '''Command UNKNOWN/UNSUPPORTED''') MAV_RESULT_FAILED = 4 # Command executed, but failed enums['MAV_RESULT'][4] = EnumEntry('MAV_RESULT_FAILED', '''Command executed, but failed''') MAV_RESULT_ENUM_END = 5 # enums['MAV_RESULT'][5] = EnumEntry('MAV_RESULT_ENUM_END', '''''') # MAV_MISSION_RESULT enums['MAV_MISSION_RESULT'] = {} MAV_MISSION_ACCEPTED = 0 # mission accepted OK enums['MAV_MISSION_RESULT'][0] = EnumEntry('MAV_MISSION_ACCEPTED', '''mission accepted OK''') MAV_MISSION_ERROR = 1 # Generic error / not accepting mission commands at all right now. enums['MAV_MISSION_RESULT'][1] = EnumEntry('MAV_MISSION_ERROR', '''Generic error / not accepting mission commands at all right now.''') MAV_MISSION_UNSUPPORTED_FRAME = 2 # Coordinate frame is not supported. enums['MAV_MISSION_RESULT'][2] = EnumEntry('MAV_MISSION_UNSUPPORTED_FRAME', '''Coordinate frame is not supported.''') MAV_MISSION_UNSUPPORTED = 3 # Command is not supported. enums['MAV_MISSION_RESULT'][3] = EnumEntry('MAV_MISSION_UNSUPPORTED', '''Command is not supported.''') MAV_MISSION_NO_SPACE = 4 # Mission item exceeds storage space. enums['MAV_MISSION_RESULT'][4] = EnumEntry('MAV_MISSION_NO_SPACE', '''Mission item exceeds storage space.''') MAV_MISSION_INVALID = 5 # One of the parameters has an invalid value. enums['MAV_MISSION_RESULT'][5] = EnumEntry('MAV_MISSION_INVALID', '''One of the parameters has an invalid value.''') MAV_MISSION_INVALID_PARAM1 = 6 # param1 has an invalid value. enums['MAV_MISSION_RESULT'][6] = EnumEntry('MAV_MISSION_INVALID_PARAM1', '''param1 has an invalid value.''') MAV_MISSION_INVALID_PARAM2 = 7 # param2 has an invalid value. enums['MAV_MISSION_RESULT'][7] = EnumEntry('MAV_MISSION_INVALID_PARAM2', '''param2 has an invalid value.''') MAV_MISSION_INVALID_PARAM3 = 8 # param3 has an invalid value. enums['MAV_MISSION_RESULT'][8] = EnumEntry('MAV_MISSION_INVALID_PARAM3', '''param3 has an invalid value.''') MAV_MISSION_INVALID_PARAM4 = 9 # param4 has an invalid value. enums['MAV_MISSION_RESULT'][9] = EnumEntry('MAV_MISSION_INVALID_PARAM4', '''param4 has an invalid value.''') MAV_MISSION_INVALID_PARAM5_X = 10 # x / param5 has an invalid value. enums['MAV_MISSION_RESULT'][10] = EnumEntry('MAV_MISSION_INVALID_PARAM5_X', '''x / param5 has an invalid value.''') MAV_MISSION_INVALID_PARAM6_Y = 11 # y / param6 has an invalid value. enums['MAV_MISSION_RESULT'][11] = EnumEntry('MAV_MISSION_INVALID_PARAM6_Y', '''y / param6 has an invalid value.''') MAV_MISSION_INVALID_PARAM7 = 12 # z / param7 has an invalid value. enums['MAV_MISSION_RESULT'][12] = EnumEntry('MAV_MISSION_INVALID_PARAM7', '''z / param7 has an invalid value.''') MAV_MISSION_INVALID_SEQUENCE = 13 # Mission item received out of sequence enums['MAV_MISSION_RESULT'][13] = EnumEntry('MAV_MISSION_INVALID_SEQUENCE', '''Mission item received out of sequence''') MAV_MISSION_DENIED = 14 # Not accepting any mission commands from this communication partner. enums['MAV_MISSION_RESULT'][14] = EnumEntry('MAV_MISSION_DENIED', '''Not accepting any mission commands from this communication partner.''') MAV_MISSION_OPERATION_CANCELLED = 15 # Current mission operation cancelled (e.g. mission upload, mission # download). enums['MAV_MISSION_RESULT'][15] = EnumEntry('MAV_MISSION_OPERATION_CANCELLED', '''Current mission operation cancelled (e.g. mission upload, mission download).''') MAV_MISSION_RESULT_ENUM_END = 16 # enums['MAV_MISSION_RESULT'][16] = EnumEntry('MAV_MISSION_RESULT_ENUM_END', '''''') # MAV_SEVERITY enums['MAV_SEVERITY'] = {} MAV_SEVERITY_EMERGENCY = 0 # System is unusable. This is a "panic" condition. enums['MAV_SEVERITY'][0] = EnumEntry('MAV_SEVERITY_EMERGENCY', '''System is unusable. This is a "panic" condition.''') MAV_SEVERITY_ALERT = 1 # Action should be taken immediately. Indicates error in non-critical # systems. enums['MAV_SEVERITY'][1] = EnumEntry('MAV_SEVERITY_ALERT', '''Action should be taken immediately. Indicates error in non-critical systems.''') MAV_SEVERITY_CRITICAL = 2 # Action must be taken immediately. Indicates failure in a primary # system. enums['MAV_SEVERITY'][2] = EnumEntry('MAV_SEVERITY_CRITICAL', '''Action must be taken immediately. Indicates failure in a primary system.''') MAV_SEVERITY_ERROR = 3 # Indicates an error in secondary/redundant systems. enums['MAV_SEVERITY'][3] = EnumEntry('MAV_SEVERITY_ERROR', '''Indicates an error in secondary/redundant systems.''') MAV_SEVERITY_WARNING = 4 # Indicates about a possible future error if this is not resolved within # a given timeframe. Example would be a low # battery warning. enums['MAV_SEVERITY'][4] = EnumEntry('MAV_SEVERITY_WARNING', '''Indicates about a possible future error if this is not resolved within a given timeframe. Example would be a low battery warning.''') MAV_SEVERITY_NOTICE = 5 # An unusual event has occurred, though not an error condition. This # should be investigated for the root cause. enums['MAV_SEVERITY'][5] = EnumEntry('MAV_SEVERITY_NOTICE', '''An unusual event has occurred, though not an error condition. This should be investigated for the root cause.''') MAV_SEVERITY_INFO = 6 # Normal operational messages. Useful for logging. No action is required # for these messages. enums['MAV_SEVERITY'][6] = EnumEntry('MAV_SEVERITY_INFO', '''Normal operational messages. Useful for logging. No action is required for these messages.''') MAV_SEVERITY_DEBUG = 7 # Useful non-operational messages that can assist in debugging. These # should not occur during normal operation. enums['MAV_SEVERITY'][7] = EnumEntry('MAV_SEVERITY_DEBUG', '''Useful non-operational messages that can assist in debugging. These should not occur during normal operation.''') MAV_SEVERITY_ENUM_END = 8 # enums['MAV_SEVERITY'][8] = EnumEntry('MAV_SEVERITY_ENUM_END', '''''') # MAV_POWER_STATUS enums['MAV_POWER_STATUS'] = {} MAV_POWER_STATUS_BRICK_VALID = 1 # main brick power supply valid enums['MAV_POWER_STATUS'][1] = EnumEntry('MAV_POWER_STATUS_BRICK_VALID', '''main brick power supply valid''') MAV_POWER_STATUS_SERVO_VALID = 2 # main servo power supply valid for FMU enums['MAV_POWER_STATUS'][2] = EnumEntry('MAV_POWER_STATUS_SERVO_VALID', '''main servo power supply valid for FMU''') MAV_POWER_STATUS_USB_CONNECTED = 4 # USB power is connected enums['MAV_POWER_STATUS'][4] = EnumEntry('MAV_POWER_STATUS_USB_CONNECTED', '''USB power is connected''') MAV_POWER_STATUS_PERIPH_OVERCURRENT = 8 # peripheral supply is in over-current state enums['MAV_POWER_STATUS'][8] = EnumEntry('MAV_POWER_STATUS_PERIPH_OVERCURRENT', '''peripheral supply is in over-current state''') MAV_POWER_STATUS_PERIPH_HIPOWER_OVERCURRENT = 16 # hi-power peripheral supply is in over-current state enums['MAV_POWER_STATUS'][16] = EnumEntry('MAV_POWER_STATUS_PERIPH_HIPOWER_OVERCURRENT', '''hi-power peripheral supply is in over-current state''') MAV_POWER_STATUS_CHANGED = 32 # Power status has changed since boot enums['MAV_POWER_STATUS'][32] = EnumEntry('MAV_POWER_STATUS_CHANGED', '''Power status has changed since boot''') MAV_POWER_STATUS_ENUM_END = 33 # enums['MAV_POWER_STATUS'][33] = EnumEntry('MAV_POWER_STATUS_ENUM_END', '''''') # SERIAL_CONTROL_DEV enums['SERIAL_CONTROL_DEV'] = {} SERIAL_CONTROL_DEV_TELEM1 = 0 # First telemetry port enums['SERIAL_CONTROL_DEV'][0] = EnumEntry('SERIAL_CONTROL_DEV_TELEM1', '''First telemetry port''') SERIAL_CONTROL_DEV_TELEM2 = 1 # Second telemetry port enums['SERIAL_CONTROL_DEV'][1] = EnumEntry('SERIAL_CONTROL_DEV_TELEM2', '''Second telemetry port''') SERIAL_CONTROL_DEV_GPS1 = 2 # First GPS port enums['SERIAL_CONTROL_DEV'][2] = EnumEntry('SERIAL_CONTROL_DEV_GPS1', '''First GPS port''') SERIAL_CONTROL_DEV_GPS2 = 3 # Second GPS port enums['SERIAL_CONTROL_DEV'][3] = EnumEntry('SERIAL_CONTROL_DEV_GPS2', '''Second GPS port''') SERIAL_CONTROL_DEV_SHELL = 10 # system shell enums['SERIAL_CONTROL_DEV'][10] = EnumEntry('SERIAL_CONTROL_DEV_SHELL', '''system shell''') SERIAL_CONTROL_SERIAL0 = 100 # SERIAL0 enums['SERIAL_CONTROL_DEV'][100] = EnumEntry('SERIAL_CONTROL_SERIAL0', '''SERIAL0''') SERIAL_CONTROL_SERIAL1 = 101 # SERIAL1 enums['SERIAL_CONTROL_DEV'][101] = EnumEntry('SERIAL_CONTROL_SERIAL1', '''SERIAL1''') SERIAL_CONTROL_SERIAL2 = 102 # SERIAL2 enums['SERIAL_CONTROL_DEV'][102] = EnumEntry('SERIAL_CONTROL_SERIAL2', '''SERIAL2''') SERIAL_CONTROL_SERIAL3 = 103 # SERIAL3 enums['SERIAL_CONTROL_DEV'][103] = EnumEntry('SERIAL_CONTROL_SERIAL3', '''SERIAL3''') SERIAL_CONTROL_SERIAL4 = 104 # SERIAL4 enums['SERIAL_CONTROL_DEV'][104] = EnumEntry('SERIAL_CONTROL_SERIAL4', '''SERIAL4''') SERIAL_CONTROL_SERIAL5 = 105 # SERIAL5 enums['SERIAL_CONTROL_DEV'][105] = EnumEntry('SERIAL_CONTROL_SERIAL5', '''SERIAL5''') SERIAL_CONTROL_SERIAL6 = 106 # SERIAL6 enums['SERIAL_CONTROL_DEV'][106] = EnumEntry('SERIAL_CONTROL_SERIAL6', '''SERIAL6''') SERIAL_CONTROL_SERIAL7 = 107 # SERIAL7 enums['SERIAL_CONTROL_DEV'][107] = EnumEntry('SERIAL_CONTROL_SERIAL7', '''SERIAL7''') SERIAL_CONTROL_SERIAL8 = 108 # SERIAL8 enums['SERIAL_CONTROL_DEV'][108] = EnumEntry('SERIAL_CONTROL_SERIAL8', '''SERIAL8''') SERIAL_CONTROL_SERIAL9 = 109 # SERIAL9 enums['SERIAL_CONTROL_DEV'][109] = EnumEntry('SERIAL_CONTROL_SERIAL9', '''SERIAL9''') SERIAL_CONTROL_DEV_ENUM_END = 110 # enums['SERIAL_CONTROL_DEV'][110] = EnumEntry('SERIAL_CONTROL_DEV_ENUM_END', '''''') # SERIAL_CONTROL_FLAG enums['SERIAL_CONTROL_FLAG'] = {} SERIAL_CONTROL_FLAG_REPLY = 1 # Set if this is a reply enums['SERIAL_CONTROL_FLAG'][1] = EnumEntry('SERIAL_CONTROL_FLAG_REPLY', '''Set if this is a reply''') SERIAL_CONTROL_FLAG_RESPOND = 2 # Set if the sender wants the receiver to send a response as another # SERIAL_CONTROL message enums['SERIAL_CONTROL_FLAG'][2] = EnumEntry('SERIAL_CONTROL_FLAG_RESPOND', '''Set if the sender wants the receiver to send a response as another SERIAL_CONTROL message''') SERIAL_CONTROL_FLAG_EXCLUSIVE = 4 # Set if access to the serial port should be removed from whatever # driver is currently using it, giving # exclusive access to the SERIAL_CONTROL # protocol. The port can be handed back by # sending a request without this flag set enums['SERIAL_CONTROL_FLAG'][4] = EnumEntry('SERIAL_CONTROL_FLAG_EXCLUSIVE', '''Set if access to the serial port should be removed from whatever driver is currently using it, giving exclusive access to the SERIAL_CONTROL protocol. The port can be handed back by sending a request without this flag set''') SERIAL_CONTROL_FLAG_BLOCKING = 8 # Block on writes to the serial port enums['SERIAL_CONTROL_FLAG'][8] = EnumEntry('SERIAL_CONTROL_FLAG_BLOCKING', '''Block on writes to the serial port''') SERIAL_CONTROL_FLAG_MULTI = 16 # Send multiple replies until port is drained enums['SERIAL_CONTROL_FLAG'][16] = EnumEntry('SERIAL_CONTROL_FLAG_MULTI', '''Send multiple replies until port is drained''') SERIAL_CONTROL_FLAG_ENUM_END = 17 # enums['SERIAL_CONTROL_FLAG'][17] = EnumEntry('SERIAL_CONTROL_FLAG_ENUM_END', '''''') # MAV_DISTANCE_SENSOR enums['MAV_DISTANCE_SENSOR'] = {} MAV_DISTANCE_SENSOR_LASER = 0 # Laser rangefinder, e.g. LightWare SF02/F or PulsedLight units enums['MAV_DISTANCE_SENSOR'][0] = EnumEntry('MAV_DISTANCE_SENSOR_LASER', '''Laser rangefinder, e.g. LightWare SF02/F or PulsedLight units''') MAV_DISTANCE_SENSOR_ULTRASOUND = 1 # Ultrasound rangefinder, e.g. MaxBotix units enums['MAV_DISTANCE_SENSOR'][1] = EnumEntry('MAV_DISTANCE_SENSOR_ULTRASOUND', '''Ultrasound rangefinder, e.g. MaxBotix units''') MAV_DISTANCE_SENSOR_INFRARED = 2 # Infrared rangefinder, e.g. Sharp units enums['MAV_DISTANCE_SENSOR'][2] = EnumEntry('MAV_DISTANCE_SENSOR_INFRARED', '''Infrared rangefinder, e.g. Sharp units''') MAV_DISTANCE_SENSOR_RADAR = 3 # Radar type, e.g. uLanding units enums['MAV_DISTANCE_SENSOR'][3] = EnumEntry('MAV_DISTANCE_SENSOR_RADAR', '''Radar type, e.g. uLanding units''') MAV_DISTANCE_SENSOR_UNKNOWN = 4 # Broken or unknown type, e.g. analog units enums['MAV_DISTANCE_SENSOR'][4] = EnumEntry('MAV_DISTANCE_SENSOR_UNKNOWN', '''Broken or unknown type, e.g. analog units''') MAV_DISTANCE_SENSOR_ENUM_END = 5 # enums['MAV_DISTANCE_SENSOR'][5] = EnumEntry('MAV_DISTANCE_SENSOR_ENUM_END', '''''') # MAV_SENSOR_ORIENTATION enums['MAV_SENSOR_ORIENTATION'] = {} MAV_SENSOR_ROTATION_NONE = 0 # Roll: 0, Pitch: 0, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][0] = EnumEntry('MAV_SENSOR_ROTATION_NONE', '''Roll: 0, Pitch: 0, Yaw: 0''') MAV_SENSOR_ROTATION_YAW_45 = 1 # Roll: 0, Pitch: 0, Yaw: 45 enums['MAV_SENSOR_ORIENTATION'][1] = EnumEntry('MAV_SENSOR_ROTATION_YAW_45', '''Roll: 0, Pitch: 0, Yaw: 45''') MAV_SENSOR_ROTATION_YAW_90 = 2 # Roll: 0, Pitch: 0, Yaw: 90 enums['MAV_SENSOR_ORIENTATION'][2] = EnumEntry('MAV_SENSOR_ROTATION_YAW_90', '''Roll: 0, Pitch: 0, Yaw: 90''') MAV_SENSOR_ROTATION_YAW_135 = 3 # Roll: 0, Pitch: 0, Yaw: 135 enums['MAV_SENSOR_ORIENTATION'][3] = EnumEntry('MAV_SENSOR_ROTATION_YAW_135', '''Roll: 0, Pitch: 0, Yaw: 135''') MAV_SENSOR_ROTATION_YAW_180 = 4 # Roll: 0, Pitch: 0, Yaw: 180 enums['MAV_SENSOR_ORIENTATION'][4] = EnumEntry('MAV_SENSOR_ROTATION_YAW_180', '''Roll: 0, Pitch: 0, Yaw: 180''') MAV_SENSOR_ROTATION_YAW_225 = 5 # Roll: 0, Pitch: 0, Yaw: 225 enums['MAV_SENSOR_ORIENTATION'][5] = EnumEntry('MAV_SENSOR_ROTATION_YAW_225', '''Roll: 0, Pitch: 0, Yaw: 225''') MAV_SENSOR_ROTATION_YAW_270 = 6 # Roll: 0, Pitch: 0, Yaw: 270 enums['MAV_SENSOR_ORIENTATION'][6] = EnumEntry('MAV_SENSOR_ROTATION_YAW_270', '''Roll: 0, Pitch: 0, Yaw: 270''') MAV_SENSOR_ROTATION_YAW_315 = 7 # Roll: 0, Pitch: 0, Yaw: 315 enums['MAV_SENSOR_ORIENTATION'][7] = EnumEntry('MAV_SENSOR_ROTATION_YAW_315', '''Roll: 0, Pitch: 0, Yaw: 315''') MAV_SENSOR_ROTATION_ROLL_180 = 8 # Roll: 180, Pitch: 0, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][8] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180', '''Roll: 180, Pitch: 0, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_180_YAW_45 = 9 # Roll: 180, Pitch: 0, Yaw: 45 enums['MAV_SENSOR_ORIENTATION'][9] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180_YAW_45', '''Roll: 180, Pitch: 0, Yaw: 45''') MAV_SENSOR_ROTATION_ROLL_180_YAW_90 = 10 # Roll: 180, Pitch: 0, Yaw: 90 enums['MAV_SENSOR_ORIENTATION'][10] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180_YAW_90', '''Roll: 180, Pitch: 0, Yaw: 90''') MAV_SENSOR_ROTATION_ROLL_180_YAW_135 = 11 # Roll: 180, Pitch: 0, Yaw: 135 enums['MAV_SENSOR_ORIENTATION'][11] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180_YAW_135', '''Roll: 180, Pitch: 0, Yaw: 135''') MAV_SENSOR_ROTATION_PITCH_180 = 12 # Roll: 0, Pitch: 180, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][12] = EnumEntry('MAV_SENSOR_ROTATION_PITCH_180', '''Roll: 0, Pitch: 180, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_180_YAW_225 = 13 # Roll: 180, Pitch: 0, Yaw: 225 enums['MAV_SENSOR_ORIENTATION'][13] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180_YAW_225', '''Roll: 180, Pitch: 0, Yaw: 225''') MAV_SENSOR_ROTATION_ROLL_180_YAW_270 = 14 # Roll: 180, Pitch: 0, Yaw: 270 enums['MAV_SENSOR_ORIENTATION'][14] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180_YAW_270', '''Roll: 180, Pitch: 0, Yaw: 270''') MAV_SENSOR_ROTATION_ROLL_180_YAW_315 = 15 # Roll: 180, Pitch: 0, Yaw: 315 enums['MAV_SENSOR_ORIENTATION'][15] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180_YAW_315', '''Roll: 180, Pitch: 0, Yaw: 315''') MAV_SENSOR_ROTATION_ROLL_90 = 16 # Roll: 90, Pitch: 0, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][16] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90', '''Roll: 90, Pitch: 0, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_90_YAW_45 = 17 # Roll: 90, Pitch: 0, Yaw: 45 enums['MAV_SENSOR_ORIENTATION'][17] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_YAW_45', '''Roll: 90, Pitch: 0, Yaw: 45''') MAV_SENSOR_ROTATION_ROLL_90_YAW_90 = 18 # Roll: 90, Pitch: 0, Yaw: 90 enums['MAV_SENSOR_ORIENTATION'][18] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_YAW_90', '''Roll: 90, Pitch: 0, Yaw: 90''') MAV_SENSOR_ROTATION_ROLL_90_YAW_135 = 19 # Roll: 90, Pitch: 0, Yaw: 135 enums['MAV_SENSOR_ORIENTATION'][19] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_YAW_135', '''Roll: 90, Pitch: 0, Yaw: 135''') MAV_SENSOR_ROTATION_ROLL_270 = 20 # Roll: 270, Pitch: 0, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][20] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_270', '''Roll: 270, Pitch: 0, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_270_YAW_45 = 21 # Roll: 270, Pitch: 0, Yaw: 45 enums['MAV_SENSOR_ORIENTATION'][21] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_270_YAW_45', '''Roll: 270, Pitch: 0, Yaw: 45''') MAV_SENSOR_ROTATION_ROLL_270_YAW_90 = 22 # Roll: 270, Pitch: 0, Yaw: 90 enums['MAV_SENSOR_ORIENTATION'][22] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_270_YAW_90', '''Roll: 270, Pitch: 0, Yaw: 90''') MAV_SENSOR_ROTATION_ROLL_270_YAW_135 = 23 # Roll: 270, Pitch: 0, Yaw: 135 enums['MAV_SENSOR_ORIENTATION'][23] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_270_YAW_135', '''Roll: 270, Pitch: 0, Yaw: 135''') MAV_SENSOR_ROTATION_PITCH_90 = 24 # Roll: 0, Pitch: 90, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][24] = EnumEntry('MAV_SENSOR_ROTATION_PITCH_90', '''Roll: 0, Pitch: 90, Yaw: 0''') MAV_SENSOR_ROTATION_PITCH_270 = 25 # Roll: 0, Pitch: 270, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][25] = EnumEntry('MAV_SENSOR_ROTATION_PITCH_270', '''Roll: 0, Pitch: 270, Yaw: 0''') MAV_SENSOR_ROTATION_PITCH_180_YAW_90 = 26 # Roll: 0, Pitch: 180, Yaw: 90 enums['MAV_SENSOR_ORIENTATION'][26] = EnumEntry('MAV_SENSOR_ROTATION_PITCH_180_YAW_90', '''Roll: 0, Pitch: 180, Yaw: 90''') MAV_SENSOR_ROTATION_PITCH_180_YAW_270 = 27 # Roll: 0, Pitch: 180, Yaw: 270 enums['MAV_SENSOR_ORIENTATION'][27] = EnumEntry('MAV_SENSOR_ROTATION_PITCH_180_YAW_270', '''Roll: 0, Pitch: 180, Yaw: 270''') MAV_SENSOR_ROTATION_ROLL_90_PITCH_90 = 28 # Roll: 90, Pitch: 90, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][28] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_PITCH_90', '''Roll: 90, Pitch: 90, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_180_PITCH_90 = 29 # Roll: 180, Pitch: 90, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][29] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180_PITCH_90', '''Roll: 180, Pitch: 90, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_270_PITCH_90 = 30 # Roll: 270, Pitch: 90, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][30] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_270_PITCH_90', '''Roll: 270, Pitch: 90, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_90_PITCH_180 = 31 # Roll: 90, Pitch: 180, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][31] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_PITCH_180', '''Roll: 90, Pitch: 180, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_270_PITCH_180 = 32 # Roll: 270, Pitch: 180, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][32] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_270_PITCH_180', '''Roll: 270, Pitch: 180, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_90_PITCH_270 = 33 # Roll: 90, Pitch: 270, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][33] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_PITCH_270', '''Roll: 90, Pitch: 270, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_180_PITCH_270 = 34 # Roll: 180, Pitch: 270, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][34] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_180_PITCH_270', '''Roll: 180, Pitch: 270, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_270_PITCH_270 = 35 # Roll: 270, Pitch: 270, Yaw: 0 enums['MAV_SENSOR_ORIENTATION'][35] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_270_PITCH_270', '''Roll: 270, Pitch: 270, Yaw: 0''') MAV_SENSOR_ROTATION_ROLL_90_PITCH_180_YAW_90 = 36 # Roll: 90, Pitch: 180, Yaw: 90 enums['MAV_SENSOR_ORIENTATION'][36] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_PITCH_180_YAW_90', '''Roll: 90, Pitch: 180, Yaw: 90''') MAV_SENSOR_ROTATION_ROLL_90_YAW_270 = 37 # Roll: 90, Pitch: 0, Yaw: 270 enums['MAV_SENSOR_ORIENTATION'][37] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_YAW_270', '''Roll: 90, Pitch: 0, Yaw: 270''') MAV_SENSOR_ROTATION_ROLL_90_PITCH_68_YAW_293 = 38 # Roll: 90, Pitch: 68, Yaw: 293 enums['MAV_SENSOR_ORIENTATION'][38] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_PITCH_68_YAW_293', '''Roll: 90, Pitch: 68, Yaw: 293''') MAV_SENSOR_ROTATION_PITCH_315 = 39 # Pitch: 315 enums['MAV_SENSOR_ORIENTATION'][39] = EnumEntry('MAV_SENSOR_ROTATION_PITCH_315', '''Pitch: 315''') MAV_SENSOR_ROTATION_ROLL_90_PITCH_315 = 40 # Roll: 90, Pitch: 315 enums['MAV_SENSOR_ORIENTATION'][40] = EnumEntry('MAV_SENSOR_ROTATION_ROLL_90_PITCH_315', '''Roll: 90, Pitch: 315''') MAV_SENSOR_ROTATION_CUSTOM = 100 # Custom orientation enums['MAV_SENSOR_ORIENTATION'][100] = EnumEntry('MAV_SENSOR_ROTATION_CUSTOM', '''Custom orientation''') MAV_SENSOR_ORIENTATION_ENUM_END = 101 # enums['MAV_SENSOR_ORIENTATION'][101] = EnumEntry('MAV_SENSOR_ORIENTATION_ENUM_END', '''''') # MAV_PROTOCOL_CAPABILITY enums['MAV_PROTOCOL_CAPABILITY'] = {} MAV_PROTOCOL_CAPABILITY_MISSION_FLOAT = 1 # Autopilot supports MISSION float message type. enums['MAV_PROTOCOL_CAPABILITY'][1] = EnumEntry('MAV_PROTOCOL_CAPABILITY_MISSION_FLOAT', '''Autopilot supports MISSION float message type.''') MAV_PROTOCOL_CAPABILITY_PARAM_FLOAT = 2 # Autopilot supports the new param float message type. enums['MAV_PROTOCOL_CAPABILITY'][2] = EnumEntry('MAV_PROTOCOL_CAPABILITY_PARAM_FLOAT', '''Autopilot supports the new param float message type.''') MAV_PROTOCOL_CAPABILITY_MISSION_INT = 4 # Autopilot supports MISSION_INT scaled integer message type. enums['MAV_PROTOCOL_CAPABILITY'][4] = EnumEntry('MAV_PROTOCOL_CAPABILITY_MISSION_INT', '''Autopilot supports MISSION_INT scaled integer message type.''') MAV_PROTOCOL_CAPABILITY_COMMAND_INT = 8 # Autopilot supports COMMAND_INT scaled integer message type. enums['MAV_PROTOCOL_CAPABILITY'][8] = EnumEntry('MAV_PROTOCOL_CAPABILITY_COMMAND_INT', '''Autopilot supports COMMAND_INT scaled integer message type.''') MAV_PROTOCOL_CAPABILITY_PARAM_UNION = 16 # Autopilot supports the new param union message type. enums['MAV_PROTOCOL_CAPABILITY'][16] = EnumEntry('MAV_PROTOCOL_CAPABILITY_PARAM_UNION', '''Autopilot supports the new param union message type.''') MAV_PROTOCOL_CAPABILITY_FTP = 32 # Autopilot supports the new FILE_TRANSFER_PROTOCOL message type. enums['MAV_PROTOCOL_CAPABILITY'][32] = EnumEntry('MAV_PROTOCOL_CAPABILITY_FTP', '''Autopilot supports the new FILE_TRANSFER_PROTOCOL message type.''') MAV_PROTOCOL_CAPABILITY_SET_ATTITUDE_TARGET = 64 # Autopilot supports commanding attitude offboard. enums['MAV_PROTOCOL_CAPABILITY'][64] = EnumEntry('MAV_PROTOCOL_CAPABILITY_SET_ATTITUDE_TARGET', '''Autopilot supports commanding attitude offboard.''') MAV_PROTOCOL_CAPABILITY_SET_POSITION_TARGET_LOCAL_NED = 128 # Autopilot supports commanding position and velocity targets in local # NED frame. enums['MAV_PROTOCOL_CAPABILITY'][128] = EnumEntry('MAV_PROTOCOL_CAPABILITY_SET_POSITION_TARGET_LOCAL_NED', '''Autopilot supports commanding position and velocity targets in local NED frame.''') MAV_PROTOCOL_CAPABILITY_SET_POSITION_TARGET_GLOBAL_INT = 256 # Autopilot supports commanding position and velocity targets in global # scaled integers. enums['MAV_PROTOCOL_CAPABILITY'][256] = EnumEntry('MAV_PROTOCOL_CAPABILITY_SET_POSITION_TARGET_GLOBAL_INT', '''Autopilot supports commanding position and velocity targets in global scaled integers.''') MAV_PROTOCOL_CAPABILITY_TERRAIN = 512 # Autopilot supports terrain protocol / data handling. enums['MAV_PROTOCOL_CAPABILITY'][512] = EnumEntry('MAV_PROTOCOL_CAPABILITY_TERRAIN', '''Autopilot supports terrain protocol / data handling.''') MAV_PROTOCOL_CAPABILITY_SET_ACTUATOR_TARGET = 1024 # Autopilot supports direct actuator control. enums['MAV_PROTOCOL_CAPABILITY'][1024] = EnumEntry('MAV_PROTOCOL_CAPABILITY_SET_ACTUATOR_TARGET', '''Autopilot supports direct actuator control.''') MAV_PROTOCOL_CAPABILITY_FLIGHT_TERMINATION = 2048 # Autopilot supports the flight termination command. enums['MAV_PROTOCOL_CAPABILITY'][2048] = EnumEntry('MAV_PROTOCOL_CAPABILITY_FLIGHT_TERMINATION', '''Autopilot supports the flight termination command.''') MAV_PROTOCOL_CAPABILITY_COMPASS_CALIBRATION = 4096 # Autopilot supports onboard compass calibration. enums['MAV_PROTOCOL_CAPABILITY'][4096] = EnumEntry('MAV_PROTOCOL_CAPABILITY_COMPASS_CALIBRATION', '''Autopilot supports onboard compass calibration.''') MAV_PROTOCOL_CAPABILITY_MAVLINK2 = 8192 # Autopilot supports MAVLink version 2. enums['MAV_PROTOCOL_CAPABILITY'][8192] = EnumEntry('MAV_PROTOCOL_CAPABILITY_MAVLINK2', '''Autopilot supports MAVLink version 2.''') MAV_PROTOCOL_CAPABILITY_MISSION_FENCE = 16384 # Autopilot supports mission fence protocol. enums['MAV_PROTOCOL_CAPABILITY'][16384] = EnumEntry('MAV_PROTOCOL_CAPABILITY_MISSION_FENCE', '''Autopilot supports mission fence protocol.''') MAV_PROTOCOL_CAPABILITY_MISSION_RALLY = 32768 # Autopilot supports mission rally point protocol. enums['MAV_PROTOCOL_CAPABILITY'][32768] = EnumEntry('MAV_PROTOCOL_CAPABILITY_MISSION_RALLY', '''Autopilot supports mission rally point protocol.''') MAV_PROTOCOL_CAPABILITY_FLIGHT_INFORMATION = 65536 # Autopilot supports the flight information protocol. enums['MAV_PROTOCOL_CAPABILITY'][65536] = EnumEntry('MAV_PROTOCOL_CAPABILITY_FLIGHT_INFORMATION', '''Autopilot supports the flight information protocol.''') MAV_PROTOCOL_CAPABILITY_ENUM_END = 65537 # enums['MAV_PROTOCOL_CAPABILITY'][65537] = EnumEntry('MAV_PROTOCOL_CAPABILITY_ENUM_END', '''''') # MAV_MISSION_TYPE enums['MAV_MISSION_TYPE'] = {} MAV_MISSION_TYPE_MISSION = 0 # Items are mission commands for main mission. enums['MAV_MISSION_TYPE'][0] = EnumEntry('MAV_MISSION_TYPE_MISSION', '''Items are mission commands for main mission.''') MAV_MISSION_TYPE_FENCE = 1 # Specifies GeoFence area(s). Items are MAV_CMD_NAV_FENCE_ GeoFence # items. enums['MAV_MISSION_TYPE'][1] = EnumEntry('MAV_MISSION_TYPE_FENCE', '''Specifies GeoFence area(s). Items are MAV_CMD_NAV_FENCE_ GeoFence items.''') MAV_MISSION_TYPE_RALLY = 2 # Specifies the rally points for the vehicle. Rally points are # alternative RTL points. Items are # MAV_CMD_NAV_RALLY_POINT rally point items. enums['MAV_MISSION_TYPE'][2] = EnumEntry('MAV_MISSION_TYPE_RALLY', '''Specifies the rally points for the vehicle. Rally points are alternative RTL points. Items are MAV_CMD_NAV_RALLY_POINT rally point items.''') MAV_MISSION_TYPE_ALL = 255 # Only used in MISSION_CLEAR_ALL to clear all mission types. enums['MAV_MISSION_TYPE'][255] = EnumEntry('MAV_MISSION_TYPE_ALL', '''Only used in MISSION_CLEAR_ALL to clear all mission types.''') MAV_MISSION_TYPE_ENUM_END = 256 # enums['MAV_MISSION_TYPE'][256] = EnumEntry('MAV_MISSION_TYPE_ENUM_END', '''''') # MAV_ESTIMATOR_TYPE enums['MAV_ESTIMATOR_TYPE'] = {} MAV_ESTIMATOR_TYPE_UNKNOWN = 0 # Unknown type of the estimator. enums['MAV_ESTIMATOR_TYPE'][0] = EnumEntry('MAV_ESTIMATOR_TYPE_UNKNOWN', '''Unknown type of the estimator.''') MAV_ESTIMATOR_TYPE_NAIVE = 1 # This is a naive estimator without any real covariance feedback. enums['MAV_ESTIMATOR_TYPE'][1] = EnumEntry('MAV_ESTIMATOR_TYPE_NAIVE', '''This is a naive estimator without any real covariance feedback.''') MAV_ESTIMATOR_TYPE_VISION = 2 # Computer vision based estimate. Might be up to scale. enums['MAV_ESTIMATOR_TYPE'][2] = EnumEntry('MAV_ESTIMATOR_TYPE_VISION', '''Computer vision based estimate. Might be up to scale.''') MAV_ESTIMATOR_TYPE_VIO = 3 # Visual-inertial estimate. enums['MAV_ESTIMATOR_TYPE'][3] = EnumEntry('MAV_ESTIMATOR_TYPE_VIO', '''Visual-inertial estimate.''') MAV_ESTIMATOR_TYPE_GPS = 4 # Plain GPS estimate. enums['MAV_ESTIMATOR_TYPE'][4] = EnumEntry('MAV_ESTIMATOR_TYPE_GPS', '''Plain GPS estimate.''') MAV_ESTIMATOR_TYPE_GPS_INS = 5 # Estimator integrating GPS and inertial sensing. enums['MAV_ESTIMATOR_TYPE'][5] = EnumEntry('MAV_ESTIMATOR_TYPE_GPS_INS', '''Estimator integrating GPS and inertial sensing.''') MAV_ESTIMATOR_TYPE_MOCAP = 6 # Estimate from external motion capturing system. enums['MAV_ESTIMATOR_TYPE'][6] = EnumEntry('MAV_ESTIMATOR_TYPE_MOCAP', '''Estimate from external motion capturing system.''') MAV_ESTIMATOR_TYPE_LIDAR = 7 # Estimator based on lidar sensor input. enums['MAV_ESTIMATOR_TYPE'][7] = EnumEntry('MAV_ESTIMATOR_TYPE_LIDAR', '''Estimator based on lidar sensor input.''') MAV_ESTIMATOR_TYPE_AUTOPILOT = 8 # Estimator on autopilot. enums['MAV_ESTIMATOR_TYPE'][8] = EnumEntry('MAV_ESTIMATOR_TYPE_AUTOPILOT', '''Estimator on autopilot.''') MAV_ESTIMATOR_TYPE_ENUM_END = 9 # enums['MAV_ESTIMATOR_TYPE'][9] = EnumEntry('MAV_ESTIMATOR_TYPE_ENUM_END', '''''') # MAV_BATTERY_TYPE enums['MAV_BATTERY_TYPE'] = {} MAV_BATTERY_TYPE_UNKNOWN = 0 # Not specified. enums['MAV_BATTERY_TYPE'][0] = EnumEntry('MAV_BATTERY_TYPE_UNKNOWN', '''Not specified.''') MAV_BATTERY_TYPE_LIPO = 1 # Lithium polymer battery enums['MAV_BATTERY_TYPE'][1] = EnumEntry('MAV_BATTERY_TYPE_LIPO', '''Lithium polymer battery''') MAV_BATTERY_TYPE_LIFE = 2 # Lithium-iron-phosphate battery enums['MAV_BATTERY_TYPE'][2] = EnumEntry('MAV_BATTERY_TYPE_LIFE', '''Lithium-iron-phosphate battery''') MAV_BATTERY_TYPE_LION = 3 # Lithium-ION battery enums['MAV_BATTERY_TYPE'][3] = EnumEntry('MAV_BATTERY_TYPE_LION', '''Lithium-ION battery''') MAV_BATTERY_TYPE_NIMH = 4 # Nickel metal hydride battery enums['MAV_BATTERY_TYPE'][4] = EnumEntry('MAV_BATTERY_TYPE_NIMH', '''Nickel metal hydride battery''') MAV_BATTERY_TYPE_ENUM_END = 5 # enums['MAV_BATTERY_TYPE'][5] = EnumEntry('MAV_BATTERY_TYPE_ENUM_END', '''''') # MAV_BATTERY_FUNCTION enums['MAV_BATTERY_FUNCTION'] = {} MAV_BATTERY_FUNCTION_UNKNOWN = 0 # Battery function is unknown enums['MAV_BATTERY_FUNCTION'][0] = EnumEntry('MAV_BATTERY_FUNCTION_UNKNOWN', '''Battery function is unknown''') MAV_BATTERY_FUNCTION_ALL = 1 # Battery supports all flight systems enums['MAV_BATTERY_FUNCTION'][1] = EnumEntry('MAV_BATTERY_FUNCTION_ALL', '''Battery supports all flight systems''') MAV_BATTERY_FUNCTION_PROPULSION = 2 # Battery for the propulsion system enums['MAV_BATTERY_FUNCTION'][2] = EnumEntry('MAV_BATTERY_FUNCTION_PROPULSION', '''Battery for the propulsion system''') MAV_BATTERY_FUNCTION_AVIONICS = 3 # Avionics battery enums['MAV_BATTERY_FUNCTION'][3] = EnumEntry('MAV_BATTERY_FUNCTION_AVIONICS', '''Avionics battery''') MAV_BATTERY_TYPE_PAYLOAD = 4 # Payload battery enums['MAV_BATTERY_FUNCTION'][4] = EnumEntry('MAV_BATTERY_TYPE_PAYLOAD', '''Payload battery''') MAV_BATTERY_FUNCTION_ENUM_END = 5 # enums['MAV_BATTERY_FUNCTION'][5] = EnumEntry('MAV_BATTERY_FUNCTION_ENUM_END', '''''') # MAV_BATTERY_CHARGE_STATE enums['MAV_BATTERY_CHARGE_STATE'] = {} MAV_BATTERY_CHARGE_STATE_UNDEFINED = 0 # Low battery state is not provided enums['MAV_BATTERY_CHARGE_STATE'][0] = EnumEntry('MAV_BATTERY_CHARGE_STATE_UNDEFINED', '''Low battery state is not provided''') MAV_BATTERY_CHARGE_STATE_OK = 1 # Battery is not in low state. Normal operation. enums['MAV_BATTERY_CHARGE_STATE'][1] = EnumEntry('MAV_BATTERY_CHARGE_STATE_OK', '''Battery is not in low state. Normal operation.''') MAV_BATTERY_CHARGE_STATE_LOW = 2 # Battery state is low, warn and monitor close. enums['MAV_BATTERY_CHARGE_STATE'][2] = EnumEntry('MAV_BATTERY_CHARGE_STATE_LOW', '''Battery state is low, warn and monitor close.''') MAV_BATTERY_CHARGE_STATE_CRITICAL = 3 # Battery state is critical, return or abort immediately. enums['MAV_BATTERY_CHARGE_STATE'][3] = EnumEntry('MAV_BATTERY_CHARGE_STATE_CRITICAL', '''Battery state is critical, return or abort immediately.''') MAV_BATTERY_CHARGE_STATE_EMERGENCY = 4 # Battery state is too low for ordinary abort sequence. Perform fastest # possible emergency stop to prevent damage. enums['MAV_BATTERY_CHARGE_STATE'][4] = EnumEntry('MAV_BATTERY_CHARGE_STATE_EMERGENCY', '''Battery state is too low for ordinary abort sequence. Perform fastest possible emergency stop to prevent damage.''') MAV_BATTERY_CHARGE_STATE_FAILED = 5 # Battery failed, damage unavoidable. enums['MAV_BATTERY_CHARGE_STATE'][5] = EnumEntry('MAV_BATTERY_CHARGE_STATE_FAILED', '''Battery failed, damage unavoidable.''') MAV_BATTERY_CHARGE_STATE_UNHEALTHY = 6 # Battery is diagnosed to be defective or an error occurred, usage is # discouraged / prohibited. enums['MAV_BATTERY_CHARGE_STATE'][6] = EnumEntry('MAV_BATTERY_CHARGE_STATE_UNHEALTHY', '''Battery is diagnosed to be defective or an error occurred, usage is discouraged / prohibited.''') MAV_BATTERY_CHARGE_STATE_CHARGING = 7 # Battery is charging. enums['MAV_BATTERY_CHARGE_STATE'][7] = EnumEntry('MAV_BATTERY_CHARGE_STATE_CHARGING', '''Battery is charging.''') MAV_BATTERY_CHARGE_STATE_ENUM_END = 8 # enums['MAV_BATTERY_CHARGE_STATE'][8] = EnumEntry('MAV_BATTERY_CHARGE_STATE_ENUM_END', '''''') # MAV_VTOL_STATE enums['MAV_VTOL_STATE'] = {} MAV_VTOL_STATE_UNDEFINED = 0 # MAV is not configured as VTOL enums['MAV_VTOL_STATE'][0] = EnumEntry('MAV_VTOL_STATE_UNDEFINED', '''MAV is not configured as VTOL''') MAV_VTOL_STATE_TRANSITION_TO_FW = 1 # VTOL is in transition from multicopter to fixed-wing enums['MAV_VTOL_STATE'][1] = EnumEntry('MAV_VTOL_STATE_TRANSITION_TO_FW', '''VTOL is in transition from multicopter to fixed-wing''') MAV_VTOL_STATE_TRANSITION_TO_MC = 2 # VTOL is in transition from fixed-wing to multicopter enums['MAV_VTOL_STATE'][2] = EnumEntry('MAV_VTOL_STATE_TRANSITION_TO_MC', '''VTOL is in transition from fixed-wing to multicopter''') MAV_VTOL_STATE_MC = 3 # VTOL is in multicopter state enums['MAV_VTOL_STATE'][3] = EnumEntry('MAV_VTOL_STATE_MC', '''VTOL is in multicopter state''') MAV_VTOL_STATE_FW = 4 # VTOL is in fixed-wing state enums['MAV_VTOL_STATE'][4] = EnumEntry('MAV_VTOL_STATE_FW', '''VTOL is in fixed-wing state''') MAV_VTOL_STATE_ENUM_END = 5 # enums['MAV_VTOL_STATE'][5] = EnumEntry('MAV_VTOL_STATE_ENUM_END', '''''') # MAV_LANDED_STATE enums['MAV_LANDED_STATE'] = {} MAV_LANDED_STATE_UNDEFINED = 0 # MAV landed state is unknown enums['MAV_LANDED_STATE'][0] = EnumEntry('MAV_LANDED_STATE_UNDEFINED', '''MAV landed state is unknown''') MAV_LANDED_STATE_ON_GROUND = 1 # MAV is landed (on ground) enums['MAV_LANDED_STATE'][1] = EnumEntry('MAV_LANDED_STATE_ON_GROUND', '''MAV is landed (on ground)''') MAV_LANDED_STATE_IN_AIR = 2 # MAV is in air enums['MAV_LANDED_STATE'][2] = EnumEntry('MAV_LANDED_STATE_IN_AIR', '''MAV is in air''') MAV_LANDED_STATE_TAKEOFF = 3 # MAV currently taking off enums['MAV_LANDED_STATE'][3] = EnumEntry('MAV_LANDED_STATE_TAKEOFF', '''MAV currently taking off''') MAV_LANDED_STATE_LANDING = 4 # MAV currently landing enums['MAV_LANDED_STATE'][4] = EnumEntry('MAV_LANDED_STATE_LANDING', '''MAV currently landing''') MAV_LANDED_STATE_ENUM_END = 5 # enums['MAV_LANDED_STATE'][5] = EnumEntry('MAV_LANDED_STATE_ENUM_END', '''''') # ADSB_ALTITUDE_TYPE enums['ADSB_ALTITUDE_TYPE'] = {} ADSB_ALTITUDE_TYPE_PRESSURE_QNH = 0 # Altitude reported from a Baro source using QNH reference enums['ADSB_ALTITUDE_TYPE'][0] = EnumEntry('ADSB_ALTITUDE_TYPE_PRESSURE_QNH', '''Altitude reported from a Baro source using QNH reference''') ADSB_ALTITUDE_TYPE_GEOMETRIC = 1 # Altitude reported from a GNSS source enums['ADSB_ALTITUDE_TYPE'][1] = EnumEntry('ADSB_ALTITUDE_TYPE_GEOMETRIC', '''Altitude reported from a GNSS source''') ADSB_ALTITUDE_TYPE_ENUM_END = 2 # enums['ADSB_ALTITUDE_TYPE'][2] = EnumEntry('ADSB_ALTITUDE_TYPE_ENUM_END', '''''') # ADSB_EMITTER_TYPE enums['ADSB_EMITTER_TYPE'] = {} ADSB_EMITTER_TYPE_NO_INFO = 0 # enums['ADSB_EMITTER_TYPE'][0] = EnumEntry('ADSB_EMITTER_TYPE_NO_INFO', '''''') ADSB_EMITTER_TYPE_LIGHT = 1 # enums['ADSB_EMITTER_TYPE'][1] = EnumEntry('ADSB_EMITTER_TYPE_LIGHT', '''''') ADSB_EMITTER_TYPE_SMALL = 2 # enums['ADSB_EMITTER_TYPE'][2] = EnumEntry('ADSB_EMITTER_TYPE_SMALL', '''''') ADSB_EMITTER_TYPE_LARGE = 3 # enums['ADSB_EMITTER_TYPE'][3] = EnumEntry('ADSB_EMITTER_TYPE_LARGE', '''''') ADSB_EMITTER_TYPE_HIGH_VORTEX_LARGE = 4 # enums['ADSB_EMITTER_TYPE'][4] = EnumEntry('ADSB_EMITTER_TYPE_HIGH_VORTEX_LARGE', '''''') ADSB_EMITTER_TYPE_HEAVY = 5 # enums['ADSB_EMITTER_TYPE'][5] = EnumEntry('ADSB_EMITTER_TYPE_HEAVY', '''''') ADSB_EMITTER_TYPE_HIGHLY_MANUV = 6 # enums['ADSB_EMITTER_TYPE'][6] = EnumEntry('ADSB_EMITTER_TYPE_HIGHLY_MANUV', '''''') ADSB_EMITTER_TYPE_ROTOCRAFT = 7 # enums['ADSB_EMITTER_TYPE'][7] = EnumEntry('ADSB_EMITTER_TYPE_ROTOCRAFT', '''''') ADSB_EMITTER_TYPE_UNASSIGNED = 8 # enums['ADSB_EMITTER_TYPE'][8] = EnumEntry('ADSB_EMITTER_TYPE_UNASSIGNED', '''''') ADSB_EMITTER_TYPE_GLIDER = 9 # enums['ADSB_EMITTER_TYPE'][9] = EnumEntry('ADSB_EMITTER_TYPE_GLIDER', '''''') ADSB_EMITTER_TYPE_LIGHTER_AIR = 10 # enums['ADSB_EMITTER_TYPE'][10] = EnumEntry('ADSB_EMITTER_TYPE_LIGHTER_AIR', '''''') ADSB_EMITTER_TYPE_PARACHUTE = 11 # enums['ADSB_EMITTER_TYPE'][11] = EnumEntry('ADSB_EMITTER_TYPE_PARACHUTE', '''''') ADSB_EMITTER_TYPE_ULTRA_LIGHT = 12 # enums['ADSB_EMITTER_TYPE'][12] = EnumEntry('ADSB_EMITTER_TYPE_ULTRA_LIGHT', '''''') ADSB_EMITTER_TYPE_UNASSIGNED2 = 13 # enums['ADSB_EMITTER_TYPE'][13] = EnumEntry('ADSB_EMITTER_TYPE_UNASSIGNED2', '''''') ADSB_EMITTER_TYPE_UAV = 14 # enums['ADSB_EMITTER_TYPE'][14] = EnumEntry('ADSB_EMITTER_TYPE_UAV', '''''') ADSB_EMITTER_TYPE_SPACE = 15 # enums['ADSB_EMITTER_TYPE'][15] = EnumEntry('ADSB_EMITTER_TYPE_SPACE', '''''') ADSB_EMITTER_TYPE_UNASSGINED3 = 16 # enums['ADSB_EMITTER_TYPE'][16] = EnumEntry('ADSB_EMITTER_TYPE_UNASSGINED3', '''''') ADSB_EMITTER_TYPE_EMERGENCY_SURFACE = 17 # enums['ADSB_EMITTER_TYPE'][17] = EnumEntry('ADSB_EMITTER_TYPE_EMERGENCY_SURFACE', '''''') ADSB_EMITTER_TYPE_SERVICE_SURFACE = 18 # enums['ADSB_EMITTER_TYPE'][18] = EnumEntry('ADSB_EMITTER_TYPE_SERVICE_SURFACE', '''''') ADSB_EMITTER_TYPE_POINT_OBSTACLE = 19 # enums['ADSB_EMITTER_TYPE'][19] = EnumEntry('ADSB_EMITTER_TYPE_POINT_OBSTACLE', '''''') ADSB_EMITTER_TYPE_ENUM_END = 20 # enums['ADSB_EMITTER_TYPE'][20] = EnumEntry('ADSB_EMITTER_TYPE_ENUM_END', '''''') # ADSB_FLAGS enums['ADSB_FLAGS'] = {} ADSB_FLAGS_VALID_COORDS = 1 # enums['ADSB_FLAGS'][1] = EnumEntry('ADSB_FLAGS_VALID_COORDS', '''''') ADSB_FLAGS_VALID_ALTITUDE = 2 # enums['ADSB_FLAGS'][2] = EnumEntry('ADSB_FLAGS_VALID_ALTITUDE', '''''') ADSB_FLAGS_VALID_HEADING = 4 # enums['ADSB_FLAGS'][4] = EnumEntry('ADSB_FLAGS_VALID_HEADING', '''''') ADSB_FLAGS_VALID_VELOCITY = 8 # enums['ADSB_FLAGS'][8] = EnumEntry('ADSB_FLAGS_VALID_VELOCITY', '''''') ADSB_FLAGS_VALID_CALLSIGN = 16 # enums['ADSB_FLAGS'][16] = EnumEntry('ADSB_FLAGS_VALID_CALLSIGN', '''''') ADSB_FLAGS_VALID_SQUAWK = 32 # enums['ADSB_FLAGS'][32] = EnumEntry('ADSB_FLAGS_VALID_SQUAWK', '''''') ADSB_FLAGS_SIMULATED = 64 # enums['ADSB_FLAGS'][64] = EnumEntry('ADSB_FLAGS_SIMULATED', '''''') ADSB_FLAGS_ENUM_END = 65 # enums['ADSB_FLAGS'][65] = EnumEntry('ADSB_FLAGS_ENUM_END', '''''') # MAV_DO_REPOSITION_FLAGS enums['MAV_DO_REPOSITION_FLAGS'] = {} MAV_DO_REPOSITION_FLAGS_CHANGE_MODE = 1 # The aircraft should immediately transition into guided. This should # not be set for follow me applications enums['MAV_DO_REPOSITION_FLAGS'][1] = EnumEntry('MAV_DO_REPOSITION_FLAGS_CHANGE_MODE', '''The aircraft should immediately transition into guided. This should not be set for follow me applications''') MAV_DO_REPOSITION_FLAGS_ENUM_END = 2 # enums['MAV_DO_REPOSITION_FLAGS'][2] = EnumEntry('MAV_DO_REPOSITION_FLAGS_ENUM_END', '''''') # ESTIMATOR_STATUS_FLAGS enums['ESTIMATOR_STATUS_FLAGS'] = {} ESTIMATOR_ATTITUDE = 1 # True if the attitude estimate is good enums['ESTIMATOR_STATUS_FLAGS'][1] = EnumEntry('ESTIMATOR_ATTITUDE', '''True if the attitude estimate is good''') ESTIMATOR_VELOCITY_HORIZ = 2 # True if the horizontal velocity estimate is good enums['ESTIMATOR_STATUS_FLAGS'][2] = EnumEntry('ESTIMATOR_VELOCITY_HORIZ', '''True if the horizontal velocity estimate is good''') ESTIMATOR_VELOCITY_VERT = 4 # True if the vertical velocity estimate is good enums['ESTIMATOR_STATUS_FLAGS'][4] = EnumEntry('ESTIMATOR_VELOCITY_VERT', '''True if the vertical velocity estimate is good''') ESTIMATOR_POS_HORIZ_REL = 8 # True if the horizontal position (relative) estimate is good enums['ESTIMATOR_STATUS_FLAGS'][8] = EnumEntry('ESTIMATOR_POS_HORIZ_REL', '''True if the horizontal position (relative) estimate is good''') ESTIMATOR_POS_HORIZ_ABS = 16 # True if the horizontal position (absolute) estimate is good enums['ESTIMATOR_STATUS_FLAGS'][16] = EnumEntry('ESTIMATOR_POS_HORIZ_ABS', '''True if the horizontal position (absolute) estimate is good''') ESTIMATOR_POS_VERT_ABS = 32 # True if the vertical position (absolute) estimate is good enums['ESTIMATOR_STATUS_FLAGS'][32] = EnumEntry('ESTIMATOR_POS_VERT_ABS', '''True if the vertical position (absolute) estimate is good''') ESTIMATOR_POS_VERT_AGL = 64 # True if the vertical position (above ground) estimate is good enums['ESTIMATOR_STATUS_FLAGS'][64] = EnumEntry('ESTIMATOR_POS_VERT_AGL', '''True if the vertical position (above ground) estimate is good''') ESTIMATOR_CONST_POS_MODE = 128 # True if the EKF is in a constant position mode and is not using # external measurements (eg GPS or optical # flow) enums['ESTIMATOR_STATUS_FLAGS'][128] = EnumEntry('ESTIMATOR_CONST_POS_MODE', '''True if the EKF is in a constant position mode and is not using external measurements (eg GPS or optical flow)''') ESTIMATOR_PRED_POS_HORIZ_REL = 256 # True if the EKF has sufficient data to enter a mode that will provide # a (relative) position estimate enums['ESTIMATOR_STATUS_FLAGS'][256] = EnumEntry('ESTIMATOR_PRED_POS_HORIZ_REL', '''True if the EKF has sufficient data to enter a mode that will provide a (relative) position estimate''') ESTIMATOR_PRED_POS_HORIZ_ABS = 512 # True if the EKF has sufficient data to enter a mode that will provide # a (absolute) position estimate enums['ESTIMATOR_STATUS_FLAGS'][512] = EnumEntry('ESTIMATOR_PRED_POS_HORIZ_ABS', '''True if the EKF has sufficient data to enter a mode that will provide a (absolute) position estimate''') ESTIMATOR_GPS_GLITCH = 1024 # True if the EKF has detected a GPS glitch enums['ESTIMATOR_STATUS_FLAGS'][1024] = EnumEntry('ESTIMATOR_GPS_GLITCH', '''True if the EKF has detected a GPS glitch''') ESTIMATOR_ACCEL_ERROR = 2048 # True if the EKF has detected bad accelerometer data enums['ESTIMATOR_STATUS_FLAGS'][2048] = EnumEntry('ESTIMATOR_ACCEL_ERROR', '''True if the EKF has detected bad accelerometer data''') ESTIMATOR_STATUS_FLAGS_ENUM_END = 2049 # enums['ESTIMATOR_STATUS_FLAGS'][2049] = EnumEntry('ESTIMATOR_STATUS_FLAGS_ENUM_END', '''''') # MOTOR_TEST_ORDER enums['MOTOR_TEST_ORDER'] = {} MOTOR_TEST_ORDER_DEFAULT = 0 # default autopilot motor test method enums['MOTOR_TEST_ORDER'][0] = EnumEntry('MOTOR_TEST_ORDER_DEFAULT', '''default autopilot motor test method''') MOTOR_TEST_ORDER_SEQUENCE = 1 # motor numbers are specified as their index in a predefined vehicle- # specific sequence enums['MOTOR_TEST_ORDER'][1] = EnumEntry('MOTOR_TEST_ORDER_SEQUENCE', '''motor numbers are specified as their index in a predefined vehicle-specific sequence''') MOTOR_TEST_ORDER_BOARD = 2 # motor numbers are specified as the output as labeled on the board enums['MOTOR_TEST_ORDER'][2] = EnumEntry('MOTOR_TEST_ORDER_BOARD', '''motor numbers are specified as the output as labeled on the board''') MOTOR_TEST_ORDER_ENUM_END = 3 # enums['MOTOR_TEST_ORDER'][3] = EnumEntry('MOTOR_TEST_ORDER_ENUM_END', '''''') # MOTOR_TEST_THROTTLE_TYPE enums['MOTOR_TEST_THROTTLE_TYPE'] = {} MOTOR_TEST_THROTTLE_PERCENT = 0 # throttle as a percentage from 0 ~ 100 enums['MOTOR_TEST_THROTTLE_TYPE'][0] = EnumEntry('MOTOR_TEST_THROTTLE_PERCENT', '''throttle as a percentage from 0 ~ 100''') MOTOR_TEST_THROTTLE_PWM = 1 # throttle as an absolute PWM value (normally in range of 1000~2000) enums['MOTOR_TEST_THROTTLE_TYPE'][1] = EnumEntry('MOTOR_TEST_THROTTLE_PWM', '''throttle as an absolute PWM value (normally in range of 1000~2000)''') MOTOR_TEST_THROTTLE_PILOT = 2 # throttle pass-through from pilot's transmitter enums['MOTOR_TEST_THROTTLE_TYPE'][2] = EnumEntry('MOTOR_TEST_THROTTLE_PILOT', '''throttle pass-through from pilot's transmitter''') MOTOR_TEST_COMPASS_CAL = 3 # per-motor compass calibration test enums['MOTOR_TEST_THROTTLE_TYPE'][3] = EnumEntry('MOTOR_TEST_COMPASS_CAL', '''per-motor compass calibration test''') MOTOR_TEST_THROTTLE_TYPE_ENUM_END = 4 # enums['MOTOR_TEST_THROTTLE_TYPE'][4] = EnumEntry('MOTOR_TEST_THROTTLE_TYPE_ENUM_END', '''''') # GPS_INPUT_IGNORE_FLAGS enums['GPS_INPUT_IGNORE_FLAGS'] = {} GPS_INPUT_IGNORE_FLAG_ALT = 1 # ignore altitude field enums['GPS_INPUT_IGNORE_FLAGS'][1] = EnumEntry('GPS_INPUT_IGNORE_FLAG_ALT', '''ignore altitude field''') GPS_INPUT_IGNORE_FLAG_HDOP = 2 # ignore hdop field enums['GPS_INPUT_IGNORE_FLAGS'][2] = EnumEntry('GPS_INPUT_IGNORE_FLAG_HDOP', '''ignore hdop field''') GPS_INPUT_IGNORE_FLAG_VDOP = 4 # ignore vdop field enums['GPS_INPUT_IGNORE_FLAGS'][4] = EnumEntry('GPS_INPUT_IGNORE_FLAG_VDOP', '''ignore vdop field''') GPS_INPUT_IGNORE_FLAG_VEL_HORIZ = 8 # ignore horizontal velocity field (vn and ve) enums['GPS_INPUT_IGNORE_FLAGS'][8] = EnumEntry('GPS_INPUT_IGNORE_FLAG_VEL_HORIZ', '''ignore horizontal velocity field (vn and ve)''') GPS_INPUT_IGNORE_FLAG_VEL_VERT = 16 # ignore vertical velocity field (vd) enums['GPS_INPUT_IGNORE_FLAGS'][16] = EnumEntry('GPS_INPUT_IGNORE_FLAG_VEL_VERT', '''ignore vertical velocity field (vd)''') GPS_INPUT_IGNORE_FLAG_SPEED_ACCURACY = 32 # ignore speed accuracy field enums['GPS_INPUT_IGNORE_FLAGS'][32] = EnumEntry('GPS_INPUT_IGNORE_FLAG_SPEED_ACCURACY', '''ignore speed accuracy field''') GPS_INPUT_IGNORE_FLAG_HORIZONTAL_ACCURACY = 64 # ignore horizontal accuracy field enums['GPS_INPUT_IGNORE_FLAGS'][64] = EnumEntry('GPS_INPUT_IGNORE_FLAG_HORIZONTAL_ACCURACY', '''ignore horizontal accuracy field''') GPS_INPUT_IGNORE_FLAG_VERTICAL_ACCURACY = 128 # ignore vertical accuracy field enums['GPS_INPUT_IGNORE_FLAGS'][128] = EnumEntry('GPS_INPUT_IGNORE_FLAG_VERTICAL_ACCURACY', '''ignore vertical accuracy field''') GPS_INPUT_IGNORE_FLAGS_ENUM_END = 129 # enums['GPS_INPUT_IGNORE_FLAGS'][129] = EnumEntry('GPS_INPUT_IGNORE_FLAGS_ENUM_END', '''''') # MAV_COLLISION_ACTION enums['MAV_COLLISION_ACTION'] = {} MAV_COLLISION_ACTION_NONE = 0 # Ignore any potential collisions enums['MAV_COLLISION_ACTION'][0] = EnumEntry('MAV_COLLISION_ACTION_NONE', '''Ignore any potential collisions''') MAV_COLLISION_ACTION_REPORT = 1 # Report potential collision enums['MAV_COLLISION_ACTION'][1] = EnumEntry('MAV_COLLISION_ACTION_REPORT', '''Report potential collision''') MAV_COLLISION_ACTION_ASCEND_OR_DESCEND = 2 # Ascend or Descend to avoid threat enums['MAV_COLLISION_ACTION'][2] = EnumEntry('MAV_COLLISION_ACTION_ASCEND_OR_DESCEND', '''Ascend or Descend to avoid threat''') MAV_COLLISION_ACTION_MOVE_HORIZONTALLY = 3 # Move horizontally to avoid threat enums['MAV_COLLISION_ACTION'][3] = EnumEntry('MAV_COLLISION_ACTION_MOVE_HORIZONTALLY', '''Move horizontally to avoid threat''') MAV_COLLISION_ACTION_MOVE_PERPENDICULAR = 4 # Aircraft to move perpendicular to the collision's velocity vector enums['MAV_COLLISION_ACTION'][4] = EnumEntry('MAV_COLLISION_ACTION_MOVE_PERPENDICULAR', '''Aircraft to move perpendicular to the collision's velocity vector''') MAV_COLLISION_ACTION_RTL = 5 # Aircraft to fly directly back to its launch point enums['MAV_COLLISION_ACTION'][5] = EnumEntry('MAV_COLLISION_ACTION_RTL', '''Aircraft to fly directly back to its launch point''') MAV_COLLISION_ACTION_HOVER = 6 # Aircraft to stop in place enums['MAV_COLLISION_ACTION'][6] = EnumEntry('MAV_COLLISION_ACTION_HOVER', '''Aircraft to stop in place''') MAV_COLLISION_ACTION_ENUM_END = 7 # enums['MAV_COLLISION_ACTION'][7] = EnumEntry('MAV_COLLISION_ACTION_ENUM_END', '''''') # MAV_COLLISION_THREAT_LEVEL enums['MAV_COLLISION_THREAT_LEVEL'] = {} MAV_COLLISION_THREAT_LEVEL_NONE = 0 # Not a threat enums['MAV_COLLISION_THREAT_LEVEL'][0] = EnumEntry('MAV_COLLISION_THREAT_LEVEL_NONE', '''Not a threat''') MAV_COLLISION_THREAT_LEVEL_LOW = 1 # Craft is mildly concerned about this threat enums['MAV_COLLISION_THREAT_LEVEL'][1] = EnumEntry('MAV_COLLISION_THREAT_LEVEL_LOW', '''Craft is mildly concerned about this threat''') MAV_COLLISION_THREAT_LEVEL_HIGH = 2 # Craft is panicking, and may take actions to avoid threat enums['MAV_COLLISION_THREAT_LEVEL'][2] = EnumEntry('MAV_COLLISION_THREAT_LEVEL_HIGH', '''Craft is panicking, and may take actions to avoid threat''') MAV_COLLISION_THREAT_LEVEL_ENUM_END = 3 # enums['MAV_COLLISION_THREAT_LEVEL'][3] = EnumEntry('MAV_COLLISION_THREAT_LEVEL_ENUM_END', '''''') # MAV_COLLISION_SRC enums['MAV_COLLISION_SRC'] = {} MAV_COLLISION_SRC_ADSB = 0 # ID field references ADSB_VEHICLE packets enums['MAV_COLLISION_SRC'][0] = EnumEntry('MAV_COLLISION_SRC_ADSB', '''ID field references ADSB_VEHICLE packets''') MAV_COLLISION_SRC_MAVLINK_GPS_GLOBAL_INT = 1 # ID field references MAVLink SRC ID enums['MAV_COLLISION_SRC'][1] = EnumEntry('MAV_COLLISION_SRC_MAVLINK_GPS_GLOBAL_INT', '''ID field references MAVLink SRC ID''') MAV_COLLISION_SRC_ENUM_END = 2 # enums['MAV_COLLISION_SRC'][2] = EnumEntry('MAV_COLLISION_SRC_ENUM_END', '''''') # GPS_FIX_TYPE enums['GPS_FIX_TYPE'] = {} GPS_FIX_TYPE_NO_GPS = 0 # No GPS connected enums['GPS_FIX_TYPE'][0] = EnumEntry('GPS_FIX_TYPE_NO_GPS', '''No GPS connected''') GPS_FIX_TYPE_NO_FIX = 1 # No position information, GPS is connected enums['GPS_FIX_TYPE'][1] = EnumEntry('GPS_FIX_TYPE_NO_FIX', '''No position information, GPS is connected''') GPS_FIX_TYPE_2D_FIX = 2 # 2D position enums['GPS_FIX_TYPE'][2] = EnumEntry('GPS_FIX_TYPE_2D_FIX', '''2D position''') GPS_FIX_TYPE_3D_FIX = 3 # 3D position enums['GPS_FIX_TYPE'][3] = EnumEntry('GPS_FIX_TYPE_3D_FIX', '''3D position''') GPS_FIX_TYPE_DGPS = 4 # DGPS/SBAS aided 3D position enums['GPS_FIX_TYPE'][4] = EnumEntry('GPS_FIX_TYPE_DGPS', '''DGPS/SBAS aided 3D position''') GPS_FIX_TYPE_RTK_FLOAT = 5 # RTK float, 3D position enums['GPS_FIX_TYPE'][5] = EnumEntry('GPS_FIX_TYPE_RTK_FLOAT', '''RTK float, 3D position''') GPS_FIX_TYPE_RTK_FIXED = 6 # RTK Fixed, 3D position enums['GPS_FIX_TYPE'][6] = EnumEntry('GPS_FIX_TYPE_RTK_FIXED', '''RTK Fixed, 3D position''') GPS_FIX_TYPE_STATIC = 7 # Static fixed, typically used for base stations enums['GPS_FIX_TYPE'][7] = EnumEntry('GPS_FIX_TYPE_STATIC', '''Static fixed, typically used for base stations''') GPS_FIX_TYPE_PPP = 8 # PPP, 3D position. enums['GPS_FIX_TYPE'][8] = EnumEntry('GPS_FIX_TYPE_PPP', '''PPP, 3D position.''') GPS_FIX_TYPE_ENUM_END = 9 # enums['GPS_FIX_TYPE'][9] = EnumEntry('GPS_FIX_TYPE_ENUM_END', '''''') # RTK_BASELINE_COORDINATE_SYSTEM enums['RTK_BASELINE_COORDINATE_SYSTEM'] = {} RTK_BASELINE_COORDINATE_SYSTEM_ECEF = 0 # Earth-centered, Earth-fixed enums['RTK_BASELINE_COORDINATE_SYSTEM'][0] = EnumEntry('RTK_BASELINE_COORDINATE_SYSTEM_ECEF', '''Earth-centered, Earth-fixed''') RTK_BASELINE_COORDINATE_SYSTEM_NED = 1 # North, East, Down enums['RTK_BASELINE_COORDINATE_SYSTEM'][1] = EnumEntry('RTK_BASELINE_COORDINATE_SYSTEM_NED', '''North, East, Down''') RTK_BASELINE_COORDINATE_SYSTEM_ENUM_END = 2 # enums['RTK_BASELINE_COORDINATE_SYSTEM'][2] = EnumEntry('RTK_BASELINE_COORDINATE_SYSTEM_ENUM_END', '''''') # LANDING_TARGET_TYPE enums['LANDING_TARGET_TYPE'] = {} LANDING_TARGET_TYPE_LIGHT_BEACON = 0 # Landing target signaled by light beacon (ex: IR-LOCK) enums['LANDING_TARGET_TYPE'][0] = EnumEntry('LANDING_TARGET_TYPE_LIGHT_BEACON', '''Landing target signaled by light beacon (ex: IR-LOCK)''') LANDING_TARGET_TYPE_RADIO_BEACON = 1 # Landing target signaled by radio beacon (ex: ILS, NDB) enums['LANDING_TARGET_TYPE'][1] = EnumEntry('LANDING_TARGET_TYPE_RADIO_BEACON', '''Landing target signaled by radio beacon (ex: ILS, NDB)''') LANDING_TARGET_TYPE_VISION_FIDUCIAL = 2 # Landing target represented by a fiducial marker (ex: ARTag) enums['LANDING_TARGET_TYPE'][2] = EnumEntry('LANDING_TARGET_TYPE_VISION_FIDUCIAL', '''Landing target represented by a fiducial marker (ex: ARTag)''') LANDING_TARGET_TYPE_VISION_OTHER = 3 # Landing target represented by a pre-defined visual shape/feature (ex: # X-marker, H-marker, square) enums['LANDING_TARGET_TYPE'][3] = EnumEntry('LANDING_TARGET_TYPE_VISION_OTHER', '''Landing target represented by a pre-defined visual shape/feature (ex: X-marker, H-marker, square)''') LANDING_TARGET_TYPE_ENUM_END = 4 # enums['LANDING_TARGET_TYPE'][4] = EnumEntry('LANDING_TARGET_TYPE_ENUM_END', '''''') # VTOL_TRANSITION_HEADING enums['VTOL_TRANSITION_HEADING'] = {} VTOL_TRANSITION_HEADING_VEHICLE_DEFAULT = 0 # Respect the heading configuration of the vehicle. enums['VTOL_TRANSITION_HEADING'][0] = EnumEntry('VTOL_TRANSITION_HEADING_VEHICLE_DEFAULT', '''Respect the heading configuration of the vehicle.''') VTOL_TRANSITION_HEADING_NEXT_WAYPOINT = 1 # Use the heading pointing towards the next waypoint. enums['VTOL_TRANSITION_HEADING'][1] = EnumEntry('VTOL_TRANSITION_HEADING_NEXT_WAYPOINT', '''Use the heading pointing towards the next waypoint.''') VTOL_TRANSITION_HEADING_TAKEOFF = 2 # Use the heading on takeoff (while sitting on the ground). enums['VTOL_TRANSITION_HEADING'][2] = EnumEntry('VTOL_TRANSITION_HEADING_TAKEOFF', '''Use the heading on takeoff (while sitting on the ground).''') VTOL_TRANSITION_HEADING_SPECIFIED = 3 # Use the specified heading in parameter 4. enums['VTOL_TRANSITION_HEADING'][3] = EnumEntry('VTOL_TRANSITION_HEADING_SPECIFIED', '''Use the specified heading in parameter 4.''') VTOL_TRANSITION_HEADING_ANY = 4 # Use the current heading when reaching takeoff altitude (potentially # facing the wind when weather-vaning is # active). enums['VTOL_TRANSITION_HEADING'][4] = EnumEntry('VTOL_TRANSITION_HEADING_ANY', '''Use the current heading when reaching takeoff altitude (potentially facing the wind when weather-vaning is active).''') VTOL_TRANSITION_HEADING_ENUM_END = 5 # enums['VTOL_TRANSITION_HEADING'][5] = EnumEntry('VTOL_TRANSITION_HEADING_ENUM_END', '''''') # CAMERA_CAP_FLAGS enums['CAMERA_CAP_FLAGS'] = {} CAMERA_CAP_FLAGS_CAPTURE_VIDEO = 1 # Camera is able to record video enums['CAMERA_CAP_FLAGS'][1] = EnumEntry('CAMERA_CAP_FLAGS_CAPTURE_VIDEO', '''Camera is able to record video''') CAMERA_CAP_FLAGS_CAPTURE_IMAGE = 2 # Camera is able to capture images enums['CAMERA_CAP_FLAGS'][2] = EnumEntry('CAMERA_CAP_FLAGS_CAPTURE_IMAGE', '''Camera is able to capture images''') CAMERA_CAP_FLAGS_HAS_MODES = 4 # Camera has separate Video and Image/Photo modes # (MAV_CMD_SET_CAMERA_MODE) enums['CAMERA_CAP_FLAGS'][4] = EnumEntry('CAMERA_CAP_FLAGS_HAS_MODES', '''Camera has separate Video and Image/Photo modes (MAV_CMD_SET_CAMERA_MODE)''') CAMERA_CAP_FLAGS_CAN_CAPTURE_IMAGE_IN_VIDEO_MODE = 8 # Camera can capture images while in video mode enums['CAMERA_CAP_FLAGS'][8] = EnumEntry('CAMERA_CAP_FLAGS_CAN_CAPTURE_IMAGE_IN_VIDEO_MODE', '''Camera can capture images while in video mode''') CAMERA_CAP_FLAGS_CAN_CAPTURE_VIDEO_IN_IMAGE_MODE = 16 # Camera can capture videos while in Photo/Image mode enums['CAMERA_CAP_FLAGS'][16] = EnumEntry('CAMERA_CAP_FLAGS_CAN_CAPTURE_VIDEO_IN_IMAGE_MODE', '''Camera can capture videos while in Photo/Image mode''') CAMERA_CAP_FLAGS_HAS_IMAGE_SURVEY_MODE = 32 # Camera has image survey mode (MAV_CMD_SET_CAMERA_MODE) enums['CAMERA_CAP_FLAGS'][32] = EnumEntry('CAMERA_CAP_FLAGS_HAS_IMAGE_SURVEY_MODE', '''Camera has image survey mode (MAV_CMD_SET_CAMERA_MODE)''') CAMERA_CAP_FLAGS_HAS_BASIC_ZOOM = 64 # Camera has basic zoom control (MAV_CMD_SET_CAMERA_ZOOM) enums['CAMERA_CAP_FLAGS'][64] = EnumEntry('CAMERA_CAP_FLAGS_HAS_BASIC_ZOOM', '''Camera has basic zoom control (MAV_CMD_SET_CAMERA_ZOOM)''') CAMERA_CAP_FLAGS_HAS_BASIC_FOCUS = 128 # Camera has basic focus control (MAV_CMD_SET_CAMERA_FOCUS) enums['CAMERA_CAP_FLAGS'][128] = EnumEntry('CAMERA_CAP_FLAGS_HAS_BASIC_FOCUS', '''Camera has basic focus control (MAV_CMD_SET_CAMERA_FOCUS)''') CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM = 256 # Camera has video streaming capabilities (use # MAV_CMD_REQUEST_VIDEO_STREAM_INFORMATION for # video streaming info) enums['CAMERA_CAP_FLAGS'][256] = EnumEntry('CAMERA_CAP_FLAGS_HAS_VIDEO_STREAM', '''Camera has video streaming capabilities (use MAV_CMD_REQUEST_VIDEO_STREAM_INFORMATION for video streaming info)''') CAMERA_CAP_FLAGS_ENUM_END = 257 # enums['CAMERA_CAP_FLAGS'][257] = EnumEntry('CAMERA_CAP_FLAGS_ENUM_END', '''''') # CAMERA_MODE enums['CAMERA_MODE'] = {} CAMERA_MODE_IMAGE = 0 # Camera is in image/photo capture mode. enums['CAMERA_MODE'][0] = EnumEntry('CAMERA_MODE_IMAGE', '''Camera is in image/photo capture mode.''') CAMERA_MODE_VIDEO = 1 # Camera is in video capture mode. enums['CAMERA_MODE'][1] = EnumEntry('CAMERA_MODE_VIDEO', '''Camera is in video capture mode.''') CAMERA_MODE_IMAGE_SURVEY = 2 # Camera is in image survey capture mode. It allows for camera # controller to do specific settings for # surveys. enums['CAMERA_MODE'][2] = EnumEntry('CAMERA_MODE_IMAGE_SURVEY', '''Camera is in image survey capture mode. It allows for camera controller to do specific settings for surveys.''') CAMERA_MODE_ENUM_END = 3 # enums['CAMERA_MODE'][3] = EnumEntry('CAMERA_MODE_ENUM_END', '''''') # MAV_ARM_AUTH_DENIED_REASON enums['MAV_ARM_AUTH_DENIED_REASON'] = {} MAV_ARM_AUTH_DENIED_REASON_GENERIC = 0 # Not a specific reason enums['MAV_ARM_AUTH_DENIED_REASON'][0] = EnumEntry('MAV_ARM_AUTH_DENIED_REASON_GENERIC', '''Not a specific reason''') MAV_ARM_AUTH_DENIED_REASON_NONE = 1 # Authorizer will send the error as string to GCS enums['MAV_ARM_AUTH_DENIED_REASON'][1] = EnumEntry('MAV_ARM_AUTH_DENIED_REASON_NONE', '''Authorizer will send the error as string to GCS''') MAV_ARM_AUTH_DENIED_REASON_INVALID_WAYPOINT = 2 # At least one waypoint have a invalid value enums['MAV_ARM_AUTH_DENIED_REASON'][2] = EnumEntry('MAV_ARM_AUTH_DENIED_REASON_INVALID_WAYPOINT', '''At least one waypoint have a invalid value''') MAV_ARM_AUTH_DENIED_REASON_TIMEOUT = 3 # Timeout in the authorizer process(in case it depends on network) enums['MAV_ARM_AUTH_DENIED_REASON'][3] = EnumEntry('MAV_ARM_AUTH_DENIED_REASON_TIMEOUT', '''Timeout in the authorizer process(in case it depends on network)''') MAV_ARM_AUTH_DENIED_REASON_AIRSPACE_IN_USE = 4 # Airspace of the mission in use by another vehicle, second result # parameter can have the waypoint id that # caused it to be denied. enums['MAV_ARM_AUTH_DENIED_REASON'][4] = EnumEntry('MAV_ARM_AUTH_DENIED_REASON_AIRSPACE_IN_USE', '''Airspace of the mission in use by another vehicle, second result parameter can have the waypoint id that caused it to be denied.''') MAV_ARM_AUTH_DENIED_REASON_BAD_WEATHER = 5 # Weather is not good to fly enums['MAV_ARM_AUTH_DENIED_REASON'][5] = EnumEntry('MAV_ARM_AUTH_DENIED_REASON_BAD_WEATHER', '''Weather is not good to fly''') MAV_ARM_AUTH_DENIED_REASON_ENUM_END = 6 # enums['MAV_ARM_AUTH_DENIED_REASON'][6] = EnumEntry('MAV_ARM_AUTH_DENIED_REASON_ENUM_END', '''''') # RC_TYPE enums['RC_TYPE'] = {} RC_TYPE_SPEKTRUM_DSM2 = 0 # Spektrum DSM2 enums['RC_TYPE'][0] = EnumEntry('RC_TYPE_SPEKTRUM_DSM2', '''Spektrum DSM2''') RC_TYPE_SPEKTRUM_DSMX = 1 # Spektrum DSMX enums['RC_TYPE'][1] = EnumEntry('RC_TYPE_SPEKTRUM_DSMX', '''Spektrum DSMX''') RC_TYPE_ENUM_END = 2 # enums['RC_TYPE'][2] = EnumEntry('RC_TYPE_ENUM_END', '''''') # POSITION_TARGET_TYPEMASK enums['POSITION_TARGET_TYPEMASK'] = {} POSITION_TARGET_TYPEMASK_X_IGNORE = 1 # Ignore position x enums['POSITION_TARGET_TYPEMASK'][1] = EnumEntry('POSITION_TARGET_TYPEMASK_X_IGNORE', '''Ignore position x''') POSITION_TARGET_TYPEMASK_Y_IGNORE = 2 # Ignore position y enums['POSITION_TARGET_TYPEMASK'][2] = EnumEntry('POSITION_TARGET_TYPEMASK_Y_IGNORE', '''Ignore position y''') POSITION_TARGET_TYPEMASK_Z_IGNORE = 4 # Ignore position z enums['POSITION_TARGET_TYPEMASK'][4] = EnumEntry('POSITION_TARGET_TYPEMASK_Z_IGNORE', '''Ignore position z''') POSITION_TARGET_TYPEMASK_VX_IGNORE = 8 # Ignore velocity x enums['POSITION_TARGET_TYPEMASK'][8] = EnumEntry('POSITION_TARGET_TYPEMASK_VX_IGNORE', '''Ignore velocity x''') POSITION_TARGET_TYPEMASK_VY_IGNORE = 16 # Ignore velocity y enums['POSITION_TARGET_TYPEMASK'][16] = EnumEntry('POSITION_TARGET_TYPEMASK_VY_IGNORE', '''Ignore velocity y''') POSITION_TARGET_TYPEMASK_VZ_IGNORE = 32 # Ignore velocity z enums['POSITION_TARGET_TYPEMASK'][32] = EnumEntry('POSITION_TARGET_TYPEMASK_VZ_IGNORE', '''Ignore velocity z''') POSITION_TARGET_TYPEMASK_AX_IGNORE = 64 # Ignore acceleration x enums['POSITION_TARGET_TYPEMASK'][64] = EnumEntry('POSITION_TARGET_TYPEMASK_AX_IGNORE', '''Ignore acceleration x''') POSITION_TARGET_TYPEMASK_AY_IGNORE = 128 # Ignore acceleration y enums['POSITION_TARGET_TYPEMASK'][128] = EnumEntry('POSITION_TARGET_TYPEMASK_AY_IGNORE', '''Ignore acceleration y''') POSITION_TARGET_TYPEMASK_AZ_IGNORE = 256 # Ignore acceleration z enums['POSITION_TARGET_TYPEMASK'][256] = EnumEntry('POSITION_TARGET_TYPEMASK_AZ_IGNORE', '''Ignore acceleration z''') POSITION_TARGET_TYPEMASK_FORCE_SET = 512 # Use force instead of acceleration enums['POSITION_TARGET_TYPEMASK'][512] = EnumEntry('POSITION_TARGET_TYPEMASK_FORCE_SET', '''Use force instead of acceleration''') POSITION_TARGET_TYPEMASK_YAW_IGNORE = 1024 # Ignore yaw enums['POSITION_TARGET_TYPEMASK'][1024] = EnumEntry('POSITION_TARGET_TYPEMASK_YAW_IGNORE', '''Ignore yaw''') POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE = 2048 # Ignore yaw rate enums['POSITION_TARGET_TYPEMASK'][2048] = EnumEntry('POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE', '''Ignore yaw rate''') POSITION_TARGET_TYPEMASK_ENUM_END = 2049 # enums['POSITION_TARGET_TYPEMASK'][2049] = EnumEntry('POSITION_TARGET_TYPEMASK_ENUM_END', '''''') # PRECISION_LAND_MODE enums['PRECISION_LAND_MODE'] = {} PRECISION_LAND_MODE_DISABLED = 0 # Normal (non-precision) landing. enums['PRECISION_LAND_MODE'][0] = EnumEntry('PRECISION_LAND_MODE_DISABLED', '''Normal (non-precision) landing.''') PRECISION_LAND_MODE_OPPORTUNISTIC = 1 # Use precision landing if beacon detected when land command accepted, # otherwise land normally. enums['PRECISION_LAND_MODE'][1] = EnumEntry('PRECISION_LAND_MODE_OPPORTUNISTIC', '''Use precision landing if beacon detected when land command accepted, otherwise land normally.''') PRECISION_LAND_MODE_REQUIRED = 2 # Use precision landing, searching for beacon if not found when land # command accepted (land normally if beacon # cannot be found). enums['PRECISION_LAND_MODE'][2] = EnumEntry('PRECISION_LAND_MODE_REQUIRED', '''Use precision landing, searching for beacon if not found when land command accepted (land normally if beacon cannot be found).''') PRECISION_LAND_MODE_ENUM_END = 3 # enums['PRECISION_LAND_MODE'][3] = EnumEntry('PRECISION_LAND_MODE_ENUM_END', '''''') # PARACHUTE_ACTION enums['PARACHUTE_ACTION'] = {} PARACHUTE_DISABLE = 0 # Disable parachute release. enums['PARACHUTE_ACTION'][0] = EnumEntry('PARACHUTE_DISABLE', '''Disable parachute release.''') PARACHUTE_ENABLE = 1 # Enable parachute release. enums['PARACHUTE_ACTION'][1] = EnumEntry('PARACHUTE_ENABLE', '''Enable parachute release.''') PARACHUTE_RELEASE = 2 # Release parachute. enums['PARACHUTE_ACTION'][2] = EnumEntry('PARACHUTE_RELEASE', '''Release parachute.''') PARACHUTE_ACTION_ENUM_END = 3 # enums['PARACHUTE_ACTION'][3] = EnumEntry('PARACHUTE_ACTION_ENUM_END', '''''') # message IDs MAVLINK_MSG_ID_BAD_DATA = -1 MAVLINK_MSG_ID_SCRIPT_ITEM = 180 MAVLINK_MSG_ID_SCRIPT_REQUEST = 181 MAVLINK_MSG_ID_SCRIPT_REQUEST_LIST = 182 MAVLINK_MSG_ID_SCRIPT_COUNT = 183 MAVLINK_MSG_ID_SCRIPT_CURRENT = 184 MAVLINK_MSG_ID_HEARTBEAT = 0 MAVLINK_MSG_ID_SYS_STATUS = 1 MAVLINK_MSG_ID_SYSTEM_TIME = 2 MAVLINK_MSG_ID_PING = 4 MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL = 5 MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL_ACK = 6 MAVLINK_MSG_ID_AUTH_KEY = 7 MAVLINK_MSG_ID_SET_MODE = 11 MAVLINK_MSG_ID_PARAM_REQUEST_READ = 20 MAVLINK_MSG_ID_PARAM_REQUEST_LIST = 21 MAVLINK_MSG_ID_PARAM_VALUE = 22 MAVLINK_MSG_ID_PARAM_SET = 23 MAVLINK_MSG_ID_GPS_RAW_INT = 24 MAVLINK_MSG_ID_GPS_STATUS = 25 MAVLINK_MSG_ID_SCALED_IMU = 26 MAVLINK_MSG_ID_RAW_IMU = 27 MAVLINK_MSG_ID_RAW_PRESSURE = 28 MAVLINK_MSG_ID_SCALED_PRESSURE = 29 MAVLINK_MSG_ID_ATTITUDE = 30 MAVLINK_MSG_ID_ATTITUDE_QUATERNION = 31 MAVLINK_MSG_ID_LOCAL_POSITION_NED = 32 MAVLINK_MSG_ID_GLOBAL_POSITION_INT = 33 MAVLINK_MSG_ID_RC_CHANNELS_SCALED = 34 MAVLINK_MSG_ID_RC_CHANNELS_RAW = 35 MAVLINK_MSG_ID_SERVO_OUTPUT_RAW = 36 MAVLINK_MSG_ID_MISSION_REQUEST_PARTIAL_LIST = 37 MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST = 38 MAVLINK_MSG_ID_MISSION_ITEM = 39 MAVLINK_MSG_ID_MISSION_REQUEST = 40 MAVLINK_MSG_ID_MISSION_SET_CURRENT = 41 MAVLINK_MSG_ID_MISSION_CURRENT = 42 MAVLINK_MSG_ID_MISSION_REQUEST_LIST = 43 MAVLINK_MSG_ID_MISSION_COUNT = 44 MAVLINK_MSG_ID_MISSION_CLEAR_ALL = 45 MAVLINK_MSG_ID_MISSION_ITEM_REACHED = 46 MAVLINK_MSG_ID_MISSION_ACK = 47 MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN = 48 MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN = 49 MAVLINK_MSG_ID_PARAM_MAP_RC = 50 MAVLINK_MSG_ID_MISSION_REQUEST_INT = 51 MAVLINK_MSG_ID_SAFETY_SET_ALLOWED_AREA = 54 MAVLINK_MSG_ID_SAFETY_ALLOWED_AREA = 55 MAVLINK_MSG_ID_ATTITUDE_QUATERNION_COV = 61 MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT = 62 MAVLINK_MSG_ID_GLOBAL_POSITION_INT_COV = 63 MAVLINK_MSG_ID_LOCAL_POSITION_NED_COV = 64 MAVLINK_MSG_ID_RC_CHANNELS = 65 MAVLINK_MSG_ID_REQUEST_DATA_STREAM = 66 MAVLINK_MSG_ID_DATA_STREAM = 67 MAVLINK_MSG_ID_MANUAL_CONTROL = 69 MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE = 70 MAVLINK_MSG_ID_MISSION_ITEM_INT = 73 MAVLINK_MSG_ID_VFR_HUD = 74 MAVLINK_MSG_ID_COMMAND_INT = 75 MAVLINK_MSG_ID_COMMAND_LONG = 76 MAVLINK_MSG_ID_COMMAND_ACK = 77 MAVLINK_MSG_ID_MANUAL_SETPOINT = 81 MAVLINK_MSG_ID_SET_ATTITUDE_TARGET = 82 MAVLINK_MSG_ID_ATTITUDE_TARGET = 83 MAVLINK_MSG_ID_SET_POSITION_TARGET_LOCAL_NED = 84 MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED = 85 MAVLINK_MSG_ID_SET_POSITION_TARGET_GLOBAL_INT = 86 MAVLINK_MSG_ID_POSITION_TARGET_GLOBAL_INT = 87 MAVLINK_MSG_ID_LOCAL_POSITION_NED_SYSTEM_GLOBAL_OFFSET = 89 MAVLINK_MSG_ID_HIL_STATE = 90 MAVLINK_MSG_ID_HIL_CONTROLS = 91 MAVLINK_MSG_ID_HIL_RC_INPUTS_RAW = 92 MAVLINK_MSG_ID_HIL_ACTUATOR_CONTROLS = 93 MAVLINK_MSG_ID_OPTICAL_FLOW = 100 MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE = 101 MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE = 102 MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE = 103 MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE = 104 MAVLINK_MSG_ID_HIGHRES_IMU = 105 MAVLINK_MSG_ID_OPTICAL_FLOW_RAD = 106 MAVLINK_MSG_ID_HIL_SENSOR = 107 MAVLINK_MSG_ID_SIM_STATE = 108 MAVLINK_MSG_ID_RADIO_STATUS = 109 MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL = 110 MAVLINK_MSG_ID_TIMESYNC = 111 MAVLINK_MSG_ID_CAMERA_TRIGGER = 112 MAVLINK_MSG_ID_HIL_GPS = 113 MAVLINK_MSG_ID_HIL_OPTICAL_FLOW = 114 MAVLINK_MSG_ID_HIL_STATE_QUATERNION = 115 MAVLINK_MSG_ID_SCALED_IMU2 = 116 MAVLINK_MSG_ID_LOG_REQUEST_LIST = 117 MAVLINK_MSG_ID_LOG_ENTRY = 118 MAVLINK_MSG_ID_LOG_REQUEST_DATA = 119 MAVLINK_MSG_ID_LOG_DATA = 120 MAVLINK_MSG_ID_LOG_ERASE = 121 MAVLINK_MSG_ID_LOG_REQUEST_END = 122 MAVLINK_MSG_ID_GPS_INJECT_DATA = 123 MAVLINK_MSG_ID_GPS2_RAW = 124 MAVLINK_MSG_ID_POWER_STATUS = 125 MAVLINK_MSG_ID_SERIAL_CONTROL = 126 MAVLINK_MSG_ID_GPS_RTK = 127 MAVLINK_MSG_ID_GPS2_RTK = 128 MAVLINK_MSG_ID_SCALED_IMU3 = 129 MAVLINK_MSG_ID_DATA_TRANSMISSION_HANDSHAKE = 130 MAVLINK_MSG_ID_ENCAPSULATED_DATA = 131 MAVLINK_MSG_ID_DISTANCE_SENSOR = 132 MAVLINK_MSG_ID_TERRAIN_REQUEST = 133 MAVLINK_MSG_ID_TERRAIN_DATA = 134 MAVLINK_MSG_ID_TERRAIN_CHECK = 135 MAVLINK_MSG_ID_TERRAIN_REPORT = 136 MAVLINK_MSG_ID_SCALED_PRESSURE2 = 137 MAVLINK_MSG_ID_ATT_POS_MOCAP = 138 MAVLINK_MSG_ID_SET_ACTUATOR_CONTROL_TARGET = 139 MAVLINK_MSG_ID_ACTUATOR_CONTROL_TARGET = 140 MAVLINK_MSG_ID_ALTITUDE = 141 MAVLINK_MSG_ID_RESOURCE_REQUEST = 142 MAVLINK_MSG_ID_SCALED_PRESSURE3 = 143 MAVLINK_MSG_ID_FOLLOW_TARGET = 144 MAVLINK_MSG_ID_CONTROL_SYSTEM_STATE = 146 MAVLINK_MSG_ID_BATTERY_STATUS = 147 MAVLINK_MSG_ID_AUTOPILOT_VERSION = 148 MAVLINK_MSG_ID_LANDING_TARGET = 149 MAVLINK_MSG_ID_FENCE_STATUS = 162 MAVLINK_MSG_ID_ESTIMATOR_STATUS = 230 MAVLINK_MSG_ID_WIND_COV = 231 MAVLINK_MSG_ID_GPS_INPUT = 232 MAVLINK_MSG_ID_GPS_RTCM_DATA = 233 MAVLINK_MSG_ID_HIGH_LATENCY = 234 MAVLINK_MSG_ID_VIBRATION = 241 MAVLINK_MSG_ID_HOME_POSITION = 242 MAVLINK_MSG_ID_SET_HOME_POSITION = 243 MAVLINK_MSG_ID_MESSAGE_INTERVAL = 244 MAVLINK_MSG_ID_EXTENDED_SYS_STATE = 245 MAVLINK_MSG_ID_ADSB_VEHICLE = 246 MAVLINK_MSG_ID_COLLISION = 247 MAVLINK_MSG_ID_V2_EXTENSION = 248 MAVLINK_MSG_ID_MEMORY_VECT = 249 MAVLINK_MSG_ID_DEBUG_VECT = 250 MAVLINK_MSG_ID_NAMED_VALUE_FLOAT = 251 MAVLINK_MSG_ID_NAMED_VALUE_INT = 252 MAVLINK_MSG_ID_STATUSTEXT = 253 MAVLINK_MSG_ID_DEBUG = 254 MAVLINK_MSG_ID_SETUP_SIGNING = 256 MAVLINK_MSG_ID_BUTTON_CHANGE = 257 MAVLINK_MSG_ID_PLAY_TUNE = 258 MAVLINK_MSG_ID_CAMERA_INFORMATION = 259 MAVLINK_MSG_ID_CAMERA_SETTINGS = 260 MAVLINK_MSG_ID_STORAGE_INFORMATION = 261 MAVLINK_MSG_ID_CAMERA_CAPTURE_STATUS = 262 MAVLINK_MSG_ID_CAMERA_IMAGE_CAPTURED = 263 MAVLINK_MSG_ID_FLIGHT_INFORMATION = 264 MAVLINK_MSG_ID_MOUNT_ORIENTATION = 265 MAVLINK_MSG_ID_LOGGING_DATA = 266 MAVLINK_MSG_ID_LOGGING_DATA_ACKED = 267 MAVLINK_MSG_ID_LOGGING_ACK = 268 MAVLINK_MSG_ID_WIFI_CONFIG_AP = 299 MAVLINK_MSG_ID_UAVCAN_NODE_STATUS = 310 MAVLINK_MSG_ID_UAVCAN_NODE_INFO = 311 MAVLINK_MSG_ID_OBSTACLE_DISTANCE = 330 MAVLINK_MSG_ID_ODOMETRY = 331 MAVLINK_MSG_ID_ISBD_LINK_STATUS = 335 MAVLINK_MSG_ID_DEBUG_FLOAT_ARRAY = 350 MAVLINK_MSG_ID_STATUSTEXT_LONG = 365 MAVLINK_MSG_ID_ACTUATOR_OUTPUT_STATUS = 375 MAVLINK_MSG_ID_WHEEL_DISTANCE = 9000 class MAVLink_script_item_message(MAVLink_message): ''' Message encoding a mission script item. This message is emitted upon a request for the next script item. ''' id = MAVLINK_MSG_ID_SCRIPT_ITEM name = 'SCRIPT_ITEM' fieldnames = ['target_system', 'target_component', 'seq', 'name'] ordered_fieldnames = ['seq', 'target_system', 'target_component', 'name'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'char'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<HBB50s' native_format = bytearray('<HBBc', 'ascii') orders = [1, 2, 0, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 50] crc_extra = 231 unpacker = struct.Struct('<HBB50s') def __init__(self, target_system, target_component, seq, name): MAVLink_message.__init__(self, MAVLink_script_item_message.id, MAVLink_script_item_message.name) self._fieldnames = MAVLink_script_item_message.fieldnames self.target_system = target_system self.target_component = target_component self.seq = seq self.name = name def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 231, struct.pack('<HBB50s', self.seq, self.target_system, self.target_component, self.name), force_mavlink1=force_mavlink1) class MAVLink_script_request_message(MAVLink_message): ''' Request script item with the sequence number seq. The response of the system to this message should be a SCRIPT_ITEM message. ''' id = MAVLINK_MSG_ID_SCRIPT_REQUEST name = 'SCRIPT_REQUEST' fieldnames = ['target_system', 'target_component', 'seq'] ordered_fieldnames = ['seq', 'target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<HBB' native_format = bytearray('<HBB', 'ascii') orders = [1, 2, 0] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 129 unpacker = struct.Struct('<HBB') def __init__(self, target_system, target_component, seq): MAVLink_message.__init__(self, MAVLink_script_request_message.id, MAVLink_script_request_message.name) self._fieldnames = MAVLink_script_request_message.fieldnames self.target_system = target_system self.target_component = target_component self.seq = seq def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 129, struct.pack('<HBB', self.seq, self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_script_request_list_message(MAVLink_message): ''' Request the overall list of mission items from the system/component. ''' id = MAVLINK_MSG_ID_SCRIPT_REQUEST_LIST name = 'SCRIPT_REQUEST_LIST' fieldnames = ['target_system', 'target_component'] ordered_fieldnames = ['target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<BB' native_format = bytearray('<BB', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 115 unpacker = struct.Struct('<BB') def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLink_script_request_list_message.id, MAVLink_script_request_list_message.name) self._fieldnames = MAVLink_script_request_list_message.fieldnames self.target_system = target_system self.target_component = target_component def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 115, struct.pack('<BB', self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_script_count_message(MAVLink_message): ''' This message is emitted as response to SCRIPT_REQUEST_LIST by the MAV to get the number of mission scripts. ''' id = MAVLINK_MSG_ID_SCRIPT_COUNT name = 'SCRIPT_COUNT' fieldnames = ['target_system', 'target_component', 'count'] ordered_fieldnames = ['count', 'target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<HBB' native_format = bytearray('<HBB', 'ascii') orders = [1, 2, 0] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 186 unpacker = struct.Struct('<HBB') def __init__(self, target_system, target_component, count): MAVLink_message.__init__(self, MAVLink_script_count_message.id, MAVLink_script_count_message.name) self._fieldnames = MAVLink_script_count_message.fieldnames self.target_system = target_system self.target_component = target_component self.count = count def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 186, struct.pack('<HBB', self.count, self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_script_current_message(MAVLink_message): ''' This message informs about the currently active SCRIPT. ''' id = MAVLINK_MSG_ID_SCRIPT_CURRENT name = 'SCRIPT_CURRENT' fieldnames = ['seq'] ordered_fieldnames = ['seq'] fieldtypes = ['uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<H' native_format = bytearray('<H', 'ascii') orders = [0] lengths = [1] array_lengths = [0] crc_extra = 40 unpacker = struct.Struct('<H') def __init__(self, seq): MAVLink_message.__init__(self, MAVLink_script_current_message.id, MAVLink_script_current_message.name) self._fieldnames = MAVLink_script_current_message.fieldnames self.seq = seq def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 40, struct.pack('<H', self.seq), force_mavlink1=force_mavlink1) class MAVLink_heartbeat_message(MAVLink_message): ''' The heartbeat message shows that a system or component is present and responding. The type and autopilot fields (along with the message component id), allow the receiving system to treat further messages from this system appropriately (e.g. by laying out the user interface based on the autopilot). This microservice is documented at https://mavlink.io/en/services/heartbeat.html ''' id = MAVLINK_MSG_ID_HEARTBEAT name = 'HEARTBEAT' fieldnames = ['type', 'autopilot', 'base_mode', 'custom_mode', 'system_status', 'mavlink_version'] ordered_fieldnames = ['custom_mode', 'type', 'autopilot', 'base_mode', 'system_status', 'mavlink_version'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint32_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {"base_mode": "bitmask"} fieldenums_by_name = {"type": "MAV_TYPE", "autopilot": "MAV_AUTOPILOT", "base_mode": "MAV_MODE_FLAG", "system_status": "MAV_STATE"} fieldunits_by_name = {} format = '<IBBBBB' native_format = bytearray('<IBBBBB', 'ascii') orders = [1, 2, 3, 0, 4, 5] lengths = [1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0] crc_extra = 50 unpacker = struct.Struct('<IBBBBB') def __init__(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version): MAVLink_message.__init__(self, MAVLink_heartbeat_message.id, MAVLink_heartbeat_message.name) self._fieldnames = MAVLink_heartbeat_message.fieldnames self.type = type self.autopilot = autopilot self.base_mode = base_mode self.custom_mode = custom_mode self.system_status = system_status self.mavlink_version = mavlink_version def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 50, struct.pack('<IBBBBB', self.custom_mode, self.type, self.autopilot, self.base_mode, self.system_status, self.mavlink_version), force_mavlink1=force_mavlink1) class MAVLink_sys_status_message(MAVLink_message): ''' The general system state. If the system is following the MAVLink standard, the system state is mainly defined by three orthogonal states/modes: The system mode, which is either LOCKED (motors shut down and locked), MANUAL (system under RC control), GUIDED (system with autonomous position control, position setpoint controlled manually) or AUTO (system guided by path/waypoint planner). The NAV_MODE defined the current flight state: LIFTOFF (often an open-loop maneuver), LANDING, WAYPOINTS or VECTOR. This represents the internal navigation state machine. The system status shows whether the system is currently active or not and if an emergency occurred. During the CRITICAL and EMERGENCY states the MAV is still considered to be active, but should start emergency procedures autonomously. After a failure occurred it should first move from active to critical to allow manual intervention and then move to emergency after a certain timeout. ''' id = MAVLINK_MSG_ID_SYS_STATUS name = 'SYS_STATUS' fieldnames = ['onboard_control_sensors_present', 'onboard_control_sensors_enabled', 'onboard_control_sensors_health', 'load', 'voltage_battery', 'current_battery', 'battery_remaining', 'drop_rate_comm', 'errors_comm', 'errors_count1', 'errors_count2', 'errors_count3', 'errors_count4'] ordered_fieldnames = ['onboard_control_sensors_present', 'onboard_control_sensors_enabled', 'onboard_control_sensors_health', 'load', 'voltage_battery', 'current_battery', 'drop_rate_comm', 'errors_comm', 'errors_count1', 'errors_count2', 'errors_count3', 'errors_count4', 'battery_remaining'] fieldtypes = ['uint32_t', 'uint32_t', 'uint32_t', 'uint16_t', 'uint16_t', 'int16_t', 'int8_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {"onboard_control_sensors_present": "bitmask", "onboard_control_sensors_enabled": "bitmask", "onboard_control_sensors_health": "bitmask"} fieldenums_by_name = {"onboard_control_sensors_present": "MAV_SYS_STATUS_SENSOR", "onboard_control_sensors_enabled": "MAV_SYS_STATUS_SENSOR", "onboard_control_sensors_health": "MAV_SYS_STATUS_SENSOR"} fieldunits_by_name = {"load": "d%", "voltage_battery": "mV", "current_battery": "cA", "battery_remaining": "%", "drop_rate_comm": "c%"} format = '<IIIHHhHHHHHHb' native_format = bytearray('<IIIHHhHHHHHHb', 'ascii') orders = [0, 1, 2, 3, 4, 5, 12, 6, 7, 8, 9, 10, 11] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 124 unpacker = struct.Struct('<IIIHHhHHHHHHb') def __init__(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4): MAVLink_message.__init__(self, MAVLink_sys_status_message.id, MAVLink_sys_status_message.name) self._fieldnames = MAVLink_sys_status_message.fieldnames self.onboard_control_sensors_present = onboard_control_sensors_present self.onboard_control_sensors_enabled = onboard_control_sensors_enabled self.onboard_control_sensors_health = onboard_control_sensors_health self.load = load self.voltage_battery = voltage_battery self.current_battery = current_battery self.battery_remaining = battery_remaining self.drop_rate_comm = drop_rate_comm self.errors_comm = errors_comm self.errors_count1 = errors_count1 self.errors_count2 = errors_count2 self.errors_count3 = errors_count3 self.errors_count4 = errors_count4 def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 124, struct.pack('<IIIHHhHHHHHHb', self.onboard_control_sensors_present, self.onboard_control_sensors_enabled, self.onboard_control_sensors_health, self.load, self.voltage_battery, self.current_battery, self.drop_rate_comm, self.errors_comm, self.errors_count1, self.errors_count2, self.errors_count3, self.errors_count4, self.battery_remaining), force_mavlink1=force_mavlink1) class MAVLink_system_time_message(MAVLink_message): ''' The system time is the time of the master clock, typically the computer clock of the main onboard computer. ''' id = MAVLINK_MSG_ID_SYSTEM_TIME name = 'SYSTEM_TIME' fieldnames = ['time_unix_usec', 'time_boot_ms'] ordered_fieldnames = ['time_unix_usec', 'time_boot_ms'] fieldtypes = ['uint64_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_unix_usec": "us", "time_boot_ms": "ms"} format = '<QI' native_format = bytearray('<QI', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 137 unpacker = struct.Struct('<QI') def __init__(self, time_unix_usec, time_boot_ms): MAVLink_message.__init__(self, MAVLink_system_time_message.id, MAVLink_system_time_message.name) self._fieldnames = MAVLink_system_time_message.fieldnames self.time_unix_usec = time_unix_usec self.time_boot_ms = time_boot_ms def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 137, struct.pack('<QI', self.time_unix_usec, self.time_boot_ms), force_mavlink1=force_mavlink1) class MAVLink_ping_message(MAVLink_message): ''' A ping message either requesting or responding to a ping. This allows to measure the system latencies, including serial port, radio modem and UDP connections. The ping microservice is documented at https://mavlink.io/en/services/ping.html ''' id = MAVLINK_MSG_ID_PING name = 'PING' fieldnames = ['time_usec', 'seq', 'target_system', 'target_component'] ordered_fieldnames = ['time_usec', 'seq', 'target_system', 'target_component'] fieldtypes = ['uint64_t', 'uint32_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<QIBB' native_format = bytearray('<QIBB', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 237 unpacker = struct.Struct('<QIBB') def __init__(self, time_usec, seq, target_system, target_component): MAVLink_message.__init__(self, MAVLink_ping_message.id, MAVLink_ping_message.name) self._fieldnames = MAVLink_ping_message.fieldnames self.time_usec = time_usec self.seq = seq self.target_system = target_system self.target_component = target_component def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 237, struct.pack('<QIBB', self.time_usec, self.seq, self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_change_operator_control_message(MAVLink_message): ''' Request to control this MAV ''' id = MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL name = 'CHANGE_OPERATOR_CONTROL' fieldnames = ['target_system', 'control_request', 'version', 'passkey'] ordered_fieldnames = ['target_system', 'control_request', 'version', 'passkey'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'char'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"version": "rad"} format = '<BBB25s' native_format = bytearray('<BBBc', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 25] crc_extra = 217 unpacker = struct.Struct('<BBB25s') def __init__(self, target_system, control_request, version, passkey): MAVLink_message.__init__(self, MAVLink_change_operator_control_message.id, MAVLink_change_operator_control_message.name) self._fieldnames = MAVLink_change_operator_control_message.fieldnames self.target_system = target_system self.control_request = control_request self.version = version self.passkey = passkey def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 217, struct.pack('<BBB25s', self.target_system, self.control_request, self.version, self.passkey), force_mavlink1=force_mavlink1) class MAVLink_change_operator_control_ack_message(MAVLink_message): ''' Accept / deny control of this MAV ''' id = MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL_ACK name = 'CHANGE_OPERATOR_CONTROL_ACK' fieldnames = ['gcs_system_id', 'control_request', 'ack'] ordered_fieldnames = ['gcs_system_id', 'control_request', 'ack'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<BBB' native_format = bytearray('<BBB', 'ascii') orders = [0, 1, 2] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 104 unpacker = struct.Struct('<BBB') def __init__(self, gcs_system_id, control_request, ack): MAVLink_message.__init__(self, MAVLink_change_operator_control_ack_message.id, MAVLink_change_operator_control_ack_message.name) self._fieldnames = MAVLink_change_operator_control_ack_message.fieldnames self.gcs_system_id = gcs_system_id self.control_request = control_request self.ack = ack def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 104, struct.pack('<BBB', self.gcs_system_id, self.control_request, self.ack), force_mavlink1=force_mavlink1) class MAVLink_auth_key_message(MAVLink_message): ''' Emit an encrypted signature / key identifying this system. PLEASE NOTE: This protocol has been kept simple, so transmitting the key requires an encrypted channel for true safety. ''' id = MAVLINK_MSG_ID_AUTH_KEY name = 'AUTH_KEY' fieldnames = ['key'] ordered_fieldnames = ['key'] fieldtypes = ['char'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<32s' native_format = bytearray('<c', 'ascii') orders = [0] lengths = [1] array_lengths = [32] crc_extra = 119 unpacker = struct.Struct('<32s') def __init__(self, key): MAVLink_message.__init__(self, MAVLink_auth_key_message.id, MAVLink_auth_key_message.name) self._fieldnames = MAVLink_auth_key_message.fieldnames self.key = key def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 119, struct.pack('<32s', self.key), force_mavlink1=force_mavlink1) class MAVLink_set_mode_message(MAVLink_message): ''' Set the system mode, as defined by enum MAV_MODE. There is no target component id as the mode is by definition for the overall aircraft, not only for one component. ''' id = MAVLINK_MSG_ID_SET_MODE name = 'SET_MODE' fieldnames = ['target_system', 'base_mode', 'custom_mode'] ordered_fieldnames = ['custom_mode', 'target_system', 'base_mode'] fieldtypes = ['uint8_t', 'uint8_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {"base_mode": "MAV_MODE"} fieldunits_by_name = {} format = '<IBB' native_format = bytearray('<IBB', 'ascii') orders = [1, 2, 0] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 89 unpacker = struct.Struct('<IBB') def __init__(self, target_system, base_mode, custom_mode): MAVLink_message.__init__(self, MAVLink_set_mode_message.id, MAVLink_set_mode_message.name) self._fieldnames = MAVLink_set_mode_message.fieldnames self.target_system = target_system self.base_mode = base_mode self.custom_mode = custom_mode def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 89, struct.pack('<IBB', self.custom_mode, self.target_system, self.base_mode), force_mavlink1=force_mavlink1) class MAVLink_param_request_read_message(MAVLink_message): ''' Request to read the onboard parameter with the param_id string id. Onboard parameters are stored as key[const char*] -> value[float]. This allows to send a parameter to any other component (such as the GCS) without the need of previous knowledge of possible parameter names. Thus the same GCS can store different parameters for different autopilots. See also https://mavlink.io/en/services/parameter.html for a full documentation of QGroundControl and IMU code. ''' id = MAVLINK_MSG_ID_PARAM_REQUEST_READ name = 'PARAM_REQUEST_READ' fieldnames = ['target_system', 'target_component', 'param_id', 'param_index'] ordered_fieldnames = ['param_index', 'target_system', 'target_component', 'param_id'] fieldtypes = ['uint8_t', 'uint8_t', 'char', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<hBB16s' native_format = bytearray('<hBBc', 'ascii') orders = [1, 2, 3, 0] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 16] crc_extra = 214 unpacker = struct.Struct('<hBB16s') def __init__(self, target_system, target_component, param_id, param_index): MAVLink_message.__init__(self, MAVLink_param_request_read_message.id, MAVLink_param_request_read_message.name) self._fieldnames = MAVLink_param_request_read_message.fieldnames self.target_system = target_system self.target_component = target_component self.param_id = param_id self.param_index = param_index def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 214, struct.pack('<hBB16s', self.param_index, self.target_system, self.target_component, self.param_id), force_mavlink1=force_mavlink1) class MAVLink_param_request_list_message(MAVLink_message): ''' Request all parameters of this component. After this request, all parameters are emitted. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html ''' id = MAVLINK_MSG_ID_PARAM_REQUEST_LIST name = 'PARAM_REQUEST_LIST' fieldnames = ['target_system', 'target_component'] ordered_fieldnames = ['target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<BB' native_format = bytearray('<BB', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 159 unpacker = struct.Struct('<BB') def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLink_param_request_list_message.id, MAVLink_param_request_list_message.name) self._fieldnames = MAVLink_param_request_list_message.fieldnames self.target_system = target_system self.target_component = target_component def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 159, struct.pack('<BB', self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_param_value_message(MAVLink_message): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html ''' id = MAVLINK_MSG_ID_PARAM_VALUE name = 'PARAM_VALUE' fieldnames = ['param_id', 'param_value', 'param_type', 'param_count', 'param_index'] ordered_fieldnames = ['param_value', 'param_count', 'param_index', 'param_id', 'param_type'] fieldtypes = ['char', 'float', 'uint8_t', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {"param_type": "MAV_PARAM_TYPE"} fieldunits_by_name = {} format = '<fHH16sB' native_format = bytearray('<fHHcB', 'ascii') orders = [3, 0, 4, 1, 2] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 16, 0] crc_extra = 220 unpacker = struct.Struct('<fHH16sB') def __init__(self, param_id, param_value, param_type, param_count, param_index): MAVLink_message.__init__(self, MAVLink_param_value_message.id, MAVLink_param_value_message.name) self._fieldnames = MAVLink_param_value_message.fieldnames self.param_id = param_id self.param_value = param_value self.param_type = param_type self.param_count = param_count self.param_index = param_index def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 220, struct.pack('<fHH16sB', self.param_value, self.param_count, self.param_index, self.param_id, self.param_type), force_mavlink1=force_mavlink1) class MAVLink_param_set_message(MAVLink_message): ''' Set a parameter value (write new value to permanent storage). IMPORTANT: The receiving component should acknowledge the new parameter value by sending a PARAM_VALUE message to all communication partners. This will also ensure that multiple GCS all have an up-to-date list of all parameters. If the sending GCS did not receive a PARAM_VALUE message within its timeout time, it should re-send the PARAM_SET message. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html ''' id = MAVLINK_MSG_ID_PARAM_SET name = 'PARAM_SET' fieldnames = ['target_system', 'target_component', 'param_id', 'param_value', 'param_type'] ordered_fieldnames = ['param_value', 'target_system', 'target_component', 'param_id', 'param_type'] fieldtypes = ['uint8_t', 'uint8_t', 'char', 'float', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"param_type": "MAV_PARAM_TYPE"} fieldunits_by_name = {} format = '<fBB16sB' native_format = bytearray('<fBBcB', 'ascii') orders = [1, 2, 3, 0, 4] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 16, 0] crc_extra = 168 unpacker = struct.Struct('<fBB16sB') def __init__(self, target_system, target_component, param_id, param_value, param_type): MAVLink_message.__init__(self, MAVLink_param_set_message.id, MAVLink_param_set_message.name) self._fieldnames = MAVLink_param_set_message.fieldnames self.target_system = target_system self.target_component = target_component self.param_id = param_id self.param_value = param_value self.param_type = param_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 168, struct.pack('<fBB16sB', self.param_value, self.target_system, self.target_component, self.param_id, self.param_type), force_mavlink1=force_mavlink1) class MAVLink_gps_raw_int_message(MAVLink_message): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the system, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. ''' id = MAVLINK_MSG_ID_GPS_RAW_INT name = 'GPS_RAW_INT' fieldnames = ['time_usec', 'fix_type', 'lat', 'lon', 'alt', 'eph', 'epv', 'vel', 'cog', 'satellites_visible', 'alt_ellipsoid', 'h_acc', 'v_acc', 'vel_acc', 'hdg_acc'] ordered_fieldnames = ['time_usec', 'lat', 'lon', 'alt', 'eph', 'epv', 'vel', 'cog', 'fix_type', 'satellites_visible', 'alt_ellipsoid', 'h_acc', 'v_acc', 'vel_acc', 'hdg_acc'] fieldtypes = ['uint64_t', 'uint8_t', 'int32_t', 'int32_t', 'int32_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint8_t', 'int32_t', 'uint32_t', 'uint32_t', 'uint32_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {"fix_type": "GPS_FIX_TYPE"} fieldunits_by_name = {"time_usec": "us", "lat": "degE7", "lon": "degE7", "alt": "mm", "vel": "cm/s", "cog": "cdeg", "alt_ellipsoid": "mm", "h_acc": "mm", "v_acc": "mm", "vel_acc": "mm", "hdg_acc": "degE5"} format = '<QiiiHHHHBBiIIII' native_format = bytearray('<QiiiHHHHBBiIIII', 'ascii') orders = [0, 8, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 24 unpacker = struct.Struct('<QiiiHHHHBBiIIII') def __init__(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, alt_ellipsoid=0, h_acc=0, v_acc=0, vel_acc=0, hdg_acc=0): MAVLink_message.__init__(self, MAVLink_gps_raw_int_message.id, MAVLink_gps_raw_int_message.name) self._fieldnames = MAVLink_gps_raw_int_message.fieldnames self.time_usec = time_usec self.fix_type = fix_type self.lat = lat self.lon = lon self.alt = alt self.eph = eph self.epv = epv self.vel = vel self.cog = cog self.satellites_visible = satellites_visible self.alt_ellipsoid = alt_ellipsoid self.h_acc = h_acc self.v_acc = v_acc self.vel_acc = vel_acc self.hdg_acc = hdg_acc def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 24, struct.pack('<QiiiHHHHBBiIIII', self.time_usec, self.lat, self.lon, self.alt, self.eph, self.epv, self.vel, self.cog, self.fix_type, self.satellites_visible, self.alt_ellipsoid, self.h_acc, self.v_acc, self.vel_acc, self.hdg_acc), force_mavlink1=force_mavlink1) class MAVLink_gps_status_message(MAVLink_message): ''' The positioning status, as reported by GPS. This message is intended to display status information about each satellite visible to the receiver. See message GLOBAL_POSITION for the global position estimate. This message can contain information for up to 20 satellites. ''' id = MAVLINK_MSG_ID_GPS_STATUS name = 'GPS_STATUS' fieldnames = ['satellites_visible', 'satellite_prn', 'satellite_used', 'satellite_elevation', 'satellite_azimuth', 'satellite_snr'] ordered_fieldnames = ['satellites_visible', 'satellite_prn', 'satellite_used', 'satellite_elevation', 'satellite_azimuth', 'satellite_snr'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"satellite_elevation": "deg", "satellite_azimuth": "deg", "satellite_snr": "dB"} format = '<B20B20B20B20B20B' native_format = bytearray('<BBBBBB', 'ascii') orders = [0, 1, 2, 3, 4, 5] lengths = [1, 20, 20, 20, 20, 20] array_lengths = [0, 20, 20, 20, 20, 20] crc_extra = 23 unpacker = struct.Struct('<B20B20B20B20B20B') def __init__(self, satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr): MAVLink_message.__init__(self, MAVLink_gps_status_message.id, MAVLink_gps_status_message.name) self._fieldnames = MAVLink_gps_status_message.fieldnames self.satellites_visible = satellites_visible self.satellite_prn = satellite_prn self.satellite_used = satellite_used self.satellite_elevation = satellite_elevation self.satellite_azimuth = satellite_azimuth self.satellite_snr = satellite_snr def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 23, struct.pack('<B20B20B20B20B20B', self.satellites_visible, self.satellite_prn[0], self.satellite_prn[1], self.satellite_prn[2], self.satellite_prn[3], self.satellite_prn[4], self.satellite_prn[5], self.satellite_prn[6], self.satellite_prn[7], self.satellite_prn[8], self.satellite_prn[9], self.satellite_prn[10], self.satellite_prn[11], self.satellite_prn[12], self.satellite_prn[13], self.satellite_prn[14], self.satellite_prn[15], self.satellite_prn[16], self.satellite_prn[17], self.satellite_prn[18], self.satellite_prn[19], self.satellite_used[0], self.satellite_used[1], self.satellite_used[2], self.satellite_used[3], self.satellite_used[4], self.satellite_used[5], self.satellite_used[6], self.satellite_used[7], self.satellite_used[8], self.satellite_used[9], self.satellite_used[10], self.satellite_used[11], self.satellite_used[12], self.satellite_used[13], self.satellite_used[14], self.satellite_used[15], self.satellite_used[16], self.satellite_used[17], self.satellite_used[18], self.satellite_used[19], self.satellite_elevation[0], self.satellite_elevation[1], self.satellite_elevation[2], self.satellite_elevation[3], self.satellite_elevation[4], self.satellite_elevation[5], self.satellite_elevation[6], self.satellite_elevation[7], self.satellite_elevation[8], self.satellite_elevation[9], self.satellite_elevation[10], self.satellite_elevation[11], self.satellite_elevation[12], self.satellite_elevation[13], self.satellite_elevation[14], self.satellite_elevation[15], self.satellite_elevation[16], self.satellite_elevation[17], self.satellite_elevation[18], self.satellite_elevation[19], self.satellite_azimuth[0], self.satellite_azimuth[1], self.satellite_azimuth[2], self.satellite_azimuth[3], self.satellite_azimuth[4], self.satellite_azimuth[5], self.satellite_azimuth[6], self.satellite_azimuth[7], self.satellite_azimuth[8], self.satellite_azimuth[9], self.satellite_azimuth[10], self.satellite_azimuth[11], self.satellite_azimuth[12], self.satellite_azimuth[13], self.satellite_azimuth[14], self.satellite_azimuth[15], self.satellite_azimuth[16], self.satellite_azimuth[17], self.satellite_azimuth[18], self.satellite_azimuth[19], self.satellite_snr[0], self.satellite_snr[1], self.satellite_snr[2], self.satellite_snr[3], self.satellite_snr[4], self.satellite_snr[5], self.satellite_snr[6], self.satellite_snr[7], self.satellite_snr[8], self.satellite_snr[9], self.satellite_snr[10], self.satellite_snr[11], self.satellite_snr[12], self.satellite_snr[13], self.satellite_snr[14], self.satellite_snr[15], self.satellite_snr[16], self.satellite_snr[17], self.satellite_snr[18], self.satellite_snr[19]), force_mavlink1=force_mavlink1) class MAVLink_scaled_imu_message(MAVLink_message): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units ''' id = MAVLINK_MSG_ID_SCALED_IMU name = 'SCALED_IMU' fieldnames = ['time_boot_ms', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'temperature'] ordered_fieldnames = ['time_boot_ms', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'temperature'] fieldtypes = ['uint32_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "xacc": "mG", "yacc": "mG", "zacc": "mG", "xgyro": "mrad/s", "ygyro": "mrad/s", "zgyro": "mrad/s", "xmag": "mgauss", "ymag": "mgauss", "zmag": "mgauss", "temperature": "cdegC"} format = '<Ihhhhhhhhhh' native_format = bytearray('<Ihhhhhhhhhh', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 170 unpacker = struct.Struct('<Ihhhhhhhhhh') def __init__(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0): MAVLink_message.__init__(self, MAVLink_scaled_imu_message.id, MAVLink_scaled_imu_message.name) self._fieldnames = MAVLink_scaled_imu_message.fieldnames self.time_boot_ms = time_boot_ms self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag self.temperature = temperature def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 170, struct.pack('<Ihhhhhhhhhh', self.time_boot_ms, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag, self.temperature), force_mavlink1=force_mavlink1) class MAVLink_raw_imu_message(MAVLink_message): ''' The RAW IMU readings for a 9DOF sensor, which is identified by the id (default IMU1). This message should always contain the true raw values without any scaling to allow data capture and system debugging. ''' id = MAVLINK_MSG_ID_RAW_IMU name = 'RAW_IMU' fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'id', 'temperature'] ordered_fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'id', 'temperature'] fieldtypes = ['uint64_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'uint8_t', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "temperature": "cdegC"} format = '<QhhhhhhhhhBh' native_format = bytearray('<QhhhhhhhhhBh', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 144 unpacker = struct.Struct('<QhhhhhhhhhBh') def __init__(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, id=0, temperature=0): MAVLink_message.__init__(self, MAVLink_raw_imu_message.id, MAVLink_raw_imu_message.name) self._fieldnames = MAVLink_raw_imu_message.fieldnames self.time_usec = time_usec self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag self.id = id self.temperature = temperature def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 144, struct.pack('<QhhhhhhhhhBh', self.time_usec, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag, self.id, self.temperature), force_mavlink1=force_mavlink1) class MAVLink_raw_pressure_message(MAVLink_message): ''' The RAW pressure readings for the typical setup of one absolute pressure and one differential pressure sensor. The sensor values should be the raw, UNSCALED ADC values. ''' id = MAVLINK_MSG_ID_RAW_PRESSURE name = 'RAW_PRESSURE' fieldnames = ['time_usec', 'press_abs', 'press_diff1', 'press_diff2', 'temperature'] ordered_fieldnames = ['time_usec', 'press_abs', 'press_diff1', 'press_diff2', 'temperature'] fieldtypes = ['uint64_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<Qhhhh' native_format = bytearray('<Qhhhh', 'ascii') orders = [0, 1, 2, 3, 4] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0] crc_extra = 67 unpacker = struct.Struct('<Qhhhh') def __init__(self, time_usec, press_abs, press_diff1, press_diff2, temperature): MAVLink_message.__init__(self, MAVLink_raw_pressure_message.id, MAVLink_raw_pressure_message.name) self._fieldnames = MAVLink_raw_pressure_message.fieldnames self.time_usec = time_usec self.press_abs = press_abs self.press_diff1 = press_diff1 self.press_diff2 = press_diff2 self.temperature = temperature def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 67, struct.pack('<Qhhhh', self.time_usec, self.press_abs, self.press_diff1, self.press_diff2, self.temperature), force_mavlink1=force_mavlink1) class MAVLink_scaled_pressure_message(MAVLink_message): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. ''' id = MAVLINK_MSG_ID_SCALED_PRESSURE name = 'SCALED_PRESSURE' fieldnames = ['time_boot_ms', 'press_abs', 'press_diff', 'temperature'] ordered_fieldnames = ['time_boot_ms', 'press_abs', 'press_diff', 'temperature'] fieldtypes = ['uint32_t', 'float', 'float', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "press_abs": "hPa", "press_diff": "hPa", "temperature": "cdegC"} format = '<Iffh' native_format = bytearray('<Iffh', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 115 unpacker = struct.Struct('<Iffh') def __init__(self, time_boot_ms, press_abs, press_diff, temperature): MAVLink_message.__init__(self, MAVLink_scaled_pressure_message.id, MAVLink_scaled_pressure_message.name) self._fieldnames = MAVLink_scaled_pressure_message.fieldnames self.time_boot_ms = time_boot_ms self.press_abs = press_abs self.press_diff = press_diff self.temperature = temperature def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 115, struct.pack('<Iffh', self.time_boot_ms, self.press_abs, self.press_diff, self.temperature), force_mavlink1=force_mavlink1) class MAVLink_attitude_message(MAVLink_message): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right). ''' id = MAVLINK_MSG_ID_ATTITUDE name = 'ATTITUDE' fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'rollspeed', 'pitchspeed', 'yawspeed'] ordered_fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'rollspeed', 'pitchspeed', 'yawspeed'] fieldtypes = ['uint32_t', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "roll": "rad", "pitch": "rad", "yaw": "rad", "rollspeed": "rad/s", "pitchspeed": "rad/s", "yawspeed": "rad/s"} format = '<Iffffff' native_format = bytearray('<Iffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 39 unpacker = struct.Struct('<Iffffff') def __init__(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed): MAVLink_message.__init__(self, MAVLink_attitude_message.id, MAVLink_attitude_message.name) self._fieldnames = MAVLink_attitude_message.fieldnames self.time_boot_ms = time_boot_ms self.roll = roll self.pitch = pitch self.yaw = yaw self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 39, struct.pack('<Iffffff', self.time_boot_ms, self.roll, self.pitch, self.yaw, self.rollspeed, self.pitchspeed, self.yawspeed), force_mavlink1=force_mavlink1) class MAVLink_attitude_quaternion_message(MAVLink_message): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0). ''' id = MAVLINK_MSG_ID_ATTITUDE_QUATERNION name = 'ATTITUDE_QUATERNION' fieldnames = ['time_boot_ms', 'q1', 'q2', 'q3', 'q4', 'rollspeed', 'pitchspeed', 'yawspeed'] ordered_fieldnames = ['time_boot_ms', 'q1', 'q2', 'q3', 'q4', 'rollspeed', 'pitchspeed', 'yawspeed'] fieldtypes = ['uint32_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "rollspeed": "rad/s", "pitchspeed": "rad/s", "yawspeed": "rad/s"} format = '<Ifffffff' native_format = bytearray('<Ifffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7] lengths = [1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 246 unpacker = struct.Struct('<Ifffffff') def __init__(self, time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed): MAVLink_message.__init__(self, MAVLink_attitude_quaternion_message.id, MAVLink_attitude_quaternion_message.name) self._fieldnames = MAVLink_attitude_quaternion_message.fieldnames self.time_boot_ms = time_boot_ms self.q1 = q1 self.q2 = q2 self.q3 = q3 self.q4 = q4 self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 246, struct.pack('<Ifffffff', self.time_boot_ms, self.q1, self.q2, self.q3, self.q4, self.rollspeed, self.pitchspeed, self.yawspeed), force_mavlink1=force_mavlink1) class MAVLink_local_position_ned_message(MAVLink_message): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) ''' id = MAVLINK_MSG_ID_LOCAL_POSITION_NED name = 'LOCAL_POSITION_NED' fieldnames = ['time_boot_ms', 'x', 'y', 'z', 'vx', 'vy', 'vz'] ordered_fieldnames = ['time_boot_ms', 'x', 'y', 'z', 'vx', 'vy', 'vz'] fieldtypes = ['uint32_t', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "x": "m", "y": "m", "z": "m", "vx": "m/s", "vy": "m/s", "vz": "m/s"} format = '<Iffffff' native_format = bytearray('<Iffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 185 unpacker = struct.Struct('<Iffffff') def __init__(self, time_boot_ms, x, y, z, vx, vy, vz): MAVLink_message.__init__(self, MAVLink_local_position_ned_message.id, MAVLink_local_position_ned_message.name) self._fieldnames = MAVLink_local_position_ned_message.fieldnames self.time_boot_ms = time_boot_ms self.x = x self.y = y self.z = z self.vx = vx self.vy = vy self.vz = vz def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 185, struct.pack('<Iffffff', self.time_boot_ms, self.x, self.y, self.z, self.vx, self.vy, self.vz), force_mavlink1=force_mavlink1) class MAVLink_global_position_int_message(MAVLink_message): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. ''' id = MAVLINK_MSG_ID_GLOBAL_POSITION_INT name = 'GLOBAL_POSITION_INT' fieldnames = ['time_boot_ms', 'lat', 'lon', 'alt', 'relative_alt', 'vx', 'vy', 'vz', 'hdg'] ordered_fieldnames = ['time_boot_ms', 'lat', 'lon', 'alt', 'relative_alt', 'vx', 'vy', 'vz', 'hdg'] fieldtypes = ['uint32_t', 'int32_t', 'int32_t', 'int32_t', 'int32_t', 'int16_t', 'int16_t', 'int16_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "lat": "degE7", "lon": "degE7", "alt": "mm", "relative_alt": "mm", "vx": "cm/s", "vy": "cm/s", "vz": "cm/s", "hdg": "cdeg"} format = '<IiiiihhhH' native_format = bytearray('<IiiiihhhH', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 104 unpacker = struct.Struct('<IiiiihhhH') def __init__(self, time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg): MAVLink_message.__init__(self, MAVLink_global_position_int_message.id, MAVLink_global_position_int_message.name) self._fieldnames = MAVLink_global_position_int_message.fieldnames self.time_boot_ms = time_boot_ms self.lat = lat self.lon = lon self.alt = alt self.relative_alt = relative_alt self.vx = vx self.vy = vy self.vz = vz self.hdg = hdg def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 104, struct.pack('<IiiiihhhH', self.time_boot_ms, self.lat, self.lon, self.alt, self.relative_alt, self.vx, self.vy, self.vz, self.hdg), force_mavlink1=force_mavlink1) class MAVLink_rc_channels_scaled_message(MAVLink_message): ''' The scaled values of the RC channels received: (-100%) -10000, (0%) 0, (100%) 10000. Channels that are inactive should be set to UINT16_MAX. ''' id = MAVLINK_MSG_ID_RC_CHANNELS_SCALED name = 'RC_CHANNELS_SCALED' fieldnames = ['time_boot_ms', 'port', 'chan1_scaled', 'chan2_scaled', 'chan3_scaled', 'chan4_scaled', 'chan5_scaled', 'chan6_scaled', 'chan7_scaled', 'chan8_scaled', 'rssi'] ordered_fieldnames = ['time_boot_ms', 'chan1_scaled', 'chan2_scaled', 'chan3_scaled', 'chan4_scaled', 'chan5_scaled', 'chan6_scaled', 'chan7_scaled', 'chan8_scaled', 'port', 'rssi'] fieldtypes = ['uint32_t', 'uint8_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms"} format = '<IhhhhhhhhBB' native_format = bytearray('<IhhhhhhhhBB', 'ascii') orders = [0, 9, 1, 2, 3, 4, 5, 6, 7, 8, 10] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 237 unpacker = struct.Struct('<IhhhhhhhhBB') def __init__(self, time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi): MAVLink_message.__init__(self, MAVLink_rc_channels_scaled_message.id, MAVLink_rc_channels_scaled_message.name) self._fieldnames = MAVLink_rc_channels_scaled_message.fieldnames self.time_boot_ms = time_boot_ms self.port = port self.chan1_scaled = chan1_scaled self.chan2_scaled = chan2_scaled self.chan3_scaled = chan3_scaled self.chan4_scaled = chan4_scaled self.chan5_scaled = chan5_scaled self.chan6_scaled = chan6_scaled self.chan7_scaled = chan7_scaled self.chan8_scaled = chan8_scaled self.rssi = rssi def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 237, struct.pack('<IhhhhhhhhBB', self.time_boot_ms, self.chan1_scaled, self.chan2_scaled, self.chan3_scaled, self.chan4_scaled, self.chan5_scaled, self.chan6_scaled, self.chan7_scaled, self.chan8_scaled, self.port, self.rssi), force_mavlink1=force_mavlink1) class MAVLink_rc_channels_raw_message(MAVLink_message): ''' The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. A value of UINT16_MAX implies the channel is unused. Individual receivers/transmitters might violate this specification. ''' id = MAVLINK_MSG_ID_RC_CHANNELS_RAW name = 'RC_CHANNELS_RAW' fieldnames = ['time_boot_ms', 'port', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'rssi'] ordered_fieldnames = ['time_boot_ms', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'port', 'rssi'] fieldtypes = ['uint32_t', 'uint8_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "chan1_raw": "us", "chan2_raw": "us", "chan3_raw": "us", "chan4_raw": "us", "chan5_raw": "us", "chan6_raw": "us", "chan7_raw": "us", "chan8_raw": "us"} format = '<IHHHHHHHHBB' native_format = bytearray('<IHHHHHHHHBB', 'ascii') orders = [0, 9, 1, 2, 3, 4, 5, 6, 7, 8, 10] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 244 unpacker = struct.Struct('<IHHHHHHHHBB') def __init__(self, time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi): MAVLink_message.__init__(self, MAVLink_rc_channels_raw_message.id, MAVLink_rc_channels_raw_message.name) self._fieldnames = MAVLink_rc_channels_raw_message.fieldnames self.time_boot_ms = time_boot_ms self.port = port self.chan1_raw = chan1_raw self.chan2_raw = chan2_raw self.chan3_raw = chan3_raw self.chan4_raw = chan4_raw self.chan5_raw = chan5_raw self.chan6_raw = chan6_raw self.chan7_raw = chan7_raw self.chan8_raw = chan8_raw self.rssi = rssi def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 244, struct.pack('<IHHHHHHHHBB', self.time_boot_ms, self.chan1_raw, self.chan2_raw, self.chan3_raw, self.chan4_raw, self.chan5_raw, self.chan6_raw, self.chan7_raw, self.chan8_raw, self.port, self.rssi), force_mavlink1=force_mavlink1) class MAVLink_servo_output_raw_message(MAVLink_message): ''' The RAW values of the servo outputs (for RC input from the remote, use the RC_CHANNELS messages). The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. ''' id = MAVLINK_MSG_ID_SERVO_OUTPUT_RAW name = 'SERVO_OUTPUT_RAW' fieldnames = ['time_usec', 'port', 'servo1_raw', 'servo2_raw', 'servo3_raw', 'servo4_raw', 'servo5_raw', 'servo6_raw', 'servo7_raw', 'servo8_raw', 'servo9_raw', 'servo10_raw', 'servo11_raw', 'servo12_raw', 'servo13_raw', 'servo14_raw', 'servo15_raw', 'servo16_raw'] ordered_fieldnames = ['time_usec', 'servo1_raw', 'servo2_raw', 'servo3_raw', 'servo4_raw', 'servo5_raw', 'servo6_raw', 'servo7_raw', 'servo8_raw', 'port', 'servo9_raw', 'servo10_raw', 'servo11_raw', 'servo12_raw', 'servo13_raw', 'servo14_raw', 'servo15_raw', 'servo16_raw'] fieldtypes = ['uint32_t', 'uint8_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "servo1_raw": "us", "servo2_raw": "us", "servo3_raw": "us", "servo4_raw": "us", "servo5_raw": "us", "servo6_raw": "us", "servo7_raw": "us", "servo8_raw": "us", "servo9_raw": "us", "servo10_raw": "us", "servo11_raw": "us", "servo12_raw": "us", "servo13_raw": "us", "servo14_raw": "us", "servo15_raw": "us", "servo16_raw": "us"} format = '<IHHHHHHHHBHHHHHHHH' native_format = bytearray('<IHHHHHHHHBHHHHHHHH', 'ascii') orders = [0, 9, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 222 unpacker = struct.Struct('<IHHHHHHHHBHHHHHHHH') def __init__(self, time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw, servo9_raw=0, servo10_raw=0, servo11_raw=0, servo12_raw=0, servo13_raw=0, servo14_raw=0, servo15_raw=0, servo16_raw=0): MAVLink_message.__init__(self, MAVLink_servo_output_raw_message.id, MAVLink_servo_output_raw_message.name) self._fieldnames = MAVLink_servo_output_raw_message.fieldnames self.time_usec = time_usec self.port = port self.servo1_raw = servo1_raw self.servo2_raw = servo2_raw self.servo3_raw = servo3_raw self.servo4_raw = servo4_raw self.servo5_raw = servo5_raw self.servo6_raw = servo6_raw self.servo7_raw = servo7_raw self.servo8_raw = servo8_raw self.servo9_raw = servo9_raw self.servo10_raw = servo10_raw self.servo11_raw = servo11_raw self.servo12_raw = servo12_raw self.servo13_raw = servo13_raw self.servo14_raw = servo14_raw self.servo15_raw = servo15_raw self.servo16_raw = servo16_raw def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 222, struct.pack('<IHHHHHHHHBHHHHHHHH', self.time_usec, self.servo1_raw, self.servo2_raw, self.servo3_raw, self.servo4_raw, self.servo5_raw, self.servo6_raw, self.servo7_raw, self.servo8_raw, self.port, self.servo9_raw, self.servo10_raw, self.servo11_raw, self.servo12_raw, self.servo13_raw, self.servo14_raw, self.servo15_raw, self.servo16_raw), force_mavlink1=force_mavlink1) class MAVLink_mission_request_partial_list_message(MAVLink_message): ''' Request a partial list of mission items from the system/component. https://mavlink.io/en/services/mission.html. If start and end index are the same, just send one waypoint. ''' id = MAVLINK_MSG_ID_MISSION_REQUEST_PARTIAL_LIST name = 'MISSION_REQUEST_PARTIAL_LIST' fieldnames = ['target_system', 'target_component', 'start_index', 'end_index', 'mission_type'] ordered_fieldnames = ['start_index', 'end_index', 'target_system', 'target_component', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'int16_t', 'int16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<hhBBB' native_format = bytearray('<hhBBB', 'ascii') orders = [2, 3, 0, 1, 4] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0] crc_extra = 212 unpacker = struct.Struct('<hhBBB') def __init__(self, target_system, target_component, start_index, end_index, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_request_partial_list_message.id, MAVLink_mission_request_partial_list_message.name) self._fieldnames = MAVLink_mission_request_partial_list_message.fieldnames self.target_system = target_system self.target_component = target_component self.start_index = start_index self.end_index = end_index self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 212, struct.pack('<hhBBB', self.start_index, self.end_index, self.target_system, self.target_component, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_mission_write_partial_list_message(MAVLink_message): ''' This message is sent to the MAV to write a partial list. If start index == end index, only one item will be transmitted / updated. If the start index is NOT 0 and above the current list size, this request should be REJECTED! ''' id = MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST name = 'MISSION_WRITE_PARTIAL_LIST' fieldnames = ['target_system', 'target_component', 'start_index', 'end_index', 'mission_type'] ordered_fieldnames = ['start_index', 'end_index', 'target_system', 'target_component', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'int16_t', 'int16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<hhBBB' native_format = bytearray('<hhBBB', 'ascii') orders = [2, 3, 0, 1, 4] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0] crc_extra = 9 unpacker = struct.Struct('<hhBBB') def __init__(self, target_system, target_component, start_index, end_index, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_write_partial_list_message.id, MAVLink_mission_write_partial_list_message.name) self._fieldnames = MAVLink_mission_write_partial_list_message.fieldnames self.target_system = target_system self.target_component = target_component self.start_index = start_index self.end_index = end_index self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 9, struct.pack('<hhBBB', self.start_index, self.end_index, self.target_system, self.target_component, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_mission_item_message(MAVLink_message): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also https://mavlink.io/en/services/mission.html. ''' id = MAVLINK_MSG_ID_MISSION_ITEM name = 'MISSION_ITEM' fieldnames = ['target_system', 'target_component', 'seq', 'frame', 'command', 'current', 'autocontinue', 'param1', 'param2', 'param3', 'param4', 'x', 'y', 'z', 'mission_type'] ordered_fieldnames = ['param1', 'param2', 'param3', 'param4', 'x', 'y', 'z', 'seq', 'command', 'target_system', 'target_component', 'frame', 'current', 'autocontinue', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint8_t', 'uint16_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"frame": "MAV_FRAME", "command": "MAV_CMD", "mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<fffffffHHBBBBBB' native_format = bytearray('<fffffffHHBBBBBB', 'ascii') orders = [9, 10, 7, 11, 8, 12, 13, 0, 1, 2, 3, 4, 5, 6, 14] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 254 unpacker = struct.Struct('<fffffffHHBBBBBB') def __init__(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_item_message.id, MAVLink_mission_item_message.name) self._fieldnames = MAVLink_mission_item_message.fieldnames self.target_system = target_system self.target_component = target_component self.seq = seq self.frame = frame self.command = command self.current = current self.autocontinue = autocontinue self.param1 = param1 self.param2 = param2 self.param3 = param3 self.param4 = param4 self.x = x self.y = y self.z = z self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 254, struct.pack('<fffffffHHBBBBBB', self.param1, self.param2, self.param3, self.param4, self.x, self.y, self.z, self.seq, self.command, self.target_system, self.target_component, self.frame, self.current, self.autocontinue, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_mission_request_message(MAVLink_message): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM message. https://mavlink.io/en/services/mission.html ''' id = MAVLINK_MSG_ID_MISSION_REQUEST name = 'MISSION_REQUEST' fieldnames = ['target_system', 'target_component', 'seq', 'mission_type'] ordered_fieldnames = ['seq', 'target_system', 'target_component', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<HBBB' native_format = bytearray('<HBBB', 'ascii') orders = [1, 2, 0, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 230 unpacker = struct.Struct('<HBBB') def __init__(self, target_system, target_component, seq, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_request_message.id, MAVLink_mission_request_message.name) self._fieldnames = MAVLink_mission_request_message.fieldnames self.target_system = target_system self.target_component = target_component self.seq = seq self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 230, struct.pack('<HBBB', self.seq, self.target_system, self.target_component, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_mission_set_current_message(MAVLink_message): ''' Set the mission item with sequence number seq as current item. This means that the MAV will continue to this mission item on the shortest path (not following the mission items in- between). ''' id = MAVLINK_MSG_ID_MISSION_SET_CURRENT name = 'MISSION_SET_CURRENT' fieldnames = ['target_system', 'target_component', 'seq'] ordered_fieldnames = ['seq', 'target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<HBB' native_format = bytearray('<HBB', 'ascii') orders = [1, 2, 0] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 28 unpacker = struct.Struct('<HBB') def __init__(self, target_system, target_component, seq): MAVLink_message.__init__(self, MAVLink_mission_set_current_message.id, MAVLink_mission_set_current_message.name) self._fieldnames = MAVLink_mission_set_current_message.fieldnames self.target_system = target_system self.target_component = target_component self.seq = seq def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 28, struct.pack('<HBB', self.seq, self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_mission_current_message(MAVLink_message): ''' Message that announces the sequence number of the current active mission item. The MAV will fly towards this mission item. ''' id = MAVLINK_MSG_ID_MISSION_CURRENT name = 'MISSION_CURRENT' fieldnames = ['seq'] ordered_fieldnames = ['seq'] fieldtypes = ['uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<H' native_format = bytearray('<H', 'ascii') orders = [0] lengths = [1] array_lengths = [0] crc_extra = 28 unpacker = struct.Struct('<H') def __init__(self, seq): MAVLink_message.__init__(self, MAVLink_mission_current_message.id, MAVLink_mission_current_message.name) self._fieldnames = MAVLink_mission_current_message.fieldnames self.seq = seq def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 28, struct.pack('<H', self.seq), force_mavlink1=force_mavlink1) class MAVLink_mission_request_list_message(MAVLink_message): ''' Request the overall list of mission items from the system/component. ''' id = MAVLINK_MSG_ID_MISSION_REQUEST_LIST name = 'MISSION_REQUEST_LIST' fieldnames = ['target_system', 'target_component', 'mission_type'] ordered_fieldnames = ['target_system', 'target_component', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<BBB' native_format = bytearray('<BBB', 'ascii') orders = [0, 1, 2] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 132 unpacker = struct.Struct('<BBB') def __init__(self, target_system, target_component, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_request_list_message.id, MAVLink_mission_request_list_message.name) self._fieldnames = MAVLink_mission_request_list_message.fieldnames self.target_system = target_system self.target_component = target_component self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 132, struct.pack('<BBB', self.target_system, self.target_component, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_mission_count_message(MAVLink_message): ''' This message is emitted as response to MISSION_REQUEST_LIST by the MAV and to initiate a write transaction. The GCS can then request the individual mission item based on the knowledge of the total number of waypoints. ''' id = MAVLINK_MSG_ID_MISSION_COUNT name = 'MISSION_COUNT' fieldnames = ['target_system', 'target_component', 'count', 'mission_type'] ordered_fieldnames = ['count', 'target_system', 'target_component', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<HBBB' native_format = bytearray('<HBBB', 'ascii') orders = [1, 2, 0, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 221 unpacker = struct.Struct('<HBBB') def __init__(self, target_system, target_component, count, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_count_message.id, MAVLink_mission_count_message.name) self._fieldnames = MAVLink_mission_count_message.fieldnames self.target_system = target_system self.target_component = target_component self.count = count self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 221, struct.pack('<HBBB', self.count, self.target_system, self.target_component, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_mission_clear_all_message(MAVLink_message): ''' Delete all mission items at once. ''' id = MAVLINK_MSG_ID_MISSION_CLEAR_ALL name = 'MISSION_CLEAR_ALL' fieldnames = ['target_system', 'target_component', 'mission_type'] ordered_fieldnames = ['target_system', 'target_component', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<BBB' native_format = bytearray('<BBB', 'ascii') orders = [0, 1, 2] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 232 unpacker = struct.Struct('<BBB') def __init__(self, target_system, target_component, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_clear_all_message.id, MAVLink_mission_clear_all_message.name) self._fieldnames = MAVLink_mission_clear_all_message.fieldnames self.target_system = target_system self.target_component = target_component self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 232, struct.pack('<BBB', self.target_system, self.target_component, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_mission_item_reached_message(MAVLink_message): ''' A certain mission item has been reached. The system will either hold this position (or circle on the orbit) or (if the autocontinue on the WP was set) continue to the next waypoint. ''' id = MAVLINK_MSG_ID_MISSION_ITEM_REACHED name = 'MISSION_ITEM_REACHED' fieldnames = ['seq'] ordered_fieldnames = ['seq'] fieldtypes = ['uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<H' native_format = bytearray('<H', 'ascii') orders = [0] lengths = [1] array_lengths = [0] crc_extra = 11 unpacker = struct.Struct('<H') def __init__(self, seq): MAVLink_message.__init__(self, MAVLink_mission_item_reached_message.id, MAVLink_mission_item_reached_message.name) self._fieldnames = MAVLink_mission_item_reached_message.fieldnames self.seq = seq def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 11, struct.pack('<H', self.seq), force_mavlink1=force_mavlink1) class MAVLink_mission_ack_message(MAVLink_message): ''' Acknowledgment message during waypoint handling. The type field states if this message is a positive ack (type=0) or if an error happened (type=non-zero). ''' id = MAVLINK_MSG_ID_MISSION_ACK name = 'MISSION_ACK' fieldnames = ['target_system', 'target_component', 'type', 'mission_type'] ordered_fieldnames = ['target_system', 'target_component', 'type', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"type": "MAV_MISSION_RESULT", "mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<BBBB' native_format = bytearray('<BBBB', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 153 unpacker = struct.Struct('<BBBB') def __init__(self, target_system, target_component, type, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_ack_message.id, MAVLink_mission_ack_message.name) self._fieldnames = MAVLink_mission_ack_message.fieldnames self.target_system = target_system self.target_component = target_component self.type = type self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 153, struct.pack('<BBBB', self.target_system, self.target_component, self.type, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_set_gps_global_origin_message(MAVLink_message): ''' Sets the GPS co-ordinates of the vehicle local origin (0,0,0) position. Vehicle should emit GPS_GLOBAL_ORIGIN irrespective of whether the origin is changed. This enables transform between the local coordinate frame and the global (GPS) coordinate frame, which may be necessary when (for example) indoor and outdoor settings are connected and the MAV should move from in- to outdoor. ''' id = MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN name = 'SET_GPS_GLOBAL_ORIGIN' fieldnames = ['target_system', 'latitude', 'longitude', 'altitude', 'time_usec'] ordered_fieldnames = ['latitude', 'longitude', 'altitude', 'target_system', 'time_usec'] fieldtypes = ['uint8_t', 'int32_t', 'int32_t', 'int32_t', 'uint64_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"latitude": "degE7", "longitude": "degE7", "altitude": "mm", "time_usec": "us"} format = '<iiiBQ' native_format = bytearray('<iiiBQ', 'ascii') orders = [3, 0, 1, 2, 4] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0] crc_extra = 41 unpacker = struct.Struct('<iiiBQ') def __init__(self, target_system, latitude, longitude, altitude, time_usec=0): MAVLink_message.__init__(self, MAVLink_set_gps_global_origin_message.id, MAVLink_set_gps_global_origin_message.name) self._fieldnames = MAVLink_set_gps_global_origin_message.fieldnames self.target_system = target_system self.latitude = latitude self.longitude = longitude self.altitude = altitude self.time_usec = time_usec def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 41, struct.pack('<iiiBQ', self.latitude, self.longitude, self.altitude, self.target_system, self.time_usec), force_mavlink1=force_mavlink1) class MAVLink_gps_global_origin_message(MAVLink_message): ''' Publishes the GPS co-ordinates of the vehicle local origin (0,0,0) position. Emitted whenever a new GPS-Local position mapping is requested or set - e.g. following SET_GPS_GLOBAL_ORIGIN message. ''' id = MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN name = 'GPS_GLOBAL_ORIGIN' fieldnames = ['latitude', 'longitude', 'altitude', 'time_usec'] ordered_fieldnames = ['latitude', 'longitude', 'altitude', 'time_usec'] fieldtypes = ['int32_t', 'int32_t', 'int32_t', 'uint64_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"latitude": "degE7", "longitude": "degE7", "altitude": "mm", "time_usec": "us"} format = '<iiiQ' native_format = bytearray('<iiiQ', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 39 unpacker = struct.Struct('<iiiQ') def __init__(self, latitude, longitude, altitude, time_usec=0): MAVLink_message.__init__(self, MAVLink_gps_global_origin_message.id, MAVLink_gps_global_origin_message.name) self._fieldnames = MAVLink_gps_global_origin_message.fieldnames self.latitude = latitude self.longitude = longitude self.altitude = altitude self.time_usec = time_usec def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 39, struct.pack('<iiiQ', self.latitude, self.longitude, self.altitude, self.time_usec), force_mavlink1=force_mavlink1) class MAVLink_param_map_rc_message(MAVLink_message): ''' Bind a RC channel to a parameter. The parameter should change according to the RC channel value. ''' id = MAVLINK_MSG_ID_PARAM_MAP_RC name = 'PARAM_MAP_RC' fieldnames = ['target_system', 'target_component', 'param_id', 'param_index', 'parameter_rc_channel_index', 'param_value0', 'scale', 'param_value_min', 'param_value_max'] ordered_fieldnames = ['param_value0', 'scale', 'param_value_min', 'param_value_max', 'param_index', 'target_system', 'target_component', 'param_id', 'parameter_rc_channel_index'] fieldtypes = ['uint8_t', 'uint8_t', 'char', 'int16_t', 'uint8_t', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<ffffhBB16sB' native_format = bytearray('<ffffhBBcB', 'ascii') orders = [5, 6, 7, 4, 8, 0, 1, 2, 3] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 16, 0] crc_extra = 78 unpacker = struct.Struct('<ffffhBB16sB') def __init__(self, target_system, target_component, param_id, param_index, parameter_rc_channel_index, param_value0, scale, param_value_min, param_value_max): MAVLink_message.__init__(self, MAVLink_param_map_rc_message.id, MAVLink_param_map_rc_message.name) self._fieldnames = MAVLink_param_map_rc_message.fieldnames self.target_system = target_system self.target_component = target_component self.param_id = param_id self.param_index = param_index self.parameter_rc_channel_index = parameter_rc_channel_index self.param_value0 = param_value0 self.scale = scale self.param_value_min = param_value_min self.param_value_max = param_value_max def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 78, struct.pack('<ffffhBB16sB', self.param_value0, self.scale, self.param_value_min, self.param_value_max, self.param_index, self.target_system, self.target_component, self.param_id, self.parameter_rc_channel_index), force_mavlink1=force_mavlink1) class MAVLink_mission_request_int_message(MAVLink_message): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM_INT message. https://mavlink.io/en/services/mission.html ''' id = MAVLINK_MSG_ID_MISSION_REQUEST_INT name = 'MISSION_REQUEST_INT' fieldnames = ['target_system', 'target_component', 'seq', 'mission_type'] ordered_fieldnames = ['seq', 'target_system', 'target_component', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<HBBB' native_format = bytearray('<HBBB', 'ascii') orders = [1, 2, 0, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 196 unpacker = struct.Struct('<HBBB') def __init__(self, target_system, target_component, seq, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_request_int_message.id, MAVLink_mission_request_int_message.name) self._fieldnames = MAVLink_mission_request_int_message.fieldnames self.target_system = target_system self.target_component = target_component self.seq = seq self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 196, struct.pack('<HBBB', self.seq, self.target_system, self.target_component, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_safety_set_allowed_area_message(MAVLink_message): ''' Set a safety zone (volume), which is defined by two corners of a cube. This message can be used to tell the MAV which setpoints/waypoints to accept and which to reject. Safety areas are often enforced by national or competition regulations. ''' id = MAVLINK_MSG_ID_SAFETY_SET_ALLOWED_AREA name = 'SAFETY_SET_ALLOWED_AREA' fieldnames = ['target_system', 'target_component', 'frame', 'p1x', 'p1y', 'p1z', 'p2x', 'p2y', 'p2z'] ordered_fieldnames = ['p1x', 'p1y', 'p1z', 'p2x', 'p2y', 'p2z', 'target_system', 'target_component', 'frame'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"frame": "MAV_FRAME"} fieldunits_by_name = {"p1x": "m", "p1y": "m", "p1z": "m", "p2x": "m", "p2y": "m", "p2z": "m"} format = '<ffffffBBB' native_format = bytearray('<ffffffBBB', 'ascii') orders = [6, 7, 8, 0, 1, 2, 3, 4, 5] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 15 unpacker = struct.Struct('<ffffffBBB') def __init__(self, target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z): MAVLink_message.__init__(self, MAVLink_safety_set_allowed_area_message.id, MAVLink_safety_set_allowed_area_message.name) self._fieldnames = MAVLink_safety_set_allowed_area_message.fieldnames self.target_system = target_system self.target_component = target_component self.frame = frame self.p1x = p1x self.p1y = p1y self.p1z = p1z self.p2x = p2x self.p2y = p2y self.p2z = p2z def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 15, struct.pack('<ffffffBBB', self.p1x, self.p1y, self.p1z, self.p2x, self.p2y, self.p2z, self.target_system, self.target_component, self.frame), force_mavlink1=force_mavlink1) class MAVLink_safety_allowed_area_message(MAVLink_message): ''' Read out the safety zone the MAV currently assumes. ''' id = MAVLINK_MSG_ID_SAFETY_ALLOWED_AREA name = 'SAFETY_ALLOWED_AREA' fieldnames = ['frame', 'p1x', 'p1y', 'p1z', 'p2x', 'p2y', 'p2z'] ordered_fieldnames = ['p1x', 'p1y', 'p1z', 'p2x', 'p2y', 'p2z', 'frame'] fieldtypes = ['uint8_t', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"frame": "MAV_FRAME"} fieldunits_by_name = {"p1x": "m", "p1y": "m", "p1z": "m", "p2x": "m", "p2y": "m", "p2z": "m"} format = '<ffffffB' native_format = bytearray('<ffffffB', 'ascii') orders = [6, 0, 1, 2, 3, 4, 5] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 3 unpacker = struct.Struct('<ffffffB') def __init__(self, frame, p1x, p1y, p1z, p2x, p2y, p2z): MAVLink_message.__init__(self, MAVLink_safety_allowed_area_message.id, MAVLink_safety_allowed_area_message.name) self._fieldnames = MAVLink_safety_allowed_area_message.fieldnames self.frame = frame self.p1x = p1x self.p1y = p1y self.p1z = p1z self.p2x = p2x self.p2y = p2y self.p2z = p2z def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 3, struct.pack('<ffffffB', self.p1x, self.p1y, self.p1z, self.p2x, self.p2y, self.p2z, self.frame), force_mavlink1=force_mavlink1) class MAVLink_attitude_quaternion_cov_message(MAVLink_message): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0). ''' id = MAVLINK_MSG_ID_ATTITUDE_QUATERNION_COV name = 'ATTITUDE_QUATERNION_COV' fieldnames = ['time_usec', 'q', 'rollspeed', 'pitchspeed', 'yawspeed', 'covariance'] ordered_fieldnames = ['time_usec', 'q', 'rollspeed', 'pitchspeed', 'yawspeed', 'covariance'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "rollspeed": "rad/s", "pitchspeed": "rad/s", "yawspeed": "rad/s"} format = '<Q4ffff9f' native_format = bytearray('<Qfffff', 'ascii') orders = [0, 1, 2, 3, 4, 5] lengths = [1, 4, 1, 1, 1, 9] array_lengths = [0, 4, 0, 0, 0, 9] crc_extra = 167 unpacker = struct.Struct('<Q4ffff9f') def __init__(self, time_usec, q, rollspeed, pitchspeed, yawspeed, covariance): MAVLink_message.__init__(self, MAVLink_attitude_quaternion_cov_message.id, MAVLink_attitude_quaternion_cov_message.name) self._fieldnames = MAVLink_attitude_quaternion_cov_message.fieldnames self.time_usec = time_usec self.q = q self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed self.covariance = covariance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 167, struct.pack('<Q4ffff9f', self.time_usec, self.q[0], self.q[1], self.q[2], self.q[3], self.rollspeed, self.pitchspeed, self.yawspeed, self.covariance[0], self.covariance[1], self.covariance[2], self.covariance[3], self.covariance[4], self.covariance[5], self.covariance[6], self.covariance[7], self.covariance[8]), force_mavlink1=force_mavlink1) class MAVLink_nav_controller_output_message(MAVLink_message): ''' The state of the fixed wing navigation and position controller. ''' id = MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT name = 'NAV_CONTROLLER_OUTPUT' fieldnames = ['nav_roll', 'nav_pitch', 'nav_bearing', 'target_bearing', 'wp_dist', 'alt_error', 'aspd_error', 'xtrack_error'] ordered_fieldnames = ['nav_roll', 'nav_pitch', 'alt_error', 'aspd_error', 'xtrack_error', 'nav_bearing', 'target_bearing', 'wp_dist'] fieldtypes = ['float', 'float', 'int16_t', 'int16_t', 'uint16_t', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"nav_roll": "deg", "nav_pitch": "deg", "nav_bearing": "deg", "target_bearing": "deg", "wp_dist": "m", "alt_error": "m", "aspd_error": "m/s", "xtrack_error": "m"} format = '<fffffhhH' native_format = bytearray('<fffffhhH', 'ascii') orders = [0, 1, 5, 6, 7, 2, 3, 4] lengths = [1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 183 unpacker = struct.Struct('<fffffhhH') def __init__(self, nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error): MAVLink_message.__init__(self, MAVLink_nav_controller_output_message.id, MAVLink_nav_controller_output_message.name) self._fieldnames = MAVLink_nav_controller_output_message.fieldnames self.nav_roll = nav_roll self.nav_pitch = nav_pitch self.nav_bearing = nav_bearing self.target_bearing = target_bearing self.wp_dist = wp_dist self.alt_error = alt_error self.aspd_error = aspd_error self.xtrack_error = xtrack_error def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 183, struct.pack('<fffffhhH', self.nav_roll, self.nav_pitch, self.alt_error, self.aspd_error, self.xtrack_error, self.nav_bearing, self.target_bearing, self.wp_dist), force_mavlink1=force_mavlink1) class MAVLink_global_position_int_cov_message(MAVLink_message): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. NOTE: This message is intended for onboard networks / companion computers and higher-bandwidth links and optimized for accuracy and completeness. Please use the GLOBAL_POSITION_INT message for a minimal subset. ''' id = MAVLINK_MSG_ID_GLOBAL_POSITION_INT_COV name = 'GLOBAL_POSITION_INT_COV' fieldnames = ['time_usec', 'estimator_type', 'lat', 'lon', 'alt', 'relative_alt', 'vx', 'vy', 'vz', 'covariance'] ordered_fieldnames = ['time_usec', 'lat', 'lon', 'alt', 'relative_alt', 'vx', 'vy', 'vz', 'covariance', 'estimator_type'] fieldtypes = ['uint64_t', 'uint8_t', 'int32_t', 'int32_t', 'int32_t', 'int32_t', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"estimator_type": "MAV_ESTIMATOR_TYPE"} fieldunits_by_name = {"time_usec": "us", "lat": "degE7", "lon": "degE7", "alt": "mm", "relative_alt": "mm", "vx": "m/s", "vy": "m/s", "vz": "m/s"} format = '<Qiiiifff36fB' native_format = bytearray('<QiiiiffffB', 'ascii') orders = [0, 9, 1, 2, 3, 4, 5, 6, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 36, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 36, 0] crc_extra = 119 unpacker = struct.Struct('<Qiiiifff36fB') def __init__(self, time_usec, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance): MAVLink_message.__init__(self, MAVLink_global_position_int_cov_message.id, MAVLink_global_position_int_cov_message.name) self._fieldnames = MAVLink_global_position_int_cov_message.fieldnames self.time_usec = time_usec self.estimator_type = estimator_type self.lat = lat self.lon = lon self.alt = alt self.relative_alt = relative_alt self.vx = vx self.vy = vy self.vz = vz self.covariance = covariance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 119, struct.pack('<Qiiiifff36fB', self.time_usec, self.lat, self.lon, self.alt, self.relative_alt, self.vx, self.vy, self.vz, self.covariance[0], self.covariance[1], self.covariance[2], self.covariance[3], self.covariance[4], self.covariance[5], self.covariance[6], self.covariance[7], self.covariance[8], self.covariance[9], self.covariance[10], self.covariance[11], self.covariance[12], self.covariance[13], self.covariance[14], self.covariance[15], self.covariance[16], self.covariance[17], self.covariance[18], self.covariance[19], self.covariance[20], self.covariance[21], self.covariance[22], self.covariance[23], self.covariance[24], self.covariance[25], self.covariance[26], self.covariance[27], self.covariance[28], self.covariance[29], self.covariance[30], self.covariance[31], self.covariance[32], self.covariance[33], self.covariance[34], self.covariance[35], self.estimator_type), force_mavlink1=force_mavlink1) class MAVLink_local_position_ned_cov_message(MAVLink_message): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) ''' id = MAVLINK_MSG_ID_LOCAL_POSITION_NED_COV name = 'LOCAL_POSITION_NED_COV' fieldnames = ['time_usec', 'estimator_type', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'ax', 'ay', 'az', 'covariance'] ordered_fieldnames = ['time_usec', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'ax', 'ay', 'az', 'covariance', 'estimator_type'] fieldtypes = ['uint64_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"estimator_type": "MAV_ESTIMATOR_TYPE"} fieldunits_by_name = {"time_usec": "us", "x": "m", "y": "m", "z": "m", "vx": "m/s", "vy": "m/s", "vz": "m/s", "ax": "m/s/s", "ay": "m/s/s", "az": "m/s/s"} format = '<Qfffffffff45fB' native_format = bytearray('<QffffffffffB', 'ascii') orders = [0, 11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 45, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 45, 0] crc_extra = 191 unpacker = struct.Struct('<Qfffffffff45fB') def __init__(self, time_usec, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance): MAVLink_message.__init__(self, MAVLink_local_position_ned_cov_message.id, MAVLink_local_position_ned_cov_message.name) self._fieldnames = MAVLink_local_position_ned_cov_message.fieldnames self.time_usec = time_usec self.estimator_type = estimator_type self.x = x self.y = y self.z = z self.vx = vx self.vy = vy self.vz = vz self.ax = ax self.ay = ay self.az = az self.covariance = covariance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 191, struct.pack('<Qfffffffff45fB', self.time_usec, self.x, self.y, self.z, self.vx, self.vy, self.vz, self.ax, self.ay, self.az, self.covariance[0], self.covariance[1], self.covariance[2], self.covariance[3], self.covariance[4], self.covariance[5], self.covariance[6], self.covariance[7], self.covariance[8], self.covariance[9], self.covariance[10], self.covariance[11], self.covariance[12], self.covariance[13], self.covariance[14], self.covariance[15], self.covariance[16], self.covariance[17], self.covariance[18], self.covariance[19], self.covariance[20], self.covariance[21], self.covariance[22], self.covariance[23], self.covariance[24], self.covariance[25], self.covariance[26], self.covariance[27], self.covariance[28], self.covariance[29], self.covariance[30], self.covariance[31], self.covariance[32], self.covariance[33], self.covariance[34], self.covariance[35], self.covariance[36], self.covariance[37], self.covariance[38], self.covariance[39], self.covariance[40], self.covariance[41], self.covariance[42], self.covariance[43], self.covariance[44], self.estimator_type), force_mavlink1=force_mavlink1) class MAVLink_rc_channels_message(MAVLink_message): ''' The PPM values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. A value of UINT16_MAX implies the channel is unused. Individual receivers/transmitters might violate this specification. ''' id = MAVLINK_MSG_ID_RC_CHANNELS name = 'RC_CHANNELS' fieldnames = ['time_boot_ms', 'chancount', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'chan9_raw', 'chan10_raw', 'chan11_raw', 'chan12_raw', 'chan13_raw', 'chan14_raw', 'chan15_raw', 'chan16_raw', 'chan17_raw', 'chan18_raw', 'rssi'] ordered_fieldnames = ['time_boot_ms', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'chan9_raw', 'chan10_raw', 'chan11_raw', 'chan12_raw', 'chan13_raw', 'chan14_raw', 'chan15_raw', 'chan16_raw', 'chan17_raw', 'chan18_raw', 'chancount', 'rssi'] fieldtypes = ['uint32_t', 'uint8_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "chan1_raw": "us", "chan2_raw": "us", "chan3_raw": "us", "chan4_raw": "us", "chan5_raw": "us", "chan6_raw": "us", "chan7_raw": "us", "chan8_raw": "us", "chan9_raw": "us", "chan10_raw": "us", "chan11_raw": "us", "chan12_raw": "us", "chan13_raw": "us", "chan14_raw": "us", "chan15_raw": "us", "chan16_raw": "us", "chan17_raw": "us", "chan18_raw": "us"} format = '<IHHHHHHHHHHHHHHHHHHBB' native_format = bytearray('<IHHHHHHHHHHHHHHHHHHBB', 'ascii') orders = [0, 19, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 118 unpacker = struct.Struct('<IHHHHHHHHHHHHHHHHHHBB') def __init__(self, time_boot_ms, chancount, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, chan13_raw, chan14_raw, chan15_raw, chan16_raw, chan17_raw, chan18_raw, rssi): MAVLink_message.__init__(self, MAVLink_rc_channels_message.id, MAVLink_rc_channels_message.name) self._fieldnames = MAVLink_rc_channels_message.fieldnames self.time_boot_ms = time_boot_ms self.chancount = chancount self.chan1_raw = chan1_raw self.chan2_raw = chan2_raw self.chan3_raw = chan3_raw self.chan4_raw = chan4_raw self.chan5_raw = chan5_raw self.chan6_raw = chan6_raw self.chan7_raw = chan7_raw self.chan8_raw = chan8_raw self.chan9_raw = chan9_raw self.chan10_raw = chan10_raw self.chan11_raw = chan11_raw self.chan12_raw = chan12_raw self.chan13_raw = chan13_raw self.chan14_raw = chan14_raw self.chan15_raw = chan15_raw self.chan16_raw = chan16_raw self.chan17_raw = chan17_raw self.chan18_raw = chan18_raw self.rssi = rssi def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 118, struct.pack('<IHHHHHHHHHHHHHHHHHHBB', self.time_boot_ms, self.chan1_raw, self.chan2_raw, self.chan3_raw, self.chan4_raw, self.chan5_raw, self.chan6_raw, self.chan7_raw, self.chan8_raw, self.chan9_raw, self.chan10_raw, self.chan11_raw, self.chan12_raw, self.chan13_raw, self.chan14_raw, self.chan15_raw, self.chan16_raw, self.chan17_raw, self.chan18_raw, self.chancount, self.rssi), force_mavlink1=force_mavlink1) class MAVLink_request_data_stream_message(MAVLink_message): ''' Request a data stream. ''' id = MAVLINK_MSG_ID_REQUEST_DATA_STREAM name = 'REQUEST_DATA_STREAM' fieldnames = ['target_system', 'target_component', 'req_stream_id', 'req_message_rate', 'start_stop'] ordered_fieldnames = ['req_message_rate', 'target_system', 'target_component', 'req_stream_id', 'start_stop'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"req_message_rate": "Hz"} format = '<HBBBB' native_format = bytearray('<HBBBB', 'ascii') orders = [1, 2, 3, 0, 4] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0] crc_extra = 148 unpacker = struct.Struct('<HBBBB') def __init__(self, target_system, target_component, req_stream_id, req_message_rate, start_stop): MAVLink_message.__init__(self, MAVLink_request_data_stream_message.id, MAVLink_request_data_stream_message.name) self._fieldnames = MAVLink_request_data_stream_message.fieldnames self.target_system = target_system self.target_component = target_component self.req_stream_id = req_stream_id self.req_message_rate = req_message_rate self.start_stop = start_stop def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 148, struct.pack('<HBBBB', self.req_message_rate, self.target_system, self.target_component, self.req_stream_id, self.start_stop), force_mavlink1=force_mavlink1) class MAVLink_data_stream_message(MAVLink_message): ''' Data stream status information. ''' id = MAVLINK_MSG_ID_DATA_STREAM name = 'DATA_STREAM' fieldnames = ['stream_id', 'message_rate', 'on_off'] ordered_fieldnames = ['message_rate', 'stream_id', 'on_off'] fieldtypes = ['uint8_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"message_rate": "Hz"} format = '<HBB' native_format = bytearray('<HBB', 'ascii') orders = [1, 0, 2] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 21 unpacker = struct.Struct('<HBB') def __init__(self, stream_id, message_rate, on_off): MAVLink_message.__init__(self, MAVLink_data_stream_message.id, MAVLink_data_stream_message.name) self._fieldnames = MAVLink_data_stream_message.fieldnames self.stream_id = stream_id self.message_rate = message_rate self.on_off = on_off def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 21, struct.pack('<HBB', self.message_rate, self.stream_id, self.on_off), force_mavlink1=force_mavlink1) class MAVLink_manual_control_message(MAVLink_message): ''' This message provides an API for manually controlling the vehicle using standard joystick axes nomenclature, along with a joystick-like input device. Unused axes can be disabled an buttons are also transmit as boolean values of their ''' id = MAVLINK_MSG_ID_MANUAL_CONTROL name = 'MANUAL_CONTROL' fieldnames = ['target', 'x', 'y', 'z', 'r', 'buttons'] ordered_fieldnames = ['x', 'y', 'z', 'r', 'buttons', 'target'] fieldtypes = ['uint8_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<hhhhHB' native_format = bytearray('<hhhhHB', 'ascii') orders = [5, 0, 1, 2, 3, 4] lengths = [1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0] crc_extra = 243 unpacker = struct.Struct('<hhhhHB') def __init__(self, target, x, y, z, r, buttons): MAVLink_message.__init__(self, MAVLink_manual_control_message.id, MAVLink_manual_control_message.name) self._fieldnames = MAVLink_manual_control_message.fieldnames self.target = target self.x = x self.y = y self.z = z self.r = r self.buttons = buttons def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 243, struct.pack('<hhhhHB', self.x, self.y, self.z, self.r, self.buttons, self.target), force_mavlink1=force_mavlink1) class MAVLink_rc_channels_override_message(MAVLink_message): ''' The RAW values of the RC channels sent to the MAV to override info received from the RC radio. A value of UINT16_MAX means no change to that channel. A value of 0 means control of that channel should be released back to the RC radio. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. ''' id = MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE name = 'RC_CHANNELS_OVERRIDE' fieldnames = ['target_system', 'target_component', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'chan9_raw', 'chan10_raw', 'chan11_raw', 'chan12_raw', 'chan13_raw', 'chan14_raw', 'chan15_raw', 'chan16_raw', 'chan17_raw', 'chan18_raw'] ordered_fieldnames = ['chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'target_system', 'target_component', 'chan9_raw', 'chan10_raw', 'chan11_raw', 'chan12_raw', 'chan13_raw', 'chan14_raw', 'chan15_raw', 'chan16_raw', 'chan17_raw', 'chan18_raw'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"chan1_raw": "us", "chan2_raw": "us", "chan3_raw": "us", "chan4_raw": "us", "chan5_raw": "us", "chan6_raw": "us", "chan7_raw": "us", "chan8_raw": "us", "chan9_raw": "us", "chan10_raw": "us", "chan11_raw": "us", "chan12_raw": "us", "chan13_raw": "us", "chan14_raw": "us", "chan15_raw": "us", "chan16_raw": "us", "chan17_raw": "us", "chan18_raw": "us"} format = '<HHHHHHHHBBHHHHHHHHHH' native_format = bytearray('<HHHHHHHHBBHHHHHHHHHH', 'ascii') orders = [8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 124 unpacker = struct.Struct('<HHHHHHHHBBHHHHHHHHHH') def __init__(self, target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw=0, chan10_raw=0, chan11_raw=0, chan12_raw=0, chan13_raw=0, chan14_raw=0, chan15_raw=0, chan16_raw=0, chan17_raw=0, chan18_raw=0): MAVLink_message.__init__(self, MAVLink_rc_channels_override_message.id, MAVLink_rc_channels_override_message.name) self._fieldnames = MAVLink_rc_channels_override_message.fieldnames self.target_system = target_system self.target_component = target_component self.chan1_raw = chan1_raw self.chan2_raw = chan2_raw self.chan3_raw = chan3_raw self.chan4_raw = chan4_raw self.chan5_raw = chan5_raw self.chan6_raw = chan6_raw self.chan7_raw = chan7_raw self.chan8_raw = chan8_raw self.chan9_raw = chan9_raw self.chan10_raw = chan10_raw self.chan11_raw = chan11_raw self.chan12_raw = chan12_raw self.chan13_raw = chan13_raw self.chan14_raw = chan14_raw self.chan15_raw = chan15_raw self.chan16_raw = chan16_raw self.chan17_raw = chan17_raw self.chan18_raw = chan18_raw def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 124, struct.pack('<HHHHHHHHBBHHHHHHHHHH', self.chan1_raw, self.chan2_raw, self.chan3_raw, self.chan4_raw, self.chan5_raw, self.chan6_raw, self.chan7_raw, self.chan8_raw, self.target_system, self.target_component, self.chan9_raw, self.chan10_raw, self.chan11_raw, self.chan12_raw, self.chan13_raw, self.chan14_raw, self.chan15_raw, self.chan16_raw, self.chan17_raw, self.chan18_raw), force_mavlink1=force_mavlink1) class MAVLink_mission_item_int_message(MAVLink_message): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also https://mavlink.io/en/services/mission.html. ''' id = MAVLINK_MSG_ID_MISSION_ITEM_INT name = 'MISSION_ITEM_INT' fieldnames = ['target_system', 'target_component', 'seq', 'frame', 'command', 'current', 'autocontinue', 'param1', 'param2', 'param3', 'param4', 'x', 'y', 'z', 'mission_type'] ordered_fieldnames = ['param1', 'param2', 'param3', 'param4', 'x', 'y', 'z', 'seq', 'command', 'target_system', 'target_component', 'frame', 'current', 'autocontinue', 'mission_type'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint8_t', 'uint16_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float', 'float', 'int32_t', 'int32_t', 'float', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"frame": "MAV_FRAME", "command": "MAV_CMD", "mission_type": "MAV_MISSION_TYPE"} fieldunits_by_name = {} format = '<ffffiifHHBBBBBB' native_format = bytearray('<ffffiifHHBBBBBB', 'ascii') orders = [9, 10, 7, 11, 8, 12, 13, 0, 1, 2, 3, 4, 5, 6, 14] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 38 unpacker = struct.Struct('<ffffiifHHBBBBBB') def __init__(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type=0): MAVLink_message.__init__(self, MAVLink_mission_item_int_message.id, MAVLink_mission_item_int_message.name) self._fieldnames = MAVLink_mission_item_int_message.fieldnames self.target_system = target_system self.target_component = target_component self.seq = seq self.frame = frame self.command = command self.current = current self.autocontinue = autocontinue self.param1 = param1 self.param2 = param2 self.param3 = param3 self.param4 = param4 self.x = x self.y = y self.z = z self.mission_type = mission_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 38, struct.pack('<ffffiifHHBBBBBB', self.param1, self.param2, self.param3, self.param4, self.x, self.y, self.z, self.seq, self.command, self.target_system, self.target_component, self.frame, self.current, self.autocontinue, self.mission_type), force_mavlink1=force_mavlink1) class MAVLink_vfr_hud_message(MAVLink_message): ''' Metrics typically displayed on a HUD for fixed wing aircraft. ''' id = MAVLINK_MSG_ID_VFR_HUD name = 'VFR_HUD' fieldnames = ['airspeed', 'groundspeed', 'heading', 'throttle', 'alt', 'climb'] ordered_fieldnames = ['airspeed', 'groundspeed', 'alt', 'climb', 'heading', 'throttle'] fieldtypes = ['float', 'float', 'int16_t', 'uint16_t', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"airspeed": "m/s", "groundspeed": "m/s", "heading": "deg", "throttle": "%", "alt": "m", "climb": "m/s"} format = '<ffffhH' native_format = bytearray('<ffffhH', 'ascii') orders = [0, 1, 4, 5, 2, 3] lengths = [1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0] crc_extra = 20 unpacker = struct.Struct('<ffffhH') def __init__(self, airspeed, groundspeed, heading, throttle, alt, climb): MAVLink_message.__init__(self, MAVLink_vfr_hud_message.id, MAVLink_vfr_hud_message.name) self._fieldnames = MAVLink_vfr_hud_message.fieldnames self.airspeed = airspeed self.groundspeed = groundspeed self.heading = heading self.throttle = throttle self.alt = alt self.climb = climb def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 20, struct.pack('<ffffhH', self.airspeed, self.groundspeed, self.alt, self.climb, self.heading, self.throttle), force_mavlink1=force_mavlink1) class MAVLink_command_int_message(MAVLink_message): ''' Message encoding a command with parameters as scaled integers. Scaling depends on the actual command value. The command microservice is documented at https://mavlink.io/en/services/command.html ''' id = MAVLINK_MSG_ID_COMMAND_INT name = 'COMMAND_INT' fieldnames = ['target_system', 'target_component', 'frame', 'command', 'current', 'autocontinue', 'param1', 'param2', 'param3', 'param4', 'x', 'y', 'z'] ordered_fieldnames = ['param1', 'param2', 'param3', 'param4', 'x', 'y', 'z', 'command', 'target_system', 'target_component', 'frame', 'current', 'autocontinue'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint16_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float', 'float', 'int32_t', 'int32_t', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"frame": "MAV_FRAME", "command": "MAV_CMD"} fieldunits_by_name = {} format = '<ffffiifHBBBBB' native_format = bytearray('<ffffiifHBBBBB', 'ascii') orders = [8, 9, 10, 7, 11, 12, 0, 1, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 158 unpacker = struct.Struct('<ffffiifHBBBBB') def __init__(self, target_system, target_component, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z): MAVLink_message.__init__(self, MAVLink_command_int_message.id, MAVLink_command_int_message.name) self._fieldnames = MAVLink_command_int_message.fieldnames self.target_system = target_system self.target_component = target_component self.frame = frame self.command = command self.current = current self.autocontinue = autocontinue self.param1 = param1 self.param2 = param2 self.param3 = param3 self.param4 = param4 self.x = x self.y = y self.z = z def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 158, struct.pack('<ffffiifHBBBBB', self.param1, self.param2, self.param3, self.param4, self.x, self.y, self.z, self.command, self.target_system, self.target_component, self.frame, self.current, self.autocontinue), force_mavlink1=force_mavlink1) class MAVLink_command_long_message(MAVLink_message): ''' Send a command with up to seven parameters to the MAV. The command microservice is documented at https://mavlink.io/en/services/command.html ''' id = MAVLINK_MSG_ID_COMMAND_LONG name = 'COMMAND_LONG' fieldnames = ['target_system', 'target_component', 'command', 'confirmation', 'param1', 'param2', 'param3', 'param4', 'param5', 'param6', 'param7'] ordered_fieldnames = ['param1', 'param2', 'param3', 'param4', 'param5', 'param6', 'param7', 'command', 'target_system', 'target_component', 'confirmation'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"command": "MAV_CMD"} fieldunits_by_name = {} format = '<fffffffHBBB' native_format = bytearray('<fffffffHBBB', 'ascii') orders = [8, 9, 7, 10, 0, 1, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 152 unpacker = struct.Struct('<fffffffHBBB') def __init__(self, target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7): MAVLink_message.__init__(self, MAVLink_command_long_message.id, MAVLink_command_long_message.name) self._fieldnames = MAVLink_command_long_message.fieldnames self.target_system = target_system self.target_component = target_component self.command = command self.confirmation = confirmation self.param1 = param1 self.param2 = param2 self.param3 = param3 self.param4 = param4 self.param5 = param5 self.param6 = param6 self.param7 = param7 def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 152, struct.pack('<fffffffHBBB', self.param1, self.param2, self.param3, self.param4, self.param5, self.param6, self.param7, self.command, self.target_system, self.target_component, self.confirmation), force_mavlink1=force_mavlink1) class MAVLink_command_ack_message(MAVLink_message): ''' Report status of a command. Includes feedback whether the command was executed. The command microservice is documented at https://mavlink.io/en/services/command.html ''' id = MAVLINK_MSG_ID_COMMAND_ACK name = 'COMMAND_ACK' fieldnames = ['command', 'result'] ordered_fieldnames = ['command', 'result'] fieldtypes = ['uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"command": "MAV_CMD", "result": "MAV_RESULT"} fieldunits_by_name = {} format = '<HB' native_format = bytearray('<HB', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 143 unpacker = struct.Struct('<HB') def __init__(self, command, result): MAVLink_message.__init__(self, MAVLink_command_ack_message.id, MAVLink_command_ack_message.name) self._fieldnames = MAVLink_command_ack_message.fieldnames self.command = command self.result = result def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 143, struct.pack('<HB', self.command, self.result), force_mavlink1=force_mavlink1) class MAVLink_manual_setpoint_message(MAVLink_message): ''' Setpoint in roll, pitch, yaw and thrust from the operator ''' id = MAVLINK_MSG_ID_MANUAL_SETPOINT name = 'MANUAL_SETPOINT' fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'thrust', 'mode_switch', 'manual_override_switch'] ordered_fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'thrust', 'mode_switch', 'manual_override_switch'] fieldtypes = ['uint32_t', 'float', 'float', 'float', 'float', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "roll": "rad/s", "pitch": "rad/s", "yaw": "rad/s"} format = '<IffffBB' native_format = bytearray('<IffffBB', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 106 unpacker = struct.Struct('<IffffBB') def __init__(self, time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch): MAVLink_message.__init__(self, MAVLink_manual_setpoint_message.id, MAVLink_manual_setpoint_message.name) self._fieldnames = MAVLink_manual_setpoint_message.fieldnames self.time_boot_ms = time_boot_ms self.roll = roll self.pitch = pitch self.yaw = yaw self.thrust = thrust self.mode_switch = mode_switch self.manual_override_switch = manual_override_switch def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 106, struct.pack('<IffffBB', self.time_boot_ms, self.roll, self.pitch, self.yaw, self.thrust, self.mode_switch, self.manual_override_switch), force_mavlink1=force_mavlink1) class MAVLink_set_attitude_target_message(MAVLink_message): ''' Sets a desired vehicle attitude. Used by an external controller to command the vehicle (manual controller or other system). ''' id = MAVLINK_MSG_ID_SET_ATTITUDE_TARGET name = 'SET_ATTITUDE_TARGET' fieldnames = ['time_boot_ms', 'target_system', 'target_component', 'type_mask', 'q', 'body_roll_rate', 'body_pitch_rate', 'body_yaw_rate', 'thrust'] ordered_fieldnames = ['time_boot_ms', 'q', 'body_roll_rate', 'body_pitch_rate', 'body_yaw_rate', 'thrust', 'target_system', 'target_component', 'type_mask'] fieldtypes = ['uint32_t', 'uint8_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "body_roll_rate": "rad/s", "body_pitch_rate": "rad/s", "body_yaw_rate": "rad/s"} format = '<I4fffffBBB' native_format = bytearray('<IfffffBBB', 'ascii') orders = [0, 6, 7, 8, 1, 2, 3, 4, 5] lengths = [1, 4, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 4, 0, 0, 0, 0, 0, 0, 0] crc_extra = 49 unpacker = struct.Struct('<I4fffffBBB') def __init__(self, time_boot_ms, target_system, target_component, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust): MAVLink_message.__init__(self, MAVLink_set_attitude_target_message.id, MAVLink_set_attitude_target_message.name) self._fieldnames = MAVLink_set_attitude_target_message.fieldnames self.time_boot_ms = time_boot_ms self.target_system = target_system self.target_component = target_component self.type_mask = type_mask self.q = q self.body_roll_rate = body_roll_rate self.body_pitch_rate = body_pitch_rate self.body_yaw_rate = body_yaw_rate self.thrust = thrust def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 49, struct.pack('<I4fffffBBB', self.time_boot_ms, self.q[0], self.q[1], self.q[2], self.q[3], self.body_roll_rate, self.body_pitch_rate, self.body_yaw_rate, self.thrust, self.target_system, self.target_component, self.type_mask), force_mavlink1=force_mavlink1) class MAVLink_attitude_target_message(MAVLink_message): ''' Reports the current commanded attitude of the vehicle as specified by the autopilot. This should match the commands sent in a SET_ATTITUDE_TARGET message if the vehicle is being controlled this way. ''' id = MAVLINK_MSG_ID_ATTITUDE_TARGET name = 'ATTITUDE_TARGET' fieldnames = ['time_boot_ms', 'type_mask', 'q', 'body_roll_rate', 'body_pitch_rate', 'body_yaw_rate', 'thrust'] ordered_fieldnames = ['time_boot_ms', 'q', 'body_roll_rate', 'body_pitch_rate', 'body_yaw_rate', 'thrust', 'type_mask'] fieldtypes = ['uint32_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {"type_mask": "bitmask"} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "body_roll_rate": "rad/s", "body_pitch_rate": "rad/s", "body_yaw_rate": "rad/s"} format = '<I4fffffB' native_format = bytearray('<IfffffB', 'ascii') orders = [0, 6, 1, 2, 3, 4, 5] lengths = [1, 4, 1, 1, 1, 1, 1] array_lengths = [0, 4, 0, 0, 0, 0, 0] crc_extra = 22 unpacker = struct.Struct('<I4fffffB') def __init__(self, time_boot_ms, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust): MAVLink_message.__init__(self, MAVLink_attitude_target_message.id, MAVLink_attitude_target_message.name) self._fieldnames = MAVLink_attitude_target_message.fieldnames self.time_boot_ms = time_boot_ms self.type_mask = type_mask self.q = q self.body_roll_rate = body_roll_rate self.body_pitch_rate = body_pitch_rate self.body_yaw_rate = body_yaw_rate self.thrust = thrust def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 22, struct.pack('<I4fffffB', self.time_boot_ms, self.q[0], self.q[1], self.q[2], self.q[3], self.body_roll_rate, self.body_pitch_rate, self.body_yaw_rate, self.thrust, self.type_mask), force_mavlink1=force_mavlink1) class MAVLink_set_position_target_local_ned_message(MAVLink_message): ''' Sets a desired vehicle position in a local north-east-down coordinate frame. Used by an external controller to command the vehicle (manual controller or other system). ''' id = MAVLINK_MSG_ID_SET_POSITION_TARGET_LOCAL_NED name = 'SET_POSITION_TARGET_LOCAL_NED' fieldnames = ['time_boot_ms', 'target_system', 'target_component', 'coordinate_frame', 'type_mask', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'afx', 'afy', 'afz', 'yaw', 'yaw_rate'] ordered_fieldnames = ['time_boot_ms', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'afx', 'afy', 'afz', 'yaw', 'yaw_rate', 'type_mask', 'target_system', 'target_component', 'coordinate_frame'] fieldtypes = ['uint32_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint16_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {"type_mask": "bitmask"} fieldenums_by_name = {"coordinate_frame": "MAV_FRAME", "type_mask": "POSITION_TARGET_TYPEMASK"} fieldunits_by_name = {"time_boot_ms": "ms", "x": "m", "y": "m", "z": "m", "vx": "m/s", "vy": "m/s", "vz": "m/s", "afx": "m/s/s", "afy": "m/s/s", "afz": "m/s/s", "yaw": "rad", "yaw_rate": "rad/s"} format = '<IfffffffffffHBBB' native_format = bytearray('<IfffffffffffHBBB', 'ascii') orders = [0, 13, 14, 15, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 143 unpacker = struct.Struct('<IfffffffffffHBBB') def __init__(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): MAVLink_message.__init__(self, MAVLink_set_position_target_local_ned_message.id, MAVLink_set_position_target_local_ned_message.name) self._fieldnames = MAVLink_set_position_target_local_ned_message.fieldnames self.time_boot_ms = time_boot_ms self.target_system = target_system self.target_component = target_component self.coordinate_frame = coordinate_frame self.type_mask = type_mask self.x = x self.y = y self.z = z self.vx = vx self.vy = vy self.vz = vz self.afx = afx self.afy = afy self.afz = afz self.yaw = yaw self.yaw_rate = yaw_rate def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 143, struct.pack('<IfffffffffffHBBB', self.time_boot_ms, self.x, self.y, self.z, self.vx, self.vy, self.vz, self.afx, self.afy, self.afz, self.yaw, self.yaw_rate, self.type_mask, self.target_system, self.target_component, self.coordinate_frame), force_mavlink1=force_mavlink1) class MAVLink_position_target_local_ned_message(MAVLink_message): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_LOCAL_NED if the vehicle is being controlled this way. ''' id = MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED name = 'POSITION_TARGET_LOCAL_NED' fieldnames = ['time_boot_ms', 'coordinate_frame', 'type_mask', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'afx', 'afy', 'afz', 'yaw', 'yaw_rate'] ordered_fieldnames = ['time_boot_ms', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'afx', 'afy', 'afz', 'yaw', 'yaw_rate', 'type_mask', 'coordinate_frame'] fieldtypes = ['uint32_t', 'uint8_t', 'uint16_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {"type_mask": "bitmask"} fieldenums_by_name = {"coordinate_frame": "MAV_FRAME", "type_mask": "POSITION_TARGET_TYPEMASK"} fieldunits_by_name = {"time_boot_ms": "ms", "x": "m", "y": "m", "z": "m", "vx": "m/s", "vy": "m/s", "vz": "m/s", "afx": "m/s/s", "afy": "m/s/s", "afz": "m/s/s", "yaw": "rad", "yaw_rate": "rad/s"} format = '<IfffffffffffHB' native_format = bytearray('<IfffffffffffHB', 'ascii') orders = [0, 13, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 140 unpacker = struct.Struct('<IfffffffffffHB') def __init__(self, time_boot_ms, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): MAVLink_message.__init__(self, MAVLink_position_target_local_ned_message.id, MAVLink_position_target_local_ned_message.name) self._fieldnames = MAVLink_position_target_local_ned_message.fieldnames self.time_boot_ms = time_boot_ms self.coordinate_frame = coordinate_frame self.type_mask = type_mask self.x = x self.y = y self.z = z self.vx = vx self.vy = vy self.vz = vz self.afx = afx self.afy = afy self.afz = afz self.yaw = yaw self.yaw_rate = yaw_rate def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 140, struct.pack('<IfffffffffffHB', self.time_boot_ms, self.x, self.y, self.z, self.vx, self.vy, self.vz, self.afx, self.afy, self.afz, self.yaw, self.yaw_rate, self.type_mask, self.coordinate_frame), force_mavlink1=force_mavlink1) class MAVLink_set_position_target_global_int_message(MAVLink_message): ''' Sets a desired vehicle position, velocity, and/or acceleration in a global coordinate system (WGS84). Used by an external controller to command the vehicle (manual controller or other system). ''' id = MAVLINK_MSG_ID_SET_POSITION_TARGET_GLOBAL_INT name = 'SET_POSITION_TARGET_GLOBAL_INT' fieldnames = ['time_boot_ms', 'target_system', 'target_component', 'coordinate_frame', 'type_mask', 'lat_int', 'lon_int', 'alt', 'vx', 'vy', 'vz', 'afx', 'afy', 'afz', 'yaw', 'yaw_rate'] ordered_fieldnames = ['time_boot_ms', 'lat_int', 'lon_int', 'alt', 'vx', 'vy', 'vz', 'afx', 'afy', 'afz', 'yaw', 'yaw_rate', 'type_mask', 'target_system', 'target_component', 'coordinate_frame'] fieldtypes = ['uint32_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint16_t', 'int32_t', 'int32_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {"type_mask": "bitmask"} fieldenums_by_name = {"coordinate_frame": "MAV_FRAME", "type_mask": "POSITION_TARGET_TYPEMASK"} fieldunits_by_name = {"time_boot_ms": "ms", "lat_int": "degE7", "lon_int": "degE7", "alt": "m", "vx": "m/s", "vy": "m/s", "vz": "m/s", "afx": "m/s/s", "afy": "m/s/s", "afz": "m/s/s", "yaw": "rad", "yaw_rate": "rad/s"} format = '<IiifffffffffHBBB' native_format = bytearray('<IiifffffffffHBBB', 'ascii') orders = [0, 13, 14, 15, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 5 unpacker = struct.Struct('<IiifffffffffHBBB') def __init__(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): MAVLink_message.__init__(self, MAVLink_set_position_target_global_int_message.id, MAVLink_set_position_target_global_int_message.name) self._fieldnames = MAVLink_set_position_target_global_int_message.fieldnames self.time_boot_ms = time_boot_ms self.target_system = target_system self.target_component = target_component self.coordinate_frame = coordinate_frame self.type_mask = type_mask self.lat_int = lat_int self.lon_int = lon_int self.alt = alt self.vx = vx self.vy = vy self.vz = vz self.afx = afx self.afy = afy self.afz = afz self.yaw = yaw self.yaw_rate = yaw_rate def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 5, struct.pack('<IiifffffffffHBBB', self.time_boot_ms, self.lat_int, self.lon_int, self.alt, self.vx, self.vy, self.vz, self.afx, self.afy, self.afz, self.yaw, self.yaw_rate, self.type_mask, self.target_system, self.target_component, self.coordinate_frame), force_mavlink1=force_mavlink1) class MAVLink_position_target_global_int_message(MAVLink_message): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_GLOBAL_INT if the vehicle is being controlled this way. ''' id = MAVLINK_MSG_ID_POSITION_TARGET_GLOBAL_INT name = 'POSITION_TARGET_GLOBAL_INT' fieldnames = ['time_boot_ms', 'coordinate_frame', 'type_mask', 'lat_int', 'lon_int', 'alt', 'vx', 'vy', 'vz', 'afx', 'afy', 'afz', 'yaw', 'yaw_rate'] ordered_fieldnames = ['time_boot_ms', 'lat_int', 'lon_int', 'alt', 'vx', 'vy', 'vz', 'afx', 'afy', 'afz', 'yaw', 'yaw_rate', 'type_mask', 'coordinate_frame'] fieldtypes = ['uint32_t', 'uint8_t', 'uint16_t', 'int32_t', 'int32_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {"type_mask": "bitmask"} fieldenums_by_name = {"coordinate_frame": "MAV_FRAME", "type_mask": "POSITION_TARGET_TYPEMASK"} fieldunits_by_name = {"time_boot_ms": "ms", "lat_int": "degE7", "lon_int": "degE7", "alt": "m", "vx": "m/s", "vy": "m/s", "vz": "m/s", "afx": "m/s/s", "afy": "m/s/s", "afz": "m/s/s", "yaw": "rad", "yaw_rate": "rad/s"} format = '<IiifffffffffHB' native_format = bytearray('<IiifffffffffHB', 'ascii') orders = [0, 13, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 150 unpacker = struct.Struct('<IiifffffffffHB') def __init__(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): MAVLink_message.__init__(self, MAVLink_position_target_global_int_message.id, MAVLink_position_target_global_int_message.name) self._fieldnames = MAVLink_position_target_global_int_message.fieldnames self.time_boot_ms = time_boot_ms self.coordinate_frame = coordinate_frame self.type_mask = type_mask self.lat_int = lat_int self.lon_int = lon_int self.alt = alt self.vx = vx self.vy = vy self.vz = vz self.afx = afx self.afy = afy self.afz = afz self.yaw = yaw self.yaw_rate = yaw_rate def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 150, struct.pack('<IiifffffffffHB', self.time_boot_ms, self.lat_int, self.lon_int, self.alt, self.vx, self.vy, self.vz, self.afx, self.afy, self.afz, self.yaw, self.yaw_rate, self.type_mask, self.coordinate_frame), force_mavlink1=force_mavlink1) class MAVLink_local_position_ned_system_global_offset_message(MAVLink_message): ''' The offset in X, Y, Z and yaw between the LOCAL_POSITION_NED messages of MAV X and the global coordinate frame in NED coordinates. Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) ''' id = MAVLINK_MSG_ID_LOCAL_POSITION_NED_SYSTEM_GLOBAL_OFFSET name = 'LOCAL_POSITION_NED_SYSTEM_GLOBAL_OFFSET' fieldnames = ['time_boot_ms', 'x', 'y', 'z', 'roll', 'pitch', 'yaw'] ordered_fieldnames = ['time_boot_ms', 'x', 'y', 'z', 'roll', 'pitch', 'yaw'] fieldtypes = ['uint32_t', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "x": "m", "y": "m", "z": "m", "roll": "rad", "pitch": "rad", "yaw": "rad"} format = '<Iffffff' native_format = bytearray('<Iffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 231 unpacker = struct.Struct('<Iffffff') def __init__(self, time_boot_ms, x, y, z, roll, pitch, yaw): MAVLink_message.__init__(self, MAVLink_local_position_ned_system_global_offset_message.id, MAVLink_local_position_ned_system_global_offset_message.name) self._fieldnames = MAVLink_local_position_ned_system_global_offset_message.fieldnames self.time_boot_ms = time_boot_ms self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 231, struct.pack('<Iffffff', self.time_boot_ms, self.x, self.y, self.z, self.roll, self.pitch, self.yaw), force_mavlink1=force_mavlink1) class MAVLink_hil_state_message(MAVLink_message): ''' Sent from simulation to autopilot. This packet is useful for high throughput applications such as hardware in the loop simulations. ''' id = MAVLINK_MSG_ID_HIL_STATE name = 'HIL_STATE' fieldnames = ['time_usec', 'roll', 'pitch', 'yaw', 'rollspeed', 'pitchspeed', 'yawspeed', 'lat', 'lon', 'alt', 'vx', 'vy', 'vz', 'xacc', 'yacc', 'zacc'] ordered_fieldnames = ['time_usec', 'roll', 'pitch', 'yaw', 'rollspeed', 'pitchspeed', 'yawspeed', 'lat', 'lon', 'alt', 'vx', 'vy', 'vz', 'xacc', 'yacc', 'zacc'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'int32_t', 'int32_t', 'int32_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "roll": "rad", "pitch": "rad", "yaw": "rad", "rollspeed": "rad/s", "pitchspeed": "rad/s", "yawspeed": "rad/s", "lat": "degE7", "lon": "degE7", "alt": "mm", "vx": "cm/s", "vy": "cm/s", "vz": "cm/s", "xacc": "mG", "yacc": "mG", "zacc": "mG"} format = '<Qffffffiiihhhhhh' native_format = bytearray('<Qffffffiiihhhhhh', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 183 unpacker = struct.Struct('<Qffffffiiihhhhhh') def __init__(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc): MAVLink_message.__init__(self, MAVLink_hil_state_message.id, MAVLink_hil_state_message.name) self._fieldnames = MAVLink_hil_state_message.fieldnames self.time_usec = time_usec self.roll = roll self.pitch = pitch self.yaw = yaw self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed self.lat = lat self.lon = lon self.alt = alt self.vx = vx self.vy = vy self.vz = vz self.xacc = xacc self.yacc = yacc self.zacc = zacc def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 183, struct.pack('<Qffffffiiihhhhhh', self.time_usec, self.roll, self.pitch, self.yaw, self.rollspeed, self.pitchspeed, self.yawspeed, self.lat, self.lon, self.alt, self.vx, self.vy, self.vz, self.xacc, self.yacc, self.zacc), force_mavlink1=force_mavlink1) class MAVLink_hil_controls_message(MAVLink_message): ''' Sent from autopilot to simulation. Hardware in the loop control outputs ''' id = MAVLINK_MSG_ID_HIL_CONTROLS name = 'HIL_CONTROLS' fieldnames = ['time_usec', 'roll_ailerons', 'pitch_elevator', 'yaw_rudder', 'throttle', 'aux1', 'aux2', 'aux3', 'aux4', 'mode', 'nav_mode'] ordered_fieldnames = ['time_usec', 'roll_ailerons', 'pitch_elevator', 'yaw_rudder', 'throttle', 'aux1', 'aux2', 'aux3', 'aux4', 'mode', 'nav_mode'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"mode": "MAV_MODE"} fieldunits_by_name = {"time_usec": "us"} format = '<QffffffffBB' native_format = bytearray('<QffffffffBB', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 63 unpacker = struct.Struct('<QffffffffBB') def __init__(self, time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode): MAVLink_message.__init__(self, MAVLink_hil_controls_message.id, MAVLink_hil_controls_message.name) self._fieldnames = MAVLink_hil_controls_message.fieldnames self.time_usec = time_usec self.roll_ailerons = roll_ailerons self.pitch_elevator = pitch_elevator self.yaw_rudder = yaw_rudder self.throttle = throttle self.aux1 = aux1 self.aux2 = aux2 self.aux3 = aux3 self.aux4 = aux4 self.mode = mode self.nav_mode = nav_mode def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 63, struct.pack('<QffffffffBB', self.time_usec, self.roll_ailerons, self.pitch_elevator, self.yaw_rudder, self.throttle, self.aux1, self.aux2, self.aux3, self.aux4, self.mode, self.nav_mode), force_mavlink1=force_mavlink1) class MAVLink_hil_rc_inputs_raw_message(MAVLink_message): ''' Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. ''' id = MAVLINK_MSG_ID_HIL_RC_INPUTS_RAW name = 'HIL_RC_INPUTS_RAW' fieldnames = ['time_usec', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'chan9_raw', 'chan10_raw', 'chan11_raw', 'chan12_raw', 'rssi'] ordered_fieldnames = ['time_usec', 'chan1_raw', 'chan2_raw', 'chan3_raw', 'chan4_raw', 'chan5_raw', 'chan6_raw', 'chan7_raw', 'chan8_raw', 'chan9_raw', 'chan10_raw', 'chan11_raw', 'chan12_raw', 'rssi'] fieldtypes = ['uint64_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "chan1_raw": "us", "chan2_raw": "us", "chan3_raw": "us", "chan4_raw": "us", "chan5_raw": "us", "chan6_raw": "us", "chan7_raw": "us", "chan8_raw": "us", "chan9_raw": "us", "chan10_raw": "us", "chan11_raw": "us", "chan12_raw": "us"} format = '<QHHHHHHHHHHHHB' native_format = bytearray('<QHHHHHHHHHHHHB', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 54 unpacker = struct.Struct('<QHHHHHHHHHHHHB') def __init__(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi): MAVLink_message.__init__(self, MAVLink_hil_rc_inputs_raw_message.id, MAVLink_hil_rc_inputs_raw_message.name) self._fieldnames = MAVLink_hil_rc_inputs_raw_message.fieldnames self.time_usec = time_usec self.chan1_raw = chan1_raw self.chan2_raw = chan2_raw self.chan3_raw = chan3_raw self.chan4_raw = chan4_raw self.chan5_raw = chan5_raw self.chan6_raw = chan6_raw self.chan7_raw = chan7_raw self.chan8_raw = chan8_raw self.chan9_raw = chan9_raw self.chan10_raw = chan10_raw self.chan11_raw = chan11_raw self.chan12_raw = chan12_raw self.rssi = rssi def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 54, struct.pack('<QHHHHHHHHHHHHB', self.time_usec, self.chan1_raw, self.chan2_raw, self.chan3_raw, self.chan4_raw, self.chan5_raw, self.chan6_raw, self.chan7_raw, self.chan8_raw, self.chan9_raw, self.chan10_raw, self.chan11_raw, self.chan12_raw, self.rssi), force_mavlink1=force_mavlink1) class MAVLink_hil_actuator_controls_message(MAVLink_message): ''' Sent from autopilot to simulation. Hardware in the loop control outputs (replacement for HIL_CONTROLS) ''' id = MAVLINK_MSG_ID_HIL_ACTUATOR_CONTROLS name = 'HIL_ACTUATOR_CONTROLS' fieldnames = ['time_usec', 'controls', 'mode', 'flags'] ordered_fieldnames = ['time_usec', 'flags', 'controls', 'mode'] fieldtypes = ['uint64_t', 'float', 'uint8_t', 'uint64_t'] fielddisplays_by_name = {"mode": "bitmask", "flags": "bitmask"} fieldenums_by_name = {"mode": "MAV_MODE_FLAG"} fieldunits_by_name = {"time_usec": "us"} format = '<QQ16fB' native_format = bytearray('<QQfB', 'ascii') orders = [0, 2, 3, 1] lengths = [1, 1, 16, 1] array_lengths = [0, 0, 16, 0] crc_extra = 47 unpacker = struct.Struct('<QQ16fB') def __init__(self, time_usec, controls, mode, flags): MAVLink_message.__init__(self, MAVLink_hil_actuator_controls_message.id, MAVLink_hil_actuator_controls_message.name) self._fieldnames = MAVLink_hil_actuator_controls_message.fieldnames self.time_usec = time_usec self.controls = controls self.mode = mode self.flags = flags def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 47, struct.pack('<QQ16fB', self.time_usec, self.flags, self.controls[0], self.controls[1], self.controls[2], self.controls[3], self.controls[4], self.controls[5], self.controls[6], self.controls[7], self.controls[8], self.controls[9], self.controls[10], self.controls[11], self.controls[12], self.controls[13], self.controls[14], self.controls[15], self.mode), force_mavlink1=force_mavlink1) class MAVLink_optical_flow_message(MAVLink_message): ''' Optical flow from a flow sensor (e.g. optical mouse sensor) ''' id = MAVLINK_MSG_ID_OPTICAL_FLOW name = 'OPTICAL_FLOW' fieldnames = ['time_usec', 'sensor_id', 'flow_x', 'flow_y', 'flow_comp_m_x', 'flow_comp_m_y', 'quality', 'ground_distance', 'flow_rate_x', 'flow_rate_y'] ordered_fieldnames = ['time_usec', 'flow_comp_m_x', 'flow_comp_m_y', 'ground_distance', 'flow_x', 'flow_y', 'sensor_id', 'quality', 'flow_rate_x', 'flow_rate_y'] fieldtypes = ['uint64_t', 'uint8_t', 'int16_t', 'int16_t', 'float', 'float', 'uint8_t', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "flow_x": "dpix", "flow_y": "dpix", "flow_comp_m_x": "m/s", "flow_comp_m_y": "m/s", "ground_distance": "m", "flow_rate_x": "rad/s", "flow_rate_y": "rad/s"} format = '<QfffhhBBff' native_format = bytearray('<QfffhhBBff', 'ascii') orders = [0, 6, 4, 5, 1, 2, 7, 3, 8, 9] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 175 unpacker = struct.Struct('<QfffhhBBff') def __init__(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance, flow_rate_x=0, flow_rate_y=0): MAVLink_message.__init__(self, MAVLink_optical_flow_message.id, MAVLink_optical_flow_message.name) self._fieldnames = MAVLink_optical_flow_message.fieldnames self.time_usec = time_usec self.sensor_id = sensor_id self.flow_x = flow_x self.flow_y = flow_y self.flow_comp_m_x = flow_comp_m_x self.flow_comp_m_y = flow_comp_m_y self.quality = quality self.ground_distance = ground_distance self.flow_rate_x = flow_rate_x self.flow_rate_y = flow_rate_y def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 175, struct.pack('<QfffhhBBff', self.time_usec, self.flow_comp_m_x, self.flow_comp_m_y, self.ground_distance, self.flow_x, self.flow_y, self.sensor_id, self.quality, self.flow_rate_x, self.flow_rate_y), force_mavlink1=force_mavlink1) class MAVLink_global_vision_position_estimate_message(MAVLink_message): ''' Global position/attitude estimate from a vision source. ''' id = MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE name = 'GLOBAL_VISION_POSITION_ESTIMATE' fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw', 'covariance', 'reset_counter'] ordered_fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw', 'covariance', 'reset_counter'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"usec": "us", "x": "m", "y": "m", "z": "m", "roll": "rad", "pitch": "rad", "yaw": "rad"} format = '<Qffffff21fB' native_format = bytearray('<QfffffffB', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 21, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 21, 0] crc_extra = 102 unpacker = struct.Struct('<Qffffff21fB') def __init__(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], reset_counter=0): MAVLink_message.__init__(self, MAVLink_global_vision_position_estimate_message.id, MAVLink_global_vision_position_estimate_message.name) self._fieldnames = MAVLink_global_vision_position_estimate_message.fieldnames self.usec = usec self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw self.covariance = covariance self.reset_counter = reset_counter def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 102, struct.pack('<Qffffff21fB', self.usec, self.x, self.y, self.z, self.roll, self.pitch, self.yaw, self.covariance[0], self.covariance[1], self.covariance[2], self.covariance[3], self.covariance[4], self.covariance[5], self.covariance[6], self.covariance[7], self.covariance[8], self.covariance[9], self.covariance[10], self.covariance[11], self.covariance[12], self.covariance[13], self.covariance[14], self.covariance[15], self.covariance[16], self.covariance[17], self.covariance[18], self.covariance[19], self.covariance[20], self.reset_counter), force_mavlink1=force_mavlink1) class MAVLink_vision_position_estimate_message(MAVLink_message): ''' Global position/attitude estimate from a vision source. ''' id = MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE name = 'VISION_POSITION_ESTIMATE' fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw', 'covariance', 'reset_counter'] ordered_fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw', 'covariance', 'reset_counter'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"usec": "us", "x": "m", "y": "m", "z": "m", "roll": "rad", "pitch": "rad", "yaw": "rad"} format = '<Qffffff21fB' native_format = bytearray('<QfffffffB', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 21, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 21, 0] crc_extra = 158 unpacker = struct.Struct('<Qffffff21fB') def __init__(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], reset_counter=0): MAVLink_message.__init__(self, MAVLink_vision_position_estimate_message.id, MAVLink_vision_position_estimate_message.name) self._fieldnames = MAVLink_vision_position_estimate_message.fieldnames self.usec = usec self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw self.covariance = covariance self.reset_counter = reset_counter def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 158, struct.pack('<Qffffff21fB', self.usec, self.x, self.y, self.z, self.roll, self.pitch, self.yaw, self.covariance[0], self.covariance[1], self.covariance[2], self.covariance[3], self.covariance[4], self.covariance[5], self.covariance[6], self.covariance[7], self.covariance[8], self.covariance[9], self.covariance[10], self.covariance[11], self.covariance[12], self.covariance[13], self.covariance[14], self.covariance[15], self.covariance[16], self.covariance[17], self.covariance[18], self.covariance[19], self.covariance[20], self.reset_counter), force_mavlink1=force_mavlink1) class MAVLink_vision_speed_estimate_message(MAVLink_message): ''' Speed estimate from a vision source. ''' id = MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE name = 'VISION_SPEED_ESTIMATE' fieldnames = ['usec', 'x', 'y', 'z', 'covariance', 'reset_counter'] ordered_fieldnames = ['usec', 'x', 'y', 'z', 'covariance', 'reset_counter'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"usec": "us", "x": "m/s", "y": "m/s", "z": "m/s"} format = '<Qfff9fB' native_format = bytearray('<QffffB', 'ascii') orders = [0, 1, 2, 3, 4, 5] lengths = [1, 1, 1, 1, 9, 1] array_lengths = [0, 0, 0, 0, 9, 0] crc_extra = 208 unpacker = struct.Struct('<Qfff9fB') def __init__(self, usec, x, y, z, covariance=[0,0,0,0,0,0,0,0,0], reset_counter=0): MAVLink_message.__init__(self, MAVLink_vision_speed_estimate_message.id, MAVLink_vision_speed_estimate_message.name) self._fieldnames = MAVLink_vision_speed_estimate_message.fieldnames self.usec = usec self.x = x self.y = y self.z = z self.covariance = covariance self.reset_counter = reset_counter def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 208, struct.pack('<Qfff9fB', self.usec, self.x, self.y, self.z, self.covariance[0], self.covariance[1], self.covariance[2], self.covariance[3], self.covariance[4], self.covariance[5], self.covariance[6], self.covariance[7], self.covariance[8], self.reset_counter), force_mavlink1=force_mavlink1) class MAVLink_vicon_position_estimate_message(MAVLink_message): ''' Global position estimate from a Vicon motion system source. ''' id = MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE name = 'VICON_POSITION_ESTIMATE' fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw', 'covariance'] ordered_fieldnames = ['usec', 'x', 'y', 'z', 'roll', 'pitch', 'yaw', 'covariance'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"usec": "us", "x": "m", "y": "m", "z": "m", "roll": "rad", "pitch": "rad", "yaw": "rad"} format = '<Qffffff21f' native_format = bytearray('<Qfffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7] lengths = [1, 1, 1, 1, 1, 1, 1, 21] array_lengths = [0, 0, 0, 0, 0, 0, 0, 21] crc_extra = 56 unpacker = struct.Struct('<Qffffff21f') def __init__(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]): MAVLink_message.__init__(self, MAVLink_vicon_position_estimate_message.id, MAVLink_vicon_position_estimate_message.name) self._fieldnames = MAVLink_vicon_position_estimate_message.fieldnames self.usec = usec self.x = x self.y = y self.z = z self.roll = roll self.pitch = pitch self.yaw = yaw self.covariance = covariance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 56, struct.pack('<Qffffff21f', self.usec, self.x, self.y, self.z, self.roll, self.pitch, self.yaw, self.covariance[0], self.covariance[1], self.covariance[2], self.covariance[3], self.covariance[4], self.covariance[5], self.covariance[6], self.covariance[7], self.covariance[8], self.covariance[9], self.covariance[10], self.covariance[11], self.covariance[12], self.covariance[13], self.covariance[14], self.covariance[15], self.covariance[16], self.covariance[17], self.covariance[18], self.covariance[19], self.covariance[20]), force_mavlink1=force_mavlink1) class MAVLink_highres_imu_message(MAVLink_message): ''' The IMU readings in SI units in NED body frame ''' id = MAVLINK_MSG_ID_HIGHRES_IMU name = 'HIGHRES_IMU' fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'abs_pressure', 'diff_pressure', 'pressure_alt', 'temperature', 'fields_updated', 'id'] ordered_fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'abs_pressure', 'diff_pressure', 'pressure_alt', 'temperature', 'fields_updated', 'id'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {"fields_updated": "bitmask"} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "xacc": "m/s/s", "yacc": "m/s/s", "zacc": "m/s/s", "xgyro": "rad/s", "ygyro": "rad/s", "zgyro": "rad/s", "xmag": "gauss", "ymag": "gauss", "zmag": "gauss", "abs_pressure": "mbar", "diff_pressure": "mbar", "temperature": "degC"} format = '<QfffffffffffffHB' native_format = bytearray('<QfffffffffffffHB', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 93 unpacker = struct.Struct('<QfffffffffffffHB') def __init__(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated, id=0): MAVLink_message.__init__(self, MAVLink_highres_imu_message.id, MAVLink_highres_imu_message.name) self._fieldnames = MAVLink_highres_imu_message.fieldnames self.time_usec = time_usec self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag self.abs_pressure = abs_pressure self.diff_pressure = diff_pressure self.pressure_alt = pressure_alt self.temperature = temperature self.fields_updated = fields_updated self.id = id def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 93, struct.pack('<QfffffffffffffHB', self.time_usec, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag, self.abs_pressure, self.diff_pressure, self.pressure_alt, self.temperature, self.fields_updated, self.id), force_mavlink1=force_mavlink1) class MAVLink_optical_flow_rad_message(MAVLink_message): ''' Optical flow from an angular rate flow sensor (e.g. PX4FLOW or mouse sensor) ''' id = MAVLINK_MSG_ID_OPTICAL_FLOW_RAD name = 'OPTICAL_FLOW_RAD' fieldnames = ['time_usec', 'sensor_id', 'integration_time_us', 'integrated_x', 'integrated_y', 'integrated_xgyro', 'integrated_ygyro', 'integrated_zgyro', 'temperature', 'quality', 'time_delta_distance_us', 'distance'] ordered_fieldnames = ['time_usec', 'integration_time_us', 'integrated_x', 'integrated_y', 'integrated_xgyro', 'integrated_ygyro', 'integrated_zgyro', 'time_delta_distance_us', 'distance', 'temperature', 'sensor_id', 'quality'] fieldtypes = ['uint64_t', 'uint8_t', 'uint32_t', 'float', 'float', 'float', 'float', 'float', 'int16_t', 'uint8_t', 'uint32_t', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "integration_time_us": "us", "integrated_x": "rad", "integrated_y": "rad", "integrated_xgyro": "rad", "integrated_ygyro": "rad", "integrated_zgyro": "rad", "temperature": "cdegC", "time_delta_distance_us": "us", "distance": "m"} format = '<QIfffffIfhBB' native_format = bytearray('<QIfffffIfhBB', 'ascii') orders = [0, 10, 1, 2, 3, 4, 5, 6, 9, 11, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 138 unpacker = struct.Struct('<QIfffffIfhBB') def __init__(self, time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance): MAVLink_message.__init__(self, MAVLink_optical_flow_rad_message.id, MAVLink_optical_flow_rad_message.name) self._fieldnames = MAVLink_optical_flow_rad_message.fieldnames self.time_usec = time_usec self.sensor_id = sensor_id self.integration_time_us = integration_time_us self.integrated_x = integrated_x self.integrated_y = integrated_y self.integrated_xgyro = integrated_xgyro self.integrated_ygyro = integrated_ygyro self.integrated_zgyro = integrated_zgyro self.temperature = temperature self.quality = quality self.time_delta_distance_us = time_delta_distance_us self.distance = distance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 138, struct.pack('<QIfffffIfhBB', self.time_usec, self.integration_time_us, self.integrated_x, self.integrated_y, self.integrated_xgyro, self.integrated_ygyro, self.integrated_zgyro, self.time_delta_distance_us, self.distance, self.temperature, self.sensor_id, self.quality), force_mavlink1=force_mavlink1) class MAVLink_hil_sensor_message(MAVLink_message): ''' The IMU readings in SI units in NED body frame ''' id = MAVLINK_MSG_ID_HIL_SENSOR name = 'HIL_SENSOR' fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'abs_pressure', 'diff_pressure', 'pressure_alt', 'temperature', 'fields_updated'] ordered_fieldnames = ['time_usec', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'abs_pressure', 'diff_pressure', 'pressure_alt', 'temperature', 'fields_updated'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint32_t'] fielddisplays_by_name = {"fields_updated": "bitmask"} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "xacc": "m/s/s", "yacc": "m/s/s", "zacc": "m/s/s", "xgyro": "rad/s", "ygyro": "rad/s", "zgyro": "rad/s", "xmag": "gauss", "ymag": "gauss", "zmag": "gauss", "abs_pressure": "mbar", "diff_pressure": "mbar", "temperature": "degC"} format = '<QfffffffffffffI' native_format = bytearray('<QfffffffffffffI', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 108 unpacker = struct.Struct('<QfffffffffffffI') def __init__(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): MAVLink_message.__init__(self, MAVLink_hil_sensor_message.id, MAVLink_hil_sensor_message.name) self._fieldnames = MAVLink_hil_sensor_message.fieldnames self.time_usec = time_usec self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag self.abs_pressure = abs_pressure self.diff_pressure = diff_pressure self.pressure_alt = pressure_alt self.temperature = temperature self.fields_updated = fields_updated def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 108, struct.pack('<QfffffffffffffI', self.time_usec, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag, self.abs_pressure, self.diff_pressure, self.pressure_alt, self.temperature, self.fields_updated), force_mavlink1=force_mavlink1) class MAVLink_sim_state_message(MAVLink_message): ''' Status of simulation environment, if used ''' id = MAVLINK_MSG_ID_SIM_STATE name = 'SIM_STATE' fieldnames = ['q1', 'q2', 'q3', 'q4', 'roll', 'pitch', 'yaw', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'lat', 'lon', 'alt', 'std_dev_horz', 'std_dev_vert', 'vn', 've', 'vd'] ordered_fieldnames = ['q1', 'q2', 'q3', 'q4', 'roll', 'pitch', 'yaw', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'lat', 'lon', 'alt', 'std_dev_horz', 'std_dev_vert', 'vn', 've', 'vd'] fieldtypes = ['float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"xacc": "m/s/s", "yacc": "m/s/s", "zacc": "m/s/s", "xgyro": "rad/s", "ygyro": "rad/s", "zgyro": "rad/s", "lat": "deg", "lon": "deg", "alt": "m", "vn": "m/s", "ve": "m/s", "vd": "m/s"} format = '<fffffffffffffffffffff' native_format = bytearray('<fffffffffffffffffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 32 unpacker = struct.Struct('<fffffffffffffffffffff') def __init__(self, q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd): MAVLink_message.__init__(self, MAVLink_sim_state_message.id, MAVLink_sim_state_message.name) self._fieldnames = MAVLink_sim_state_message.fieldnames self.q1 = q1 self.q2 = q2 self.q3 = q3 self.q4 = q4 self.roll = roll self.pitch = pitch self.yaw = yaw self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.lat = lat self.lon = lon self.alt = alt self.std_dev_horz = std_dev_horz self.std_dev_vert = std_dev_vert self.vn = vn self.ve = ve self.vd = vd def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 32, struct.pack('<fffffffffffffffffffff', self.q1, self.q2, self.q3, self.q4, self.roll, self.pitch, self.yaw, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.lat, self.lon, self.alt, self.std_dev_horz, self.std_dev_vert, self.vn, self.ve, self.vd), force_mavlink1=force_mavlink1) class MAVLink_radio_status_message(MAVLink_message): ''' Status generated by radio and injected into MAVLink stream. ''' id = MAVLINK_MSG_ID_RADIO_STATUS name = 'RADIO_STATUS' fieldnames = ['rssi', 'remrssi', 'txbuf', 'noise', 'remnoise', 'rxerrors', 'fixed'] ordered_fieldnames = ['rxerrors', 'fixed', 'rssi', 'remrssi', 'txbuf', 'noise', 'remnoise'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"txbuf": "%"} format = '<HHBBBBB' native_format = bytearray('<HHBBBBB', 'ascii') orders = [2, 3, 4, 5, 6, 0, 1] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 185 unpacker = struct.Struct('<HHBBBBB') def __init__(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed): MAVLink_message.__init__(self, MAVLink_radio_status_message.id, MAVLink_radio_status_message.name) self._fieldnames = MAVLink_radio_status_message.fieldnames self.rssi = rssi self.remrssi = remrssi self.txbuf = txbuf self.noise = noise self.remnoise = remnoise self.rxerrors = rxerrors self.fixed = fixed def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 185, struct.pack('<HHBBBBB', self.rxerrors, self.fixed, self.rssi, self.remrssi, self.txbuf, self.noise, self.remnoise), force_mavlink1=force_mavlink1) class MAVLink_file_transfer_protocol_message(MAVLink_message): ''' File transfer message ''' id = MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL name = 'FILE_TRANSFER_PROTOCOL' fieldnames = ['target_network', 'target_system', 'target_component', 'payload'] ordered_fieldnames = ['target_network', 'target_system', 'target_component', 'payload'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<BBB251B' native_format = bytearray('<BBBB', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 251] array_lengths = [0, 0, 0, 251] crc_extra = 84 unpacker = struct.Struct('<BBB251B') def __init__(self, target_network, target_system, target_component, payload): MAVLink_message.__init__(self, MAVLink_file_transfer_protocol_message.id, MAVLink_file_transfer_protocol_message.name) self._fieldnames = MAVLink_file_transfer_protocol_message.fieldnames self.target_network = target_network self.target_system = target_system self.target_component = target_component self.payload = payload def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 84, struct.pack('<BBB251B', self.target_network, self.target_system, self.target_component, self.payload[0], self.payload[1], self.payload[2], self.payload[3], self.payload[4], self.payload[5], self.payload[6], self.payload[7], self.payload[8], self.payload[9], self.payload[10], self.payload[11], self.payload[12], self.payload[13], self.payload[14], self.payload[15], self.payload[16], self.payload[17], self.payload[18], self.payload[19], self.payload[20], self.payload[21], self.payload[22], self.payload[23], self.payload[24], self.payload[25], self.payload[26], self.payload[27], self.payload[28], self.payload[29], self.payload[30], self.payload[31], self.payload[32], self.payload[33], self.payload[34], self.payload[35], self.payload[36], self.payload[37], self.payload[38], self.payload[39], self.payload[40], self.payload[41], self.payload[42], self.payload[43], self.payload[44], self.payload[45], self.payload[46], self.payload[47], self.payload[48], self.payload[49], self.payload[50], self.payload[51], self.payload[52], self.payload[53], self.payload[54], self.payload[55], self.payload[56], self.payload[57], self.payload[58], self.payload[59], self.payload[60], self.payload[61], self.payload[62], self.payload[63], self.payload[64], self.payload[65], self.payload[66], self.payload[67], self.payload[68], self.payload[69], self.payload[70], self.payload[71], self.payload[72], self.payload[73], self.payload[74], self.payload[75], self.payload[76], self.payload[77], self.payload[78], self.payload[79], self.payload[80], self.payload[81], self.payload[82], self.payload[83], self.payload[84], self.payload[85], self.payload[86], self.payload[87], self.payload[88], self.payload[89], self.payload[90], self.payload[91], self.payload[92], self.payload[93], self.payload[94], self.payload[95], self.payload[96], self.payload[97], self.payload[98], self.payload[99], self.payload[100], self.payload[101], self.payload[102], self.payload[103], self.payload[104], self.payload[105], self.payload[106], self.payload[107], self.payload[108], self.payload[109], self.payload[110], self.payload[111], self.payload[112], self.payload[113], self.payload[114], self.payload[115], self.payload[116], self.payload[117], self.payload[118], self.payload[119], self.payload[120], self.payload[121], self.payload[122], self.payload[123], self.payload[124], self.payload[125], self.payload[126], self.payload[127], self.payload[128], self.payload[129], self.payload[130], self.payload[131], self.payload[132], self.payload[133], self.payload[134], self.payload[135], self.payload[136], self.payload[137], self.payload[138], self.payload[139], self.payload[140], self.payload[141], self.payload[142], self.payload[143], self.payload[144], self.payload[145], self.payload[146], self.payload[147], self.payload[148], self.payload[149], self.payload[150], self.payload[151], self.payload[152], self.payload[153], self.payload[154], self.payload[155], self.payload[156], self.payload[157], self.payload[158], self.payload[159], self.payload[160], self.payload[161], self.payload[162], self.payload[163], self.payload[164], self.payload[165], self.payload[166], self.payload[167], self.payload[168], self.payload[169], self.payload[170], self.payload[171], self.payload[172], self.payload[173], self.payload[174], self.payload[175], self.payload[176], self.payload[177], self.payload[178], self.payload[179], self.payload[180], self.payload[181], self.payload[182], self.payload[183], self.payload[184], self.payload[185], self.payload[186], self.payload[187], self.payload[188], self.payload[189], self.payload[190], self.payload[191], self.payload[192], self.payload[193], self.payload[194], self.payload[195], self.payload[196], self.payload[197], self.payload[198], self.payload[199], self.payload[200], self.payload[201], self.payload[202], self.payload[203], self.payload[204], self.payload[205], self.payload[206], self.payload[207], self.payload[208], self.payload[209], self.payload[210], self.payload[211], self.payload[212], self.payload[213], self.payload[214], self.payload[215], self.payload[216], self.payload[217], self.payload[218], self.payload[219], self.payload[220], self.payload[221], self.payload[222], self.payload[223], self.payload[224], self.payload[225], self.payload[226], self.payload[227], self.payload[228], self.payload[229], self.payload[230], self.payload[231], self.payload[232], self.payload[233], self.payload[234], self.payload[235], self.payload[236], self.payload[237], self.payload[238], self.payload[239], self.payload[240], self.payload[241], self.payload[242], self.payload[243], self.payload[244], self.payload[245], self.payload[246], self.payload[247], self.payload[248], self.payload[249], self.payload[250]), force_mavlink1=force_mavlink1) class MAVLink_timesync_message(MAVLink_message): ''' Time synchronization message. ''' id = MAVLINK_MSG_ID_TIMESYNC name = 'TIMESYNC' fieldnames = ['tc1', 'ts1'] ordered_fieldnames = ['tc1', 'ts1'] fieldtypes = ['int64_t', 'int64_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<qq' native_format = bytearray('<qq', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 34 unpacker = struct.Struct('<qq') def __init__(self, tc1, ts1): MAVLink_message.__init__(self, MAVLink_timesync_message.id, MAVLink_timesync_message.name) self._fieldnames = MAVLink_timesync_message.fieldnames self.tc1 = tc1 self.ts1 = ts1 def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 34, struct.pack('<qq', self.tc1, self.ts1), force_mavlink1=force_mavlink1) class MAVLink_camera_trigger_message(MAVLink_message): ''' Camera-IMU triggering and synchronisation message. ''' id = MAVLINK_MSG_ID_CAMERA_TRIGGER name = 'CAMERA_TRIGGER' fieldnames = ['time_usec', 'seq'] ordered_fieldnames = ['time_usec', 'seq'] fieldtypes = ['uint64_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<QI' native_format = bytearray('<QI', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 174 unpacker = struct.Struct('<QI') def __init__(self, time_usec, seq): MAVLink_message.__init__(self, MAVLink_camera_trigger_message.id, MAVLink_camera_trigger_message.name) self._fieldnames = MAVLink_camera_trigger_message.fieldnames self.time_usec = time_usec self.seq = seq def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 174, struct.pack('<QI', self.time_usec, self.seq), force_mavlink1=force_mavlink1) class MAVLink_hil_gps_message(MAVLink_message): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. ''' id = MAVLINK_MSG_ID_HIL_GPS name = 'HIL_GPS' fieldnames = ['time_usec', 'fix_type', 'lat', 'lon', 'alt', 'eph', 'epv', 'vel', 'vn', 've', 'vd', 'cog', 'satellites_visible'] ordered_fieldnames = ['time_usec', 'lat', 'lon', 'alt', 'eph', 'epv', 'vel', 'vn', 've', 'vd', 'cog', 'fix_type', 'satellites_visible'] fieldtypes = ['uint64_t', 'uint8_t', 'int32_t', 'int32_t', 'int32_t', 'uint16_t', 'uint16_t', 'uint16_t', 'int16_t', 'int16_t', 'int16_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "lat": "degE7", "lon": "degE7", "alt": "mm", "eph": "cm", "epv": "cm", "vel": "cm/s", "vn": "cm/s", "ve": "cm/s", "vd": "cm/s", "cog": "cdeg"} format = '<QiiiHHHhhhHBB' native_format = bytearray('<QiiiHHHhhhHBB', 'ascii') orders = [0, 11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 124 unpacker = struct.Struct('<QiiiHHHhhhHBB') def __init__(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible): MAVLink_message.__init__(self, MAVLink_hil_gps_message.id, MAVLink_hil_gps_message.name) self._fieldnames = MAVLink_hil_gps_message.fieldnames self.time_usec = time_usec self.fix_type = fix_type self.lat = lat self.lon = lon self.alt = alt self.eph = eph self.epv = epv self.vel = vel self.vn = vn self.ve = ve self.vd = vd self.cog = cog self.satellites_visible = satellites_visible def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 124, struct.pack('<QiiiHHHhhhHBB', self.time_usec, self.lat, self.lon, self.alt, self.eph, self.epv, self.vel, self.vn, self.ve, self.vd, self.cog, self.fix_type, self.satellites_visible), force_mavlink1=force_mavlink1) class MAVLink_hil_optical_flow_message(MAVLink_message): ''' Simulated optical flow from a flow sensor (e.g. PX4FLOW or optical mouse sensor) ''' id = MAVLINK_MSG_ID_HIL_OPTICAL_FLOW name = 'HIL_OPTICAL_FLOW' fieldnames = ['time_usec', 'sensor_id', 'integration_time_us', 'integrated_x', 'integrated_y', 'integrated_xgyro', 'integrated_ygyro', 'integrated_zgyro', 'temperature', 'quality', 'time_delta_distance_us', 'distance'] ordered_fieldnames = ['time_usec', 'integration_time_us', 'integrated_x', 'integrated_y', 'integrated_xgyro', 'integrated_ygyro', 'integrated_zgyro', 'time_delta_distance_us', 'distance', 'temperature', 'sensor_id', 'quality'] fieldtypes = ['uint64_t', 'uint8_t', 'uint32_t', 'float', 'float', 'float', 'float', 'float', 'int16_t', 'uint8_t', 'uint32_t', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "integration_time_us": "us", "integrated_x": "rad", "integrated_y": "rad", "integrated_xgyro": "rad", "integrated_ygyro": "rad", "integrated_zgyro": "rad", "temperature": "cdegC", "time_delta_distance_us": "us", "distance": "m"} format = '<QIfffffIfhBB' native_format = bytearray('<QIfffffIfhBB', 'ascii') orders = [0, 10, 1, 2, 3, 4, 5, 6, 9, 11, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 237 unpacker = struct.Struct('<QIfffffIfhBB') def __init__(self, time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance): MAVLink_message.__init__(self, MAVLink_hil_optical_flow_message.id, MAVLink_hil_optical_flow_message.name) self._fieldnames = MAVLink_hil_optical_flow_message.fieldnames self.time_usec = time_usec self.sensor_id = sensor_id self.integration_time_us = integration_time_us self.integrated_x = integrated_x self.integrated_y = integrated_y self.integrated_xgyro = integrated_xgyro self.integrated_ygyro = integrated_ygyro self.integrated_zgyro = integrated_zgyro self.temperature = temperature self.quality = quality self.time_delta_distance_us = time_delta_distance_us self.distance = distance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 237, struct.pack('<QIfffffIfhBB', self.time_usec, self.integration_time_us, self.integrated_x, self.integrated_y, self.integrated_xgyro, self.integrated_ygyro, self.integrated_zgyro, self.time_delta_distance_us, self.distance, self.temperature, self.sensor_id, self.quality), force_mavlink1=force_mavlink1) class MAVLink_hil_state_quaternion_message(MAVLink_message): ''' Sent from simulation to autopilot, avoids in contrast to HIL_STATE singularities. This packet is useful for high throughput applications such as hardware in the loop simulations. ''' id = MAVLINK_MSG_ID_HIL_STATE_QUATERNION name = 'HIL_STATE_QUATERNION' fieldnames = ['time_usec', 'attitude_quaternion', 'rollspeed', 'pitchspeed', 'yawspeed', 'lat', 'lon', 'alt', 'vx', 'vy', 'vz', 'ind_airspeed', 'true_airspeed', 'xacc', 'yacc', 'zacc'] ordered_fieldnames = ['time_usec', 'attitude_quaternion', 'rollspeed', 'pitchspeed', 'yawspeed', 'lat', 'lon', 'alt', 'vx', 'vy', 'vz', 'ind_airspeed', 'true_airspeed', 'xacc', 'yacc', 'zacc'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'int32_t', 'int32_t', 'int32_t', 'int16_t', 'int16_t', 'int16_t', 'uint16_t', 'uint16_t', 'int16_t', 'int16_t', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "rollspeed": "rad/s", "pitchspeed": "rad/s", "yawspeed": "rad/s", "lat": "degE7", "lon": "degE7", "alt": "mm", "vx": "cm/s", "vy": "cm/s", "vz": "cm/s", "ind_airspeed": "cm/s", "true_airspeed": "cm/s", "xacc": "mG", "yacc": "mG", "zacc": "mG"} format = '<Q4ffffiiihhhHHhhh' native_format = bytearray('<QffffiiihhhHHhhh', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] lengths = [1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 4 unpacker = struct.Struct('<Q4ffffiiihhhHHhhh') def __init__(self, time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc): MAVLink_message.__init__(self, MAVLink_hil_state_quaternion_message.id, MAVLink_hil_state_quaternion_message.name) self._fieldnames = MAVLink_hil_state_quaternion_message.fieldnames self.time_usec = time_usec self.attitude_quaternion = attitude_quaternion self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed self.lat = lat self.lon = lon self.alt = alt self.vx = vx self.vy = vy self.vz = vz self.ind_airspeed = ind_airspeed self.true_airspeed = true_airspeed self.xacc = xacc self.yacc = yacc self.zacc = zacc def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 4, struct.pack('<Q4ffffiiihhhHHhhh', self.time_usec, self.attitude_quaternion[0], self.attitude_quaternion[1], self.attitude_quaternion[2], self.attitude_quaternion[3], self.rollspeed, self.pitchspeed, self.yawspeed, self.lat, self.lon, self.alt, self.vx, self.vy, self.vz, self.ind_airspeed, self.true_airspeed, self.xacc, self.yacc, self.zacc), force_mavlink1=force_mavlink1) class MAVLink_scaled_imu2_message(MAVLink_message): ''' The RAW IMU readings for secondary 9DOF sensor setup. This message should contain the scaled values to the described units ''' id = MAVLINK_MSG_ID_SCALED_IMU2 name = 'SCALED_IMU2' fieldnames = ['time_boot_ms', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'temperature'] ordered_fieldnames = ['time_boot_ms', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'temperature'] fieldtypes = ['uint32_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "xacc": "mG", "yacc": "mG", "zacc": "mG", "xgyro": "mrad/s", "ygyro": "mrad/s", "zgyro": "mrad/s", "xmag": "mgauss", "ymag": "mgauss", "zmag": "mgauss", "temperature": "cdegC"} format = '<Ihhhhhhhhhh' native_format = bytearray('<Ihhhhhhhhhh', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 76 unpacker = struct.Struct('<Ihhhhhhhhhh') def __init__(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0): MAVLink_message.__init__(self, MAVLink_scaled_imu2_message.id, MAVLink_scaled_imu2_message.name) self._fieldnames = MAVLink_scaled_imu2_message.fieldnames self.time_boot_ms = time_boot_ms self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag self.temperature = temperature def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 76, struct.pack('<Ihhhhhhhhhh', self.time_boot_ms, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag, self.temperature), force_mavlink1=force_mavlink1) class MAVLink_log_request_list_message(MAVLink_message): ''' Request a list of available logs. On some systems calling this may stop on-board logging until LOG_REQUEST_END is called. ''' id = MAVLINK_MSG_ID_LOG_REQUEST_LIST name = 'LOG_REQUEST_LIST' fieldnames = ['target_system', 'target_component', 'start', 'end'] ordered_fieldnames = ['start', 'end', 'target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<HHBB' native_format = bytearray('<HHBB', 'ascii') orders = [2, 3, 0, 1] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 128 unpacker = struct.Struct('<HHBB') def __init__(self, target_system, target_component, start, end): MAVLink_message.__init__(self, MAVLink_log_request_list_message.id, MAVLink_log_request_list_message.name) self._fieldnames = MAVLink_log_request_list_message.fieldnames self.target_system = target_system self.target_component = target_component self.start = start self.end = end def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 128, struct.pack('<HHBB', self.start, self.end, self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_log_entry_message(MAVLink_message): ''' Reply to LOG_REQUEST_LIST ''' id = MAVLINK_MSG_ID_LOG_ENTRY name = 'LOG_ENTRY' fieldnames = ['id', 'num_logs', 'last_log_num', 'time_utc', 'size'] ordered_fieldnames = ['time_utc', 'size', 'id', 'num_logs', 'last_log_num'] fieldtypes = ['uint16_t', 'uint16_t', 'uint16_t', 'uint32_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_utc": "s", "size": "bytes"} format = '<IIHHH' native_format = bytearray('<IIHHH', 'ascii') orders = [2, 3, 4, 0, 1] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0] crc_extra = 56 unpacker = struct.Struct('<IIHHH') def __init__(self, id, num_logs, last_log_num, time_utc, size): MAVLink_message.__init__(self, MAVLink_log_entry_message.id, MAVLink_log_entry_message.name) self._fieldnames = MAVLink_log_entry_message.fieldnames self.id = id self.num_logs = num_logs self.last_log_num = last_log_num self.time_utc = time_utc self.size = size def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 56, struct.pack('<IIHHH', self.time_utc, self.size, self.id, self.num_logs, self.last_log_num), force_mavlink1=force_mavlink1) class MAVLink_log_request_data_message(MAVLink_message): ''' Request a chunk of a log ''' id = MAVLINK_MSG_ID_LOG_REQUEST_DATA name = 'LOG_REQUEST_DATA' fieldnames = ['target_system', 'target_component', 'id', 'ofs', 'count'] ordered_fieldnames = ['ofs', 'count', 'id', 'target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"count": "bytes"} format = '<IIHBB' native_format = bytearray('<IIHBB', 'ascii') orders = [3, 4, 2, 0, 1] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0] crc_extra = 116 unpacker = struct.Struct('<IIHBB') def __init__(self, target_system, target_component, id, ofs, count): MAVLink_message.__init__(self, MAVLink_log_request_data_message.id, MAVLink_log_request_data_message.name) self._fieldnames = MAVLink_log_request_data_message.fieldnames self.target_system = target_system self.target_component = target_component self.id = id self.ofs = ofs self.count = count def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 116, struct.pack('<IIHBB', self.ofs, self.count, self.id, self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_log_data_message(MAVLink_message): ''' Reply to LOG_REQUEST_DATA ''' id = MAVLINK_MSG_ID_LOG_DATA name = 'LOG_DATA' fieldnames = ['id', 'ofs', 'count', 'data'] ordered_fieldnames = ['ofs', 'id', 'count', 'data'] fieldtypes = ['uint16_t', 'uint32_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"count": "bytes"} format = '<IHB90B' native_format = bytearray('<IHBB', 'ascii') orders = [1, 0, 2, 3] lengths = [1, 1, 1, 90] array_lengths = [0, 0, 0, 90] crc_extra = 134 unpacker = struct.Struct('<IHB90B') def __init__(self, id, ofs, count, data): MAVLink_message.__init__(self, MAVLink_log_data_message.id, MAVLink_log_data_message.name) self._fieldnames = MAVLink_log_data_message.fieldnames self.id = id self.ofs = ofs self.count = count self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 134, struct.pack('<IHB90B', self.ofs, self.id, self.count, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.data[16], self.data[17], self.data[18], self.data[19], self.data[20], self.data[21], self.data[22], self.data[23], self.data[24], self.data[25], self.data[26], self.data[27], self.data[28], self.data[29], self.data[30], self.data[31], self.data[32], self.data[33], self.data[34], self.data[35], self.data[36], self.data[37], self.data[38], self.data[39], self.data[40], self.data[41], self.data[42], self.data[43], self.data[44], self.data[45], self.data[46], self.data[47], self.data[48], self.data[49], self.data[50], self.data[51], self.data[52], self.data[53], self.data[54], self.data[55], self.data[56], self.data[57], self.data[58], self.data[59], self.data[60], self.data[61], self.data[62], self.data[63], self.data[64], self.data[65], self.data[66], self.data[67], self.data[68], self.data[69], self.data[70], self.data[71], self.data[72], self.data[73], self.data[74], self.data[75], self.data[76], self.data[77], self.data[78], self.data[79], self.data[80], self.data[81], self.data[82], self.data[83], self.data[84], self.data[85], self.data[86], self.data[87], self.data[88], self.data[89]), force_mavlink1=force_mavlink1) class MAVLink_log_erase_message(MAVLink_message): ''' Erase all logs ''' id = MAVLINK_MSG_ID_LOG_ERASE name = 'LOG_ERASE' fieldnames = ['target_system', 'target_component'] ordered_fieldnames = ['target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<BB' native_format = bytearray('<BB', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 237 unpacker = struct.Struct('<BB') def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLink_log_erase_message.id, MAVLink_log_erase_message.name) self._fieldnames = MAVLink_log_erase_message.fieldnames self.target_system = target_system self.target_component = target_component def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 237, struct.pack('<BB', self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_log_request_end_message(MAVLink_message): ''' Stop log transfer and resume normal logging ''' id = MAVLINK_MSG_ID_LOG_REQUEST_END name = 'LOG_REQUEST_END' fieldnames = ['target_system', 'target_component'] ordered_fieldnames = ['target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<BB' native_format = bytearray('<BB', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 203 unpacker = struct.Struct('<BB') def __init__(self, target_system, target_component): MAVLink_message.__init__(self, MAVLink_log_request_end_message.id, MAVLink_log_request_end_message.name) self._fieldnames = MAVLink_log_request_end_message.fieldnames self.target_system = target_system self.target_component = target_component def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 203, struct.pack('<BB', self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_gps_inject_data_message(MAVLink_message): ''' Data for injecting into the onboard GPS (used for DGPS) ''' id = MAVLINK_MSG_ID_GPS_INJECT_DATA name = 'GPS_INJECT_DATA' fieldnames = ['target_system', 'target_component', 'len', 'data'] ordered_fieldnames = ['target_system', 'target_component', 'len', 'data'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"len": "bytes"} format = '<BBB110B' native_format = bytearray('<BBBB', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 110] array_lengths = [0, 0, 0, 110] crc_extra = 250 unpacker = struct.Struct('<BBB110B') def __init__(self, target_system, target_component, len, data): MAVLink_message.__init__(self, MAVLink_gps_inject_data_message.id, MAVLink_gps_inject_data_message.name) self._fieldnames = MAVLink_gps_inject_data_message.fieldnames self.target_system = target_system self.target_component = target_component self.len = len self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 250, struct.pack('<BBB110B', self.target_system, self.target_component, self.len, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.data[16], self.data[17], self.data[18], self.data[19], self.data[20], self.data[21], self.data[22], self.data[23], self.data[24], self.data[25], self.data[26], self.data[27], self.data[28], self.data[29], self.data[30], self.data[31], self.data[32], self.data[33], self.data[34], self.data[35], self.data[36], self.data[37], self.data[38], self.data[39], self.data[40], self.data[41], self.data[42], self.data[43], self.data[44], self.data[45], self.data[46], self.data[47], self.data[48], self.data[49], self.data[50], self.data[51], self.data[52], self.data[53], self.data[54], self.data[55], self.data[56], self.data[57], self.data[58], self.data[59], self.data[60], self.data[61], self.data[62], self.data[63], self.data[64], self.data[65], self.data[66], self.data[67], self.data[68], self.data[69], self.data[70], self.data[71], self.data[72], self.data[73], self.data[74], self.data[75], self.data[76], self.data[77], self.data[78], self.data[79], self.data[80], self.data[81], self.data[82], self.data[83], self.data[84], self.data[85], self.data[86], self.data[87], self.data[88], self.data[89], self.data[90], self.data[91], self.data[92], self.data[93], self.data[94], self.data[95], self.data[96], self.data[97], self.data[98], self.data[99], self.data[100], self.data[101], self.data[102], self.data[103], self.data[104], self.data[105], self.data[106], self.data[107], self.data[108], self.data[109]), force_mavlink1=force_mavlink1) class MAVLink_gps2_raw_message(MAVLink_message): ''' Second GPS data. ''' id = MAVLINK_MSG_ID_GPS2_RAW name = 'GPS2_RAW' fieldnames = ['time_usec', 'fix_type', 'lat', 'lon', 'alt', 'eph', 'epv', 'vel', 'cog', 'satellites_visible', 'dgps_numch', 'dgps_age'] ordered_fieldnames = ['time_usec', 'lat', 'lon', 'alt', 'dgps_age', 'eph', 'epv', 'vel', 'cog', 'fix_type', 'satellites_visible', 'dgps_numch'] fieldtypes = ['uint64_t', 'uint8_t', 'int32_t', 'int32_t', 'int32_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint8_t', 'uint8_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {"fix_type": "GPS_FIX_TYPE"} fieldunits_by_name = {"time_usec": "us", "lat": "degE7", "lon": "degE7", "alt": "mm", "eph": "cm", "epv": "cm", "vel": "cm/s", "cog": "cdeg", "dgps_age": "ms"} format = '<QiiiIHHHHBBB' native_format = bytearray('<QiiiIHHHHBBB', 'ascii') orders = [0, 9, 1, 2, 3, 5, 6, 7, 8, 10, 11, 4] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 87 unpacker = struct.Struct('<QiiiIHHHHBBB') def __init__(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age): MAVLink_message.__init__(self, MAVLink_gps2_raw_message.id, MAVLink_gps2_raw_message.name) self._fieldnames = MAVLink_gps2_raw_message.fieldnames self.time_usec = time_usec self.fix_type = fix_type self.lat = lat self.lon = lon self.alt = alt self.eph = eph self.epv = epv self.vel = vel self.cog = cog self.satellites_visible = satellites_visible self.dgps_numch = dgps_numch self.dgps_age = dgps_age def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 87, struct.pack('<QiiiIHHHHBBB', self.time_usec, self.lat, self.lon, self.alt, self.dgps_age, self.eph, self.epv, self.vel, self.cog, self.fix_type, self.satellites_visible, self.dgps_numch), force_mavlink1=force_mavlink1) class MAVLink_power_status_message(MAVLink_message): ''' Power supply status ''' id = MAVLINK_MSG_ID_POWER_STATUS name = 'POWER_STATUS' fieldnames = ['Vcc', 'Vservo', 'flags'] ordered_fieldnames = ['Vcc', 'Vservo', 'flags'] fieldtypes = ['uint16_t', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {"flags": "bitmask"} fieldenums_by_name = {"flags": "MAV_POWER_STATUS"} fieldunits_by_name = {"Vcc": "mV", "Vservo": "mV"} format = '<HHH' native_format = bytearray('<HHH', 'ascii') orders = [0, 1, 2] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 203 unpacker = struct.Struct('<HHH') def __init__(self, Vcc, Vservo, flags): MAVLink_message.__init__(self, MAVLink_power_status_message.id, MAVLink_power_status_message.name) self._fieldnames = MAVLink_power_status_message.fieldnames self.Vcc = Vcc self.Vservo = Vservo self.flags = flags def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 203, struct.pack('<HHH', self.Vcc, self.Vservo, self.flags), force_mavlink1=force_mavlink1) class MAVLink_serial_control_message(MAVLink_message): ''' Control a serial port. This can be used for raw access to an onboard serial peripheral such as a GPS or telemetry radio. It is designed to make it possible to update the devices firmware via MAVLink messages or change the devices settings. A message with zero bytes can be used to change just the baudrate. ''' id = MAVLINK_MSG_ID_SERIAL_CONTROL name = 'SERIAL_CONTROL' fieldnames = ['device', 'flags', 'timeout', 'baudrate', 'count', 'data'] ordered_fieldnames = ['baudrate', 'timeout', 'device', 'flags', 'count', 'data'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {"flags": "bitmask"} fieldenums_by_name = {"device": "SERIAL_CONTROL_DEV", "flags": "SERIAL_CONTROL_FLAG"} fieldunits_by_name = {"timeout": "ms", "baudrate": "bits/s", "count": "bytes"} format = '<IHBBB70B' native_format = bytearray('<IHBBBB', 'ascii') orders = [2, 3, 1, 0, 4, 5] lengths = [1, 1, 1, 1, 1, 70] array_lengths = [0, 0, 0, 0, 0, 70] crc_extra = 220 unpacker = struct.Struct('<IHBBB70B') def __init__(self, device, flags, timeout, baudrate, count, data): MAVLink_message.__init__(self, MAVLink_serial_control_message.id, MAVLink_serial_control_message.name) self._fieldnames = MAVLink_serial_control_message.fieldnames self.device = device self.flags = flags self.timeout = timeout self.baudrate = baudrate self.count = count self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 220, struct.pack('<IHBBB70B', self.baudrate, self.timeout, self.device, self.flags, self.count, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.data[16], self.data[17], self.data[18], self.data[19], self.data[20], self.data[21], self.data[22], self.data[23], self.data[24], self.data[25], self.data[26], self.data[27], self.data[28], self.data[29], self.data[30], self.data[31], self.data[32], self.data[33], self.data[34], self.data[35], self.data[36], self.data[37], self.data[38], self.data[39], self.data[40], self.data[41], self.data[42], self.data[43], self.data[44], self.data[45], self.data[46], self.data[47], self.data[48], self.data[49], self.data[50], self.data[51], self.data[52], self.data[53], self.data[54], self.data[55], self.data[56], self.data[57], self.data[58], self.data[59], self.data[60], self.data[61], self.data[62], self.data[63], self.data[64], self.data[65], self.data[66], self.data[67], self.data[68], self.data[69]), force_mavlink1=force_mavlink1) class MAVLink_gps_rtk_message(MAVLink_message): ''' RTK GPS data. Gives information on the relative baseline calculation the GPS is reporting ''' id = MAVLINK_MSG_ID_GPS_RTK name = 'GPS_RTK' fieldnames = ['time_last_baseline_ms', 'rtk_receiver_id', 'wn', 'tow', 'rtk_health', 'rtk_rate', 'nsats', 'baseline_coords_type', 'baseline_a_mm', 'baseline_b_mm', 'baseline_c_mm', 'accuracy', 'iar_num_hypotheses'] ordered_fieldnames = ['time_last_baseline_ms', 'tow', 'baseline_a_mm', 'baseline_b_mm', 'baseline_c_mm', 'accuracy', 'iar_num_hypotheses', 'wn', 'rtk_receiver_id', 'rtk_health', 'rtk_rate', 'nsats', 'baseline_coords_type'] fieldtypes = ['uint32_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'int32_t', 'int32_t', 'int32_t', 'uint32_t', 'int32_t'] fielddisplays_by_name = {} fieldenums_by_name = {"baseline_coords_type": "RTK_BASELINE_COORDINATE_SYSTEM"} fieldunits_by_name = {"time_last_baseline_ms": "ms", "tow": "ms", "rtk_rate": "Hz", "baseline_a_mm": "mm", "baseline_b_mm": "mm", "baseline_c_mm": "mm"} format = '<IIiiiIiHBBBBB' native_format = bytearray('<IIiiiIiHBBBBB', 'ascii') orders = [0, 8, 7, 1, 9, 10, 11, 12, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 25 unpacker = struct.Struct('<IIiiiIiHBBBBB') def __init__(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses): MAVLink_message.__init__(self, MAVLink_gps_rtk_message.id, MAVLink_gps_rtk_message.name) self._fieldnames = MAVLink_gps_rtk_message.fieldnames self.time_last_baseline_ms = time_last_baseline_ms self.rtk_receiver_id = rtk_receiver_id self.wn = wn self.tow = tow self.rtk_health = rtk_health self.rtk_rate = rtk_rate self.nsats = nsats self.baseline_coords_type = baseline_coords_type self.baseline_a_mm = baseline_a_mm self.baseline_b_mm = baseline_b_mm self.baseline_c_mm = baseline_c_mm self.accuracy = accuracy self.iar_num_hypotheses = iar_num_hypotheses def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 25, struct.pack('<IIiiiIiHBBBBB', self.time_last_baseline_ms, self.tow, self.baseline_a_mm, self.baseline_b_mm, self.baseline_c_mm, self.accuracy, self.iar_num_hypotheses, self.wn, self.rtk_receiver_id, self.rtk_health, self.rtk_rate, self.nsats, self.baseline_coords_type), force_mavlink1=force_mavlink1) class MAVLink_gps2_rtk_message(MAVLink_message): ''' RTK GPS data. Gives information on the relative baseline calculation the GPS is reporting ''' id = MAVLINK_MSG_ID_GPS2_RTK name = 'GPS2_RTK' fieldnames = ['time_last_baseline_ms', 'rtk_receiver_id', 'wn', 'tow', 'rtk_health', 'rtk_rate', 'nsats', 'baseline_coords_type', 'baseline_a_mm', 'baseline_b_mm', 'baseline_c_mm', 'accuracy', 'iar_num_hypotheses'] ordered_fieldnames = ['time_last_baseline_ms', 'tow', 'baseline_a_mm', 'baseline_b_mm', 'baseline_c_mm', 'accuracy', 'iar_num_hypotheses', 'wn', 'rtk_receiver_id', 'rtk_health', 'rtk_rate', 'nsats', 'baseline_coords_type'] fieldtypes = ['uint32_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'int32_t', 'int32_t', 'int32_t', 'uint32_t', 'int32_t'] fielddisplays_by_name = {} fieldenums_by_name = {"baseline_coords_type": "RTK_BASELINE_COORDINATE_SYSTEM"} fieldunits_by_name = {"time_last_baseline_ms": "ms", "tow": "ms", "rtk_rate": "Hz", "baseline_a_mm": "mm", "baseline_b_mm": "mm", "baseline_c_mm": "mm"} format = '<IIiiiIiHBBBBB' native_format = bytearray('<IIiiiIiHBBBBB', 'ascii') orders = [0, 8, 7, 1, 9, 10, 11, 12, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 226 unpacker = struct.Struct('<IIiiiIiHBBBBB') def __init__(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses): MAVLink_message.__init__(self, MAVLink_gps2_rtk_message.id, MAVLink_gps2_rtk_message.name) self._fieldnames = MAVLink_gps2_rtk_message.fieldnames self.time_last_baseline_ms = time_last_baseline_ms self.rtk_receiver_id = rtk_receiver_id self.wn = wn self.tow = tow self.rtk_health = rtk_health self.rtk_rate = rtk_rate self.nsats = nsats self.baseline_coords_type = baseline_coords_type self.baseline_a_mm = baseline_a_mm self.baseline_b_mm = baseline_b_mm self.baseline_c_mm = baseline_c_mm self.accuracy = accuracy self.iar_num_hypotheses = iar_num_hypotheses def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 226, struct.pack('<IIiiiIiHBBBBB', self.time_last_baseline_ms, self.tow, self.baseline_a_mm, self.baseline_b_mm, self.baseline_c_mm, self.accuracy, self.iar_num_hypotheses, self.wn, self.rtk_receiver_id, self.rtk_health, self.rtk_rate, self.nsats, self.baseline_coords_type), force_mavlink1=force_mavlink1) class MAVLink_scaled_imu3_message(MAVLink_message): ''' The RAW IMU readings for 3rd 9DOF sensor setup. This message should contain the scaled values to the described units ''' id = MAVLINK_MSG_ID_SCALED_IMU3 name = 'SCALED_IMU3' fieldnames = ['time_boot_ms', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'temperature'] ordered_fieldnames = ['time_boot_ms', 'xacc', 'yacc', 'zacc', 'xgyro', 'ygyro', 'zgyro', 'xmag', 'ymag', 'zmag', 'temperature'] fieldtypes = ['uint32_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "xacc": "mG", "yacc": "mG", "zacc": "mG", "xgyro": "mrad/s", "ygyro": "mrad/s", "zgyro": "mrad/s", "xmag": "mgauss", "ymag": "mgauss", "zmag": "mgauss", "temperature": "cdegC"} format = '<Ihhhhhhhhhh' native_format = bytearray('<Ihhhhhhhhhh', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 46 unpacker = struct.Struct('<Ihhhhhhhhhh') def __init__(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0): MAVLink_message.__init__(self, MAVLink_scaled_imu3_message.id, MAVLink_scaled_imu3_message.name) self._fieldnames = MAVLink_scaled_imu3_message.fieldnames self.time_boot_ms = time_boot_ms self.xacc = xacc self.yacc = yacc self.zacc = zacc self.xgyro = xgyro self.ygyro = ygyro self.zgyro = zgyro self.xmag = xmag self.ymag = ymag self.zmag = zmag self.temperature = temperature def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 46, struct.pack('<Ihhhhhhhhhh', self.time_boot_ms, self.xacc, self.yacc, self.zacc, self.xgyro, self.ygyro, self.zgyro, self.xmag, self.ymag, self.zmag, self.temperature), force_mavlink1=force_mavlink1) class MAVLink_data_transmission_handshake_message(MAVLink_message): ''' Handshake message to initiate, control and stop image streaming when using the Image Transmission Protocol: https://mavlink.io/en/services/image_transmission.html. ''' id = MAVLINK_MSG_ID_DATA_TRANSMISSION_HANDSHAKE name = 'DATA_TRANSMISSION_HANDSHAKE' fieldnames = ['type', 'size', 'width', 'height', 'packets', 'payload', 'jpg_quality'] ordered_fieldnames = ['size', 'width', 'height', 'packets', 'type', 'payload', 'jpg_quality'] fieldtypes = ['uint8_t', 'uint32_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"type": "MAVLINK_DATA_STREAM_TYPE"} fieldunits_by_name = {"size": "bytes", "payload": "bytes", "jpg_quality": "%"} format = '<IHHHBBB' native_format = bytearray('<IHHHBBB', 'ascii') orders = [4, 0, 1, 2, 3, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 29 unpacker = struct.Struct('<IHHHBBB') def __init__(self, type, size, width, height, packets, payload, jpg_quality): MAVLink_message.__init__(self, MAVLink_data_transmission_handshake_message.id, MAVLink_data_transmission_handshake_message.name) self._fieldnames = MAVLink_data_transmission_handshake_message.fieldnames self.type = type self.size = size self.width = width self.height = height self.packets = packets self.payload = payload self.jpg_quality = jpg_quality def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 29, struct.pack('<IHHHBBB', self.size, self.width, self.height, self.packets, self.type, self.payload, self.jpg_quality), force_mavlink1=force_mavlink1) class MAVLink_encapsulated_data_message(MAVLink_message): ''' Data packet for images sent using the Image Transmission Protocol: https://mavlink.io/en/services/image_transmission.html. ''' id = MAVLINK_MSG_ID_ENCAPSULATED_DATA name = 'ENCAPSULATED_DATA' fieldnames = ['seqnr', 'data'] ordered_fieldnames = ['seqnr', 'data'] fieldtypes = ['uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<H253B' native_format = bytearray('<HB', 'ascii') orders = [0, 1] lengths = [1, 253] array_lengths = [0, 253] crc_extra = 223 unpacker = struct.Struct('<H253B') def __init__(self, seqnr, data): MAVLink_message.__init__(self, MAVLink_encapsulated_data_message.id, MAVLink_encapsulated_data_message.name) self._fieldnames = MAVLink_encapsulated_data_message.fieldnames self.seqnr = seqnr self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 223, struct.pack('<H253B', self.seqnr, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.data[16], self.data[17], self.data[18], self.data[19], self.data[20], self.data[21], self.data[22], self.data[23], self.data[24], self.data[25], self.data[26], self.data[27], self.data[28], self.data[29], self.data[30], self.data[31], self.data[32], self.data[33], self.data[34], self.data[35], self.data[36], self.data[37], self.data[38], self.data[39], self.data[40], self.data[41], self.data[42], self.data[43], self.data[44], self.data[45], self.data[46], self.data[47], self.data[48], self.data[49], self.data[50], self.data[51], self.data[52], self.data[53], self.data[54], self.data[55], self.data[56], self.data[57], self.data[58], self.data[59], self.data[60], self.data[61], self.data[62], self.data[63], self.data[64], self.data[65], self.data[66], self.data[67], self.data[68], self.data[69], self.data[70], self.data[71], self.data[72], self.data[73], self.data[74], self.data[75], self.data[76], self.data[77], self.data[78], self.data[79], self.data[80], self.data[81], self.data[82], self.data[83], self.data[84], self.data[85], self.data[86], self.data[87], self.data[88], self.data[89], self.data[90], self.data[91], self.data[92], self.data[93], self.data[94], self.data[95], self.data[96], self.data[97], self.data[98], self.data[99], self.data[100], self.data[101], self.data[102], self.data[103], self.data[104], self.data[105], self.data[106], self.data[107], self.data[108], self.data[109], self.data[110], self.data[111], self.data[112], self.data[113], self.data[114], self.data[115], self.data[116], self.data[117], self.data[118], self.data[119], self.data[120], self.data[121], self.data[122], self.data[123], self.data[124], self.data[125], self.data[126], self.data[127], self.data[128], self.data[129], self.data[130], self.data[131], self.data[132], self.data[133], self.data[134], self.data[135], self.data[136], self.data[137], self.data[138], self.data[139], self.data[140], self.data[141], self.data[142], self.data[143], self.data[144], self.data[145], self.data[146], self.data[147], self.data[148], self.data[149], self.data[150], self.data[151], self.data[152], self.data[153], self.data[154], self.data[155], self.data[156], self.data[157], self.data[158], self.data[159], self.data[160], self.data[161], self.data[162], self.data[163], self.data[164], self.data[165], self.data[166], self.data[167], self.data[168], self.data[169], self.data[170], self.data[171], self.data[172], self.data[173], self.data[174], self.data[175], self.data[176], self.data[177], self.data[178], self.data[179], self.data[180], self.data[181], self.data[182], self.data[183], self.data[184], self.data[185], self.data[186], self.data[187], self.data[188], self.data[189], self.data[190], self.data[191], self.data[192], self.data[193], self.data[194], self.data[195], self.data[196], self.data[197], self.data[198], self.data[199], self.data[200], self.data[201], self.data[202], self.data[203], self.data[204], self.data[205], self.data[206], self.data[207], self.data[208], self.data[209], self.data[210], self.data[211], self.data[212], self.data[213], self.data[214], self.data[215], self.data[216], self.data[217], self.data[218], self.data[219], self.data[220], self.data[221], self.data[222], self.data[223], self.data[224], self.data[225], self.data[226], self.data[227], self.data[228], self.data[229], self.data[230], self.data[231], self.data[232], self.data[233], self.data[234], self.data[235], self.data[236], self.data[237], self.data[238], self.data[239], self.data[240], self.data[241], self.data[242], self.data[243], self.data[244], self.data[245], self.data[246], self.data[247], self.data[248], self.data[249], self.data[250], self.data[251], self.data[252]), force_mavlink1=force_mavlink1) class MAVLink_distance_sensor_message(MAVLink_message): ''' Distance sensor information for an onboard rangefinder. ''' id = MAVLINK_MSG_ID_DISTANCE_SENSOR name = 'DISTANCE_SENSOR' fieldnames = ['time_boot_ms', 'min_distance', 'max_distance', 'current_distance', 'type', 'id', 'orientation', 'covariance', 'horizontal_fov', 'vertical_fov', 'quaternion'] ordered_fieldnames = ['time_boot_ms', 'min_distance', 'max_distance', 'current_distance', 'type', 'id', 'orientation', 'covariance', 'horizontal_fov', 'vertical_fov', 'quaternion'] fieldtypes = ['uint32_t', 'uint16_t', 'uint16_t', 'uint16_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"type": "MAV_DISTANCE_SENSOR", "orientation": "MAV_SENSOR_ORIENTATION"} fieldunits_by_name = {"time_boot_ms": "ms", "min_distance": "cm", "max_distance": "cm", "current_distance": "cm", "covariance": "cm^2", "horizontal_fov": "rad", "vertical_fov": "rad"} format = '<IHHHBBBBff4f' native_format = bytearray('<IHHHBBBBfff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4] crc_extra = 85 unpacker = struct.Struct('<IHHHBBBBff4f') def __init__(self, time_boot_ms, min_distance, max_distance, current_distance, type, id, orientation, covariance, horizontal_fov=0, vertical_fov=0, quaternion=[0,0,0,0]): MAVLink_message.__init__(self, MAVLink_distance_sensor_message.id, MAVLink_distance_sensor_message.name) self._fieldnames = MAVLink_distance_sensor_message.fieldnames self.time_boot_ms = time_boot_ms self.min_distance = min_distance self.max_distance = max_distance self.current_distance = current_distance self.type = type self.id = id self.orientation = orientation self.covariance = covariance self.horizontal_fov = horizontal_fov self.vertical_fov = vertical_fov self.quaternion = quaternion def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 85, struct.pack('<IHHHBBBBff4f', self.time_boot_ms, self.min_distance, self.max_distance, self.current_distance, self.type, self.id, self.orientation, self.covariance, self.horizontal_fov, self.vertical_fov, self.quaternion[0], self.quaternion[1], self.quaternion[2], self.quaternion[3]), force_mavlink1=force_mavlink1) class MAVLink_terrain_request_message(MAVLink_message): ''' Request for terrain data and terrain status ''' id = MAVLINK_MSG_ID_TERRAIN_REQUEST name = 'TERRAIN_REQUEST' fieldnames = ['lat', 'lon', 'grid_spacing', 'mask'] ordered_fieldnames = ['mask', 'lat', 'lon', 'grid_spacing'] fieldtypes = ['int32_t', 'int32_t', 'uint16_t', 'uint64_t'] fielddisplays_by_name = {"mask": "bitmask"} fieldenums_by_name = {} fieldunits_by_name = {"lat": "degE7", "lon": "degE7", "grid_spacing": "m"} format = '<QiiH' native_format = bytearray('<QiiH', 'ascii') orders = [1, 2, 3, 0] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 6 unpacker = struct.Struct('<QiiH') def __init__(self, lat, lon, grid_spacing, mask): MAVLink_message.__init__(self, MAVLink_terrain_request_message.id, MAVLink_terrain_request_message.name) self._fieldnames = MAVLink_terrain_request_message.fieldnames self.lat = lat self.lon = lon self.grid_spacing = grid_spacing self.mask = mask def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 6, struct.pack('<QiiH', self.mask, self.lat, self.lon, self.grid_spacing), force_mavlink1=force_mavlink1) class MAVLink_terrain_data_message(MAVLink_message): ''' Terrain data sent from GCS. The lat/lon and grid_spacing must be the same as a lat/lon from a TERRAIN_REQUEST ''' id = MAVLINK_MSG_ID_TERRAIN_DATA name = 'TERRAIN_DATA' fieldnames = ['lat', 'lon', 'grid_spacing', 'gridbit', 'data'] ordered_fieldnames = ['lat', 'lon', 'grid_spacing', 'data', 'gridbit'] fieldtypes = ['int32_t', 'int32_t', 'uint16_t', 'uint8_t', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"lat": "degE7", "lon": "degE7", "grid_spacing": "m", "data": "m"} format = '<iiH16hB' native_format = bytearray('<iiHhB', 'ascii') orders = [0, 1, 2, 4, 3] lengths = [1, 1, 1, 16, 1] array_lengths = [0, 0, 0, 16, 0] crc_extra = 229 unpacker = struct.Struct('<iiH16hB') def __init__(self, lat, lon, grid_spacing, gridbit, data): MAVLink_message.__init__(self, MAVLink_terrain_data_message.id, MAVLink_terrain_data_message.name) self._fieldnames = MAVLink_terrain_data_message.fieldnames self.lat = lat self.lon = lon self.grid_spacing = grid_spacing self.gridbit = gridbit self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 229, struct.pack('<iiH16hB', self.lat, self.lon, self.grid_spacing, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.gridbit), force_mavlink1=force_mavlink1) class MAVLink_terrain_check_message(MAVLink_message): ''' Request that the vehicle report terrain height at the given location. Used by GCS to check if vehicle has all terrain data needed for a mission. ''' id = MAVLINK_MSG_ID_TERRAIN_CHECK name = 'TERRAIN_CHECK' fieldnames = ['lat', 'lon'] ordered_fieldnames = ['lat', 'lon'] fieldtypes = ['int32_t', 'int32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"lat": "degE7", "lon": "degE7"} format = '<ii' native_format = bytearray('<ii', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 203 unpacker = struct.Struct('<ii') def __init__(self, lat, lon): MAVLink_message.__init__(self, MAVLink_terrain_check_message.id, MAVLink_terrain_check_message.name) self._fieldnames = MAVLink_terrain_check_message.fieldnames self.lat = lat self.lon = lon def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 203, struct.pack('<ii', self.lat, self.lon), force_mavlink1=force_mavlink1) class MAVLink_terrain_report_message(MAVLink_message): ''' Response from a TERRAIN_CHECK request ''' id = MAVLINK_MSG_ID_TERRAIN_REPORT name = 'TERRAIN_REPORT' fieldnames = ['lat', 'lon', 'spacing', 'terrain_height', 'current_height', 'pending', 'loaded'] ordered_fieldnames = ['lat', 'lon', 'terrain_height', 'current_height', 'spacing', 'pending', 'loaded'] fieldtypes = ['int32_t', 'int32_t', 'uint16_t', 'float', 'float', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"lat": "degE7", "lon": "degE7", "terrain_height": "m", "current_height": "m"} format = '<iiffHHH' native_format = bytearray('<iiffHHH', 'ascii') orders = [0, 1, 4, 2, 3, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 1 unpacker = struct.Struct('<iiffHHH') def __init__(self, lat, lon, spacing, terrain_height, current_height, pending, loaded): MAVLink_message.__init__(self, MAVLink_terrain_report_message.id, MAVLink_terrain_report_message.name) self._fieldnames = MAVLink_terrain_report_message.fieldnames self.lat = lat self.lon = lon self.spacing = spacing self.terrain_height = terrain_height self.current_height = current_height self.pending = pending self.loaded = loaded def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 1, struct.pack('<iiffHHH', self.lat, self.lon, self.terrain_height, self.current_height, self.spacing, self.pending, self.loaded), force_mavlink1=force_mavlink1) class MAVLink_scaled_pressure2_message(MAVLink_message): ''' Barometer readings for 2nd barometer ''' id = MAVLINK_MSG_ID_SCALED_PRESSURE2 name = 'SCALED_PRESSURE2' fieldnames = ['time_boot_ms', 'press_abs', 'press_diff', 'temperature'] ordered_fieldnames = ['time_boot_ms', 'press_abs', 'press_diff', 'temperature'] fieldtypes = ['uint32_t', 'float', 'float', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "press_abs": "hPa", "press_diff": "hPa", "temperature": "cdegC"} format = '<Iffh' native_format = bytearray('<Iffh', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 195 unpacker = struct.Struct('<Iffh') def __init__(self, time_boot_ms, press_abs, press_diff, temperature): MAVLink_message.__init__(self, MAVLink_scaled_pressure2_message.id, MAVLink_scaled_pressure2_message.name) self._fieldnames = MAVLink_scaled_pressure2_message.fieldnames self.time_boot_ms = time_boot_ms self.press_abs = press_abs self.press_diff = press_diff self.temperature = temperature def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 195, struct.pack('<Iffh', self.time_boot_ms, self.press_abs, self.press_diff, self.temperature), force_mavlink1=force_mavlink1) class MAVLink_att_pos_mocap_message(MAVLink_message): ''' Motion capture attitude and position ''' id = MAVLINK_MSG_ID_ATT_POS_MOCAP name = 'ATT_POS_MOCAP' fieldnames = ['time_usec', 'q', 'x', 'y', 'z', 'covariance'] ordered_fieldnames = ['time_usec', 'q', 'x', 'y', 'z', 'covariance'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "x": "m", "y": "m", "z": "m"} format = '<Q4ffff21f' native_format = bytearray('<Qfffff', 'ascii') orders = [0, 1, 2, 3, 4, 5] lengths = [1, 4, 1, 1, 1, 21] array_lengths = [0, 4, 0, 0, 0, 21] crc_extra = 109 unpacker = struct.Struct('<Q4ffff21f') def __init__(self, time_usec, q, x, y, z, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]): MAVLink_message.__init__(self, MAVLink_att_pos_mocap_message.id, MAVLink_att_pos_mocap_message.name) self._fieldnames = MAVLink_att_pos_mocap_message.fieldnames self.time_usec = time_usec self.q = q self.x = x self.y = y self.z = z self.covariance = covariance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 109, struct.pack('<Q4ffff21f', self.time_usec, self.q[0], self.q[1], self.q[2], self.q[3], self.x, self.y, self.z, self.covariance[0], self.covariance[1], self.covariance[2], self.covariance[3], self.covariance[4], self.covariance[5], self.covariance[6], self.covariance[7], self.covariance[8], self.covariance[9], self.covariance[10], self.covariance[11], self.covariance[12], self.covariance[13], self.covariance[14], self.covariance[15], self.covariance[16], self.covariance[17], self.covariance[18], self.covariance[19], self.covariance[20]), force_mavlink1=force_mavlink1) class MAVLink_set_actuator_control_target_message(MAVLink_message): ''' Set the vehicle attitude and body angular rates. ''' id = MAVLINK_MSG_ID_SET_ACTUATOR_CONTROL_TARGET name = 'SET_ACTUATOR_CONTROL_TARGET' fieldnames = ['time_usec', 'group_mlx', 'target_system', 'target_component', 'controls'] ordered_fieldnames = ['time_usec', 'controls', 'group_mlx', 'target_system', 'target_component'] fieldtypes = ['uint64_t', 'uint8_t', 'uint8_t', 'uint8_t', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<Q8fBBB' native_format = bytearray('<QfBBB', 'ascii') orders = [0, 2, 3, 4, 1] lengths = [1, 8, 1, 1, 1] array_lengths = [0, 8, 0, 0, 0] crc_extra = 168 unpacker = struct.Struct('<Q8fBBB') def __init__(self, time_usec, group_mlx, target_system, target_component, controls): MAVLink_message.__init__(self, MAVLink_set_actuator_control_target_message.id, MAVLink_set_actuator_control_target_message.name) self._fieldnames = MAVLink_set_actuator_control_target_message.fieldnames self.time_usec = time_usec self.group_mlx = group_mlx self.target_system = target_system self.target_component = target_component self.controls = controls def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 168, struct.pack('<Q8fBBB', self.time_usec, self.controls[0], self.controls[1], self.controls[2], self.controls[3], self.controls[4], self.controls[5], self.controls[6], self.controls[7], self.group_mlx, self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_actuator_control_target_message(MAVLink_message): ''' Set the vehicle attitude and body angular rates. ''' id = MAVLINK_MSG_ID_ACTUATOR_CONTROL_TARGET name = 'ACTUATOR_CONTROL_TARGET' fieldnames = ['time_usec', 'group_mlx', 'controls'] ordered_fieldnames = ['time_usec', 'controls', 'group_mlx'] fieldtypes = ['uint64_t', 'uint8_t', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<Q8fB' native_format = bytearray('<QfB', 'ascii') orders = [0, 2, 1] lengths = [1, 8, 1] array_lengths = [0, 8, 0] crc_extra = 181 unpacker = struct.Struct('<Q8fB') def __init__(self, time_usec, group_mlx, controls): MAVLink_message.__init__(self, MAVLink_actuator_control_target_message.id, MAVLink_actuator_control_target_message.name) self._fieldnames = MAVLink_actuator_control_target_message.fieldnames self.time_usec = time_usec self.group_mlx = group_mlx self.controls = controls def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 181, struct.pack('<Q8fB', self.time_usec, self.controls[0], self.controls[1], self.controls[2], self.controls[3], self.controls[4], self.controls[5], self.controls[6], self.controls[7], self.group_mlx), force_mavlink1=force_mavlink1) class MAVLink_altitude_message(MAVLink_message): ''' The current system altitude. ''' id = MAVLINK_MSG_ID_ALTITUDE name = 'ALTITUDE' fieldnames = ['time_usec', 'altitude_monotonic', 'altitude_amsl', 'altitude_local', 'altitude_relative', 'altitude_terrain', 'bottom_clearance'] ordered_fieldnames = ['time_usec', 'altitude_monotonic', 'altitude_amsl', 'altitude_local', 'altitude_relative', 'altitude_terrain', 'bottom_clearance'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "altitude_monotonic": "m", "altitude_amsl": "m", "altitude_local": "m", "altitude_relative": "m", "altitude_terrain": "m", "bottom_clearance": "m"} format = '<Qffffff' native_format = bytearray('<Qffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 47 unpacker = struct.Struct('<Qffffff') def __init__(self, time_usec, altitude_monotonic, altitude_amsl, altitude_local, altitude_relative, altitude_terrain, bottom_clearance): MAVLink_message.__init__(self, MAVLink_altitude_message.id, MAVLink_altitude_message.name) self._fieldnames = MAVLink_altitude_message.fieldnames self.time_usec = time_usec self.altitude_monotonic = altitude_monotonic self.altitude_amsl = altitude_amsl self.altitude_local = altitude_local self.altitude_relative = altitude_relative self.altitude_terrain = altitude_terrain self.bottom_clearance = bottom_clearance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 47, struct.pack('<Qffffff', self.time_usec, self.altitude_monotonic, self.altitude_amsl, self.altitude_local, self.altitude_relative, self.altitude_terrain, self.bottom_clearance), force_mavlink1=force_mavlink1) class MAVLink_resource_request_message(MAVLink_message): ''' The autopilot is requesting a resource (file, binary, other type of data) ''' id = MAVLINK_MSG_ID_RESOURCE_REQUEST name = 'RESOURCE_REQUEST' fieldnames = ['request_id', 'uri_type', 'uri', 'transfer_type', 'storage'] ordered_fieldnames = ['request_id', 'uri_type', 'uri', 'transfer_type', 'storage'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<BB120BB120B' native_format = bytearray('<BBBBB', 'ascii') orders = [0, 1, 2, 3, 4] lengths = [1, 1, 120, 1, 120] array_lengths = [0, 0, 120, 0, 120] crc_extra = 72 unpacker = struct.Struct('<BB120BB120B') def __init__(self, request_id, uri_type, uri, transfer_type, storage): MAVLink_message.__init__(self, MAVLink_resource_request_message.id, MAVLink_resource_request_message.name) self._fieldnames = MAVLink_resource_request_message.fieldnames self.request_id = request_id self.uri_type = uri_type self.uri = uri self.transfer_type = transfer_type self.storage = storage def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 72, struct.pack('<BB120BB120B', self.request_id, self.uri_type, self.uri[0], self.uri[1], self.uri[2], self.uri[3], self.uri[4], self.uri[5], self.uri[6], self.uri[7], self.uri[8], self.uri[9], self.uri[10], self.uri[11], self.uri[12], self.uri[13], self.uri[14], self.uri[15], self.uri[16], self.uri[17], self.uri[18], self.uri[19], self.uri[20], self.uri[21], self.uri[22], self.uri[23], self.uri[24], self.uri[25], self.uri[26], self.uri[27], self.uri[28], self.uri[29], self.uri[30], self.uri[31], self.uri[32], self.uri[33], self.uri[34], self.uri[35], self.uri[36], self.uri[37], self.uri[38], self.uri[39], self.uri[40], self.uri[41], self.uri[42], self.uri[43], self.uri[44], self.uri[45], self.uri[46], self.uri[47], self.uri[48], self.uri[49], self.uri[50], self.uri[51], self.uri[52], self.uri[53], self.uri[54], self.uri[55], self.uri[56], self.uri[57], self.uri[58], self.uri[59], self.uri[60], self.uri[61], self.uri[62], self.uri[63], self.uri[64], self.uri[65], self.uri[66], self.uri[67], self.uri[68], self.uri[69], self.uri[70], self.uri[71], self.uri[72], self.uri[73], self.uri[74], self.uri[75], self.uri[76], self.uri[77], self.uri[78], self.uri[79], self.uri[80], self.uri[81], self.uri[82], self.uri[83], self.uri[84], self.uri[85], self.uri[86], self.uri[87], self.uri[88], self.uri[89], self.uri[90], self.uri[91], self.uri[92], self.uri[93], self.uri[94], self.uri[95], self.uri[96], self.uri[97], self.uri[98], self.uri[99], self.uri[100], self.uri[101], self.uri[102], self.uri[103], self.uri[104], self.uri[105], self.uri[106], self.uri[107], self.uri[108], self.uri[109], self.uri[110], self.uri[111], self.uri[112], self.uri[113], self.uri[114], self.uri[115], self.uri[116], self.uri[117], self.uri[118], self.uri[119], self.transfer_type, self.storage[0], self.storage[1], self.storage[2], self.storage[3], self.storage[4], self.storage[5], self.storage[6], self.storage[7], self.storage[8], self.storage[9], self.storage[10], self.storage[11], self.storage[12], self.storage[13], self.storage[14], self.storage[15], self.storage[16], self.storage[17], self.storage[18], self.storage[19], self.storage[20], self.storage[21], self.storage[22], self.storage[23], self.storage[24], self.storage[25], self.storage[26], self.storage[27], self.storage[28], self.storage[29], self.storage[30], self.storage[31], self.storage[32], self.storage[33], self.storage[34], self.storage[35], self.storage[36], self.storage[37], self.storage[38], self.storage[39], self.storage[40], self.storage[41], self.storage[42], self.storage[43], self.storage[44], self.storage[45], self.storage[46], self.storage[47], self.storage[48], self.storage[49], self.storage[50], self.storage[51], self.storage[52], self.storage[53], self.storage[54], self.storage[55], self.storage[56], self.storage[57], self.storage[58], self.storage[59], self.storage[60], self.storage[61], self.storage[62], self.storage[63], self.storage[64], self.storage[65], self.storage[66], self.storage[67], self.storage[68], self.storage[69], self.storage[70], self.storage[71], self.storage[72], self.storage[73], self.storage[74], self.storage[75], self.storage[76], self.storage[77], self.storage[78], self.storage[79], self.storage[80], self.storage[81], self.storage[82], self.storage[83], self.storage[84], self.storage[85], self.storage[86], self.storage[87], self.storage[88], self.storage[89], self.storage[90], self.storage[91], self.storage[92], self.storage[93], self.storage[94], self.storage[95], self.storage[96], self.storage[97], self.storage[98], self.storage[99], self.storage[100], self.storage[101], self.storage[102], self.storage[103], self.storage[104], self.storage[105], self.storage[106], self.storage[107], self.storage[108], self.storage[109], self.storage[110], self.storage[111], self.storage[112], self.storage[113], self.storage[114], self.storage[115], self.storage[116], self.storage[117], self.storage[118], self.storage[119]), force_mavlink1=force_mavlink1) class MAVLink_scaled_pressure3_message(MAVLink_message): ''' Barometer readings for 3rd barometer ''' id = MAVLINK_MSG_ID_SCALED_PRESSURE3 name = 'SCALED_PRESSURE3' fieldnames = ['time_boot_ms', 'press_abs', 'press_diff', 'temperature'] ordered_fieldnames = ['time_boot_ms', 'press_abs', 'press_diff', 'temperature'] fieldtypes = ['uint32_t', 'float', 'float', 'int16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "press_abs": "hPa", "press_diff": "hPa", "temperature": "cdegC"} format = '<Iffh' native_format = bytearray('<Iffh', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 131 unpacker = struct.Struct('<Iffh') def __init__(self, time_boot_ms, press_abs, press_diff, temperature): MAVLink_message.__init__(self, MAVLink_scaled_pressure3_message.id, MAVLink_scaled_pressure3_message.name) self._fieldnames = MAVLink_scaled_pressure3_message.fieldnames self.time_boot_ms = time_boot_ms self.press_abs = press_abs self.press_diff = press_diff self.temperature = temperature def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 131, struct.pack('<Iffh', self.time_boot_ms, self.press_abs, self.press_diff, self.temperature), force_mavlink1=force_mavlink1) class MAVLink_follow_target_message(MAVLink_message): ''' Current motion information from a designated system ''' id = MAVLINK_MSG_ID_FOLLOW_TARGET name = 'FOLLOW_TARGET' fieldnames = ['timestamp', 'est_capabilities', 'lat', 'lon', 'alt', 'vel', 'acc', 'attitude_q', 'rates', 'position_cov', 'custom_state'] ordered_fieldnames = ['timestamp', 'custom_state', 'lat', 'lon', 'alt', 'vel', 'acc', 'attitude_q', 'rates', 'position_cov', 'est_capabilities'] fieldtypes = ['uint64_t', 'uint8_t', 'int32_t', 'int32_t', 'float', 'float', 'float', 'float', 'float', 'float', 'uint64_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"timestamp": "ms", "lat": "degE7", "lon": "degE7", "alt": "m", "vel": "m/s", "acc": "m/s/s"} format = '<QQiif3f3f4f3f3fB' native_format = bytearray('<QQiiffffffB', 'ascii') orders = [0, 10, 2, 3, 4, 5, 6, 7, 8, 9, 1] lengths = [1, 1, 1, 1, 1, 3, 3, 4, 3, 3, 1] array_lengths = [0, 0, 0, 0, 0, 3, 3, 4, 3, 3, 0] crc_extra = 127 unpacker = struct.Struct('<QQiif3f3f4f3f3fB') def __init__(self, timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state): MAVLink_message.__init__(self, MAVLink_follow_target_message.id, MAVLink_follow_target_message.name) self._fieldnames = MAVLink_follow_target_message.fieldnames self.timestamp = timestamp self.est_capabilities = est_capabilities self.lat = lat self.lon = lon self.alt = alt self.vel = vel self.acc = acc self.attitude_q = attitude_q self.rates = rates self.position_cov = position_cov self.custom_state = custom_state def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 127, struct.pack('<QQiif3f3f4f3f3fB', self.timestamp, self.custom_state, self.lat, self.lon, self.alt, self.vel[0], self.vel[1], self.vel[2], self.acc[0], self.acc[1], self.acc[2], self.attitude_q[0], self.attitude_q[1], self.attitude_q[2], self.attitude_q[3], self.rates[0], self.rates[1], self.rates[2], self.position_cov[0], self.position_cov[1], self.position_cov[2], self.est_capabilities), force_mavlink1=force_mavlink1) class MAVLink_control_system_state_message(MAVLink_message): ''' The smoothed, monotonic system state used to feed the control loops of the system. ''' id = MAVLINK_MSG_ID_CONTROL_SYSTEM_STATE name = 'CONTROL_SYSTEM_STATE' fieldnames = ['time_usec', 'x_acc', 'y_acc', 'z_acc', 'x_vel', 'y_vel', 'z_vel', 'x_pos', 'y_pos', 'z_pos', 'airspeed', 'vel_variance', 'pos_variance', 'q', 'roll_rate', 'pitch_rate', 'yaw_rate'] ordered_fieldnames = ['time_usec', 'x_acc', 'y_acc', 'z_acc', 'x_vel', 'y_vel', 'z_vel', 'x_pos', 'y_pos', 'z_pos', 'airspeed', 'vel_variance', 'pos_variance', 'q', 'roll_rate', 'pitch_rate', 'yaw_rate'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "x_acc": "m/s/s", "y_acc": "m/s/s", "z_acc": "m/s/s", "x_vel": "m/s", "y_vel": "m/s", "z_vel": "m/s", "x_pos": "m", "y_pos": "m", "z_pos": "m", "airspeed": "m/s", "roll_rate": "rad/s", "pitch_rate": "rad/s", "yaw_rate": "rad/s"} format = '<Qffffffffff3f3f4ffff' native_format = bytearray('<Qffffffffffffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 4, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 0, 0, 0] crc_extra = 103 unpacker = struct.Struct('<Qffffffffff3f3f4ffff') def __init__(self, time_usec, x_acc, y_acc, z_acc, x_vel, y_vel, z_vel, x_pos, y_pos, z_pos, airspeed, vel_variance, pos_variance, q, roll_rate, pitch_rate, yaw_rate): MAVLink_message.__init__(self, MAVLink_control_system_state_message.id, MAVLink_control_system_state_message.name) self._fieldnames = MAVLink_control_system_state_message.fieldnames self.time_usec = time_usec self.x_acc = x_acc self.y_acc = y_acc self.z_acc = z_acc self.x_vel = x_vel self.y_vel = y_vel self.z_vel = z_vel self.x_pos = x_pos self.y_pos = y_pos self.z_pos = z_pos self.airspeed = airspeed self.vel_variance = vel_variance self.pos_variance = pos_variance self.q = q self.roll_rate = roll_rate self.pitch_rate = pitch_rate self.yaw_rate = yaw_rate def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 103, struct.pack('<Qffffffffff3f3f4ffff', self.time_usec, self.x_acc, self.y_acc, self.z_acc, self.x_vel, self.y_vel, self.z_vel, self.x_pos, self.y_pos, self.z_pos, self.airspeed, self.vel_variance[0], self.vel_variance[1], self.vel_variance[2], self.pos_variance[0], self.pos_variance[1], self.pos_variance[2], self.q[0], self.q[1], self.q[2], self.q[3], self.roll_rate, self.pitch_rate, self.yaw_rate), force_mavlink1=force_mavlink1) class MAVLink_battery_status_message(MAVLink_message): ''' Battery information ''' id = MAVLINK_MSG_ID_BATTERY_STATUS name = 'BATTERY_STATUS' fieldnames = ['id', 'battery_function', 'type', 'temperature', 'voltages', 'current_battery', 'current_consumed', 'energy_consumed', 'battery_remaining', 'time_remaining', 'charge_state'] ordered_fieldnames = ['current_consumed', 'energy_consumed', 'temperature', 'voltages', 'current_battery', 'id', 'battery_function', 'type', 'battery_remaining', 'time_remaining', 'charge_state'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'int16_t', 'uint16_t', 'int16_t', 'int32_t', 'int32_t', 'int8_t', 'int32_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"battery_function": "MAV_BATTERY_FUNCTION", "type": "MAV_BATTERY_TYPE", "charge_state": "MAV_BATTERY_CHARGE_STATE"} fieldunits_by_name = {"temperature": "cdegC", "voltages": "mV", "current_battery": "cA", "current_consumed": "mAh", "energy_consumed": "hJ", "battery_remaining": "%", "time_remaining": "s"} format = '<iih10HhBBBbiB' native_format = bytearray('<iihHhBBBbiB', 'ascii') orders = [5, 6, 7, 2, 3, 4, 0, 1, 8, 9, 10] lengths = [1, 1, 1, 10, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0] crc_extra = 154 unpacker = struct.Struct('<iih10HhBBBbiB') def __init__(self, id, battery_function, type, temperature, voltages, current_battery, current_consumed, energy_consumed, battery_remaining, time_remaining=0, charge_state=0): MAVLink_message.__init__(self, MAVLink_battery_status_message.id, MAVLink_battery_status_message.name) self._fieldnames = MAVLink_battery_status_message.fieldnames self.id = id self.battery_function = battery_function self.type = type self.temperature = temperature self.voltages = voltages self.current_battery = current_battery self.current_consumed = current_consumed self.energy_consumed = energy_consumed self.battery_remaining = battery_remaining self.time_remaining = time_remaining self.charge_state = charge_state def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 154, struct.pack('<iih10HhBBBbiB', self.current_consumed, self.energy_consumed, self.temperature, self.voltages[0], self.voltages[1], self.voltages[2], self.voltages[3], self.voltages[4], self.voltages[5], self.voltages[6], self.voltages[7], self.voltages[8], self.voltages[9], self.current_battery, self.id, self.battery_function, self.type, self.battery_remaining, self.time_remaining, self.charge_state), force_mavlink1=force_mavlink1) class MAVLink_autopilot_version_message(MAVLink_message): ''' Version and capability of autopilot software. This should be emitted in response to a MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES command. ''' id = MAVLINK_MSG_ID_AUTOPILOT_VERSION name = 'AUTOPILOT_VERSION' fieldnames = ['capabilities', 'flight_sw_version', 'middleware_sw_version', 'os_sw_version', 'board_version', 'flight_custom_version', 'middleware_custom_version', 'os_custom_version', 'vendor_id', 'product_id', 'uid', 'uid2'] ordered_fieldnames = ['capabilities', 'uid', 'flight_sw_version', 'middleware_sw_version', 'os_sw_version', 'board_version', 'vendor_id', 'product_id', 'flight_custom_version', 'middleware_custom_version', 'os_custom_version', 'uid2'] fieldtypes = ['uint64_t', 'uint32_t', 'uint32_t', 'uint32_t', 'uint32_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint16_t', 'uint16_t', 'uint64_t', 'uint8_t'] fielddisplays_by_name = {"capabilities": "bitmask"} fieldenums_by_name = {"capabilities": "MAV_PROTOCOL_CAPABILITY"} fieldunits_by_name = {} format = '<QQIIIIHH8B8B8B18B' native_format = bytearray('<QQIIIIHHBBBB', 'ascii') orders = [0, 2, 3, 4, 5, 8, 9, 10, 6, 7, 1, 11] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8, 18] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 18] crc_extra = 178 unpacker = struct.Struct('<QQIIIIHH8B8B8B18B') def __init__(self, capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid, uid2=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]): MAVLink_message.__init__(self, MAVLink_autopilot_version_message.id, MAVLink_autopilot_version_message.name) self._fieldnames = MAVLink_autopilot_version_message.fieldnames self.capabilities = capabilities self.flight_sw_version = flight_sw_version self.middleware_sw_version = middleware_sw_version self.os_sw_version = os_sw_version self.board_version = board_version self.flight_custom_version = flight_custom_version self.middleware_custom_version = middleware_custom_version self.os_custom_version = os_custom_version self.vendor_id = vendor_id self.product_id = product_id self.uid = uid self.uid2 = uid2 def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 178, struct.pack('<QQIIIIHH8B8B8B18B', self.capabilities, self.uid, self.flight_sw_version, self.middleware_sw_version, self.os_sw_version, self.board_version, self.vendor_id, self.product_id, self.flight_custom_version[0], self.flight_custom_version[1], self.flight_custom_version[2], self.flight_custom_version[3], self.flight_custom_version[4], self.flight_custom_version[5], self.flight_custom_version[6], self.flight_custom_version[7], self.middleware_custom_version[0], self.middleware_custom_version[1], self.middleware_custom_version[2], self.middleware_custom_version[3], self.middleware_custom_version[4], self.middleware_custom_version[5], self.middleware_custom_version[6], self.middleware_custom_version[7], self.os_custom_version[0], self.os_custom_version[1], self.os_custom_version[2], self.os_custom_version[3], self.os_custom_version[4], self.os_custom_version[5], self.os_custom_version[6], self.os_custom_version[7], self.uid2[0], self.uid2[1], self.uid2[2], self.uid2[3], self.uid2[4], self.uid2[5], self.uid2[6], self.uid2[7], self.uid2[8], self.uid2[9], self.uid2[10], self.uid2[11], self.uid2[12], self.uid2[13], self.uid2[14], self.uid2[15], self.uid2[16], self.uid2[17]), force_mavlink1=force_mavlink1) class MAVLink_landing_target_message(MAVLink_message): ''' The location of a landing target. See: https://mavlink.io/en/services/landing_target.html ''' id = MAVLINK_MSG_ID_LANDING_TARGET name = 'LANDING_TARGET' fieldnames = ['time_usec', 'target_num', 'frame', 'angle_x', 'angle_y', 'distance', 'size_x', 'size_y', 'x', 'y', 'z', 'q', 'type', 'position_valid'] ordered_fieldnames = ['time_usec', 'angle_x', 'angle_y', 'distance', 'size_x', 'size_y', 'target_num', 'frame', 'x', 'y', 'z', 'q', 'type', 'position_valid'] fieldtypes = ['uint64_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"frame": "MAV_FRAME", "type": "LANDING_TARGET_TYPE"} fieldunits_by_name = {"time_usec": "us", "angle_x": "rad", "angle_y": "rad", "distance": "m", "size_x": "rad", "size_y": "rad", "x": "m", "y": "m", "z": "m"} format = '<QfffffBBfff4fBB' native_format = bytearray('<QfffffBBffffBB', 'ascii') orders = [0, 6, 7, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0] crc_extra = 200 unpacker = struct.Struct('<QfffffBBfff4fBB') def __init__(self, time_usec, target_num, frame, angle_x, angle_y, distance, size_x, size_y, x=0, y=0, z=0, q=[0,0,0,0], type=0, position_valid=0): MAVLink_message.__init__(self, MAVLink_landing_target_message.id, MAVLink_landing_target_message.name) self._fieldnames = MAVLink_landing_target_message.fieldnames self.time_usec = time_usec self.target_num = target_num self.frame = frame self.angle_x = angle_x self.angle_y = angle_y self.distance = distance self.size_x = size_x self.size_y = size_y self.x = x self.y = y self.z = z self.q = q self.type = type self.position_valid = position_valid def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 200, struct.pack('<QfffffBBfff4fBB', self.time_usec, self.angle_x, self.angle_y, self.distance, self.size_x, self.size_y, self.target_num, self.frame, self.x, self.y, self.z, self.q[0], self.q[1], self.q[2], self.q[3], self.type, self.position_valid), force_mavlink1=force_mavlink1) class MAVLink_fence_status_message(MAVLink_message): ''' Status of geo-fencing. Sent in extended status stream when fencing enabled. ''' id = MAVLINK_MSG_ID_FENCE_STATUS name = 'FENCE_STATUS' fieldnames = ['breach_status', 'breach_count', 'breach_type', 'breach_time'] ordered_fieldnames = ['breach_time', 'breach_count', 'breach_status', 'breach_type'] fieldtypes = ['uint8_t', 'uint16_t', 'uint8_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {"breach_type": "FENCE_BREACH"} fieldunits_by_name = {"breach_time": "ms"} format = '<IHBB' native_format = bytearray('<IHBB', 'ascii') orders = [2, 1, 3, 0] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 189 unpacker = struct.Struct('<IHBB') def __init__(self, breach_status, breach_count, breach_type, breach_time): MAVLink_message.__init__(self, MAVLink_fence_status_message.id, MAVLink_fence_status_message.name) self._fieldnames = MAVLink_fence_status_message.fieldnames self.breach_status = breach_status self.breach_count = breach_count self.breach_type = breach_type self.breach_time = breach_time def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 189, struct.pack('<IHBB', self.breach_time, self.breach_count, self.breach_status, self.breach_type), force_mavlink1=force_mavlink1) class MAVLink_estimator_status_message(MAVLink_message): ''' Estimator status message including flags, innovation test ratios and estimated accuracies. The flags message is an integer bitmask containing information on which EKF outputs are valid. See the ESTIMATOR_STATUS_FLAGS enum definition for further information. The innovation test ratios show the magnitude of the sensor innovation divided by the innovation check threshold. Under normal operation the innovation test ratios should be below 0.5 with occasional values up to 1.0. Values greater than 1.0 should be rare under normal operation and indicate that a measurement has been rejected by the filter. The user should be notified if an innovation test ratio greater than 1.0 is recorded. Notifications for values in the range between 0.5 and 1.0 should be optional and controllable by the user. ''' id = MAVLINK_MSG_ID_ESTIMATOR_STATUS name = 'ESTIMATOR_STATUS' fieldnames = ['time_usec', 'flags', 'vel_ratio', 'pos_horiz_ratio', 'pos_vert_ratio', 'mag_ratio', 'hagl_ratio', 'tas_ratio', 'pos_horiz_accuracy', 'pos_vert_accuracy'] ordered_fieldnames = ['time_usec', 'vel_ratio', 'pos_horiz_ratio', 'pos_vert_ratio', 'mag_ratio', 'hagl_ratio', 'tas_ratio', 'pos_horiz_accuracy', 'pos_vert_accuracy', 'flags'] fieldtypes = ['uint64_t', 'uint16_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {"flags": "bitmask"} fieldenums_by_name = {"flags": "ESTIMATOR_STATUS_FLAGS"} fieldunits_by_name = {"time_usec": "us", "pos_horiz_accuracy": "m", "pos_vert_accuracy": "m"} format = '<QffffffffH' native_format = bytearray('<QffffffffH', 'ascii') orders = [0, 9, 1, 2, 3, 4, 5, 6, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 163 unpacker = struct.Struct('<QffffffffH') def __init__(self, time_usec, flags, vel_ratio, pos_horiz_ratio, pos_vert_ratio, mag_ratio, hagl_ratio, tas_ratio, pos_horiz_accuracy, pos_vert_accuracy): MAVLink_message.__init__(self, MAVLink_estimator_status_message.id, MAVLink_estimator_status_message.name) self._fieldnames = MAVLink_estimator_status_message.fieldnames self.time_usec = time_usec self.flags = flags self.vel_ratio = vel_ratio self.pos_horiz_ratio = pos_horiz_ratio self.pos_vert_ratio = pos_vert_ratio self.mag_ratio = mag_ratio self.hagl_ratio = hagl_ratio self.tas_ratio = tas_ratio self.pos_horiz_accuracy = pos_horiz_accuracy self.pos_vert_accuracy = pos_vert_accuracy def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 163, struct.pack('<QffffffffH', self.time_usec, self.vel_ratio, self.pos_horiz_ratio, self.pos_vert_ratio, self.mag_ratio, self.hagl_ratio, self.tas_ratio, self.pos_horiz_accuracy, self.pos_vert_accuracy, self.flags), force_mavlink1=force_mavlink1) class MAVLink_wind_cov_message(MAVLink_message): ''' Wind covariance estimate from vehicle. ''' id = MAVLINK_MSG_ID_WIND_COV name = 'WIND_COV' fieldnames = ['time_usec', 'wind_x', 'wind_y', 'wind_z', 'var_horiz', 'var_vert', 'wind_alt', 'horiz_accuracy', 'vert_accuracy'] ordered_fieldnames = ['time_usec', 'wind_x', 'wind_y', 'wind_z', 'var_horiz', 'var_vert', 'wind_alt', 'horiz_accuracy', 'vert_accuracy'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "wind_x": "m/s", "wind_y": "m/s", "wind_z": "m/s", "var_horiz": "m/s", "var_vert": "m/s", "wind_alt": "m", "horiz_accuracy": "m", "vert_accuracy": "m"} format = '<Qffffffff' native_format = bytearray('<Qffffffff', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 105 unpacker = struct.Struct('<Qffffffff') def __init__(self, time_usec, wind_x, wind_y, wind_z, var_horiz, var_vert, wind_alt, horiz_accuracy, vert_accuracy): MAVLink_message.__init__(self, MAVLink_wind_cov_message.id, MAVLink_wind_cov_message.name) self._fieldnames = MAVLink_wind_cov_message.fieldnames self.time_usec = time_usec self.wind_x = wind_x self.wind_y = wind_y self.wind_z = wind_z self.var_horiz = var_horiz self.var_vert = var_vert self.wind_alt = wind_alt self.horiz_accuracy = horiz_accuracy self.vert_accuracy = vert_accuracy def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 105, struct.pack('<Qffffffff', self.time_usec, self.wind_x, self.wind_y, self.wind_z, self.var_horiz, self.var_vert, self.wind_alt, self.horiz_accuracy, self.vert_accuracy), force_mavlink1=force_mavlink1) class MAVLink_gps_input_message(MAVLink_message): ''' GPS sensor input message. This is a raw sensor value sent by the GPS. This is NOT the global position estimate of the system. ''' id = MAVLINK_MSG_ID_GPS_INPUT name = 'GPS_INPUT' fieldnames = ['time_usec', 'gps_id', 'ignore_flags', 'time_week_ms', 'time_week', 'fix_type', 'lat', 'lon', 'alt', 'hdop', 'vdop', 'vn', 've', 'vd', 'speed_accuracy', 'horiz_accuracy', 'vert_accuracy', 'satellites_visible', 'yaw'] ordered_fieldnames = ['time_usec', 'time_week_ms', 'lat', 'lon', 'alt', 'hdop', 'vdop', 'vn', 've', 'vd', 'speed_accuracy', 'horiz_accuracy', 'vert_accuracy', 'ignore_flags', 'time_week', 'gps_id', 'fix_type', 'satellites_visible', 'yaw'] fieldtypes = ['uint64_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint16_t', 'uint8_t', 'int32_t', 'int32_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint8_t', 'uint16_t'] fielddisplays_by_name = {"ignore_flags": "bitmask"} fieldenums_by_name = {"ignore_flags": "GPS_INPUT_IGNORE_FLAGS"} fieldunits_by_name = {"time_usec": "us", "time_week_ms": "ms", "lat": "degE7", "lon": "degE7", "alt": "m", "hdop": "m", "vdop": "m", "vn": "m/s", "ve": "m/s", "vd": "m/s", "speed_accuracy": "m/s", "horiz_accuracy": "m", "vert_accuracy": "m", "yaw": "cdeg"} format = '<QIiifffffffffHHBBBH' native_format = bytearray('<QIiifffffffffHHBBBH', 'ascii') orders = [0, 15, 13, 1, 14, 16, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 17, 18] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 151 unpacker = struct.Struct('<QIiifffffffffHHBBBH') def __init__(self, time_usec, gps_id, ignore_flags, time_week_ms, time_week, fix_type, lat, lon, alt, hdop, vdop, vn, ve, vd, speed_accuracy, horiz_accuracy, vert_accuracy, satellites_visible, yaw=0): MAVLink_message.__init__(self, MAVLink_gps_input_message.id, MAVLink_gps_input_message.name) self._fieldnames = MAVLink_gps_input_message.fieldnames self.time_usec = time_usec self.gps_id = gps_id self.ignore_flags = ignore_flags self.time_week_ms = time_week_ms self.time_week = time_week self.fix_type = fix_type self.lat = lat self.lon = lon self.alt = alt self.hdop = hdop self.vdop = vdop self.vn = vn self.ve = ve self.vd = vd self.speed_accuracy = speed_accuracy self.horiz_accuracy = horiz_accuracy self.vert_accuracy = vert_accuracy self.satellites_visible = satellites_visible self.yaw = yaw def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 151, struct.pack('<QIiifffffffffHHBBBH', self.time_usec, self.time_week_ms, self.lat, self.lon, self.alt, self.hdop, self.vdop, self.vn, self.ve, self.vd, self.speed_accuracy, self.horiz_accuracy, self.vert_accuracy, self.ignore_flags, self.time_week, self.gps_id, self.fix_type, self.satellites_visible, self.yaw), force_mavlink1=force_mavlink1) class MAVLink_gps_rtcm_data_message(MAVLink_message): ''' RTCM message for injecting into the onboard GPS (used for DGPS) ''' id = MAVLINK_MSG_ID_GPS_RTCM_DATA name = 'GPS_RTCM_DATA' fieldnames = ['flags', 'len', 'data'] ordered_fieldnames = ['flags', 'len', 'data'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"len": "bytes"} format = '<BB180B' native_format = bytearray('<BBB', 'ascii') orders = [0, 1, 2] lengths = [1, 1, 180] array_lengths = [0, 0, 180] crc_extra = 35 unpacker = struct.Struct('<BB180B') def __init__(self, flags, len, data): MAVLink_message.__init__(self, MAVLink_gps_rtcm_data_message.id, MAVLink_gps_rtcm_data_message.name) self._fieldnames = MAVLink_gps_rtcm_data_message.fieldnames self.flags = flags self.len = len self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 35, struct.pack('<BB180B', self.flags, self.len, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.data[16], self.data[17], self.data[18], self.data[19], self.data[20], self.data[21], self.data[22], self.data[23], self.data[24], self.data[25], self.data[26], self.data[27], self.data[28], self.data[29], self.data[30], self.data[31], self.data[32], self.data[33], self.data[34], self.data[35], self.data[36], self.data[37], self.data[38], self.data[39], self.data[40], self.data[41], self.data[42], self.data[43], self.data[44], self.data[45], self.data[46], self.data[47], self.data[48], self.data[49], self.data[50], self.data[51], self.data[52], self.data[53], self.data[54], self.data[55], self.data[56], self.data[57], self.data[58], self.data[59], self.data[60], self.data[61], self.data[62], self.data[63], self.data[64], self.data[65], self.data[66], self.data[67], self.data[68], self.data[69], self.data[70], self.data[71], self.data[72], self.data[73], self.data[74], self.data[75], self.data[76], self.data[77], self.data[78], self.data[79], self.data[80], self.data[81], self.data[82], self.data[83], self.data[84], self.data[85], self.data[86], self.data[87], self.data[88], self.data[89], self.data[90], self.data[91], self.data[92], self.data[93], self.data[94], self.data[95], self.data[96], self.data[97], self.data[98], self.data[99], self.data[100], self.data[101], self.data[102], self.data[103], self.data[104], self.data[105], self.data[106], self.data[107], self.data[108], self.data[109], self.data[110], self.data[111], self.data[112], self.data[113], self.data[114], self.data[115], self.data[116], self.data[117], self.data[118], self.data[119], self.data[120], self.data[121], self.data[122], self.data[123], self.data[124], self.data[125], self.data[126], self.data[127], self.data[128], self.data[129], self.data[130], self.data[131], self.data[132], self.data[133], self.data[134], self.data[135], self.data[136], self.data[137], self.data[138], self.data[139], self.data[140], self.data[141], self.data[142], self.data[143], self.data[144], self.data[145], self.data[146], self.data[147], self.data[148], self.data[149], self.data[150], self.data[151], self.data[152], self.data[153], self.data[154], self.data[155], self.data[156], self.data[157], self.data[158], self.data[159], self.data[160], self.data[161], self.data[162], self.data[163], self.data[164], self.data[165], self.data[166], self.data[167], self.data[168], self.data[169], self.data[170], self.data[171], self.data[172], self.data[173], self.data[174], self.data[175], self.data[176], self.data[177], self.data[178], self.data[179]), force_mavlink1=force_mavlink1) class MAVLink_high_latency_message(MAVLink_message): ''' Message appropriate for high latency connections like Iridium ''' id = MAVLINK_MSG_ID_HIGH_LATENCY name = 'HIGH_LATENCY' fieldnames = ['base_mode', 'custom_mode', 'landed_state', 'roll', 'pitch', 'heading', 'throttle', 'heading_sp', 'latitude', 'longitude', 'altitude_amsl', 'altitude_sp', 'airspeed', 'airspeed_sp', 'groundspeed', 'climb_rate', 'gps_nsat', 'gps_fix_type', 'battery_remaining', 'temperature', 'temperature_air', 'failsafe', 'wp_num', 'wp_distance'] ordered_fieldnames = ['custom_mode', 'latitude', 'longitude', 'roll', 'pitch', 'heading', 'heading_sp', 'altitude_amsl', 'altitude_sp', 'wp_distance', 'base_mode', 'landed_state', 'throttle', 'airspeed', 'airspeed_sp', 'groundspeed', 'climb_rate', 'gps_nsat', 'gps_fix_type', 'battery_remaining', 'temperature', 'temperature_air', 'failsafe', 'wp_num'] fieldtypes = ['uint8_t', 'uint32_t', 'uint8_t', 'int16_t', 'int16_t', 'uint16_t', 'int8_t', 'int16_t', 'int32_t', 'int32_t', 'int16_t', 'int16_t', 'uint8_t', 'uint8_t', 'uint8_t', 'int8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'int8_t', 'int8_t', 'uint8_t', 'uint8_t', 'uint16_t'] fielddisplays_by_name = {"base_mode": "bitmask", "custom_mode": "bitmask"} fieldenums_by_name = {"base_mode": "MAV_MODE_FLAG", "landed_state": "MAV_LANDED_STATE", "gps_fix_type": "GPS_FIX_TYPE"} fieldunits_by_name = {"roll": "cdeg", "pitch": "cdeg", "heading": "cdeg", "throttle": "%", "heading_sp": "cdeg", "latitude": "degE7", "longitude": "degE7", "altitude_amsl": "m", "altitude_sp": "m", "airspeed": "m/s", "airspeed_sp": "m/s", "groundspeed": "m/s", "climb_rate": "m/s", "battery_remaining": "%", "temperature": "degC", "temperature_air": "degC", "wp_distance": "m"} format = '<IiihhHhhhHBBbBBBbBBBbbBB' native_format = bytearray('<IiihhHhhhHBBbBBBbBBBbbBB', 'ascii') orders = [10, 0, 11, 3, 4, 5, 12, 6, 1, 2, 7, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 9] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 150 unpacker = struct.Struct('<IiihhHhhhHBBbBBBbBBBbbBB') def __init__(self, base_mode, custom_mode, landed_state, roll, pitch, heading, throttle, heading_sp, latitude, longitude, altitude_amsl, altitude_sp, airspeed, airspeed_sp, groundspeed, climb_rate, gps_nsat, gps_fix_type, battery_remaining, temperature, temperature_air, failsafe, wp_num, wp_distance): MAVLink_message.__init__(self, MAVLink_high_latency_message.id, MAVLink_high_latency_message.name) self._fieldnames = MAVLink_high_latency_message.fieldnames self.base_mode = base_mode self.custom_mode = custom_mode self.landed_state = landed_state self.roll = roll self.pitch = pitch self.heading = heading self.throttle = throttle self.heading_sp = heading_sp self.latitude = latitude self.longitude = longitude self.altitude_amsl = altitude_amsl self.altitude_sp = altitude_sp self.airspeed = airspeed self.airspeed_sp = airspeed_sp self.groundspeed = groundspeed self.climb_rate = climb_rate self.gps_nsat = gps_nsat self.gps_fix_type = gps_fix_type self.battery_remaining = battery_remaining self.temperature = temperature self.temperature_air = temperature_air self.failsafe = failsafe self.wp_num = wp_num self.wp_distance = wp_distance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 150, struct.pack('<IiihhHhhhHBBbBBBbBBBbbBB', self.custom_mode, self.latitude, self.longitude, self.roll, self.pitch, self.heading, self.heading_sp, self.altitude_amsl, self.altitude_sp, self.wp_distance, self.base_mode, self.landed_state, self.throttle, self.airspeed, self.airspeed_sp, self.groundspeed, self.climb_rate, self.gps_nsat, self.gps_fix_type, self.battery_remaining, self.temperature, self.temperature_air, self.failsafe, self.wp_num), force_mavlink1=force_mavlink1) class MAVLink_vibration_message(MAVLink_message): ''' Vibration levels and accelerometer clipping ''' id = MAVLINK_MSG_ID_VIBRATION name = 'VIBRATION' fieldnames = ['time_usec', 'vibration_x', 'vibration_y', 'vibration_z', 'clipping_0', 'clipping_1', 'clipping_2'] ordered_fieldnames = ['time_usec', 'vibration_x', 'vibration_y', 'vibration_z', 'clipping_0', 'clipping_1', 'clipping_2'] fieldtypes = ['uint64_t', 'float', 'float', 'float', 'uint32_t', 'uint32_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<QfffIII' native_format = bytearray('<QfffIII', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 90 unpacker = struct.Struct('<QfffIII') def __init__(self, time_usec, vibration_x, vibration_y, vibration_z, clipping_0, clipping_1, clipping_2): MAVLink_message.__init__(self, MAVLink_vibration_message.id, MAVLink_vibration_message.name) self._fieldnames = MAVLink_vibration_message.fieldnames self.time_usec = time_usec self.vibration_x = vibration_x self.vibration_y = vibration_y self.vibration_z = vibration_z self.clipping_0 = clipping_0 self.clipping_1 = clipping_1 self.clipping_2 = clipping_2 def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 90, struct.pack('<QfffIII', self.time_usec, self.vibration_x, self.vibration_y, self.vibration_z, self.clipping_0, self.clipping_1, self.clipping_2), force_mavlink1=force_mavlink1) class MAVLink_home_position_message(MAVLink_message): ''' This message can be requested by sending the MAV_CMD_GET_HOME_POSITION command. The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitly set by the operator before or after. The position the system will return to and land on. The global and local positions encode the position in the respective coordinate frames, while the q parameter encodes the orientation of the surface. Under normal conditions it describes the heading and terrain slope, which can be used by the aircraft to adjust the approach. The approach 3D vector describes the point to which the system should fly in normal flight mode and then perform a landing sequence along the vector. ''' id = MAVLINK_MSG_ID_HOME_POSITION name = 'HOME_POSITION' fieldnames = ['latitude', 'longitude', 'altitude', 'x', 'y', 'z', 'q', 'approach_x', 'approach_y', 'approach_z', 'time_usec'] ordered_fieldnames = ['latitude', 'longitude', 'altitude', 'x', 'y', 'z', 'q', 'approach_x', 'approach_y', 'approach_z', 'time_usec'] fieldtypes = ['int32_t', 'int32_t', 'int32_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint64_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"latitude": "degE7", "longitude": "degE7", "altitude": "mm", "x": "m", "y": "m", "z": "m", "approach_x": "m", "approach_y": "m", "approach_z": "m", "time_usec": "us"} format = '<iiifff4ffffQ' native_format = bytearray('<iiifffffffQ', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] lengths = [1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0] crc_extra = 104 unpacker = struct.Struct('<iiifff4ffffQ') def __init__(self, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec=0): MAVLink_message.__init__(self, MAVLink_home_position_message.id, MAVLink_home_position_message.name) self._fieldnames = MAVLink_home_position_message.fieldnames self.latitude = latitude self.longitude = longitude self.altitude = altitude self.x = x self.y = y self.z = z self.q = q self.approach_x = approach_x self.approach_y = approach_y self.approach_z = approach_z self.time_usec = time_usec def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 104, struct.pack('<iiifff4ffffQ', self.latitude, self.longitude, self.altitude, self.x, self.y, self.z, self.q[0], self.q[1], self.q[2], self.q[3], self.approach_x, self.approach_y, self.approach_z, self.time_usec), force_mavlink1=force_mavlink1) class MAVLink_set_home_position_message(MAVLink_message): ''' The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitly set by the operator before or after. The global and local positions encode the position in the respective coordinate frames, while the q parameter encodes the orientation of the surface. Under normal conditions it describes the heading and terrain slope, which can be used by the aircraft to adjust the approach. The approach 3D vector describes the point to which the system should fly in normal flight mode and then perform a landing sequence along the vector. ''' id = MAVLINK_MSG_ID_SET_HOME_POSITION name = 'SET_HOME_POSITION' fieldnames = ['target_system', 'latitude', 'longitude', 'altitude', 'x', 'y', 'z', 'q', 'approach_x', 'approach_y', 'approach_z', 'time_usec'] ordered_fieldnames = ['latitude', 'longitude', 'altitude', 'x', 'y', 'z', 'q', 'approach_x', 'approach_y', 'approach_z', 'target_system', 'time_usec'] fieldtypes = ['uint8_t', 'int32_t', 'int32_t', 'int32_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint64_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"latitude": "degE7", "longitude": "degE7", "altitude": "mm", "x": "m", "y": "m", "z": "m", "approach_x": "m", "approach_y": "m", "approach_z": "m", "time_usec": "us"} format = '<iiifff4ffffBQ' native_format = bytearray('<iiifffffffBQ', 'ascii') orders = [10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11] lengths = [1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0] crc_extra = 85 unpacker = struct.Struct('<iiifff4ffffBQ') def __init__(self, target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec=0): MAVLink_message.__init__(self, MAVLink_set_home_position_message.id, MAVLink_set_home_position_message.name) self._fieldnames = MAVLink_set_home_position_message.fieldnames self.target_system = target_system self.latitude = latitude self.longitude = longitude self.altitude = altitude self.x = x self.y = y self.z = z self.q = q self.approach_x = approach_x self.approach_y = approach_y self.approach_z = approach_z self.time_usec = time_usec def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 85, struct.pack('<iiifff4ffffBQ', self.latitude, self.longitude, self.altitude, self.x, self.y, self.z, self.q[0], self.q[1], self.q[2], self.q[3], self.approach_x, self.approach_y, self.approach_z, self.target_system, self.time_usec), force_mavlink1=force_mavlink1) class MAVLink_message_interval_message(MAVLink_message): ''' The interval between messages for a particular MAVLink message ID. This message is the response to the MAV_CMD_GET_MESSAGE_INTERVAL command. This interface replaces DATA_STREAM. ''' id = MAVLINK_MSG_ID_MESSAGE_INTERVAL name = 'MESSAGE_INTERVAL' fieldnames = ['message_id', 'interval_us'] ordered_fieldnames = ['interval_us', 'message_id'] fieldtypes = ['uint16_t', 'int32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"interval_us": "us"} format = '<iH' native_format = bytearray('<iH', 'ascii') orders = [1, 0] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 95 unpacker = struct.Struct('<iH') def __init__(self, message_id, interval_us): MAVLink_message.__init__(self, MAVLink_message_interval_message.id, MAVLink_message_interval_message.name) self._fieldnames = MAVLink_message_interval_message.fieldnames self.message_id = message_id self.interval_us = interval_us def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 95, struct.pack('<iH', self.interval_us, self.message_id), force_mavlink1=force_mavlink1) class MAVLink_extended_sys_state_message(MAVLink_message): ''' Provides state for additional features ''' id = MAVLINK_MSG_ID_EXTENDED_SYS_STATE name = 'EXTENDED_SYS_STATE' fieldnames = ['vtol_state', 'landed_state'] ordered_fieldnames = ['vtol_state', 'landed_state'] fieldtypes = ['uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"vtol_state": "MAV_VTOL_STATE", "landed_state": "MAV_LANDED_STATE"} fieldunits_by_name = {} format = '<BB' native_format = bytearray('<BB', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 0] crc_extra = 130 unpacker = struct.Struct('<BB') def __init__(self, vtol_state, landed_state): MAVLink_message.__init__(self, MAVLink_extended_sys_state_message.id, MAVLink_extended_sys_state_message.name) self._fieldnames = MAVLink_extended_sys_state_message.fieldnames self.vtol_state = vtol_state self.landed_state = landed_state def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 130, struct.pack('<BB', self.vtol_state, self.landed_state), force_mavlink1=force_mavlink1) class MAVLink_adsb_vehicle_message(MAVLink_message): ''' The location and information of an ADSB vehicle ''' id = MAVLINK_MSG_ID_ADSB_VEHICLE name = 'ADSB_VEHICLE' fieldnames = ['ICAO_address', 'lat', 'lon', 'altitude_type', 'altitude', 'heading', 'hor_velocity', 'ver_velocity', 'callsign', 'emitter_type', 'tslc', 'flags', 'squawk'] ordered_fieldnames = ['ICAO_address', 'lat', 'lon', 'altitude', 'heading', 'hor_velocity', 'ver_velocity', 'flags', 'squawk', 'altitude_type', 'callsign', 'emitter_type', 'tslc'] fieldtypes = ['uint32_t', 'int32_t', 'int32_t', 'uint8_t', 'int32_t', 'uint16_t', 'uint16_t', 'int16_t', 'char', 'uint8_t', 'uint8_t', 'uint16_t', 'uint16_t'] fielddisplays_by_name = {"flags": "bitmask"} fieldenums_by_name = {"altitude_type": "ADSB_ALTITUDE_TYPE", "emitter_type": "ADSB_EMITTER_TYPE", "flags": "ADSB_FLAGS"} fieldunits_by_name = {"lat": "degE7", "lon": "degE7", "altitude": "mm", "heading": "cdeg", "hor_velocity": "cm/s", "ver_velocity": "cm/s", "tslc": "s"} format = '<IiiiHHhHHB9sBB' native_format = bytearray('<IiiiHHhHHBcBB', 'ascii') orders = [0, 1, 2, 9, 3, 4, 5, 6, 10, 11, 12, 7, 8] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0] crc_extra = 184 unpacker = struct.Struct('<IiiiHHhHHB9sBB') def __init__(self, ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, callsign, emitter_type, tslc, flags, squawk): MAVLink_message.__init__(self, MAVLink_adsb_vehicle_message.id, MAVLink_adsb_vehicle_message.name) self._fieldnames = MAVLink_adsb_vehicle_message.fieldnames self.ICAO_address = ICAO_address self.lat = lat self.lon = lon self.altitude_type = altitude_type self.altitude = altitude self.heading = heading self.hor_velocity = hor_velocity self.ver_velocity = ver_velocity self.callsign = callsign self.emitter_type = emitter_type self.tslc = tslc self.flags = flags self.squawk = squawk def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 184, struct.pack('<IiiiHHhHHB9sBB', self.ICAO_address, self.lat, self.lon, self.altitude, self.heading, self.hor_velocity, self.ver_velocity, self.flags, self.squawk, self.altitude_type, self.callsign, self.emitter_type, self.tslc), force_mavlink1=force_mavlink1) class MAVLink_collision_message(MAVLink_message): ''' Information about a potential collision ''' id = MAVLINK_MSG_ID_COLLISION name = 'COLLISION' fieldnames = ['src', 'id', 'action', 'threat_level', 'time_to_minimum_delta', 'altitude_minimum_delta', 'horizontal_minimum_delta'] ordered_fieldnames = ['id', 'time_to_minimum_delta', 'altitude_minimum_delta', 'horizontal_minimum_delta', 'src', 'action', 'threat_level'] fieldtypes = ['uint8_t', 'uint32_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"src": "MAV_COLLISION_SRC", "action": "MAV_COLLISION_ACTION", "threat_level": "MAV_COLLISION_THREAT_LEVEL"} fieldunits_by_name = {"time_to_minimum_delta": "s", "altitude_minimum_delta": "m", "horizontal_minimum_delta": "m"} format = '<IfffBBB' native_format = bytearray('<IfffBBB', 'ascii') orders = [4, 0, 5, 6, 1, 2, 3] lengths = [1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0] crc_extra = 81 unpacker = struct.Struct('<IfffBBB') def __init__(self, src, id, action, threat_level, time_to_minimum_delta, altitude_minimum_delta, horizontal_minimum_delta): MAVLink_message.__init__(self, MAVLink_collision_message.id, MAVLink_collision_message.name) self._fieldnames = MAVLink_collision_message.fieldnames self.src = src self.id = id self.action = action self.threat_level = threat_level self.time_to_minimum_delta = time_to_minimum_delta self.altitude_minimum_delta = altitude_minimum_delta self.horizontal_minimum_delta = horizontal_minimum_delta def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 81, struct.pack('<IfffBBB', self.id, self.time_to_minimum_delta, self.altitude_minimum_delta, self.horizontal_minimum_delta, self.src, self.action, self.threat_level), force_mavlink1=force_mavlink1) class MAVLink_v2_extension_message(MAVLink_message): ''' Message implementing parts of the V2 payload specs in V1 frames for transitional support. ''' id = MAVLINK_MSG_ID_V2_EXTENSION name = 'V2_EXTENSION' fieldnames = ['target_network', 'target_system', 'target_component', 'message_type', 'payload'] ordered_fieldnames = ['message_type', 'target_network', 'target_system', 'target_component', 'payload'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint16_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<HBBB249B' native_format = bytearray('<HBBBB', 'ascii') orders = [1, 2, 3, 0, 4] lengths = [1, 1, 1, 1, 249] array_lengths = [0, 0, 0, 0, 249] crc_extra = 8 unpacker = struct.Struct('<HBBB249B') def __init__(self, target_network, target_system, target_component, message_type, payload): MAVLink_message.__init__(self, MAVLink_v2_extension_message.id, MAVLink_v2_extension_message.name) self._fieldnames = MAVLink_v2_extension_message.fieldnames self.target_network = target_network self.target_system = target_system self.target_component = target_component self.message_type = message_type self.payload = payload def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 8, struct.pack('<HBBB249B', self.message_type, self.target_network, self.target_system, self.target_component, self.payload[0], self.payload[1], self.payload[2], self.payload[3], self.payload[4], self.payload[5], self.payload[6], self.payload[7], self.payload[8], self.payload[9], self.payload[10], self.payload[11], self.payload[12], self.payload[13], self.payload[14], self.payload[15], self.payload[16], self.payload[17], self.payload[18], self.payload[19], self.payload[20], self.payload[21], self.payload[22], self.payload[23], self.payload[24], self.payload[25], self.payload[26], self.payload[27], self.payload[28], self.payload[29], self.payload[30], self.payload[31], self.payload[32], self.payload[33], self.payload[34], self.payload[35], self.payload[36], self.payload[37], self.payload[38], self.payload[39], self.payload[40], self.payload[41], self.payload[42], self.payload[43], self.payload[44], self.payload[45], self.payload[46], self.payload[47], self.payload[48], self.payload[49], self.payload[50], self.payload[51], self.payload[52], self.payload[53], self.payload[54], self.payload[55], self.payload[56], self.payload[57], self.payload[58], self.payload[59], self.payload[60], self.payload[61], self.payload[62], self.payload[63], self.payload[64], self.payload[65], self.payload[66], self.payload[67], self.payload[68], self.payload[69], self.payload[70], self.payload[71], self.payload[72], self.payload[73], self.payload[74], self.payload[75], self.payload[76], self.payload[77], self.payload[78], self.payload[79], self.payload[80], self.payload[81], self.payload[82], self.payload[83], self.payload[84], self.payload[85], self.payload[86], self.payload[87], self.payload[88], self.payload[89], self.payload[90], self.payload[91], self.payload[92], self.payload[93], self.payload[94], self.payload[95], self.payload[96], self.payload[97], self.payload[98], self.payload[99], self.payload[100], self.payload[101], self.payload[102], self.payload[103], self.payload[104], self.payload[105], self.payload[106], self.payload[107], self.payload[108], self.payload[109], self.payload[110], self.payload[111], self.payload[112], self.payload[113], self.payload[114], self.payload[115], self.payload[116], self.payload[117], self.payload[118], self.payload[119], self.payload[120], self.payload[121], self.payload[122], self.payload[123], self.payload[124], self.payload[125], self.payload[126], self.payload[127], self.payload[128], self.payload[129], self.payload[130], self.payload[131], self.payload[132], self.payload[133], self.payload[134], self.payload[135], self.payload[136], self.payload[137], self.payload[138], self.payload[139], self.payload[140], self.payload[141], self.payload[142], self.payload[143], self.payload[144], self.payload[145], self.payload[146], self.payload[147], self.payload[148], self.payload[149], self.payload[150], self.payload[151], self.payload[152], self.payload[153], self.payload[154], self.payload[155], self.payload[156], self.payload[157], self.payload[158], self.payload[159], self.payload[160], self.payload[161], self.payload[162], self.payload[163], self.payload[164], self.payload[165], self.payload[166], self.payload[167], self.payload[168], self.payload[169], self.payload[170], self.payload[171], self.payload[172], self.payload[173], self.payload[174], self.payload[175], self.payload[176], self.payload[177], self.payload[178], self.payload[179], self.payload[180], self.payload[181], self.payload[182], self.payload[183], self.payload[184], self.payload[185], self.payload[186], self.payload[187], self.payload[188], self.payload[189], self.payload[190], self.payload[191], self.payload[192], self.payload[193], self.payload[194], self.payload[195], self.payload[196], self.payload[197], self.payload[198], self.payload[199], self.payload[200], self.payload[201], self.payload[202], self.payload[203], self.payload[204], self.payload[205], self.payload[206], self.payload[207], self.payload[208], self.payload[209], self.payload[210], self.payload[211], self.payload[212], self.payload[213], self.payload[214], self.payload[215], self.payload[216], self.payload[217], self.payload[218], self.payload[219], self.payload[220], self.payload[221], self.payload[222], self.payload[223], self.payload[224], self.payload[225], self.payload[226], self.payload[227], self.payload[228], self.payload[229], self.payload[230], self.payload[231], self.payload[232], self.payload[233], self.payload[234], self.payload[235], self.payload[236], self.payload[237], self.payload[238], self.payload[239], self.payload[240], self.payload[241], self.payload[242], self.payload[243], self.payload[244], self.payload[245], self.payload[246], self.payload[247], self.payload[248]), force_mavlink1=force_mavlink1) class MAVLink_memory_vect_message(MAVLink_message): ''' Send raw controller memory. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. ''' id = MAVLINK_MSG_ID_MEMORY_VECT name = 'MEMORY_VECT' fieldnames = ['address', 'ver', 'type', 'value'] ordered_fieldnames = ['address', 'ver', 'type', 'value'] fieldtypes = ['uint16_t', 'uint8_t', 'uint8_t', 'int8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<HBB32b' native_format = bytearray('<HBBb', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 32] array_lengths = [0, 0, 0, 32] crc_extra = 204 unpacker = struct.Struct('<HBB32b') def __init__(self, address, ver, type, value): MAVLink_message.__init__(self, MAVLink_memory_vect_message.id, MAVLink_memory_vect_message.name) self._fieldnames = MAVLink_memory_vect_message.fieldnames self.address = address self.ver = ver self.type = type self.value = value def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 204, struct.pack('<HBB32b', self.address, self.ver, self.type, self.value[0], self.value[1], self.value[2], self.value[3], self.value[4], self.value[5], self.value[6], self.value[7], self.value[8], self.value[9], self.value[10], self.value[11], self.value[12], self.value[13], self.value[14], self.value[15], self.value[16], self.value[17], self.value[18], self.value[19], self.value[20], self.value[21], self.value[22], self.value[23], self.value[24], self.value[25], self.value[26], self.value[27], self.value[28], self.value[29], self.value[30], self.value[31]), force_mavlink1=force_mavlink1) class MAVLink_debug_vect_message(MAVLink_message): ''' To debug something using a named 3D vector. ''' id = MAVLINK_MSG_ID_DEBUG_VECT name = 'DEBUG_VECT' fieldnames = ['name', 'time_usec', 'x', 'y', 'z'] ordered_fieldnames = ['time_usec', 'x', 'y', 'z', 'name'] fieldtypes = ['char', 'uint64_t', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<Qfff10s' native_format = bytearray('<Qfffc', 'ascii') orders = [4, 0, 1, 2, 3] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 10] crc_extra = 49 unpacker = struct.Struct('<Qfff10s') def __init__(self, name, time_usec, x, y, z): MAVLink_message.__init__(self, MAVLink_debug_vect_message.id, MAVLink_debug_vect_message.name) self._fieldnames = MAVLink_debug_vect_message.fieldnames self.name = name self.time_usec = time_usec self.x = x self.y = y self.z = z def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 49, struct.pack('<Qfff10s', self.time_usec, self.x, self.y, self.z, self.name), force_mavlink1=force_mavlink1) class MAVLink_named_value_float_message(MAVLink_message): ''' Send a key-value pair as float. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. ''' id = MAVLINK_MSG_ID_NAMED_VALUE_FLOAT name = 'NAMED_VALUE_FLOAT' fieldnames = ['time_boot_ms', 'name', 'value'] ordered_fieldnames = ['time_boot_ms', 'value', 'name'] fieldtypes = ['uint32_t', 'char', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms"} format = '<If10s' native_format = bytearray('<Ifc', 'ascii') orders = [0, 2, 1] lengths = [1, 1, 1] array_lengths = [0, 0, 10] crc_extra = 170 unpacker = struct.Struct('<If10s') def __init__(self, time_boot_ms, name, value): MAVLink_message.__init__(self, MAVLink_named_value_float_message.id, MAVLink_named_value_float_message.name) self._fieldnames = MAVLink_named_value_float_message.fieldnames self.time_boot_ms = time_boot_ms self.name = name self.value = value def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 170, struct.pack('<If10s', self.time_boot_ms, self.value, self.name), force_mavlink1=force_mavlink1) class MAVLink_named_value_int_message(MAVLink_message): ''' Send a key-value pair as integer. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. ''' id = MAVLINK_MSG_ID_NAMED_VALUE_INT name = 'NAMED_VALUE_INT' fieldnames = ['time_boot_ms', 'name', 'value'] ordered_fieldnames = ['time_boot_ms', 'value', 'name'] fieldtypes = ['uint32_t', 'char', 'int32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms"} format = '<Ii10s' native_format = bytearray('<Iic', 'ascii') orders = [0, 2, 1] lengths = [1, 1, 1] array_lengths = [0, 0, 10] crc_extra = 44 unpacker = struct.Struct('<Ii10s') def __init__(self, time_boot_ms, name, value): MAVLink_message.__init__(self, MAVLink_named_value_int_message.id, MAVLink_named_value_int_message.name) self._fieldnames = MAVLink_named_value_int_message.fieldnames self.time_boot_ms = time_boot_ms self.name = name self.value = value def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 44, struct.pack('<Ii10s', self.time_boot_ms, self.value, self.name), force_mavlink1=force_mavlink1) class MAVLink_statustext_message(MAVLink_message): ''' Status text message. These messages are printed in yellow in the COMM console of QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status and error messages. If implemented wisely, these messages are buffered on the MCU and sent only at a limited rate (e.g. 10 Hz). ''' id = MAVLINK_MSG_ID_STATUSTEXT name = 'STATUSTEXT' fieldnames = ['severity', 'text'] ordered_fieldnames = ['severity', 'text'] fieldtypes = ['uint8_t', 'char'] fielddisplays_by_name = {} fieldenums_by_name = {"severity": "MAV_SEVERITY"} fieldunits_by_name = {} format = '<B50s' native_format = bytearray('<Bc', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 50] crc_extra = 83 unpacker = struct.Struct('<B50s') def __init__(self, severity, text): MAVLink_message.__init__(self, MAVLink_statustext_message.id, MAVLink_statustext_message.name) self._fieldnames = MAVLink_statustext_message.fieldnames self.severity = severity self.text = text def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 83, struct.pack('<B50s', self.severity, self.text), force_mavlink1=force_mavlink1) class MAVLink_debug_message(MAVLink_message): ''' Send a debug value. The index is used to discriminate between values. These values show up in the plot of QGroundControl as DEBUG N. ''' id = MAVLINK_MSG_ID_DEBUG name = 'DEBUG' fieldnames = ['time_boot_ms', 'ind', 'value'] ordered_fieldnames = ['time_boot_ms', 'value', 'ind'] fieldtypes = ['uint32_t', 'uint8_t', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms"} format = '<IfB' native_format = bytearray('<IfB', 'ascii') orders = [0, 2, 1] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 46 unpacker = struct.Struct('<IfB') def __init__(self, time_boot_ms, ind, value): MAVLink_message.__init__(self, MAVLink_debug_message.id, MAVLink_debug_message.name) self._fieldnames = MAVLink_debug_message.fieldnames self.time_boot_ms = time_boot_ms self.ind = ind self.value = value def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 46, struct.pack('<IfB', self.time_boot_ms, self.value, self.ind), force_mavlink1=force_mavlink1) class MAVLink_setup_signing_message(MAVLink_message): ''' Setup a MAVLink2 signing key. If called with secret_key of all zero and zero initial_timestamp will disable signing ''' id = MAVLINK_MSG_ID_SETUP_SIGNING name = 'SETUP_SIGNING' fieldnames = ['target_system', 'target_component', 'secret_key', 'initial_timestamp'] ordered_fieldnames = ['initial_timestamp', 'target_system', 'target_component', 'secret_key'] fieldtypes = ['uint8_t', 'uint8_t', 'uint8_t', 'uint64_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<QBB32B' native_format = bytearray('<QBBB', 'ascii') orders = [1, 2, 3, 0] lengths = [1, 1, 1, 32] array_lengths = [0, 0, 0, 32] crc_extra = 71 unpacker = struct.Struct('<QBB32B') def __init__(self, target_system, target_component, secret_key, initial_timestamp): MAVLink_message.__init__(self, MAVLink_setup_signing_message.id, MAVLink_setup_signing_message.name) self._fieldnames = MAVLink_setup_signing_message.fieldnames self.target_system = target_system self.target_component = target_component self.secret_key = secret_key self.initial_timestamp = initial_timestamp def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 71, struct.pack('<QBB32B', self.initial_timestamp, self.target_system, self.target_component, self.secret_key[0], self.secret_key[1], self.secret_key[2], self.secret_key[3], self.secret_key[4], self.secret_key[5], self.secret_key[6], self.secret_key[7], self.secret_key[8], self.secret_key[9], self.secret_key[10], self.secret_key[11], self.secret_key[12], self.secret_key[13], self.secret_key[14], self.secret_key[15], self.secret_key[16], self.secret_key[17], self.secret_key[18], self.secret_key[19], self.secret_key[20], self.secret_key[21], self.secret_key[22], self.secret_key[23], self.secret_key[24], self.secret_key[25], self.secret_key[26], self.secret_key[27], self.secret_key[28], self.secret_key[29], self.secret_key[30], self.secret_key[31]), force_mavlink1=force_mavlink1) class MAVLink_button_change_message(MAVLink_message): ''' Report button state change. ''' id = MAVLINK_MSG_ID_BUTTON_CHANGE name = 'BUTTON_CHANGE' fieldnames = ['time_boot_ms', 'last_change_ms', 'state'] ordered_fieldnames = ['time_boot_ms', 'last_change_ms', 'state'] fieldtypes = ['uint32_t', 'uint32_t', 'uint8_t'] fielddisplays_by_name = {"state": "bitmask"} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "last_change_ms": "ms"} format = '<IIB' native_format = bytearray('<IIB', 'ascii') orders = [0, 1, 2] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 131 unpacker = struct.Struct('<IIB') def __init__(self, time_boot_ms, last_change_ms, state): MAVLink_message.__init__(self, MAVLink_button_change_message.id, MAVLink_button_change_message.name) self._fieldnames = MAVLink_button_change_message.fieldnames self.time_boot_ms = time_boot_ms self.last_change_ms = last_change_ms self.state = state def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 131, struct.pack('<IIB', self.time_boot_ms, self.last_change_ms, self.state), force_mavlink1=force_mavlink1) class MAVLink_play_tune_message(MAVLink_message): ''' Control vehicle tone generation (buzzer) ''' id = MAVLINK_MSG_ID_PLAY_TUNE name = 'PLAY_TUNE' fieldnames = ['target_system', 'target_component', 'tune', 'tune2'] ordered_fieldnames = ['target_system', 'target_component', 'tune', 'tune2'] fieldtypes = ['uint8_t', 'uint8_t', 'char', 'char'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<BB30s200s' native_format = bytearray('<BBcc', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 30, 200] crc_extra = 187 unpacker = struct.Struct('<BB30s200s') def __init__(self, target_system, target_component, tune, tune2=['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','']): MAVLink_message.__init__(self, MAVLink_play_tune_message.id, MAVLink_play_tune_message.name) self._fieldnames = MAVLink_play_tune_message.fieldnames self.target_system = target_system self.target_component = target_component self.tune = tune self.tune2 = tune2 def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 187, struct.pack('<BB30s200s', self.target_system, self.target_component, self.tune, self.tune2), force_mavlink1=force_mavlink1) class MAVLink_camera_information_message(MAVLink_message): ''' Information about a camera ''' id = MAVLINK_MSG_ID_CAMERA_INFORMATION name = 'CAMERA_INFORMATION' fieldnames = ['time_boot_ms', 'vendor_name', 'model_name', 'firmware_version', 'focal_length', 'sensor_size_h', 'sensor_size_v', 'resolution_h', 'resolution_v', 'lens_id', 'flags', 'cam_definition_version', 'cam_definition_uri'] ordered_fieldnames = ['time_boot_ms', 'firmware_version', 'focal_length', 'sensor_size_h', 'sensor_size_v', 'flags', 'resolution_h', 'resolution_v', 'cam_definition_version', 'vendor_name', 'model_name', 'lens_id', 'cam_definition_uri'] fieldtypes = ['uint32_t', 'uint8_t', 'uint8_t', 'uint32_t', 'float', 'float', 'float', 'uint16_t', 'uint16_t', 'uint8_t', 'uint32_t', 'uint16_t', 'char'] fielddisplays_by_name = {"flags": "bitmask"} fieldenums_by_name = {"flags": "CAMERA_CAP_FLAGS"} fieldunits_by_name = {"time_boot_ms": "ms", "focal_length": "mm", "sensor_size_h": "mm", "sensor_size_v": "mm", "resolution_h": "pix", "resolution_v": "pix"} format = '<IIfffIHHH32B32BB140s' native_format = bytearray('<IIfffIHHHBBBc', 'ascii') orders = [0, 9, 10, 1, 2, 3, 4, 6, 7, 11, 5, 8, 12] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 32, 32, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 32, 0, 140] crc_extra = 92 unpacker = struct.Struct('<IIfffIHHH32B32BB140s') def __init__(self, time_boot_ms, vendor_name, model_name, firmware_version, focal_length, sensor_size_h, sensor_size_v, resolution_h, resolution_v, lens_id, flags, cam_definition_version, cam_definition_uri): MAVLink_message.__init__(self, MAVLink_camera_information_message.id, MAVLink_camera_information_message.name) self._fieldnames = MAVLink_camera_information_message.fieldnames self.time_boot_ms = time_boot_ms self.vendor_name = vendor_name self.model_name = model_name self.firmware_version = firmware_version self.focal_length = focal_length self.sensor_size_h = sensor_size_h self.sensor_size_v = sensor_size_v self.resolution_h = resolution_h self.resolution_v = resolution_v self.lens_id = lens_id self.flags = flags self.cam_definition_version = cam_definition_version self.cam_definition_uri = cam_definition_uri def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 92, struct.pack('<IIfffIHHH32B32BB140s', self.time_boot_ms, self.firmware_version, self.focal_length, self.sensor_size_h, self.sensor_size_v, self.flags, self.resolution_h, self.resolution_v, self.cam_definition_version, self.vendor_name[0], self.vendor_name[1], self.vendor_name[2], self.vendor_name[3], self.vendor_name[4], self.vendor_name[5], self.vendor_name[6], self.vendor_name[7], self.vendor_name[8], self.vendor_name[9], self.vendor_name[10], self.vendor_name[11], self.vendor_name[12], self.vendor_name[13], self.vendor_name[14], self.vendor_name[15], self.vendor_name[16], self.vendor_name[17], self.vendor_name[18], self.vendor_name[19], self.vendor_name[20], self.vendor_name[21], self.vendor_name[22], self.vendor_name[23], self.vendor_name[24], self.vendor_name[25], self.vendor_name[26], self.vendor_name[27], self.vendor_name[28], self.vendor_name[29], self.vendor_name[30], self.vendor_name[31], self.model_name[0], self.model_name[1], self.model_name[2], self.model_name[3], self.model_name[4], self.model_name[5], self.model_name[6], self.model_name[7], self.model_name[8], self.model_name[9], self.model_name[10], self.model_name[11], self.model_name[12], self.model_name[13], self.model_name[14], self.model_name[15], self.model_name[16], self.model_name[17], self.model_name[18], self.model_name[19], self.model_name[20], self.model_name[21], self.model_name[22], self.model_name[23], self.model_name[24], self.model_name[25], self.model_name[26], self.model_name[27], self.model_name[28], self.model_name[29], self.model_name[30], self.model_name[31], self.lens_id, self.cam_definition_uri), force_mavlink1=force_mavlink1) class MAVLink_camera_settings_message(MAVLink_message): ''' Settings of a camera, can be requested using MAV_CMD_REQUEST_CAMERA_SETTINGS. ''' id = MAVLINK_MSG_ID_CAMERA_SETTINGS name = 'CAMERA_SETTINGS' fieldnames = ['time_boot_ms', 'mode_id', 'zoomLevel', 'focusLevel'] ordered_fieldnames = ['time_boot_ms', 'mode_id', 'zoomLevel', 'focusLevel'] fieldtypes = ['uint32_t', 'uint8_t', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"mode_id": "CAMERA_MODE"} fieldunits_by_name = {"time_boot_ms": "ms"} format = '<IBff' native_format = bytearray('<IBff', 'ascii') orders = [0, 1, 2, 3] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 146 unpacker = struct.Struct('<IBff') def __init__(self, time_boot_ms, mode_id, zoomLevel=0, focusLevel=0): MAVLink_message.__init__(self, MAVLink_camera_settings_message.id, MAVLink_camera_settings_message.name) self._fieldnames = MAVLink_camera_settings_message.fieldnames self.time_boot_ms = time_boot_ms self.mode_id = mode_id self.zoomLevel = zoomLevel self.focusLevel = focusLevel def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 146, struct.pack('<IBff', self.time_boot_ms, self.mode_id, self.zoomLevel, self.focusLevel), force_mavlink1=force_mavlink1) class MAVLink_storage_information_message(MAVLink_message): ''' Information about a storage medium. This message is sent in response to a request and whenever the status of the storage changes (STORAGE_STATUS). ''' id = MAVLINK_MSG_ID_STORAGE_INFORMATION name = 'STORAGE_INFORMATION' fieldnames = ['time_boot_ms', 'storage_id', 'storage_count', 'status', 'total_capacity', 'used_capacity', 'available_capacity', 'read_speed', 'write_speed'] ordered_fieldnames = ['time_boot_ms', 'total_capacity', 'used_capacity', 'available_capacity', 'read_speed', 'write_speed', 'storage_id', 'storage_count', 'status'] fieldtypes = ['uint32_t', 'uint8_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {"status": "STORAGE_STATUS"} fieldunits_by_name = {"time_boot_ms": "ms", "total_capacity": "MiB", "used_capacity": "MiB", "available_capacity": "MiB", "read_speed": "MiB/s", "write_speed": "MiB/s"} format = '<IfffffBBB' native_format = bytearray('<IfffffBBB', 'ascii') orders = [0, 6, 7, 8, 1, 2, 3, 4, 5] lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 179 unpacker = struct.Struct('<IfffffBBB') def __init__(self, time_boot_ms, storage_id, storage_count, status, total_capacity, used_capacity, available_capacity, read_speed, write_speed): MAVLink_message.__init__(self, MAVLink_storage_information_message.id, MAVLink_storage_information_message.name) self._fieldnames = MAVLink_storage_information_message.fieldnames self.time_boot_ms = time_boot_ms self.storage_id = storage_id self.storage_count = storage_count self.status = status self.total_capacity = total_capacity self.used_capacity = used_capacity self.available_capacity = available_capacity self.read_speed = read_speed self.write_speed = write_speed def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 179, struct.pack('<IfffffBBB', self.time_boot_ms, self.total_capacity, self.used_capacity, self.available_capacity, self.read_speed, self.write_speed, self.storage_id, self.storage_count, self.status), force_mavlink1=force_mavlink1) class MAVLink_camera_capture_status_message(MAVLink_message): ''' Information about the status of a capture. ''' id = MAVLINK_MSG_ID_CAMERA_CAPTURE_STATUS name = 'CAMERA_CAPTURE_STATUS' fieldnames = ['time_boot_ms', 'image_status', 'video_status', 'image_interval', 'recording_time_ms', 'available_capacity'] ordered_fieldnames = ['time_boot_ms', 'image_interval', 'recording_time_ms', 'available_capacity', 'image_status', 'video_status'] fieldtypes = ['uint32_t', 'uint8_t', 'uint8_t', 'float', 'uint32_t', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "image_interval": "s", "recording_time_ms": "ms", "available_capacity": "MiB"} format = '<IfIfBB' native_format = bytearray('<IfIfBB', 'ascii') orders = [0, 4, 5, 1, 2, 3] lengths = [1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0] crc_extra = 12 unpacker = struct.Struct('<IfIfBB') def __init__(self, time_boot_ms, image_status, video_status, image_interval, recording_time_ms, available_capacity): MAVLink_message.__init__(self, MAVLink_camera_capture_status_message.id, MAVLink_camera_capture_status_message.name) self._fieldnames = MAVLink_camera_capture_status_message.fieldnames self.time_boot_ms = time_boot_ms self.image_status = image_status self.video_status = video_status self.image_interval = image_interval self.recording_time_ms = recording_time_ms self.available_capacity = available_capacity def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 12, struct.pack('<IfIfBB', self.time_boot_ms, self.image_interval, self.recording_time_ms, self.available_capacity, self.image_status, self.video_status), force_mavlink1=force_mavlink1) class MAVLink_camera_image_captured_message(MAVLink_message): ''' Information about a captured image ''' id = MAVLINK_MSG_ID_CAMERA_IMAGE_CAPTURED name = 'CAMERA_IMAGE_CAPTURED' fieldnames = ['time_boot_ms', 'time_utc', 'camera_id', 'lat', 'lon', 'alt', 'relative_alt', 'q', 'image_index', 'capture_result', 'file_url'] ordered_fieldnames = ['time_utc', 'time_boot_ms', 'lat', 'lon', 'alt', 'relative_alt', 'q', 'image_index', 'camera_id', 'capture_result', 'file_url'] fieldtypes = ['uint32_t', 'uint64_t', 'uint8_t', 'int32_t', 'int32_t', 'int32_t', 'int32_t', 'float', 'int32_t', 'int8_t', 'char'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "time_utc": "us", "lat": "degE7", "lon": "degE7", "alt": "mm", "relative_alt": "mm"} format = '<QIiiii4fiBb205s' native_format = bytearray('<QIiiiifiBbc', 'ascii') orders = [1, 0, 8, 2, 3, 4, 5, 6, 7, 9, 10] lengths = [1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 205] crc_extra = 133 unpacker = struct.Struct('<QIiiii4fiBb205s') def __init__(self, time_boot_ms, time_utc, camera_id, lat, lon, alt, relative_alt, q, image_index, capture_result, file_url): MAVLink_message.__init__(self, MAVLink_camera_image_captured_message.id, MAVLink_camera_image_captured_message.name) self._fieldnames = MAVLink_camera_image_captured_message.fieldnames self.time_boot_ms = time_boot_ms self.time_utc = time_utc self.camera_id = camera_id self.lat = lat self.lon = lon self.alt = alt self.relative_alt = relative_alt self.q = q self.image_index = image_index self.capture_result = capture_result self.file_url = file_url def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 133, struct.pack('<QIiiii4fiBb205s', self.time_utc, self.time_boot_ms, self.lat, self.lon, self.alt, self.relative_alt, self.q[0], self.q[1], self.q[2], self.q[3], self.image_index, self.camera_id, self.capture_result, self.file_url), force_mavlink1=force_mavlink1) class MAVLink_flight_information_message(MAVLink_message): ''' Information about flight since last arming. ''' id = MAVLINK_MSG_ID_FLIGHT_INFORMATION name = 'FLIGHT_INFORMATION' fieldnames = ['time_boot_ms', 'arming_time_utc', 'takeoff_time_utc', 'flight_uuid'] ordered_fieldnames = ['arming_time_utc', 'takeoff_time_utc', 'flight_uuid', 'time_boot_ms'] fieldtypes = ['uint32_t', 'uint64_t', 'uint64_t', 'uint64_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "arming_time_utc": "us", "takeoff_time_utc": "us"} format = '<QQQI' native_format = bytearray('<QQQI', 'ascii') orders = [3, 0, 1, 2] lengths = [1, 1, 1, 1] array_lengths = [0, 0, 0, 0] crc_extra = 49 unpacker = struct.Struct('<QQQI') def __init__(self, time_boot_ms, arming_time_utc, takeoff_time_utc, flight_uuid): MAVLink_message.__init__(self, MAVLink_flight_information_message.id, MAVLink_flight_information_message.name) self._fieldnames = MAVLink_flight_information_message.fieldnames self.time_boot_ms = time_boot_ms self.arming_time_utc = arming_time_utc self.takeoff_time_utc = takeoff_time_utc self.flight_uuid = flight_uuid def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 49, struct.pack('<QQQI', self.arming_time_utc, self.takeoff_time_utc, self.flight_uuid, self.time_boot_ms), force_mavlink1=force_mavlink1) class MAVLink_mount_orientation_message(MAVLink_message): ''' Orientation of a mount ''' id = MAVLINK_MSG_ID_MOUNT_ORIENTATION name = 'MOUNT_ORIENTATION' fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'yaw_absolute'] ordered_fieldnames = ['time_boot_ms', 'roll', 'pitch', 'yaw', 'yaw_absolute'] fieldtypes = ['uint32_t', 'float', 'float', 'float', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_boot_ms": "ms", "roll": "deg", "pitch": "deg", "yaw": "deg", "yaw_absolute": "deg"} format = '<Iffff' native_format = bytearray('<Iffff', 'ascii') orders = [0, 1, 2, 3, 4] lengths = [1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0] crc_extra = 26 unpacker = struct.Struct('<Iffff') def __init__(self, time_boot_ms, roll, pitch, yaw, yaw_absolute=0): MAVLink_message.__init__(self, MAVLink_mount_orientation_message.id, MAVLink_mount_orientation_message.name) self._fieldnames = MAVLink_mount_orientation_message.fieldnames self.time_boot_ms = time_boot_ms self.roll = roll self.pitch = pitch self.yaw = yaw self.yaw_absolute = yaw_absolute def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 26, struct.pack('<Iffff', self.time_boot_ms, self.roll, self.pitch, self.yaw, self.yaw_absolute), force_mavlink1=force_mavlink1) class MAVLink_logging_data_message(MAVLink_message): ''' A message containing logged data (see also MAV_CMD_LOGGING_START) ''' id = MAVLINK_MSG_ID_LOGGING_DATA name = 'LOGGING_DATA' fieldnames = ['target_system', 'target_component', 'sequence', 'length', 'first_message_offset', 'data'] ordered_fieldnames = ['sequence', 'target_system', 'target_component', 'length', 'first_message_offset', 'data'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"length": "bytes", "first_message_offset": "bytes"} format = '<HBBBB249B' native_format = bytearray('<HBBBBB', 'ascii') orders = [1, 2, 0, 3, 4, 5] lengths = [1, 1, 1, 1, 1, 249] array_lengths = [0, 0, 0, 0, 0, 249] crc_extra = 193 unpacker = struct.Struct('<HBBBB249B') def __init__(self, target_system, target_component, sequence, length, first_message_offset, data): MAVLink_message.__init__(self, MAVLink_logging_data_message.id, MAVLink_logging_data_message.name) self._fieldnames = MAVLink_logging_data_message.fieldnames self.target_system = target_system self.target_component = target_component self.sequence = sequence self.length = length self.first_message_offset = first_message_offset self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 193, struct.pack('<HBBBB249B', self.sequence, self.target_system, self.target_component, self.length, self.first_message_offset, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.data[16], self.data[17], self.data[18], self.data[19], self.data[20], self.data[21], self.data[22], self.data[23], self.data[24], self.data[25], self.data[26], self.data[27], self.data[28], self.data[29], self.data[30], self.data[31], self.data[32], self.data[33], self.data[34], self.data[35], self.data[36], self.data[37], self.data[38], self.data[39], self.data[40], self.data[41], self.data[42], self.data[43], self.data[44], self.data[45], self.data[46], self.data[47], self.data[48], self.data[49], self.data[50], self.data[51], self.data[52], self.data[53], self.data[54], self.data[55], self.data[56], self.data[57], self.data[58], self.data[59], self.data[60], self.data[61], self.data[62], self.data[63], self.data[64], self.data[65], self.data[66], self.data[67], self.data[68], self.data[69], self.data[70], self.data[71], self.data[72], self.data[73], self.data[74], self.data[75], self.data[76], self.data[77], self.data[78], self.data[79], self.data[80], self.data[81], self.data[82], self.data[83], self.data[84], self.data[85], self.data[86], self.data[87], self.data[88], self.data[89], self.data[90], self.data[91], self.data[92], self.data[93], self.data[94], self.data[95], self.data[96], self.data[97], self.data[98], self.data[99], self.data[100], self.data[101], self.data[102], self.data[103], self.data[104], self.data[105], self.data[106], self.data[107], self.data[108], self.data[109], self.data[110], self.data[111], self.data[112], self.data[113], self.data[114], self.data[115], self.data[116], self.data[117], self.data[118], self.data[119], self.data[120], self.data[121], self.data[122], self.data[123], self.data[124], self.data[125], self.data[126], self.data[127], self.data[128], self.data[129], self.data[130], self.data[131], self.data[132], self.data[133], self.data[134], self.data[135], self.data[136], self.data[137], self.data[138], self.data[139], self.data[140], self.data[141], self.data[142], self.data[143], self.data[144], self.data[145], self.data[146], self.data[147], self.data[148], self.data[149], self.data[150], self.data[151], self.data[152], self.data[153], self.data[154], self.data[155], self.data[156], self.data[157], self.data[158], self.data[159], self.data[160], self.data[161], self.data[162], self.data[163], self.data[164], self.data[165], self.data[166], self.data[167], self.data[168], self.data[169], self.data[170], self.data[171], self.data[172], self.data[173], self.data[174], self.data[175], self.data[176], self.data[177], self.data[178], self.data[179], self.data[180], self.data[181], self.data[182], self.data[183], self.data[184], self.data[185], self.data[186], self.data[187], self.data[188], self.data[189], self.data[190], self.data[191], self.data[192], self.data[193], self.data[194], self.data[195], self.data[196], self.data[197], self.data[198], self.data[199], self.data[200], self.data[201], self.data[202], self.data[203], self.data[204], self.data[205], self.data[206], self.data[207], self.data[208], self.data[209], self.data[210], self.data[211], self.data[212], self.data[213], self.data[214], self.data[215], self.data[216], self.data[217], self.data[218], self.data[219], self.data[220], self.data[221], self.data[222], self.data[223], self.data[224], self.data[225], self.data[226], self.data[227], self.data[228], self.data[229], self.data[230], self.data[231], self.data[232], self.data[233], self.data[234], self.data[235], self.data[236], self.data[237], self.data[238], self.data[239], self.data[240], self.data[241], self.data[242], self.data[243], self.data[244], self.data[245], self.data[246], self.data[247], self.data[248]), force_mavlink1=force_mavlink1) class MAVLink_logging_data_acked_message(MAVLink_message): ''' A message containing logged data which requires a LOGGING_ACK to be sent back ''' id = MAVLINK_MSG_ID_LOGGING_DATA_ACKED name = 'LOGGING_DATA_ACKED' fieldnames = ['target_system', 'target_component', 'sequence', 'length', 'first_message_offset', 'data'] ordered_fieldnames = ['sequence', 'target_system', 'target_component', 'length', 'first_message_offset', 'data'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t', 'uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"length": "bytes", "first_message_offset": "bytes"} format = '<HBBBB249B' native_format = bytearray('<HBBBBB', 'ascii') orders = [1, 2, 0, 3, 4, 5] lengths = [1, 1, 1, 1, 1, 249] array_lengths = [0, 0, 0, 0, 0, 249] crc_extra = 35 unpacker = struct.Struct('<HBBBB249B') def __init__(self, target_system, target_component, sequence, length, first_message_offset, data): MAVLink_message.__init__(self, MAVLink_logging_data_acked_message.id, MAVLink_logging_data_acked_message.name) self._fieldnames = MAVLink_logging_data_acked_message.fieldnames self.target_system = target_system self.target_component = target_component self.sequence = sequence self.length = length self.first_message_offset = first_message_offset self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 35, struct.pack('<HBBBB249B', self.sequence, self.target_system, self.target_component, self.length, self.first_message_offset, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.data[16], self.data[17], self.data[18], self.data[19], self.data[20], self.data[21], self.data[22], self.data[23], self.data[24], self.data[25], self.data[26], self.data[27], self.data[28], self.data[29], self.data[30], self.data[31], self.data[32], self.data[33], self.data[34], self.data[35], self.data[36], self.data[37], self.data[38], self.data[39], self.data[40], self.data[41], self.data[42], self.data[43], self.data[44], self.data[45], self.data[46], self.data[47], self.data[48], self.data[49], self.data[50], self.data[51], self.data[52], self.data[53], self.data[54], self.data[55], self.data[56], self.data[57], self.data[58], self.data[59], self.data[60], self.data[61], self.data[62], self.data[63], self.data[64], self.data[65], self.data[66], self.data[67], self.data[68], self.data[69], self.data[70], self.data[71], self.data[72], self.data[73], self.data[74], self.data[75], self.data[76], self.data[77], self.data[78], self.data[79], self.data[80], self.data[81], self.data[82], self.data[83], self.data[84], self.data[85], self.data[86], self.data[87], self.data[88], self.data[89], self.data[90], self.data[91], self.data[92], self.data[93], self.data[94], self.data[95], self.data[96], self.data[97], self.data[98], self.data[99], self.data[100], self.data[101], self.data[102], self.data[103], self.data[104], self.data[105], self.data[106], self.data[107], self.data[108], self.data[109], self.data[110], self.data[111], self.data[112], self.data[113], self.data[114], self.data[115], self.data[116], self.data[117], self.data[118], self.data[119], self.data[120], self.data[121], self.data[122], self.data[123], self.data[124], self.data[125], self.data[126], self.data[127], self.data[128], self.data[129], self.data[130], self.data[131], self.data[132], self.data[133], self.data[134], self.data[135], self.data[136], self.data[137], self.data[138], self.data[139], self.data[140], self.data[141], self.data[142], self.data[143], self.data[144], self.data[145], self.data[146], self.data[147], self.data[148], self.data[149], self.data[150], self.data[151], self.data[152], self.data[153], self.data[154], self.data[155], self.data[156], self.data[157], self.data[158], self.data[159], self.data[160], self.data[161], self.data[162], self.data[163], self.data[164], self.data[165], self.data[166], self.data[167], self.data[168], self.data[169], self.data[170], self.data[171], self.data[172], self.data[173], self.data[174], self.data[175], self.data[176], self.data[177], self.data[178], self.data[179], self.data[180], self.data[181], self.data[182], self.data[183], self.data[184], self.data[185], self.data[186], self.data[187], self.data[188], self.data[189], self.data[190], self.data[191], self.data[192], self.data[193], self.data[194], self.data[195], self.data[196], self.data[197], self.data[198], self.data[199], self.data[200], self.data[201], self.data[202], self.data[203], self.data[204], self.data[205], self.data[206], self.data[207], self.data[208], self.data[209], self.data[210], self.data[211], self.data[212], self.data[213], self.data[214], self.data[215], self.data[216], self.data[217], self.data[218], self.data[219], self.data[220], self.data[221], self.data[222], self.data[223], self.data[224], self.data[225], self.data[226], self.data[227], self.data[228], self.data[229], self.data[230], self.data[231], self.data[232], self.data[233], self.data[234], self.data[235], self.data[236], self.data[237], self.data[238], self.data[239], self.data[240], self.data[241], self.data[242], self.data[243], self.data[244], self.data[245], self.data[246], self.data[247], self.data[248]), force_mavlink1=force_mavlink1) class MAVLink_logging_ack_message(MAVLink_message): ''' An ack for a LOGGING_DATA_ACKED message ''' id = MAVLINK_MSG_ID_LOGGING_ACK name = 'LOGGING_ACK' fieldnames = ['target_system', 'target_component', 'sequence'] ordered_fieldnames = ['sequence', 'target_system', 'target_component'] fieldtypes = ['uint8_t', 'uint8_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<HBB' native_format = bytearray('<HBB', 'ascii') orders = [1, 2, 0] lengths = [1, 1, 1] array_lengths = [0, 0, 0] crc_extra = 14 unpacker = struct.Struct('<HBB') def __init__(self, target_system, target_component, sequence): MAVLink_message.__init__(self, MAVLink_logging_ack_message.id, MAVLink_logging_ack_message.name) self._fieldnames = MAVLink_logging_ack_message.fieldnames self.target_system = target_system self.target_component = target_component self.sequence = sequence def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 14, struct.pack('<HBB', self.sequence, self.target_system, self.target_component), force_mavlink1=force_mavlink1) class MAVLink_wifi_config_ap_message(MAVLink_message): ''' Configure AP SSID and Password. ''' id = MAVLINK_MSG_ID_WIFI_CONFIG_AP name = 'WIFI_CONFIG_AP' fieldnames = ['ssid', 'password'] ordered_fieldnames = ['ssid', 'password'] fieldtypes = ['char', 'char'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {} format = '<32s64s' native_format = bytearray('<cc', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [32, 64] crc_extra = 19 unpacker = struct.Struct('<32s64s') def __init__(self, ssid, password): MAVLink_message.__init__(self, MAVLink_wifi_config_ap_message.id, MAVLink_wifi_config_ap_message.name) self._fieldnames = MAVLink_wifi_config_ap_message.fieldnames self.ssid = ssid self.password = password def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 19, struct.pack('<32s64s', self.ssid, self.password), force_mavlink1=force_mavlink1) class MAVLink_uavcan_node_status_message(MAVLink_message): ''' General status information of an UAVCAN node. Please refer to the definition of the UAVCAN message "uavcan.protocol.NodeStatus" for the background information. The UAVCAN specification is available at http://uavcan.org. ''' id = MAVLINK_MSG_ID_UAVCAN_NODE_STATUS name = 'UAVCAN_NODE_STATUS' fieldnames = ['time_usec', 'uptime_sec', 'health', 'mode', 'sub_mode', 'vendor_specific_status_code'] ordered_fieldnames = ['time_usec', 'uptime_sec', 'vendor_specific_status_code', 'health', 'mode', 'sub_mode'] fieldtypes = ['uint64_t', 'uint32_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint16_t'] fielddisplays_by_name = {} fieldenums_by_name = {"health": "UAVCAN_NODE_HEALTH", "mode": "UAVCAN_NODE_MODE"} fieldunits_by_name = {"time_usec": "us", "uptime_sec": "s"} format = '<QIHBBB' native_format = bytearray('<QIHBBB', 'ascii') orders = [0, 1, 3, 4, 5, 2] lengths = [1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0] crc_extra = 28 unpacker = struct.Struct('<QIHBBB') def __init__(self, time_usec, uptime_sec, health, mode, sub_mode, vendor_specific_status_code): MAVLink_message.__init__(self, MAVLink_uavcan_node_status_message.id, MAVLink_uavcan_node_status_message.name) self._fieldnames = MAVLink_uavcan_node_status_message.fieldnames self.time_usec = time_usec self.uptime_sec = uptime_sec self.health = health self.mode = mode self.sub_mode = sub_mode self.vendor_specific_status_code = vendor_specific_status_code def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 28, struct.pack('<QIHBBB', self.time_usec, self.uptime_sec, self.vendor_specific_status_code, self.health, self.mode, self.sub_mode), force_mavlink1=force_mavlink1) class MAVLink_uavcan_node_info_message(MAVLink_message): ''' General information describing a particular UAVCAN node. Please refer to the definition of the UAVCAN service "uavcan.protocol.GetNodeInfo" for the background information. This message should be emitted by the system whenever a new node appears online, or an existing node reboots. Additionally, it can be emitted upon request from the other end of the MAVLink channel (see MAV_CMD_UAVCAN_GET_NODE_INFO). It is also not prohibited to emit this message unconditionally at a low frequency. The UAVCAN specification is available at http://uavcan.org. ''' id = MAVLINK_MSG_ID_UAVCAN_NODE_INFO name = 'UAVCAN_NODE_INFO' fieldnames = ['time_usec', 'uptime_sec', 'name', 'hw_version_major', 'hw_version_minor', 'hw_unique_id', 'sw_version_major', 'sw_version_minor', 'sw_vcs_commit'] ordered_fieldnames = ['time_usec', 'uptime_sec', 'sw_vcs_commit', 'name', 'hw_version_major', 'hw_version_minor', 'hw_unique_id', 'sw_version_major', 'sw_version_minor'] fieldtypes = ['uint64_t', 'uint32_t', 'char', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint32_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "uptime_sec": "s"} format = '<QII80sBB16BBB' native_format = bytearray('<QIIcBBBBB', 'ascii') orders = [0, 1, 3, 4, 5, 6, 7, 8, 2] lengths = [1, 1, 1, 1, 1, 1, 16, 1, 1] array_lengths = [0, 0, 0, 80, 0, 0, 16, 0, 0] crc_extra = 95 unpacker = struct.Struct('<QII80sBB16BBB') def __init__(self, time_usec, uptime_sec, name, hw_version_major, hw_version_minor, hw_unique_id, sw_version_major, sw_version_minor, sw_vcs_commit): MAVLink_message.__init__(self, MAVLink_uavcan_node_info_message.id, MAVLink_uavcan_node_info_message.name) self._fieldnames = MAVLink_uavcan_node_info_message.fieldnames self.time_usec = time_usec self.uptime_sec = uptime_sec self.name = name self.hw_version_major = hw_version_major self.hw_version_minor = hw_version_minor self.hw_unique_id = hw_unique_id self.sw_version_major = sw_version_major self.sw_version_minor = sw_version_minor self.sw_vcs_commit = sw_vcs_commit def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 95, struct.pack('<QII80sBB16BBB', self.time_usec, self.uptime_sec, self.sw_vcs_commit, self.name, self.hw_version_major, self.hw_version_minor, self.hw_unique_id[0], self.hw_unique_id[1], self.hw_unique_id[2], self.hw_unique_id[3], self.hw_unique_id[4], self.hw_unique_id[5], self.hw_unique_id[6], self.hw_unique_id[7], self.hw_unique_id[8], self.hw_unique_id[9], self.hw_unique_id[10], self.hw_unique_id[11], self.hw_unique_id[12], self.hw_unique_id[13], self.hw_unique_id[14], self.hw_unique_id[15], self.sw_version_major, self.sw_version_minor), force_mavlink1=force_mavlink1) class MAVLink_obstacle_distance_message(MAVLink_message): ''' Obstacle distances in front of the sensor, starting from the left in increment degrees to the right ''' id = MAVLINK_MSG_ID_OBSTACLE_DISTANCE name = 'OBSTACLE_DISTANCE' fieldnames = ['time_usec', 'sensor_type', 'distances', 'increment', 'min_distance', 'max_distance', 'increment_f', 'angle_offset', 'frame'] ordered_fieldnames = ['time_usec', 'distances', 'min_distance', 'max_distance', 'sensor_type', 'increment', 'increment_f', 'angle_offset', 'frame'] fieldtypes = ['uint64_t', 'uint8_t', 'uint16_t', 'uint8_t', 'uint16_t', 'uint16_t', 'float', 'float', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"sensor_type": "MAV_DISTANCE_SENSOR", "frame": "MAV_FRAME"} fieldunits_by_name = {"time_usec": "us", "distances": "cm", "increment": "deg", "min_distance": "cm", "max_distance": "cm", "increment_f": "deg", "angle_offset": "deg"} format = '<Q72HHHBBffB' native_format = bytearray('<QHHHBBffB', 'ascii') orders = [0, 4, 1, 5, 2, 3, 6, 7, 8] lengths = [1, 72, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 72, 0, 0, 0, 0, 0, 0, 0] crc_extra = 23 unpacker = struct.Struct('<Q72HHHBBffB') def __init__(self, time_usec, sensor_type, distances, increment, min_distance, max_distance, increment_f=0, angle_offset=0, frame=0): MAVLink_message.__init__(self, MAVLink_obstacle_distance_message.id, MAVLink_obstacle_distance_message.name) self._fieldnames = MAVLink_obstacle_distance_message.fieldnames self.time_usec = time_usec self.sensor_type = sensor_type self.distances = distances self.increment = increment self.min_distance = min_distance self.max_distance = max_distance self.increment_f = increment_f self.angle_offset = angle_offset self.frame = frame def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 23, struct.pack('<Q72HHHBBffB', self.time_usec, self.distances[0], self.distances[1], self.distances[2], self.distances[3], self.distances[4], self.distances[5], self.distances[6], self.distances[7], self.distances[8], self.distances[9], self.distances[10], self.distances[11], self.distances[12], self.distances[13], self.distances[14], self.distances[15], self.distances[16], self.distances[17], self.distances[18], self.distances[19], self.distances[20], self.distances[21], self.distances[22], self.distances[23], self.distances[24], self.distances[25], self.distances[26], self.distances[27], self.distances[28], self.distances[29], self.distances[30], self.distances[31], self.distances[32], self.distances[33], self.distances[34], self.distances[35], self.distances[36], self.distances[37], self.distances[38], self.distances[39], self.distances[40], self.distances[41], self.distances[42], self.distances[43], self.distances[44], self.distances[45], self.distances[46], self.distances[47], self.distances[48], self.distances[49], self.distances[50], self.distances[51], self.distances[52], self.distances[53], self.distances[54], self.distances[55], self.distances[56], self.distances[57], self.distances[58], self.distances[59], self.distances[60], self.distances[61], self.distances[62], self.distances[63], self.distances[64], self.distances[65], self.distances[66], self.distances[67], self.distances[68], self.distances[69], self.distances[70], self.distances[71], self.min_distance, self.max_distance, self.sensor_type, self.increment, self.increment_f, self.angle_offset, self.frame), force_mavlink1=force_mavlink1) class MAVLink_odometry_message(MAVLink_message): ''' Odometry message to communicate odometry information with an external interface. Fits ROS REP 147 standard for aerial vehicles (http://www.ros.org/reps/rep-0147.html). ''' id = MAVLINK_MSG_ID_ODOMETRY name = 'ODOMETRY' fieldnames = ['time_usec', 'frame_id', 'child_frame_id', 'x', 'y', 'z', 'q', 'vx', 'vy', 'vz', 'rollspeed', 'pitchspeed', 'yawspeed', 'pose_covariance', 'velocity_covariance', 'reset_counter', 'estimator_type'] ordered_fieldnames = ['time_usec', 'x', 'y', 'z', 'q', 'vx', 'vy', 'vz', 'rollspeed', 'pitchspeed', 'yawspeed', 'pose_covariance', 'velocity_covariance', 'frame_id', 'child_frame_id', 'reset_counter', 'estimator_type'] fieldtypes = ['uint64_t', 'uint8_t', 'uint8_t', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'float', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {"frame_id": "MAV_FRAME", "child_frame_id": "MAV_FRAME", "estimator_type": "MAV_ESTIMATOR_TYPE"} fieldunits_by_name = {"time_usec": "us", "x": "m", "y": "m", "z": "m", "vx": "m/s", "vy": "m/s", "vz": "m/s", "rollspeed": "rad/s", "pitchspeed": "rad/s", "yawspeed": "rad/s"} format = '<Qfff4fffffff21f21fBBBB' native_format = bytearray('<QffffffffffffBBBB', 'ascii') orders = [0, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 16] lengths = [1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 21, 21, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 21, 21, 0, 0, 0, 0] crc_extra = 91 unpacker = struct.Struct('<Qfff4fffffff21f21fBBBB') def __init__(self, time_usec, frame_id, child_frame_id, x, y, z, q, vx, vy, vz, rollspeed, pitchspeed, yawspeed, pose_covariance, velocity_covariance, reset_counter=0, estimator_type=0): MAVLink_message.__init__(self, MAVLink_odometry_message.id, MAVLink_odometry_message.name) self._fieldnames = MAVLink_odometry_message.fieldnames self.time_usec = time_usec self.frame_id = frame_id self.child_frame_id = child_frame_id self.x = x self.y = y self.z = z self.q = q self.vx = vx self.vy = vy self.vz = vz self.rollspeed = rollspeed self.pitchspeed = pitchspeed self.yawspeed = yawspeed self.pose_covariance = pose_covariance self.velocity_covariance = velocity_covariance self.reset_counter = reset_counter self.estimator_type = estimator_type def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 91, struct.pack('<Qfff4fffffff21f21fBBBB', self.time_usec, self.x, self.y, self.z, self.q[0], self.q[1], self.q[2], self.q[3], self.vx, self.vy, self.vz, self.rollspeed, self.pitchspeed, self.yawspeed, self.pose_covariance[0], self.pose_covariance[1], self.pose_covariance[2], self.pose_covariance[3], self.pose_covariance[4], self.pose_covariance[5], self.pose_covariance[6], self.pose_covariance[7], self.pose_covariance[8], self.pose_covariance[9], self.pose_covariance[10], self.pose_covariance[11], self.pose_covariance[12], self.pose_covariance[13], self.pose_covariance[14], self.pose_covariance[15], self.pose_covariance[16], self.pose_covariance[17], self.pose_covariance[18], self.pose_covariance[19], self.pose_covariance[20], self.velocity_covariance[0], self.velocity_covariance[1], self.velocity_covariance[2], self.velocity_covariance[3], self.velocity_covariance[4], self.velocity_covariance[5], self.velocity_covariance[6], self.velocity_covariance[7], self.velocity_covariance[8], self.velocity_covariance[9], self.velocity_covariance[10], self.velocity_covariance[11], self.velocity_covariance[12], self.velocity_covariance[13], self.velocity_covariance[14], self.velocity_covariance[15], self.velocity_covariance[16], self.velocity_covariance[17], self.velocity_covariance[18], self.velocity_covariance[19], self.velocity_covariance[20], self.frame_id, self.child_frame_id, self.reset_counter, self.estimator_type), force_mavlink1=force_mavlink1) class MAVLink_isbd_link_status_message(MAVLink_message): ''' Status of the Iridium SBD link. ''' id = MAVLINK_MSG_ID_ISBD_LINK_STATUS name = 'ISBD_LINK_STATUS' fieldnames = ['timestamp', 'last_heartbeat', 'failed_sessions', 'successful_sessions', 'signal_quality', 'ring_pending', 'tx_session_pending', 'rx_session_pending'] ordered_fieldnames = ['timestamp', 'last_heartbeat', 'failed_sessions', 'successful_sessions', 'signal_quality', 'ring_pending', 'tx_session_pending', 'rx_session_pending'] fieldtypes = ['uint64_t', 'uint64_t', 'uint16_t', 'uint16_t', 'uint8_t', 'uint8_t', 'uint8_t', 'uint8_t'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"timestamp": "us", "last_heartbeat": "us"} format = '<QQHHBBBB' native_format = bytearray('<QQHHBBBB', 'ascii') orders = [0, 1, 2, 3, 4, 5, 6, 7] lengths = [1, 1, 1, 1, 1, 1, 1, 1] array_lengths = [0, 0, 0, 0, 0, 0, 0, 0] crc_extra = 225 unpacker = struct.Struct('<QQHHBBBB') def __init__(self, timestamp, last_heartbeat, failed_sessions, successful_sessions, signal_quality, ring_pending, tx_session_pending, rx_session_pending): MAVLink_message.__init__(self, MAVLink_isbd_link_status_message.id, MAVLink_isbd_link_status_message.name) self._fieldnames = MAVLink_isbd_link_status_message.fieldnames self.timestamp = timestamp self.last_heartbeat = last_heartbeat self.failed_sessions = failed_sessions self.successful_sessions = successful_sessions self.signal_quality = signal_quality self.ring_pending = ring_pending self.tx_session_pending = tx_session_pending self.rx_session_pending = rx_session_pending def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 225, struct.pack('<QQHHBBBB', self.timestamp, self.last_heartbeat, self.failed_sessions, self.successful_sessions, self.signal_quality, self.ring_pending, self.tx_session_pending, self.rx_session_pending), force_mavlink1=force_mavlink1) class MAVLink_debug_float_array_message(MAVLink_message): ''' Large debug/prototyping array. The message uses the maximum available payload for data. The array_id and name fields are used to discriminate between messages in code and in user interfaces (respectively). Do not use in production code. ''' id = MAVLINK_MSG_ID_DEBUG_FLOAT_ARRAY name = 'DEBUG_FLOAT_ARRAY' fieldnames = ['time_usec', 'name', 'array_id', 'data'] ordered_fieldnames = ['time_usec', 'array_id', 'name', 'data'] fieldtypes = ['uint64_t', 'char', 'uint16_t', 'float'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<QH10s58f' native_format = bytearray('<QHcf', 'ascii') orders = [0, 2, 1, 3] lengths = [1, 1, 1, 58] array_lengths = [0, 0, 10, 58] crc_extra = 232 unpacker = struct.Struct('<QH10s58f') def __init__(self, time_usec, name, array_id, data=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]): MAVLink_message.__init__(self, MAVLink_debug_float_array_message.id, MAVLink_debug_float_array_message.name) self._fieldnames = MAVLink_debug_float_array_message.fieldnames self.time_usec = time_usec self.name = name self.array_id = array_id self.data = data def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 232, struct.pack('<QH10s58f', self.time_usec, self.array_id, self.name, self.data[0], self.data[1], self.data[2], self.data[3], self.data[4], self.data[5], self.data[6], self.data[7], self.data[8], self.data[9], self.data[10], self.data[11], self.data[12], self.data[13], self.data[14], self.data[15], self.data[16], self.data[17], self.data[18], self.data[19], self.data[20], self.data[21], self.data[22], self.data[23], self.data[24], self.data[25], self.data[26], self.data[27], self.data[28], self.data[29], self.data[30], self.data[31], self.data[32], self.data[33], self.data[34], self.data[35], self.data[36], self.data[37], self.data[38], self.data[39], self.data[40], self.data[41], self.data[42], self.data[43], self.data[44], self.data[45], self.data[46], self.data[47], self.data[48], self.data[49], self.data[50], self.data[51], self.data[52], self.data[53], self.data[54], self.data[55], self.data[56], self.data[57]), force_mavlink1=force_mavlink1) class MAVLink_statustext_long_message(MAVLink_message): ''' Status text message (use only for important status and error messages). The full message payload can be used for status text, but we recommend that updates be kept concise. Note: The message is intended as a less restrictive replacement for STATUSTEXT. ''' id = MAVLINK_MSG_ID_STATUSTEXT_LONG name = 'STATUSTEXT_LONG' fieldnames = ['severity', 'text'] ordered_fieldnames = ['severity', 'text'] fieldtypes = ['uint8_t', 'char'] fielddisplays_by_name = {} fieldenums_by_name = {"severity": "MAV_SEVERITY"} fieldunits_by_name = {} format = '<B254s' native_format = bytearray('<Bc', 'ascii') orders = [0, 1] lengths = [1, 1] array_lengths = [0, 254] crc_extra = 36 unpacker = struct.Struct('<B254s') def __init__(self, severity, text): MAVLink_message.__init__(self, MAVLink_statustext_long_message.id, MAVLink_statustext_long_message.name) self._fieldnames = MAVLink_statustext_long_message.fieldnames self.severity = severity self.text = text def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 36, struct.pack('<B254s', self.severity, self.text), force_mavlink1=force_mavlink1) class MAVLink_actuator_output_status_message(MAVLink_message): ''' The raw values of the actuator outputs. ''' id = MAVLINK_MSG_ID_ACTUATOR_OUTPUT_STATUS name = 'ACTUATOR_OUTPUT_STATUS' fieldnames = ['time_usec', 'active', 'actuator'] ordered_fieldnames = ['time_usec', 'active', 'actuator'] fieldtypes = ['uint64_t', 'uint32_t', 'float'] fielddisplays_by_name = {"active": "bitmask"} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us"} format = '<QI32f' native_format = bytearray('<QIf', 'ascii') orders = [0, 1, 2] lengths = [1, 1, 32] array_lengths = [0, 0, 32] crc_extra = 251 unpacker = struct.Struct('<QI32f') def __init__(self, time_usec, active, actuator): MAVLink_message.__init__(self, MAVLink_actuator_output_status_message.id, MAVLink_actuator_output_status_message.name) self._fieldnames = MAVLink_actuator_output_status_message.fieldnames self.time_usec = time_usec self.active = active self.actuator = actuator def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 251, struct.pack('<QI32f', self.time_usec, self.active, self.actuator[0], self.actuator[1], self.actuator[2], self.actuator[3], self.actuator[4], self.actuator[5], self.actuator[6], self.actuator[7], self.actuator[8], self.actuator[9], self.actuator[10], self.actuator[11], self.actuator[12], self.actuator[13], self.actuator[14], self.actuator[15], self.actuator[16], self.actuator[17], self.actuator[18], self.actuator[19], self.actuator[20], self.actuator[21], self.actuator[22], self.actuator[23], self.actuator[24], self.actuator[25], self.actuator[26], self.actuator[27], self.actuator[28], self.actuator[29], self.actuator[30], self.actuator[31]), force_mavlink1=force_mavlink1) class MAVLink_wheel_distance_message(MAVLink_message): ''' Cumulative distance traveled for each reported wheel. ''' id = MAVLINK_MSG_ID_WHEEL_DISTANCE name = 'WHEEL_DISTANCE' fieldnames = ['time_usec', 'count', 'distance'] ordered_fieldnames = ['time_usec', 'distance', 'count'] fieldtypes = ['uint64_t', 'uint8_t', 'double'] fielddisplays_by_name = {} fieldenums_by_name = {} fieldunits_by_name = {"time_usec": "us", "distance": "m"} format = '<Q16dB' native_format = bytearray('<QdB', 'ascii') orders = [0, 2, 1] lengths = [1, 16, 1] array_lengths = [0, 16, 0] crc_extra = 113 unpacker = struct.Struct('<Q16dB') def __init__(self, time_usec, count, distance): MAVLink_message.__init__(self, MAVLink_wheel_distance_message.id, MAVLink_wheel_distance_message.name) self._fieldnames = MAVLink_wheel_distance_message.fieldnames self.time_usec = time_usec self.count = count self.distance = distance def pack(self, mav, force_mavlink1=False): return MAVLink_message.pack(self, mav, 113, struct.pack('<Q16dB', self.time_usec, self.distance[0], self.distance[1], self.distance[2], self.distance[3], self.distance[4], self.distance[5], self.distance[6], self.distance[7], self.distance[8], self.distance[9], self.distance[10], self.distance[11], self.distance[12], self.distance[13], self.distance[14], self.distance[15], self.count), force_mavlink1=force_mavlink1) mavlink_map = { MAVLINK_MSG_ID_SCRIPT_ITEM : MAVLink_script_item_message, MAVLINK_MSG_ID_SCRIPT_REQUEST : MAVLink_script_request_message, MAVLINK_MSG_ID_SCRIPT_REQUEST_LIST : MAVLink_script_request_list_message, MAVLINK_MSG_ID_SCRIPT_COUNT : MAVLink_script_count_message, MAVLINK_MSG_ID_SCRIPT_CURRENT : MAVLink_script_current_message, MAVLINK_MSG_ID_HEARTBEAT : MAVLink_heartbeat_message, MAVLINK_MSG_ID_SYS_STATUS : MAVLink_sys_status_message, MAVLINK_MSG_ID_SYSTEM_TIME : MAVLink_system_time_message, MAVLINK_MSG_ID_PING : MAVLink_ping_message, MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL : MAVLink_change_operator_control_message, MAVLINK_MSG_ID_CHANGE_OPERATOR_CONTROL_ACK : MAVLink_change_operator_control_ack_message, MAVLINK_MSG_ID_AUTH_KEY : MAVLink_auth_key_message, MAVLINK_MSG_ID_SET_MODE : MAVLink_set_mode_message, MAVLINK_MSG_ID_PARAM_REQUEST_READ : MAVLink_param_request_read_message, MAVLINK_MSG_ID_PARAM_REQUEST_LIST : MAVLink_param_request_list_message, MAVLINK_MSG_ID_PARAM_VALUE : MAVLink_param_value_message, MAVLINK_MSG_ID_PARAM_SET : MAVLink_param_set_message, MAVLINK_MSG_ID_GPS_RAW_INT : MAVLink_gps_raw_int_message, MAVLINK_MSG_ID_GPS_STATUS : MAVLink_gps_status_message, MAVLINK_MSG_ID_SCALED_IMU : MAVLink_scaled_imu_message, MAVLINK_MSG_ID_RAW_IMU : MAVLink_raw_imu_message, MAVLINK_MSG_ID_RAW_PRESSURE : MAVLink_raw_pressure_message, MAVLINK_MSG_ID_SCALED_PRESSURE : MAVLink_scaled_pressure_message, MAVLINK_MSG_ID_ATTITUDE : MAVLink_attitude_message, MAVLINK_MSG_ID_ATTITUDE_QUATERNION : MAVLink_attitude_quaternion_message, MAVLINK_MSG_ID_LOCAL_POSITION_NED : MAVLink_local_position_ned_message, MAVLINK_MSG_ID_GLOBAL_POSITION_INT : MAVLink_global_position_int_message, MAVLINK_MSG_ID_RC_CHANNELS_SCALED : MAVLink_rc_channels_scaled_message, MAVLINK_MSG_ID_RC_CHANNELS_RAW : MAVLink_rc_channels_raw_message, MAVLINK_MSG_ID_SERVO_OUTPUT_RAW : MAVLink_servo_output_raw_message, MAVLINK_MSG_ID_MISSION_REQUEST_PARTIAL_LIST : MAVLink_mission_request_partial_list_message, MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST : MAVLink_mission_write_partial_list_message, MAVLINK_MSG_ID_MISSION_ITEM : MAVLink_mission_item_message, MAVLINK_MSG_ID_MISSION_REQUEST : MAVLink_mission_request_message, MAVLINK_MSG_ID_MISSION_SET_CURRENT : MAVLink_mission_set_current_message, MAVLINK_MSG_ID_MISSION_CURRENT : MAVLink_mission_current_message, MAVLINK_MSG_ID_MISSION_REQUEST_LIST : MAVLink_mission_request_list_message, MAVLINK_MSG_ID_MISSION_COUNT : MAVLink_mission_count_message, MAVLINK_MSG_ID_MISSION_CLEAR_ALL : MAVLink_mission_clear_all_message, MAVLINK_MSG_ID_MISSION_ITEM_REACHED : MAVLink_mission_item_reached_message, MAVLINK_MSG_ID_MISSION_ACK : MAVLink_mission_ack_message, MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN : MAVLink_set_gps_global_origin_message, MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN : MAVLink_gps_global_origin_message, MAVLINK_MSG_ID_PARAM_MAP_RC : MAVLink_param_map_rc_message, MAVLINK_MSG_ID_MISSION_REQUEST_INT : MAVLink_mission_request_int_message, MAVLINK_MSG_ID_SAFETY_SET_ALLOWED_AREA : MAVLink_safety_set_allowed_area_message, MAVLINK_MSG_ID_SAFETY_ALLOWED_AREA : MAVLink_safety_allowed_area_message, MAVLINK_MSG_ID_ATTITUDE_QUATERNION_COV : MAVLink_attitude_quaternion_cov_message, MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT : MAVLink_nav_controller_output_message, MAVLINK_MSG_ID_GLOBAL_POSITION_INT_COV : MAVLink_global_position_int_cov_message, MAVLINK_MSG_ID_LOCAL_POSITION_NED_COV : MAVLink_local_position_ned_cov_message, MAVLINK_MSG_ID_RC_CHANNELS : MAVLink_rc_channels_message, MAVLINK_MSG_ID_REQUEST_DATA_STREAM : MAVLink_request_data_stream_message, MAVLINK_MSG_ID_DATA_STREAM : MAVLink_data_stream_message, MAVLINK_MSG_ID_MANUAL_CONTROL : MAVLink_manual_control_message, MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE : MAVLink_rc_channels_override_message, MAVLINK_MSG_ID_MISSION_ITEM_INT : MAVLink_mission_item_int_message, MAVLINK_MSG_ID_VFR_HUD : MAVLink_vfr_hud_message, MAVLINK_MSG_ID_COMMAND_INT : MAVLink_command_int_message, MAVLINK_MSG_ID_COMMAND_LONG : MAVLink_command_long_message, MAVLINK_MSG_ID_COMMAND_ACK : MAVLink_command_ack_message, MAVLINK_MSG_ID_MANUAL_SETPOINT : MAVLink_manual_setpoint_message, MAVLINK_MSG_ID_SET_ATTITUDE_TARGET : MAVLink_set_attitude_target_message, MAVLINK_MSG_ID_ATTITUDE_TARGET : MAVLink_attitude_target_message, MAVLINK_MSG_ID_SET_POSITION_TARGET_LOCAL_NED : MAVLink_set_position_target_local_ned_message, MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED : MAVLink_position_target_local_ned_message, MAVLINK_MSG_ID_SET_POSITION_TARGET_GLOBAL_INT : MAVLink_set_position_target_global_int_message, MAVLINK_MSG_ID_POSITION_TARGET_GLOBAL_INT : MAVLink_position_target_global_int_message, MAVLINK_MSG_ID_LOCAL_POSITION_NED_SYSTEM_GLOBAL_OFFSET : MAVLink_local_position_ned_system_global_offset_message, MAVLINK_MSG_ID_HIL_STATE : MAVLink_hil_state_message, MAVLINK_MSG_ID_HIL_CONTROLS : MAVLink_hil_controls_message, MAVLINK_MSG_ID_HIL_RC_INPUTS_RAW : MAVLink_hil_rc_inputs_raw_message, MAVLINK_MSG_ID_HIL_ACTUATOR_CONTROLS : MAVLink_hil_actuator_controls_message, MAVLINK_MSG_ID_OPTICAL_FLOW : MAVLink_optical_flow_message, MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE : MAVLink_global_vision_position_estimate_message, MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE : MAVLink_vision_position_estimate_message, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE : MAVLink_vision_speed_estimate_message, MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE : MAVLink_vicon_position_estimate_message, MAVLINK_MSG_ID_HIGHRES_IMU : MAVLink_highres_imu_message, MAVLINK_MSG_ID_OPTICAL_FLOW_RAD : MAVLink_optical_flow_rad_message, MAVLINK_MSG_ID_HIL_SENSOR : MAVLink_hil_sensor_message, MAVLINK_MSG_ID_SIM_STATE : MAVLink_sim_state_message, MAVLINK_MSG_ID_RADIO_STATUS : MAVLink_radio_status_message, MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL : MAVLink_file_transfer_protocol_message, MAVLINK_MSG_ID_TIMESYNC : MAVLink_timesync_message, MAVLINK_MSG_ID_CAMERA_TRIGGER : MAVLink_camera_trigger_message, MAVLINK_MSG_ID_HIL_GPS : MAVLink_hil_gps_message, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW : MAVLink_hil_optical_flow_message, MAVLINK_MSG_ID_HIL_STATE_QUATERNION : MAVLink_hil_state_quaternion_message, MAVLINK_MSG_ID_SCALED_IMU2 : MAVLink_scaled_imu2_message, MAVLINK_MSG_ID_LOG_REQUEST_LIST : MAVLink_log_request_list_message, MAVLINK_MSG_ID_LOG_ENTRY : MAVLink_log_entry_message, MAVLINK_MSG_ID_LOG_REQUEST_DATA : MAVLink_log_request_data_message, MAVLINK_MSG_ID_LOG_DATA : MAVLink_log_data_message, MAVLINK_MSG_ID_LOG_ERASE : MAVLink_log_erase_message, MAVLINK_MSG_ID_LOG_REQUEST_END : MAVLink_log_request_end_message, MAVLINK_MSG_ID_GPS_INJECT_DATA : MAVLink_gps_inject_data_message, MAVLINK_MSG_ID_GPS2_RAW : MAVLink_gps2_raw_message, MAVLINK_MSG_ID_POWER_STATUS : MAVLink_power_status_message, MAVLINK_MSG_ID_SERIAL_CONTROL : MAVLink_serial_control_message, MAVLINK_MSG_ID_GPS_RTK : MAVLink_gps_rtk_message, MAVLINK_MSG_ID_GPS2_RTK : MAVLink_gps2_rtk_message, MAVLINK_MSG_ID_SCALED_IMU3 : MAVLink_scaled_imu3_message, MAVLINK_MSG_ID_DATA_TRANSMISSION_HANDSHAKE : MAVLink_data_transmission_handshake_message, MAVLINK_MSG_ID_ENCAPSULATED_DATA : MAVLink_encapsulated_data_message, MAVLINK_MSG_ID_DISTANCE_SENSOR : MAVLink_distance_sensor_message, MAVLINK_MSG_ID_TERRAIN_REQUEST : MAVLink_terrain_request_message, MAVLINK_MSG_ID_TERRAIN_DATA : MAVLink_terrain_data_message, MAVLINK_MSG_ID_TERRAIN_CHECK : MAVLink_terrain_check_message, MAVLINK_MSG_ID_TERRAIN_REPORT : MAVLink_terrain_report_message, MAVLINK_MSG_ID_SCALED_PRESSURE2 : MAVLink_scaled_pressure2_message, MAVLINK_MSG_ID_ATT_POS_MOCAP : MAVLink_att_pos_mocap_message, MAVLINK_MSG_ID_SET_ACTUATOR_CONTROL_TARGET : MAVLink_set_actuator_control_target_message, MAVLINK_MSG_ID_ACTUATOR_CONTROL_TARGET : MAVLink_actuator_control_target_message, MAVLINK_MSG_ID_ALTITUDE : MAVLink_altitude_message, MAVLINK_MSG_ID_RESOURCE_REQUEST : MAVLink_resource_request_message, MAVLINK_MSG_ID_SCALED_PRESSURE3 : MAVLink_scaled_pressure3_message, MAVLINK_MSG_ID_FOLLOW_TARGET : MAVLink_follow_target_message, MAVLINK_MSG_ID_CONTROL_SYSTEM_STATE : MAVLink_control_system_state_message, MAVLINK_MSG_ID_BATTERY_STATUS : MAVLink_battery_status_message, MAVLINK_MSG_ID_AUTOPILOT_VERSION : MAVLink_autopilot_version_message, MAVLINK_MSG_ID_LANDING_TARGET : MAVLink_landing_target_message, MAVLINK_MSG_ID_FENCE_STATUS : MAVLink_fence_status_message, MAVLINK_MSG_ID_ESTIMATOR_STATUS : MAVLink_estimator_status_message, MAVLINK_MSG_ID_WIND_COV : MAVLink_wind_cov_message, MAVLINK_MSG_ID_GPS_INPUT : MAVLink_gps_input_message, MAVLINK_MSG_ID_GPS_RTCM_DATA : MAVLink_gps_rtcm_data_message, MAVLINK_MSG_ID_HIGH_LATENCY : MAVLink_high_latency_message, MAVLINK_MSG_ID_VIBRATION : MAVLink_vibration_message, MAVLINK_MSG_ID_HOME_POSITION : MAVLink_home_position_message, MAVLINK_MSG_ID_SET_HOME_POSITION : MAVLink_set_home_position_message, MAVLINK_MSG_ID_MESSAGE_INTERVAL : MAVLink_message_interval_message, MAVLINK_MSG_ID_EXTENDED_SYS_STATE : MAVLink_extended_sys_state_message, MAVLINK_MSG_ID_ADSB_VEHICLE : MAVLink_adsb_vehicle_message, MAVLINK_MSG_ID_COLLISION : MAVLink_collision_message, MAVLINK_MSG_ID_V2_EXTENSION : MAVLink_v2_extension_message, MAVLINK_MSG_ID_MEMORY_VECT : MAVLink_memory_vect_message, MAVLINK_MSG_ID_DEBUG_VECT : MAVLink_debug_vect_message, MAVLINK_MSG_ID_NAMED_VALUE_FLOAT : MAVLink_named_value_float_message, MAVLINK_MSG_ID_NAMED_VALUE_INT : MAVLink_named_value_int_message, MAVLINK_MSG_ID_STATUSTEXT : MAVLink_statustext_message, MAVLINK_MSG_ID_DEBUG : MAVLink_debug_message, MAVLINK_MSG_ID_SETUP_SIGNING : MAVLink_setup_signing_message, MAVLINK_MSG_ID_BUTTON_CHANGE : MAVLink_button_change_message, MAVLINK_MSG_ID_PLAY_TUNE : MAVLink_play_tune_message, MAVLINK_MSG_ID_CAMERA_INFORMATION : MAVLink_camera_information_message, MAVLINK_MSG_ID_CAMERA_SETTINGS : MAVLink_camera_settings_message, MAVLINK_MSG_ID_STORAGE_INFORMATION : MAVLink_storage_information_message, MAVLINK_MSG_ID_CAMERA_CAPTURE_STATUS : MAVLink_camera_capture_status_message, MAVLINK_MSG_ID_CAMERA_IMAGE_CAPTURED : MAVLink_camera_image_captured_message, MAVLINK_MSG_ID_FLIGHT_INFORMATION : MAVLink_flight_information_message, MAVLINK_MSG_ID_MOUNT_ORIENTATION : MAVLink_mount_orientation_message, MAVLINK_MSG_ID_LOGGING_DATA : MAVLink_logging_data_message, MAVLINK_MSG_ID_LOGGING_DATA_ACKED : MAVLink_logging_data_acked_message, MAVLINK_MSG_ID_LOGGING_ACK : MAVLink_logging_ack_message, MAVLINK_MSG_ID_WIFI_CONFIG_AP : MAVLink_wifi_config_ap_message, MAVLINK_MSG_ID_UAVCAN_NODE_STATUS : MAVLink_uavcan_node_status_message, MAVLINK_MSG_ID_UAVCAN_NODE_INFO : MAVLink_uavcan_node_info_message, MAVLINK_MSG_ID_OBSTACLE_DISTANCE : MAVLink_obstacle_distance_message, MAVLINK_MSG_ID_ODOMETRY : MAVLink_odometry_message, MAVLINK_MSG_ID_ISBD_LINK_STATUS : MAVLink_isbd_link_status_message, MAVLINK_MSG_ID_DEBUG_FLOAT_ARRAY : MAVLink_debug_float_array_message, MAVLINK_MSG_ID_STATUSTEXT_LONG : MAVLink_statustext_long_message, MAVLINK_MSG_ID_ACTUATOR_OUTPUT_STATUS : MAVLink_actuator_output_status_message, MAVLINK_MSG_ID_WHEEL_DISTANCE : MAVLink_wheel_distance_message, } class MAVError(Exception): '''MAVLink error class''' def __init__(self, msg): Exception.__init__(self, msg) self.message = msg class MAVString(str): '''NUL terminated string''' def __init__(self, s): str.__init__(self) def __str__(self): i = self.find(chr(0)) if i == -1: return self[:] return self[0:i] class MAVLink_bad_data(MAVLink_message): ''' a piece of bad data in a mavlink stream ''' def __init__(self, data, reason): MAVLink_message.__init__(self, MAVLINK_MSG_ID_BAD_DATA, 'BAD_DATA') self._fieldnames = ['data', 'reason'] self.data = data self.reason = reason self._msgbuf = data def __str__(self): '''Override the __str__ function from MAVLink_messages because non-printable characters are common in to be the reason for this message to exist.''' return '%s {%s, data:%s}' % (self._type, self.reason, [('%x' % ord(i) if isinstance(i, str) else '%x' % i) for i in self.data]) class MAVLinkSigning(object): '''MAVLink signing state class''' def __init__(self): self.secret_key = None self.timestamp = 0 self.link_id = 0 self.sign_outgoing = False self.allow_unsigned_callback = None self.stream_timestamps = {} self.sig_count = 0 self.badsig_count = 0 self.goodsig_count = 0 self.unsigned_count = 0 self.reject_count = 0 class MAVLink(object): '''MAVLink protocol handling class''' def __init__(self, file, srcSystem=0, srcComponent=0, use_native=False): self.seq = 0 self.file = file self.srcSystem = srcSystem self.srcComponent = srcComponent self.callback = None self.callback_args = None self.callback_kwargs = None self.send_callback = None self.send_callback_args = None self.send_callback_kwargs = None self.buf = bytearray() self.buf_index = 0 self.expected_length = HEADER_LEN_V1+2 self.have_prefix_error = False self.robust_parsing = False self.protocol_marker = 253 self.little_endian = True self.crc_extra = True self.sort_fields = True self.total_packets_sent = 0 self.total_bytes_sent = 0 self.total_packets_received = 0 self.total_bytes_received = 0 self.total_receive_errors = 0 self.startup_time = time.time() self.signing = MAVLinkSigning() if native_supported and (use_native or native_testing or native_force): print("NOTE: mavnative is currently beta-test code") self.native = mavnative.NativeConnection(MAVLink_message, mavlink_map) else: self.native = None if native_testing: self.test_buf = bytearray() self.mav20_unpacker = struct.Struct('<cBBBBBBHB') self.mav10_unpacker = struct.Struct('<cBBBBB') self.mav20_h3_unpacker = struct.Struct('BBB') self.mav_csum_unpacker = struct.Struct('<H') self.mav_sign_unpacker = struct.Struct('<IH') def set_callback(self, callback, *args, **kwargs): self.callback = callback self.callback_args = args self.callback_kwargs = kwargs def set_send_callback(self, callback, *args, **kwargs): self.send_callback = callback self.send_callback_args = args self.send_callback_kwargs = kwargs def send(self, mavmsg, force_mavlink1=False): '''send a MAVLink message''' buf = mavmsg.pack(self, force_mavlink1=force_mavlink1) self.file.write(buf) self.seq = (self.seq + 1) % 256 self.total_packets_sent += 1 self.total_bytes_sent += len(buf) if self.send_callback: self.send_callback(mavmsg, *self.send_callback_args, **self.send_callback_kwargs) def buf_len(self): return len(self.buf) - self.buf_index def bytes_needed(self): '''return number of bytes needed for next parsing stage''' if self.native: ret = self.native.expected_length - self.buf_len() else: ret = self.expected_length - self.buf_len() if ret <= 0: return 1 return ret def __parse_char_native(self, c): '''this method exists only to see in profiling results''' m = self.native.parse_chars(c) return m def __callbacks(self, msg): '''this method exists only to make profiling results easier to read''' if self.callback: self.callback(msg, *self.callback_args, **self.callback_kwargs) def parse_char(self, c): '''input some data bytes, possibly returning a new message''' self.buf.extend(c) self.total_bytes_received += len(c) if self.native: if native_testing: self.test_buf.extend(c) m = self.__parse_char_native(self.test_buf) m2 = self.__parse_char_legacy() if m2 != m: print("Native: %s\nLegacy: %s\n" % (m, m2)) raise Exception('Native vs. Legacy mismatch') else: m = self.__parse_char_native(self.buf) else: m = self.__parse_char_legacy() if m is not None: self.total_packets_received += 1 self.__callbacks(m) else: # XXX The idea here is if we've read something and there's nothing left in # the buffer, reset it to 0 which frees the memory if self.buf_len() == 0 and self.buf_index != 0: self.buf = bytearray() self.buf_index = 0 return m def __parse_char_legacy(self): '''input some data bytes, possibly returning a new message (uses no native code)''' header_len = HEADER_LEN_V1 if self.buf_len() >= 1 and self.buf[self.buf_index] == PROTOCOL_MARKER_V2: header_len = HEADER_LEN_V2 if self.buf_len() >= 1 and self.buf[self.buf_index] != PROTOCOL_MARKER_V1 and self.buf[self.buf_index] != PROTOCOL_MARKER_V2: magic = self.buf[self.buf_index] self.buf_index += 1 if self.robust_parsing: m = MAVLink_bad_data(bytearray([magic]), 'Bad prefix') self.expected_length = header_len+2 self.total_receive_errors += 1 return m if self.have_prefix_error: return None self.have_prefix_error = True self.total_receive_errors += 1 raise MAVError("invalid MAVLink prefix '%s'" % magic) self.have_prefix_error = False if self.buf_len() >= 3: sbuf = self.buf[self.buf_index:3+self.buf_index] if sys.version_info.major < 3: sbuf = str(sbuf) (magic, self.expected_length, incompat_flags) = self.mav20_h3_unpacker.unpack(sbuf) if magic == PROTOCOL_MARKER_V2 and (incompat_flags & MAVLINK_IFLAG_SIGNED): self.expected_length += MAVLINK_SIGNATURE_BLOCK_LEN self.expected_length += header_len + 2 if self.expected_length >= (header_len+2) and self.buf_len() >= self.expected_length: mbuf = array.array('B', self.buf[self.buf_index:self.buf_index+self.expected_length]) self.buf_index += self.expected_length self.expected_length = header_len+2 if self.robust_parsing: try: if magic == PROTOCOL_MARKER_V2 and (incompat_flags & ~MAVLINK_IFLAG_SIGNED) != 0: raise MAVError('invalid incompat_flags 0x%x 0x%x %u' % (incompat_flags, magic, self.expected_length)) m = self.decode(mbuf) except MAVError as reason: m = MAVLink_bad_data(mbuf, reason.message) self.total_receive_errors += 1 else: if magic == PROTOCOL_MARKER_V2 and (incompat_flags & ~MAVLINK_IFLAG_SIGNED) != 0: raise MAVError('invalid incompat_flags 0x%x 0x%x %u' % (incompat_flags, magic, self.expected_length)) m = self.decode(mbuf) return m return None def parse_buffer(self, s): '''input some data bytes, possibly returning a list of new messages''' m = self.parse_char(s) if m is None: return None ret = [m] while True: m = self.parse_char("") if m is None: return ret ret.append(m) return ret def check_signature(self, msgbuf, srcSystem, srcComponent): '''check signature on incoming message''' if isinstance(msgbuf, array.array): msgbuf = msgbuf.tostring() timestamp_buf = msgbuf[-12:-6] link_id = msgbuf[-13] (tlow, thigh) = self.mav_sign_unpacker.unpack(timestamp_buf) timestamp = tlow + (thigh<<32) # see if the timestamp is acceptable stream_key = (link_id,srcSystem,srcComponent) if stream_key in self.signing.stream_timestamps: if timestamp <= self.signing.stream_timestamps[stream_key]: # reject old timestamp # print('old timestamp') return False else: # a new stream has appeared. Accept the timestamp if it is at most # one minute behind our current timestamp if timestamp + 6000*1000 < self.signing.timestamp: # print('bad new stream ', timestamp/(100.0*1000*60*60*24*365), self.signing.timestamp/(100.0*1000*60*60*24*365)) return False self.signing.stream_timestamps[stream_key] = timestamp # print('new stream') h = hashlib.new('sha256') h.update(self.signing.secret_key) h.update(msgbuf[:-6]) if str(type(msgbuf)) == "<class 'bytes'>": # Python 3 sig1 = h.digest()[:6] sig2 = msgbuf[-6:] else: sig1 = str(h.digest())[:6] sig2 = str(msgbuf)[-6:] if sig1 != sig2: # print('sig mismatch') return False # the timestamp we next send with is the max of the received timestamp and # our current timestamp self.signing.timestamp = max(self.signing.timestamp, timestamp) return True def decode(self, msgbuf): '''decode a buffer as a MAVLink message''' # decode the header if msgbuf[0] != PROTOCOL_MARKER_V1: headerlen = 10 try: magic, mlen, incompat_flags, compat_flags, seq, srcSystem, srcComponent, msgIdlow, msgIdhigh = self.mav20_unpacker.unpack(msgbuf[:headerlen]) except struct.error as emsg: raise MAVError('Unable to unpack MAVLink header: %s' % emsg) msgId = msgIdlow | (msgIdhigh<<16) mapkey = msgId else: headerlen = 6 try: magic, mlen, seq, srcSystem, srcComponent, msgId = self.mav10_unpacker.unpack(msgbuf[:headerlen]) incompat_flags = 0 compat_flags = 0 except struct.error as emsg: raise MAVError('Unable to unpack MAVLink header: %s' % emsg) mapkey = msgId if (incompat_flags & MAVLINK_IFLAG_SIGNED) != 0: signature_len = MAVLINK_SIGNATURE_BLOCK_LEN else: signature_len = 0 if ord(magic) != PROTOCOL_MARKER_V1 and ord(magic) != PROTOCOL_MARKER_V2: raise MAVError("invalid MAVLink prefix '%s'" % magic) if mlen != len(msgbuf)-(headerlen+2+signature_len): raise MAVError('invalid MAVLink message length. Got %u expected %u, msgId=%u headerlen=%u' % (len(msgbuf)-(headerlen+2+signature_len), mlen, msgId, headerlen)) if not mapkey in mavlink_map: raise MAVError('unknown MAVLink message ID %s' % str(mapkey)) # decode the payload type = mavlink_map[mapkey] fmt = type.format order_map = type.orders len_map = type.lengths crc_extra = type.crc_extra # decode the checksum try: crc, = self.mav_csum_unpacker.unpack(msgbuf[-(2+signature_len):][:2]) except struct.error as emsg: raise MAVError('Unable to unpack MAVLink CRC: %s' % emsg) crcbuf = msgbuf[1:-(2+signature_len)] if True: # using CRC extra crcbuf.append(crc_extra) crc2 = x25crc(crcbuf) if crc != crc2.crc: raise MAVError('invalid MAVLink CRC in msgID %u 0x%04x should be 0x%04x' % (msgId, crc, crc2.crc)) sig_ok = False if signature_len == MAVLINK_SIGNATURE_BLOCK_LEN: self.signing.sig_count += 1 if self.signing.secret_key is not None: accept_signature = False if signature_len == MAVLINK_SIGNATURE_BLOCK_LEN: sig_ok = self.check_signature(msgbuf, srcSystem, srcComponent) accept_signature = sig_ok if sig_ok: self.signing.goodsig_count += 1 else: self.signing.badsig_count += 1 if not accept_signature and self.signing.allow_unsigned_callback is not None: accept_signature = self.signing.allow_unsigned_callback(self, msgId) if accept_signature: self.signing.unsigned_count += 1 else: self.signing.reject_count += 1 elif self.signing.allow_unsigned_callback is not None: accept_signature = self.signing.allow_unsigned_callback(self, msgId) if accept_signature: self.signing.unsigned_count += 1 else: self.signing.reject_count += 1 if not accept_signature: raise MAVError('Invalid signature') csize = type.unpacker.size mbuf = msgbuf[headerlen:-(2+signature_len)] if len(mbuf) < csize: # zero pad to give right size mbuf.extend([0]*(csize - len(mbuf))) if len(mbuf) < csize: raise MAVError('Bad message of type %s length %u needs %s' % ( type, len(mbuf), csize)) mbuf = mbuf[:csize] try: t = type.unpacker.unpack(mbuf) except struct.error as emsg: raise MAVError('Unable to unpack MAVLink payload type=%s fmt=%s payloadLength=%u: %s' % ( type, fmt, len(mbuf), emsg)) tlist = list(t) # handle sorted fields if True: t = tlist[:] if sum(len_map) == len(len_map): # message has no arrays in it for i in range(0, len(tlist)): tlist[i] = t[order_map[i]] else: # message has some arrays tlist = [] for i in range(0, len(order_map)): order = order_map[i] L = len_map[order] tip = sum(len_map[:order]) field = t[tip] if L == 1 or isinstance(field, str): tlist.append(field) else: tlist.append(t[tip:(tip + L)]) # terminate any strings for i in range(0, len(tlist)): if type.fieldtypes[i] == 'char': if sys.version_info.major >= 3: tlist[i] = tlist[i].decode('utf-8') tlist[i] = str(MAVString(tlist[i])) t = tuple(tlist) # construct the message object try: m = type(*t) except Exception as emsg: raise MAVError('Unable to instantiate MAVLink message of type %s : %s' % (type, emsg)) m._signed = sig_ok if m._signed: m._link_id = msgbuf[-13] m._msgbuf = msgbuf m._payload = msgbuf[6:-(2+signature_len)] m._crc = crc m._header = MAVLink_header(msgId, incompat_flags, compat_flags, mlen, seq, srcSystem, srcComponent) return m def script_item_encode(self, target_system, target_component, seq, name): ''' Message encoding a mission script item. This message is emitted upon a request for the next script item. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) name : The name of the mission script, NULL terminated. (type:char) ''' return MAVLink_script_item_message(target_system, target_component, seq, name) def script_item_send(self, target_system, target_component, seq, name, force_mavlink1=False): ''' Message encoding a mission script item. This message is emitted upon a request for the next script item. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) name : The name of the mission script, NULL terminated. (type:char) ''' return self.send(self.script_item_encode(target_system, target_component, seq, name), force_mavlink1=force_mavlink1) def script_request_encode(self, target_system, target_component, seq): ''' Request script item with the sequence number seq. The response of the system to this message should be a SCRIPT_ITEM message. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) ''' return MAVLink_script_request_message(target_system, target_component, seq) def script_request_send(self, target_system, target_component, seq, force_mavlink1=False): ''' Request script item with the sequence number seq. The response of the system to this message should be a SCRIPT_ITEM message. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) ''' return self.send(self.script_request_encode(target_system, target_component, seq), force_mavlink1=force_mavlink1) def script_request_list_encode(self, target_system, target_component): ''' Request the overall list of mission items from the system/component. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return MAVLink_script_request_list_message(target_system, target_component) def script_request_list_send(self, target_system, target_component, force_mavlink1=False): ''' Request the overall list of mission items from the system/component. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return self.send(self.script_request_list_encode(target_system, target_component), force_mavlink1=force_mavlink1) def script_count_encode(self, target_system, target_component, count): ''' This message is emitted as response to SCRIPT_REQUEST_LIST by the MAV to get the number of mission scripts. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) count : Number of script items in the sequence (type:uint16_t) ''' return MAVLink_script_count_message(target_system, target_component, count) def script_count_send(self, target_system, target_component, count, force_mavlink1=False): ''' This message is emitted as response to SCRIPT_REQUEST_LIST by the MAV to get the number of mission scripts. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) count : Number of script items in the sequence (type:uint16_t) ''' return self.send(self.script_count_encode(target_system, target_component, count), force_mavlink1=force_mavlink1) def script_current_encode(self, seq): ''' This message informs about the currently active SCRIPT. seq : Active Sequence (type:uint16_t) ''' return MAVLink_script_current_message(seq) def script_current_send(self, seq, force_mavlink1=False): ''' This message informs about the currently active SCRIPT. seq : Active Sequence (type:uint16_t) ''' return self.send(self.script_current_encode(seq), force_mavlink1=force_mavlink1) def heartbeat_encode(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version=3): ''' The heartbeat message shows that a system or component is present and responding. The type and autopilot fields (along with the message component id), allow the receiving system to treat further messages from this system appropriately (e.g. by laying out the user interface based on the autopilot). This microservice is documented at https://mavlink.io/en/services/heartbeat.html type : Vehicle or component type. For a flight controller component the vehicle type (quadrotor, helicopter, etc.). For other components the component type (e.g. camera, gimbal, etc.). This should be used in preference to component id for identifying the component type. (type:uint8_t, values:MAV_TYPE) autopilot : Autopilot type / class. Use MAV_AUTOPILOT_INVALID for components that are not flight controllers. (type:uint8_t, values:MAV_AUTOPILOT) base_mode : System mode bitmap. (type:uint8_t, values:MAV_MODE_FLAG) custom_mode : A bitfield for use for autopilot-specific flags (type:uint32_t) system_status : System status flag. (type:uint8_t, values:MAV_STATE) mavlink_version : MAVLink version, not writable by user, gets added by protocol because of magic data type: uint8_t_mavlink_version (type:uint8_t) ''' return MAVLink_heartbeat_message(type, autopilot, base_mode, custom_mode, system_status, mavlink_version) def heartbeat_send(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version=3, force_mavlink1=False): ''' The heartbeat message shows that a system or component is present and responding. The type and autopilot fields (along with the message component id), allow the receiving system to treat further messages from this system appropriately (e.g. by laying out the user interface based on the autopilot). This microservice is documented at https://mavlink.io/en/services/heartbeat.html type : Vehicle or component type. For a flight controller component the vehicle type (quadrotor, helicopter, etc.). For other components the component type (e.g. camera, gimbal, etc.). This should be used in preference to component id for identifying the component type. (type:uint8_t, values:MAV_TYPE) autopilot : Autopilot type / class. Use MAV_AUTOPILOT_INVALID for components that are not flight controllers. (type:uint8_t, values:MAV_AUTOPILOT) base_mode : System mode bitmap. (type:uint8_t, values:MAV_MODE_FLAG) custom_mode : A bitfield for use for autopilot-specific flags (type:uint32_t) system_status : System status flag. (type:uint8_t, values:MAV_STATE) mavlink_version : MAVLink version, not writable by user, gets added by protocol because of magic data type: uint8_t_mavlink_version (type:uint8_t) ''' return self.send(self.heartbeat_encode(type, autopilot, base_mode, custom_mode, system_status, mavlink_version), force_mavlink1=force_mavlink1) def sys_status_encode(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4): ''' The general system state. If the system is following the MAVLink standard, the system state is mainly defined by three orthogonal states/modes: The system mode, which is either LOCKED (motors shut down and locked), MANUAL (system under RC control), GUIDED (system with autonomous position control, position setpoint controlled manually) or AUTO (system guided by path/waypoint planner). The NAV_MODE defined the current flight state: LIFTOFF (often an open-loop maneuver), LANDING, WAYPOINTS or VECTOR. This represents the internal navigation state machine. The system status shows whether the system is currently active or not and if an emergency occurred. During the CRITICAL and EMERGENCY states the MAV is still considered to be active, but should start emergency procedures autonomously. After a failure occurred it should first move from active to critical to allow manual intervention and then move to emergency after a certain timeout. onboard_control_sensors_present : Bitmap showing which onboard controllers and sensors are present. Value of 0: not present. Value of 1: present. (type:uint32_t, values:MAV_SYS_STATUS_SENSOR) onboard_control_sensors_enabled : Bitmap showing which onboard controllers and sensors are enabled: Value of 0: not enabled. Value of 1: enabled. (type:uint32_t, values:MAV_SYS_STATUS_SENSOR) onboard_control_sensors_health : Bitmap showing which onboard controllers and sensors have an error (or are operational). Value of 0: error. Value of 1: healthy. (type:uint32_t, values:MAV_SYS_STATUS_SENSOR) load : Maximum usage in percent of the mainloop time. Values: [0-1000] - should always be below 1000 [d%] (type:uint16_t) voltage_battery : Battery voltage, UINT16_MAX: Voltage not sent by autopilot [mV] (type:uint16_t) current_battery : Battery current, -1: Current not sent by autopilot [cA] (type:int16_t) battery_remaining : Battery energy remaining, -1: Battery remaining energy not sent by autopilot [%] (type:int8_t) drop_rate_comm : Communication drop rate, (UART, I2C, SPI, CAN), dropped packets on all links (packets that were corrupted on reception on the MAV) [c%] (type:uint16_t) errors_comm : Communication errors (UART, I2C, SPI, CAN), dropped packets on all links (packets that were corrupted on reception on the MAV) (type:uint16_t) errors_count1 : Autopilot-specific errors (type:uint16_t) errors_count2 : Autopilot-specific errors (type:uint16_t) errors_count3 : Autopilot-specific errors (type:uint16_t) errors_count4 : Autopilot-specific errors (type:uint16_t) ''' return MAVLink_sys_status_message(onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4) def sys_status_send(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4, force_mavlink1=False): ''' The general system state. If the system is following the MAVLink standard, the system state is mainly defined by three orthogonal states/modes: The system mode, which is either LOCKED (motors shut down and locked), MANUAL (system under RC control), GUIDED (system with autonomous position control, position setpoint controlled manually) or AUTO (system guided by path/waypoint planner). The NAV_MODE defined the current flight state: LIFTOFF (often an open-loop maneuver), LANDING, WAYPOINTS or VECTOR. This represents the internal navigation state machine. The system status shows whether the system is currently active or not and if an emergency occurred. During the CRITICAL and EMERGENCY states the MAV is still considered to be active, but should start emergency procedures autonomously. After a failure occurred it should first move from active to critical to allow manual intervention and then move to emergency after a certain timeout. onboard_control_sensors_present : Bitmap showing which onboard controllers and sensors are present. Value of 0: not present. Value of 1: present. (type:uint32_t, values:MAV_SYS_STATUS_SENSOR) onboard_control_sensors_enabled : Bitmap showing which onboard controllers and sensors are enabled: Value of 0: not enabled. Value of 1: enabled. (type:uint32_t, values:MAV_SYS_STATUS_SENSOR) onboard_control_sensors_health : Bitmap showing which onboard controllers and sensors have an error (or are operational). Value of 0: error. Value of 1: healthy. (type:uint32_t, values:MAV_SYS_STATUS_SENSOR) load : Maximum usage in percent of the mainloop time. Values: [0-1000] - should always be below 1000 [d%] (type:uint16_t) voltage_battery : Battery voltage, UINT16_MAX: Voltage not sent by autopilot [mV] (type:uint16_t) current_battery : Battery current, -1: Current not sent by autopilot [cA] (type:int16_t) battery_remaining : Battery energy remaining, -1: Battery remaining energy not sent by autopilot [%] (type:int8_t) drop_rate_comm : Communication drop rate, (UART, I2C, SPI, CAN), dropped packets on all links (packets that were corrupted on reception on the MAV) [c%] (type:uint16_t) errors_comm : Communication errors (UART, I2C, SPI, CAN), dropped packets on all links (packets that were corrupted on reception on the MAV) (type:uint16_t) errors_count1 : Autopilot-specific errors (type:uint16_t) errors_count2 : Autopilot-specific errors (type:uint16_t) errors_count3 : Autopilot-specific errors (type:uint16_t) errors_count4 : Autopilot-specific errors (type:uint16_t) ''' return self.send(self.sys_status_encode(onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4), force_mavlink1=force_mavlink1) def system_time_encode(self, time_unix_usec, time_boot_ms): ''' The system time is the time of the master clock, typically the computer clock of the main onboard computer. time_unix_usec : Timestamp (UNIX epoch time). [us] (type:uint64_t) time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) ''' return MAVLink_system_time_message(time_unix_usec, time_boot_ms) def system_time_send(self, time_unix_usec, time_boot_ms, force_mavlink1=False): ''' The system time is the time of the master clock, typically the computer clock of the main onboard computer. time_unix_usec : Timestamp (UNIX epoch time). [us] (type:uint64_t) time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) ''' return self.send(self.system_time_encode(time_unix_usec, time_boot_ms), force_mavlink1=force_mavlink1) def ping_encode(self, time_usec, seq, target_system, target_component): ''' A ping message either requesting or responding to a ping. This allows to measure the system latencies, including serial port, radio modem and UDP connections. The ping microservice is documented at https://mavlink.io/en/services/ping.html time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) seq : PING sequence (type:uint32_t) target_system : 0: request ping from all receiving systems. If greater than 0: message is a ping response and number is the system id of the requesting system (type:uint8_t) target_component : 0: request ping from all receiving components. If greater than 0: message is a ping response and number is the component id of the requesting component. (type:uint8_t) ''' return MAVLink_ping_message(time_usec, seq, target_system, target_component) def ping_send(self, time_usec, seq, target_system, target_component, force_mavlink1=False): ''' A ping message either requesting or responding to a ping. This allows to measure the system latencies, including serial port, radio modem and UDP connections. The ping microservice is documented at https://mavlink.io/en/services/ping.html time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) seq : PING sequence (type:uint32_t) target_system : 0: request ping from all receiving systems. If greater than 0: message is a ping response and number is the system id of the requesting system (type:uint8_t) target_component : 0: request ping from all receiving components. If greater than 0: message is a ping response and number is the component id of the requesting component. (type:uint8_t) ''' return self.send(self.ping_encode(time_usec, seq, target_system, target_component), force_mavlink1=force_mavlink1) def change_operator_control_encode(self, target_system, control_request, version, passkey): ''' Request to control this MAV target_system : System the GCS requests control for (type:uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (type:uint8_t) version : 0: key as plaintext, 1-255: future, different hashing/encryption variants. The GCS should in general use the safest mode possible initially and then gradually move down the encryption level if it gets a NACK message indicating an encryption mismatch. [rad] (type:uint8_t) passkey : Password / Key, depending on version plaintext or encrypted. 25 or less characters, NULL terminated. The characters may involve A-Z, a-z, 0-9, and "!?,.-" (type:char) ''' return MAVLink_change_operator_control_message(target_system, control_request, version, passkey) def change_operator_control_send(self, target_system, control_request, version, passkey, force_mavlink1=False): ''' Request to control this MAV target_system : System the GCS requests control for (type:uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (type:uint8_t) version : 0: key as plaintext, 1-255: future, different hashing/encryption variants. The GCS should in general use the safest mode possible initially and then gradually move down the encryption level if it gets a NACK message indicating an encryption mismatch. [rad] (type:uint8_t) passkey : Password / Key, depending on version plaintext or encrypted. 25 or less characters, NULL terminated. The characters may involve A-Z, a-z, 0-9, and "!?,.-" (type:char) ''' return self.send(self.change_operator_control_encode(target_system, control_request, version, passkey), force_mavlink1=force_mavlink1) def change_operator_control_ack_encode(self, gcs_system_id, control_request, ack): ''' Accept / deny control of this MAV gcs_system_id : ID of the GCS this message (type:uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (type:uint8_t) ack : 0: ACK, 1: NACK: Wrong passkey, 2: NACK: Unsupported passkey encryption method, 3: NACK: Already under control (type:uint8_t) ''' return MAVLink_change_operator_control_ack_message(gcs_system_id, control_request, ack) def change_operator_control_ack_send(self, gcs_system_id, control_request, ack, force_mavlink1=False): ''' Accept / deny control of this MAV gcs_system_id : ID of the GCS this message (type:uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (type:uint8_t) ack : 0: ACK, 1: NACK: Wrong passkey, 2: NACK: Unsupported passkey encryption method, 3: NACK: Already under control (type:uint8_t) ''' return self.send(self.change_operator_control_ack_encode(gcs_system_id, control_request, ack), force_mavlink1=force_mavlink1) def auth_key_encode(self, key): ''' Emit an encrypted signature / key identifying this system. PLEASE NOTE: This protocol has been kept simple, so transmitting the key requires an encrypted channel for true safety. key : key (type:char) ''' return MAVLink_auth_key_message(key) def auth_key_send(self, key, force_mavlink1=False): ''' Emit an encrypted signature / key identifying this system. PLEASE NOTE: This protocol has been kept simple, so transmitting the key requires an encrypted channel for true safety. key : key (type:char) ''' return self.send(self.auth_key_encode(key), force_mavlink1=force_mavlink1) def set_mode_encode(self, target_system, base_mode, custom_mode): ''' Set the system mode, as defined by enum MAV_MODE. There is no target component id as the mode is by definition for the overall aircraft, not only for one component. target_system : The system setting the mode (type:uint8_t) base_mode : The new base mode. (type:uint8_t, values:MAV_MODE) custom_mode : The new autopilot-specific mode. This field can be ignored by an autopilot. (type:uint32_t) ''' return MAVLink_set_mode_message(target_system, base_mode, custom_mode) def set_mode_send(self, target_system, base_mode, custom_mode, force_mavlink1=False): ''' Set the system mode, as defined by enum MAV_MODE. There is no target component id as the mode is by definition for the overall aircraft, not only for one component. target_system : The system setting the mode (type:uint8_t) base_mode : The new base mode. (type:uint8_t, values:MAV_MODE) custom_mode : The new autopilot-specific mode. This field can be ignored by an autopilot. (type:uint32_t) ''' return self.send(self.set_mode_encode(target_system, base_mode, custom_mode), force_mavlink1=force_mavlink1) def param_request_read_encode(self, target_system, target_component, param_id, param_index): ''' Request to read the onboard parameter with the param_id string id. Onboard parameters are stored as key[const char*] -> value[float]. This allows to send a parameter to any other component (such as the GCS) without the need of previous knowledge of possible parameter names. Thus the same GCS can store different parameters for different autopilots. See also https://mavlink.io/en/services/parameter.html for a full documentation of QGroundControl and IMU code. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (type:char) param_index : Parameter index. Send -1 to use the param ID field as identifier (else the param id will be ignored) (type:int16_t) ''' return MAVLink_param_request_read_message(target_system, target_component, param_id, param_index) def param_request_read_send(self, target_system, target_component, param_id, param_index, force_mavlink1=False): ''' Request to read the onboard parameter with the param_id string id. Onboard parameters are stored as key[const char*] -> value[float]. This allows to send a parameter to any other component (such as the GCS) without the need of previous knowledge of possible parameter names. Thus the same GCS can store different parameters for different autopilots. See also https://mavlink.io/en/services/parameter.html for a full documentation of QGroundControl and IMU code. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (type:char) param_index : Parameter index. Send -1 to use the param ID field as identifier (else the param id will be ignored) (type:int16_t) ''' return self.send(self.param_request_read_encode(target_system, target_component, param_id, param_index), force_mavlink1=force_mavlink1) def param_request_list_encode(self, target_system, target_component): ''' Request all parameters of this component. After this request, all parameters are emitted. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return MAVLink_param_request_list_message(target_system, target_component) def param_request_list_send(self, target_system, target_component, force_mavlink1=False): ''' Request all parameters of this component. After this request, all parameters are emitted. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return self.send(self.param_request_list_encode(target_system, target_component), force_mavlink1=force_mavlink1) def param_value_encode(self, param_id, param_value, param_type, param_count, param_index): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (type:char) param_value : Onboard parameter value (type:float) param_type : Onboard parameter type. (type:uint8_t, values:MAV_PARAM_TYPE) param_count : Total number of onboard parameters (type:uint16_t) param_index : Index of this onboard parameter (type:uint16_t) ''' return MAVLink_param_value_message(param_id, param_value, param_type, param_count, param_index) def param_value_send(self, param_id, param_value, param_type, param_count, param_index, force_mavlink1=False): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (type:char) param_value : Onboard parameter value (type:float) param_type : Onboard parameter type. (type:uint8_t, values:MAV_PARAM_TYPE) param_count : Total number of onboard parameters (type:uint16_t) param_index : Index of this onboard parameter (type:uint16_t) ''' return self.send(self.param_value_encode(param_id, param_value, param_type, param_count, param_index), force_mavlink1=force_mavlink1) def param_set_encode(self, target_system, target_component, param_id, param_value, param_type): ''' Set a parameter value (write new value to permanent storage). IMPORTANT: The receiving component should acknowledge the new parameter value by sending a PARAM_VALUE message to all communication partners. This will also ensure that multiple GCS all have an up-to-date list of all parameters. If the sending GCS did not receive a PARAM_VALUE message within its timeout time, it should re-send the PARAM_SET message. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (type:char) param_value : Onboard parameter value (type:float) param_type : Onboard parameter type. (type:uint8_t, values:MAV_PARAM_TYPE) ''' return MAVLink_param_set_message(target_system, target_component, param_id, param_value, param_type) def param_set_send(self, target_system, target_component, param_id, param_value, param_type, force_mavlink1=False): ''' Set a parameter value (write new value to permanent storage). IMPORTANT: The receiving component should acknowledge the new parameter value by sending a PARAM_VALUE message to all communication partners. This will also ensure that multiple GCS all have an up-to-date list of all parameters. If the sending GCS did not receive a PARAM_VALUE message within its timeout time, it should re-send the PARAM_SET message. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (type:char) param_value : Onboard parameter value (type:float) param_type : Onboard parameter type. (type:uint8_t, values:MAV_PARAM_TYPE) ''' return self.send(self.param_set_encode(target_system, target_component, param_id, param_value, param_type), force_mavlink1=force_mavlink1) def gps_raw_int_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, alt_ellipsoid=0, h_acc=0, v_acc=0, vel_acc=0, hdg_acc=0): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the system, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) fix_type : GPS fix type. (type:uint8_t, values:GPS_FIX_TYPE) lat : Latitude (WGS84, EGM96 ellipsoid) [degE7] (type:int32_t) lon : Longitude (WGS84, EGM96 ellipsoid) [degE7] (type:int32_t) alt : Altitude (MSL). Positive for up. Note that virtually all GPS modules provide the MSL altitude in addition to the WGS84 altitude. [mm] (type:int32_t) eph : GPS HDOP horizontal dilution of position (unitless). If unknown, set to: UINT16_MAX (type:uint16_t) epv : GPS VDOP vertical dilution of position (unitless). If unknown, set to: UINT16_MAX (type:uint16_t) vel : GPS ground speed. If unknown, set to: UINT16_MAX [cm/s] (type:uint16_t) cog : Course over ground (NOT heading, but direction of movement) in degrees * 100, 0.0..359.99 degrees. If unknown, set to: UINT16_MAX [cdeg] (type:uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (type:uint8_t) alt_ellipsoid : Altitude (above WGS84, EGM96 ellipsoid). Positive for up. [mm] (type:int32_t) h_acc : Position uncertainty. Positive for up. [mm] (type:uint32_t) v_acc : Altitude uncertainty. Positive for up. [mm] (type:uint32_t) vel_acc : Speed uncertainty. Positive for up. [mm] (type:uint32_t) hdg_acc : Heading / track uncertainty [degE5] (type:uint32_t) ''' return MAVLink_gps_raw_int_message(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, alt_ellipsoid, h_acc, v_acc, vel_acc, hdg_acc) def gps_raw_int_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, alt_ellipsoid=0, h_acc=0, v_acc=0, vel_acc=0, hdg_acc=0, force_mavlink1=False): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the system, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) fix_type : GPS fix type. (type:uint8_t, values:GPS_FIX_TYPE) lat : Latitude (WGS84, EGM96 ellipsoid) [degE7] (type:int32_t) lon : Longitude (WGS84, EGM96 ellipsoid) [degE7] (type:int32_t) alt : Altitude (MSL). Positive for up. Note that virtually all GPS modules provide the MSL altitude in addition to the WGS84 altitude. [mm] (type:int32_t) eph : GPS HDOP horizontal dilution of position (unitless). If unknown, set to: UINT16_MAX (type:uint16_t) epv : GPS VDOP vertical dilution of position (unitless). If unknown, set to: UINT16_MAX (type:uint16_t) vel : GPS ground speed. If unknown, set to: UINT16_MAX [cm/s] (type:uint16_t) cog : Course over ground (NOT heading, but direction of movement) in degrees * 100, 0.0..359.99 degrees. If unknown, set to: UINT16_MAX [cdeg] (type:uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (type:uint8_t) alt_ellipsoid : Altitude (above WGS84, EGM96 ellipsoid). Positive for up. [mm] (type:int32_t) h_acc : Position uncertainty. Positive for up. [mm] (type:uint32_t) v_acc : Altitude uncertainty. Positive for up. [mm] (type:uint32_t) vel_acc : Speed uncertainty. Positive for up. [mm] (type:uint32_t) hdg_acc : Heading / track uncertainty [degE5] (type:uint32_t) ''' return self.send(self.gps_raw_int_encode(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, alt_ellipsoid, h_acc, v_acc, vel_acc, hdg_acc), force_mavlink1=force_mavlink1) def gps_status_encode(self, satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr): ''' The positioning status, as reported by GPS. This message is intended to display status information about each satellite visible to the receiver. See message GLOBAL_POSITION for the global position estimate. This message can contain information for up to 20 satellites. satellites_visible : Number of satellites visible (type:uint8_t) satellite_prn : Global satellite ID (type:uint8_t) satellite_used : 0: Satellite not used, 1: used for localization (type:uint8_t) satellite_elevation : Elevation (0: right on top of receiver, 90: on the horizon) of satellite [deg] (type:uint8_t) satellite_azimuth : Direction of satellite, 0: 0 deg, 255: 360 deg. [deg] (type:uint8_t) satellite_snr : Signal to noise ratio of satellite [dB] (type:uint8_t) ''' return MAVLink_gps_status_message(satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr) def gps_status_send(self, satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr, force_mavlink1=False): ''' The positioning status, as reported by GPS. This message is intended to display status information about each satellite visible to the receiver. See message GLOBAL_POSITION for the global position estimate. This message can contain information for up to 20 satellites. satellites_visible : Number of satellites visible (type:uint8_t) satellite_prn : Global satellite ID (type:uint8_t) satellite_used : 0: Satellite not used, 1: used for localization (type:uint8_t) satellite_elevation : Elevation (0: right on top of receiver, 90: on the horizon) of satellite [deg] (type:uint8_t) satellite_azimuth : Direction of satellite, 0: 0 deg, 255: 360 deg. [deg] (type:uint8_t) satellite_snr : Signal to noise ratio of satellite [dB] (type:uint8_t) ''' return self.send(self.gps_status_encode(satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr), force_mavlink1=force_mavlink1) def scaled_imu_encode(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) xgyro : Angular speed around X axis [mrad/s] (type:int16_t) ygyro : Angular speed around Y axis [mrad/s] (type:int16_t) zgyro : Angular speed around Z axis [mrad/s] (type:int16_t) xmag : X Magnetic field [mgauss] (type:int16_t) ymag : Y Magnetic field [mgauss] (type:int16_t) zmag : Z Magnetic field [mgauss] (type:int16_t) temperature : Temperature, 0: IMU does not provide temperature values. If the IMU is at 0C it must send 1 (0.01C). [cdegC] (type:int16_t) ''' return MAVLink_scaled_imu_message(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature) def scaled_imu_send(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0, force_mavlink1=False): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) xgyro : Angular speed around X axis [mrad/s] (type:int16_t) ygyro : Angular speed around Y axis [mrad/s] (type:int16_t) zgyro : Angular speed around Z axis [mrad/s] (type:int16_t) xmag : X Magnetic field [mgauss] (type:int16_t) ymag : Y Magnetic field [mgauss] (type:int16_t) zmag : Z Magnetic field [mgauss] (type:int16_t) temperature : Temperature, 0: IMU does not provide temperature values. If the IMU is at 0C it must send 1 (0.01C). [cdegC] (type:int16_t) ''' return self.send(self.scaled_imu_encode(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature), force_mavlink1=force_mavlink1) def raw_imu_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, id=0, temperature=0): ''' The RAW IMU readings for a 9DOF sensor, which is identified by the id (default IMU1). This message should always contain the true raw values without any scaling to allow data capture and system debugging. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) xacc : X acceleration (raw) (type:int16_t) yacc : Y acceleration (raw) (type:int16_t) zacc : Z acceleration (raw) (type:int16_t) xgyro : Angular speed around X axis (raw) (type:int16_t) ygyro : Angular speed around Y axis (raw) (type:int16_t) zgyro : Angular speed around Z axis (raw) (type:int16_t) xmag : X Magnetic field (raw) (type:int16_t) ymag : Y Magnetic field (raw) (type:int16_t) zmag : Z Magnetic field (raw) (type:int16_t) id : Id. Ids are numbered from 0 and map to IMUs numbered from 1 (e.g. IMU1 will have a message with id=0) (type:uint8_t) temperature : Temperature, 0: IMU does not provide temperature values. If the IMU is at 0C it must send 1 (0.01C). [cdegC] (type:int16_t) ''' return MAVLink_raw_imu_message(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, id, temperature) def raw_imu_send(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, id=0, temperature=0, force_mavlink1=False): ''' The RAW IMU readings for a 9DOF sensor, which is identified by the id (default IMU1). This message should always contain the true raw values without any scaling to allow data capture and system debugging. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) xacc : X acceleration (raw) (type:int16_t) yacc : Y acceleration (raw) (type:int16_t) zacc : Z acceleration (raw) (type:int16_t) xgyro : Angular speed around X axis (raw) (type:int16_t) ygyro : Angular speed around Y axis (raw) (type:int16_t) zgyro : Angular speed around Z axis (raw) (type:int16_t) xmag : X Magnetic field (raw) (type:int16_t) ymag : Y Magnetic field (raw) (type:int16_t) zmag : Z Magnetic field (raw) (type:int16_t) id : Id. Ids are numbered from 0 and map to IMUs numbered from 1 (e.g. IMU1 will have a message with id=0) (type:uint8_t) temperature : Temperature, 0: IMU does not provide temperature values. If the IMU is at 0C it must send 1 (0.01C). [cdegC] (type:int16_t) ''' return self.send(self.raw_imu_encode(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, id, temperature), force_mavlink1=force_mavlink1) def raw_pressure_encode(self, time_usec, press_abs, press_diff1, press_diff2, temperature): ''' The RAW pressure readings for the typical setup of one absolute pressure and one differential pressure sensor. The sensor values should be the raw, UNSCALED ADC values. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) press_abs : Absolute pressure (raw) (type:int16_t) press_diff1 : Differential pressure 1 (raw, 0 if nonexistent) (type:int16_t) press_diff2 : Differential pressure 2 (raw, 0 if nonexistent) (type:int16_t) temperature : Raw Temperature measurement (raw) (type:int16_t) ''' return MAVLink_raw_pressure_message(time_usec, press_abs, press_diff1, press_diff2, temperature) def raw_pressure_send(self, time_usec, press_abs, press_diff1, press_diff2, temperature, force_mavlink1=False): ''' The RAW pressure readings for the typical setup of one absolute pressure and one differential pressure sensor. The sensor values should be the raw, UNSCALED ADC values. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) press_abs : Absolute pressure (raw) (type:int16_t) press_diff1 : Differential pressure 1 (raw, 0 if nonexistent) (type:int16_t) press_diff2 : Differential pressure 2 (raw, 0 if nonexistent) (type:int16_t) temperature : Raw Temperature measurement (raw) (type:int16_t) ''' return self.send(self.raw_pressure_encode(time_usec, press_abs, press_diff1, press_diff2, temperature), force_mavlink1=force_mavlink1) def scaled_pressure_encode(self, time_boot_ms, press_abs, press_diff, temperature): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) press_abs : Absolute pressure [hPa] (type:float) press_diff : Differential pressure 1 [hPa] (type:float) temperature : Temperature [cdegC] (type:int16_t) ''' return MAVLink_scaled_pressure_message(time_boot_ms, press_abs, press_diff, temperature) def scaled_pressure_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) press_abs : Absolute pressure [hPa] (type:float) press_diff : Differential pressure 1 [hPa] (type:float) temperature : Temperature [cdegC] (type:int16_t) ''' return self.send(self.scaled_pressure_encode(time_boot_ms, press_abs, press_diff, temperature), force_mavlink1=force_mavlink1) def attitude_encode(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) roll : Roll angle (-pi..+pi) [rad] (type:float) pitch : Pitch angle (-pi..+pi) [rad] (type:float) yaw : Yaw angle (-pi..+pi) [rad] (type:float) rollspeed : Roll angular speed [rad/s] (type:float) pitchspeed : Pitch angular speed [rad/s] (type:float) yawspeed : Yaw angular speed [rad/s] (type:float) ''' return MAVLink_attitude_message(time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed) def attitude_send(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, force_mavlink1=False): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) roll : Roll angle (-pi..+pi) [rad] (type:float) pitch : Pitch angle (-pi..+pi) [rad] (type:float) yaw : Yaw angle (-pi..+pi) [rad] (type:float) rollspeed : Roll angular speed [rad/s] (type:float) pitchspeed : Pitch angular speed [rad/s] (type:float) yawspeed : Yaw angular speed [rad/s] (type:float) ''' return self.send(self.attitude_encode(time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed), force_mavlink1=force_mavlink1) def attitude_quaternion_encode(self, time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) q1 : Quaternion component 1, w (1 in null-rotation) (type:float) q2 : Quaternion component 2, x (0 in null-rotation) (type:float) q3 : Quaternion component 3, y (0 in null-rotation) (type:float) q4 : Quaternion component 4, z (0 in null-rotation) (type:float) rollspeed : Roll angular speed [rad/s] (type:float) pitchspeed : Pitch angular speed [rad/s] (type:float) yawspeed : Yaw angular speed [rad/s] (type:float) ''' return MAVLink_attitude_quaternion_message(time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed) def attitude_quaternion_send(self, time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed, force_mavlink1=False): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) q1 : Quaternion component 1, w (1 in null-rotation) (type:float) q2 : Quaternion component 2, x (0 in null-rotation) (type:float) q3 : Quaternion component 3, y (0 in null-rotation) (type:float) q4 : Quaternion component 4, z (0 in null-rotation) (type:float) rollspeed : Roll angular speed [rad/s] (type:float) pitchspeed : Pitch angular speed [rad/s] (type:float) yawspeed : Yaw angular speed [rad/s] (type:float) ''' return self.send(self.attitude_quaternion_encode(time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed), force_mavlink1=force_mavlink1) def local_position_ned_encode(self, time_boot_ms, x, y, z, vx, vy, vz): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) x : X Position [m] (type:float) y : Y Position [m] (type:float) z : Z Position [m] (type:float) vx : X Speed [m/s] (type:float) vy : Y Speed [m/s] (type:float) vz : Z Speed [m/s] (type:float) ''' return MAVLink_local_position_ned_message(time_boot_ms, x, y, z, vx, vy, vz) def local_position_ned_send(self, time_boot_ms, x, y, z, vx, vy, vz, force_mavlink1=False): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) x : X Position [m] (type:float) y : Y Position [m] (type:float) z : Z Position [m] (type:float) vx : X Speed [m/s] (type:float) vy : Y Speed [m/s] (type:float) vz : Z Speed [m/s] (type:float) ''' return self.send(self.local_position_ned_encode(time_boot_ms, x, y, z, vx, vy, vz), force_mavlink1=force_mavlink1) def global_position_int_encode(self, time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) lat : Latitude, expressed [degE7] (type:int32_t) lon : Longitude, expressed [degE7] (type:int32_t) alt : Altitude (MSL). Note that virtually all GPS modules provide both WGS84 and MSL. [mm] (type:int32_t) relative_alt : Altitude above ground [mm] (type:int32_t) vx : Ground X Speed (Latitude, positive north) [cm/s] (type:int16_t) vy : Ground Y Speed (Longitude, positive east) [cm/s] (type:int16_t) vz : Ground Z Speed (Altitude, positive down) [cm/s] (type:int16_t) hdg : Vehicle heading (yaw angle), 0.0..359.99 degrees. If unknown, set to: UINT16_MAX [cdeg] (type:uint16_t) ''' return MAVLink_global_position_int_message(time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg) def global_position_int_send(self, time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg, force_mavlink1=False): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) lat : Latitude, expressed [degE7] (type:int32_t) lon : Longitude, expressed [degE7] (type:int32_t) alt : Altitude (MSL). Note that virtually all GPS modules provide both WGS84 and MSL. [mm] (type:int32_t) relative_alt : Altitude above ground [mm] (type:int32_t) vx : Ground X Speed (Latitude, positive north) [cm/s] (type:int16_t) vy : Ground Y Speed (Longitude, positive east) [cm/s] (type:int16_t) vz : Ground Z Speed (Altitude, positive down) [cm/s] (type:int16_t) hdg : Vehicle heading (yaw angle), 0.0..359.99 degrees. If unknown, set to: UINT16_MAX [cdeg] (type:uint16_t) ''' return self.send(self.global_position_int_encode(time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg), force_mavlink1=force_mavlink1) def rc_channels_scaled_encode(self, time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi): ''' The scaled values of the RC channels received: (-100%) -10000, (0%) 0, (100%) 10000. Channels that are inactive should be set to UINT16_MAX. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) port : Servo output port (set of 8 outputs = 1 port). Flight stacks running on Pixhawk should use: 0 = MAIN, 1 = AUX. (type:uint8_t) chan1_scaled : RC channel 1 value scaled. (type:int16_t) chan2_scaled : RC channel 2 value scaled. (type:int16_t) chan3_scaled : RC channel 3 value scaled. (type:int16_t) chan4_scaled : RC channel 4 value scaled. (type:int16_t) chan5_scaled : RC channel 5 value scaled. (type:int16_t) chan6_scaled : RC channel 6 value scaled. (type:int16_t) chan7_scaled : RC channel 7 value scaled. (type:int16_t) chan8_scaled : RC channel 8 value scaled. (type:int16_t) rssi : Receive signal strength indicator in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) ''' return MAVLink_rc_channels_scaled_message(time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi) def rc_channels_scaled_send(self, time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi, force_mavlink1=False): ''' The scaled values of the RC channels received: (-100%) -10000, (0%) 0, (100%) 10000. Channels that are inactive should be set to UINT16_MAX. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) port : Servo output port (set of 8 outputs = 1 port). Flight stacks running on Pixhawk should use: 0 = MAIN, 1 = AUX. (type:uint8_t) chan1_scaled : RC channel 1 value scaled. (type:int16_t) chan2_scaled : RC channel 2 value scaled. (type:int16_t) chan3_scaled : RC channel 3 value scaled. (type:int16_t) chan4_scaled : RC channel 4 value scaled. (type:int16_t) chan5_scaled : RC channel 5 value scaled. (type:int16_t) chan6_scaled : RC channel 6 value scaled. (type:int16_t) chan7_scaled : RC channel 7 value scaled. (type:int16_t) chan8_scaled : RC channel 8 value scaled. (type:int16_t) rssi : Receive signal strength indicator in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) ''' return self.send(self.rc_channels_scaled_encode(time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi), force_mavlink1=force_mavlink1) def rc_channels_raw_encode(self, time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi): ''' The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. A value of UINT16_MAX implies the channel is unused. Individual receivers/transmitters might violate this specification. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) port : Servo output port (set of 8 outputs = 1 port). Flight stacks running on Pixhawk should use: 0 = MAIN, 1 = AUX. (type:uint8_t) chan1_raw : RC channel 1 value. [us] (type:uint16_t) chan2_raw : RC channel 2 value. [us] (type:uint16_t) chan3_raw : RC channel 3 value. [us] (type:uint16_t) chan4_raw : RC channel 4 value. [us] (type:uint16_t) chan5_raw : RC channel 5 value. [us] (type:uint16_t) chan6_raw : RC channel 6 value. [us] (type:uint16_t) chan7_raw : RC channel 7 value. [us] (type:uint16_t) chan8_raw : RC channel 8 value. [us] (type:uint16_t) rssi : Receive signal strength indicator in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) ''' return MAVLink_rc_channels_raw_message(time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi) def rc_channels_raw_send(self, time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi, force_mavlink1=False): ''' The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. A value of UINT16_MAX implies the channel is unused. Individual receivers/transmitters might violate this specification. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) port : Servo output port (set of 8 outputs = 1 port). Flight stacks running on Pixhawk should use: 0 = MAIN, 1 = AUX. (type:uint8_t) chan1_raw : RC channel 1 value. [us] (type:uint16_t) chan2_raw : RC channel 2 value. [us] (type:uint16_t) chan3_raw : RC channel 3 value. [us] (type:uint16_t) chan4_raw : RC channel 4 value. [us] (type:uint16_t) chan5_raw : RC channel 5 value. [us] (type:uint16_t) chan6_raw : RC channel 6 value. [us] (type:uint16_t) chan7_raw : RC channel 7 value. [us] (type:uint16_t) chan8_raw : RC channel 8 value. [us] (type:uint16_t) rssi : Receive signal strength indicator in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) ''' return self.send(self.rc_channels_raw_encode(time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi), force_mavlink1=force_mavlink1) def servo_output_raw_encode(self, time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw, servo9_raw=0, servo10_raw=0, servo11_raw=0, servo12_raw=0, servo13_raw=0, servo14_raw=0, servo15_raw=0, servo16_raw=0): ''' The RAW values of the servo outputs (for RC input from the remote, use the RC_CHANNELS messages). The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint32_t) port : Servo output port (set of 8 outputs = 1 port). Flight stacks running on Pixhawk should use: 0 = MAIN, 1 = AUX. (type:uint8_t) servo1_raw : Servo output 1 value [us] (type:uint16_t) servo2_raw : Servo output 2 value [us] (type:uint16_t) servo3_raw : Servo output 3 value [us] (type:uint16_t) servo4_raw : Servo output 4 value [us] (type:uint16_t) servo5_raw : Servo output 5 value [us] (type:uint16_t) servo6_raw : Servo output 6 value [us] (type:uint16_t) servo7_raw : Servo output 7 value [us] (type:uint16_t) servo8_raw : Servo output 8 value [us] (type:uint16_t) servo9_raw : Servo output 9 value [us] (type:uint16_t) servo10_raw : Servo output 10 value [us] (type:uint16_t) servo11_raw : Servo output 11 value [us] (type:uint16_t) servo12_raw : Servo output 12 value [us] (type:uint16_t) servo13_raw : Servo output 13 value [us] (type:uint16_t) servo14_raw : Servo output 14 value [us] (type:uint16_t) servo15_raw : Servo output 15 value [us] (type:uint16_t) servo16_raw : Servo output 16 value [us] (type:uint16_t) ''' return MAVLink_servo_output_raw_message(time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw, servo9_raw, servo10_raw, servo11_raw, servo12_raw, servo13_raw, servo14_raw, servo15_raw, servo16_raw) def servo_output_raw_send(self, time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw, servo9_raw=0, servo10_raw=0, servo11_raw=0, servo12_raw=0, servo13_raw=0, servo14_raw=0, servo15_raw=0, servo16_raw=0, force_mavlink1=False): ''' The RAW values of the servo outputs (for RC input from the remote, use the RC_CHANNELS messages). The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint32_t) port : Servo output port (set of 8 outputs = 1 port). Flight stacks running on Pixhawk should use: 0 = MAIN, 1 = AUX. (type:uint8_t) servo1_raw : Servo output 1 value [us] (type:uint16_t) servo2_raw : Servo output 2 value [us] (type:uint16_t) servo3_raw : Servo output 3 value [us] (type:uint16_t) servo4_raw : Servo output 4 value [us] (type:uint16_t) servo5_raw : Servo output 5 value [us] (type:uint16_t) servo6_raw : Servo output 6 value [us] (type:uint16_t) servo7_raw : Servo output 7 value [us] (type:uint16_t) servo8_raw : Servo output 8 value [us] (type:uint16_t) servo9_raw : Servo output 9 value [us] (type:uint16_t) servo10_raw : Servo output 10 value [us] (type:uint16_t) servo11_raw : Servo output 11 value [us] (type:uint16_t) servo12_raw : Servo output 12 value [us] (type:uint16_t) servo13_raw : Servo output 13 value [us] (type:uint16_t) servo14_raw : Servo output 14 value [us] (type:uint16_t) servo15_raw : Servo output 15 value [us] (type:uint16_t) servo16_raw : Servo output 16 value [us] (type:uint16_t) ''' return self.send(self.servo_output_raw_encode(time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw, servo9_raw, servo10_raw, servo11_raw, servo12_raw, servo13_raw, servo14_raw, servo15_raw, servo16_raw), force_mavlink1=force_mavlink1) def mission_request_partial_list_encode(self, target_system, target_component, start_index, end_index, mission_type=0): ''' Request a partial list of mission items from the system/component. https://mavlink.io/en/services/mission.html. If start and end index are the same, just send one waypoint. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) start_index : Start index (type:int16_t) end_index : End index, -1 by default (-1: send list to end). Else a valid index of the list (type:int16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_request_partial_list_message(target_system, target_component, start_index, end_index, mission_type) def mission_request_partial_list_send(self, target_system, target_component, start_index, end_index, mission_type=0, force_mavlink1=False): ''' Request a partial list of mission items from the system/component. https://mavlink.io/en/services/mission.html. If start and end index are the same, just send one waypoint. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) start_index : Start index (type:int16_t) end_index : End index, -1 by default (-1: send list to end). Else a valid index of the list (type:int16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_request_partial_list_encode(target_system, target_component, start_index, end_index, mission_type), force_mavlink1=force_mavlink1) def mission_write_partial_list_encode(self, target_system, target_component, start_index, end_index, mission_type=0): ''' This message is sent to the MAV to write a partial list. If start index == end index, only one item will be transmitted / updated. If the start index is NOT 0 and above the current list size, this request should be REJECTED! target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) start_index : Start index. Must be smaller / equal to the largest index of the current onboard list. (type:int16_t) end_index : End index, equal or greater than start index. (type:int16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_write_partial_list_message(target_system, target_component, start_index, end_index, mission_type) def mission_write_partial_list_send(self, target_system, target_component, start_index, end_index, mission_type=0, force_mavlink1=False): ''' This message is sent to the MAV to write a partial list. If start index == end index, only one item will be transmitted / updated. If the start index is NOT 0 and above the current list size, this request should be REJECTED! target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) start_index : Start index. Must be smaller / equal to the largest index of the current onboard list. (type:int16_t) end_index : End index, equal or greater than start index. (type:int16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_write_partial_list_encode(target_system, target_component, start_index, end_index, mission_type), force_mavlink1=force_mavlink1) def mission_item_encode(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type=0): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also https://mavlink.io/en/services/mission.html. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) frame : The coordinate system of the waypoint. (type:uint8_t, values:MAV_FRAME) command : The scheduled action for the waypoint. (type:uint16_t, values:MAV_CMD) current : false:0, true:1 (type:uint8_t) autocontinue : Autocontinue to next waypoint (type:uint8_t) param1 : PARAM1, see MAV_CMD enum (type:float) param2 : PARAM2, see MAV_CMD enum (type:float) param3 : PARAM3, see MAV_CMD enum (type:float) param4 : PARAM4, see MAV_CMD enum (type:float) x : PARAM5 / local: X coordinate, global: latitude (type:float) y : PARAM6 / local: Y coordinate, global: longitude (type:float) z : PARAM7 / local: Z coordinate, global: altitude (relative or absolute, depending on frame). (type:float) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_item_message(target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type) def mission_item_send(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type=0, force_mavlink1=False): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also https://mavlink.io/en/services/mission.html. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) frame : The coordinate system of the waypoint. (type:uint8_t, values:MAV_FRAME) command : The scheduled action for the waypoint. (type:uint16_t, values:MAV_CMD) current : false:0, true:1 (type:uint8_t) autocontinue : Autocontinue to next waypoint (type:uint8_t) param1 : PARAM1, see MAV_CMD enum (type:float) param2 : PARAM2, see MAV_CMD enum (type:float) param3 : PARAM3, see MAV_CMD enum (type:float) param4 : PARAM4, see MAV_CMD enum (type:float) x : PARAM5 / local: X coordinate, global: latitude (type:float) y : PARAM6 / local: Y coordinate, global: longitude (type:float) z : PARAM7 / local: Z coordinate, global: altitude (relative or absolute, depending on frame). (type:float) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_item_encode(target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type), force_mavlink1=force_mavlink1) def mission_request_encode(self, target_system, target_component, seq, mission_type=0): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM message. https://mavlink.io/en/services/mission.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_request_message(target_system, target_component, seq, mission_type) def mission_request_send(self, target_system, target_component, seq, mission_type=0, force_mavlink1=False): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM message. https://mavlink.io/en/services/mission.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_request_encode(target_system, target_component, seq, mission_type), force_mavlink1=force_mavlink1) def mission_set_current_encode(self, target_system, target_component, seq): ''' Set the mission item with sequence number seq as current item. This means that the MAV will continue to this mission item on the shortest path (not following the mission items in-between). target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) ''' return MAVLink_mission_set_current_message(target_system, target_component, seq) def mission_set_current_send(self, target_system, target_component, seq, force_mavlink1=False): ''' Set the mission item with sequence number seq as current item. This means that the MAV will continue to this mission item on the shortest path (not following the mission items in-between). target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) ''' return self.send(self.mission_set_current_encode(target_system, target_component, seq), force_mavlink1=force_mavlink1) def mission_current_encode(self, seq): ''' Message that announces the sequence number of the current active mission item. The MAV will fly towards this mission item. seq : Sequence (type:uint16_t) ''' return MAVLink_mission_current_message(seq) def mission_current_send(self, seq, force_mavlink1=False): ''' Message that announces the sequence number of the current active mission item. The MAV will fly towards this mission item. seq : Sequence (type:uint16_t) ''' return self.send(self.mission_current_encode(seq), force_mavlink1=force_mavlink1) def mission_request_list_encode(self, target_system, target_component, mission_type=0): ''' Request the overall list of mission items from the system/component. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_request_list_message(target_system, target_component, mission_type) def mission_request_list_send(self, target_system, target_component, mission_type=0, force_mavlink1=False): ''' Request the overall list of mission items from the system/component. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_request_list_encode(target_system, target_component, mission_type), force_mavlink1=force_mavlink1) def mission_count_encode(self, target_system, target_component, count, mission_type=0): ''' This message is emitted as response to MISSION_REQUEST_LIST by the MAV and to initiate a write transaction. The GCS can then request the individual mission item based on the knowledge of the total number of waypoints. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) count : Number of mission items in the sequence (type:uint16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_count_message(target_system, target_component, count, mission_type) def mission_count_send(self, target_system, target_component, count, mission_type=0, force_mavlink1=False): ''' This message is emitted as response to MISSION_REQUEST_LIST by the MAV and to initiate a write transaction. The GCS can then request the individual mission item based on the knowledge of the total number of waypoints. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) count : Number of mission items in the sequence (type:uint16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_count_encode(target_system, target_component, count, mission_type), force_mavlink1=force_mavlink1) def mission_clear_all_encode(self, target_system, target_component, mission_type=0): ''' Delete all mission items at once. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_clear_all_message(target_system, target_component, mission_type) def mission_clear_all_send(self, target_system, target_component, mission_type=0, force_mavlink1=False): ''' Delete all mission items at once. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_clear_all_encode(target_system, target_component, mission_type), force_mavlink1=force_mavlink1) def mission_item_reached_encode(self, seq): ''' A certain mission item has been reached. The system will either hold this position (or circle on the orbit) or (if the autocontinue on the WP was set) continue to the next waypoint. seq : Sequence (type:uint16_t) ''' return MAVLink_mission_item_reached_message(seq) def mission_item_reached_send(self, seq, force_mavlink1=False): ''' A certain mission item has been reached. The system will either hold this position (or circle on the orbit) or (if the autocontinue on the WP was set) continue to the next waypoint. seq : Sequence (type:uint16_t) ''' return self.send(self.mission_item_reached_encode(seq), force_mavlink1=force_mavlink1) def mission_ack_encode(self, target_system, target_component, type, mission_type=0): ''' Acknowledgment message during waypoint handling. The type field states if this message is a positive ack (type=0) or if an error happened (type=non-zero). target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) type : Mission result. (type:uint8_t, values:MAV_MISSION_RESULT) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_ack_message(target_system, target_component, type, mission_type) def mission_ack_send(self, target_system, target_component, type, mission_type=0, force_mavlink1=False): ''' Acknowledgment message during waypoint handling. The type field states if this message is a positive ack (type=0) or if an error happened (type=non-zero). target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) type : Mission result. (type:uint8_t, values:MAV_MISSION_RESULT) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_ack_encode(target_system, target_component, type, mission_type), force_mavlink1=force_mavlink1) def set_gps_global_origin_encode(self, target_system, latitude, longitude, altitude, time_usec=0): ''' Sets the GPS co-ordinates of the vehicle local origin (0,0,0) position. Vehicle should emit GPS_GLOBAL_ORIGIN irrespective of whether the origin is changed. This enables transform between the local coordinate frame and the global (GPS) coordinate frame, which may be necessary when (for example) indoor and outdoor settings are connected and the MAV should move from in- to outdoor. target_system : System ID (type:uint8_t) latitude : Latitude (WGS84) [degE7] (type:int32_t) longitude : Longitude (WGS84) [degE7] (type:int32_t) altitude : Altitude (MSL). Positive for up. [mm] (type:int32_t) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) ''' return MAVLink_set_gps_global_origin_message(target_system, latitude, longitude, altitude, time_usec) def set_gps_global_origin_send(self, target_system, latitude, longitude, altitude, time_usec=0, force_mavlink1=False): ''' Sets the GPS co-ordinates of the vehicle local origin (0,0,0) position. Vehicle should emit GPS_GLOBAL_ORIGIN irrespective of whether the origin is changed. This enables transform between the local coordinate frame and the global (GPS) coordinate frame, which may be necessary when (for example) indoor and outdoor settings are connected and the MAV should move from in- to outdoor. target_system : System ID (type:uint8_t) latitude : Latitude (WGS84) [degE7] (type:int32_t) longitude : Longitude (WGS84) [degE7] (type:int32_t) altitude : Altitude (MSL). Positive for up. [mm] (type:int32_t) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) ''' return self.send(self.set_gps_global_origin_encode(target_system, latitude, longitude, altitude, time_usec), force_mavlink1=force_mavlink1) def gps_global_origin_encode(self, latitude, longitude, altitude, time_usec=0): ''' Publishes the GPS co-ordinates of the vehicle local origin (0,0,0) position. Emitted whenever a new GPS-Local position mapping is requested or set - e.g. following SET_GPS_GLOBAL_ORIGIN message. latitude : Latitude (WGS84) [degE7] (type:int32_t) longitude : Longitude (WGS84) [degE7] (type:int32_t) altitude : Altitude (MSL). Positive for up. [mm] (type:int32_t) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) ''' return MAVLink_gps_global_origin_message(latitude, longitude, altitude, time_usec) def gps_global_origin_send(self, latitude, longitude, altitude, time_usec=0, force_mavlink1=False): ''' Publishes the GPS co-ordinates of the vehicle local origin (0,0,0) position. Emitted whenever a new GPS-Local position mapping is requested or set - e.g. following SET_GPS_GLOBAL_ORIGIN message. latitude : Latitude (WGS84) [degE7] (type:int32_t) longitude : Longitude (WGS84) [degE7] (type:int32_t) altitude : Altitude (MSL). Positive for up. [mm] (type:int32_t) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) ''' return self.send(self.gps_global_origin_encode(latitude, longitude, altitude, time_usec), force_mavlink1=force_mavlink1) def param_map_rc_encode(self, target_system, target_component, param_id, param_index, parameter_rc_channel_index, param_value0, scale, param_value_min, param_value_max): ''' Bind a RC channel to a parameter. The parameter should change according to the RC channel value. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (type:char) param_index : Parameter index. Send -1 to use the param ID field as identifier (else the param id will be ignored), send -2 to disable any existing map for this rc_channel_index. (type:int16_t) parameter_rc_channel_index : Index of parameter RC channel. Not equal to the RC channel id. Typically corresponds to a potentiometer-knob on the RC. (type:uint8_t) param_value0 : Initial parameter value (type:float) scale : Scale, maps the RC range [-1, 1] to a parameter value (type:float) param_value_min : Minimum param value. The protocol does not define if this overwrites an onboard minimum value. (Depends on implementation) (type:float) param_value_max : Maximum param value. The protocol does not define if this overwrites an onboard maximum value. (Depends on implementation) (type:float) ''' return MAVLink_param_map_rc_message(target_system, target_component, param_id, param_index, parameter_rc_channel_index, param_value0, scale, param_value_min, param_value_max) def param_map_rc_send(self, target_system, target_component, param_id, param_index, parameter_rc_channel_index, param_value0, scale, param_value_min, param_value_max, force_mavlink1=False): ''' Bind a RC channel to a parameter. The parameter should change according to the RC channel value. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (type:char) param_index : Parameter index. Send -1 to use the param ID field as identifier (else the param id will be ignored), send -2 to disable any existing map for this rc_channel_index. (type:int16_t) parameter_rc_channel_index : Index of parameter RC channel. Not equal to the RC channel id. Typically corresponds to a potentiometer-knob on the RC. (type:uint8_t) param_value0 : Initial parameter value (type:float) scale : Scale, maps the RC range [-1, 1] to a parameter value (type:float) param_value_min : Minimum param value. The protocol does not define if this overwrites an onboard minimum value. (Depends on implementation) (type:float) param_value_max : Maximum param value. The protocol does not define if this overwrites an onboard maximum value. (Depends on implementation) (type:float) ''' return self.send(self.param_map_rc_encode(target_system, target_component, param_id, param_index, parameter_rc_channel_index, param_value0, scale, param_value_min, param_value_max), force_mavlink1=force_mavlink1) def mission_request_int_encode(self, target_system, target_component, seq, mission_type=0): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM_INT message. https://mavlink.io/en/services/mission.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_request_int_message(target_system, target_component, seq, mission_type) def mission_request_int_send(self, target_system, target_component, seq, mission_type=0, force_mavlink1=False): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM_INT message. https://mavlink.io/en/services/mission.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Sequence (type:uint16_t) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_request_int_encode(target_system, target_component, seq, mission_type), force_mavlink1=force_mavlink1) def safety_set_allowed_area_encode(self, target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z): ''' Set a safety zone (volume), which is defined by two corners of a cube. This message can be used to tell the MAV which setpoints/waypoints to accept and which to reject. Safety areas are often enforced by national or competition regulations. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) frame : Coordinate frame. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (type:uint8_t, values:MAV_FRAME) p1x : x position 1 / Latitude 1 [m] (type:float) p1y : y position 1 / Longitude 1 [m] (type:float) p1z : z position 1 / Altitude 1 [m] (type:float) p2x : x position 2 / Latitude 2 [m] (type:float) p2y : y position 2 / Longitude 2 [m] (type:float) p2z : z position 2 / Altitude 2 [m] (type:float) ''' return MAVLink_safety_set_allowed_area_message(target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z) def safety_set_allowed_area_send(self, target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z, force_mavlink1=False): ''' Set a safety zone (volume), which is defined by two corners of a cube. This message can be used to tell the MAV which setpoints/waypoints to accept and which to reject. Safety areas are often enforced by national or competition regulations. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) frame : Coordinate frame. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (type:uint8_t, values:MAV_FRAME) p1x : x position 1 / Latitude 1 [m] (type:float) p1y : y position 1 / Longitude 1 [m] (type:float) p1z : z position 1 / Altitude 1 [m] (type:float) p2x : x position 2 / Latitude 2 [m] (type:float) p2y : y position 2 / Longitude 2 [m] (type:float) p2z : z position 2 / Altitude 2 [m] (type:float) ''' return self.send(self.safety_set_allowed_area_encode(target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z), force_mavlink1=force_mavlink1) def safety_allowed_area_encode(self, frame, p1x, p1y, p1z, p2x, p2y, p2z): ''' Read out the safety zone the MAV currently assumes. frame : Coordinate frame. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (type:uint8_t, values:MAV_FRAME) p1x : x position 1 / Latitude 1 [m] (type:float) p1y : y position 1 / Longitude 1 [m] (type:float) p1z : z position 1 / Altitude 1 [m] (type:float) p2x : x position 2 / Latitude 2 [m] (type:float) p2y : y position 2 / Longitude 2 [m] (type:float) p2z : z position 2 / Altitude 2 [m] (type:float) ''' return MAVLink_safety_allowed_area_message(frame, p1x, p1y, p1z, p2x, p2y, p2z) def safety_allowed_area_send(self, frame, p1x, p1y, p1z, p2x, p2y, p2z, force_mavlink1=False): ''' Read out the safety zone the MAV currently assumes. frame : Coordinate frame. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (type:uint8_t, values:MAV_FRAME) p1x : x position 1 / Latitude 1 [m] (type:float) p1y : y position 1 / Longitude 1 [m] (type:float) p1z : z position 1 / Altitude 1 [m] (type:float) p2x : x position 2 / Latitude 2 [m] (type:float) p2y : y position 2 / Longitude 2 [m] (type:float) p2z : z position 2 / Altitude 2 [m] (type:float) ''' return self.send(self.safety_allowed_area_encode(frame, p1x, p1y, p1z, p2x, p2y, p2z), force_mavlink1=force_mavlink1) def attitude_quaternion_cov_encode(self, time_usec, q, rollspeed, pitchspeed, yawspeed, covariance): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0). time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) q : Quaternion components, w, x, y, z (1 0 0 0 is the null-rotation) (type:float) rollspeed : Roll angular speed [rad/s] (type:float) pitchspeed : Pitch angular speed [rad/s] (type:float) yawspeed : Yaw angular speed [rad/s] (type:float) covariance : Row-major representation of a 3x3 attitude covariance matrix (states: roll, pitch, yaw; first three entries are the first ROW, next three entries are the second row, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return MAVLink_attitude_quaternion_cov_message(time_usec, q, rollspeed, pitchspeed, yawspeed, covariance) def attitude_quaternion_cov_send(self, time_usec, q, rollspeed, pitchspeed, yawspeed, covariance, force_mavlink1=False): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0). time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) q : Quaternion components, w, x, y, z (1 0 0 0 is the null-rotation) (type:float) rollspeed : Roll angular speed [rad/s] (type:float) pitchspeed : Pitch angular speed [rad/s] (type:float) yawspeed : Yaw angular speed [rad/s] (type:float) covariance : Row-major representation of a 3x3 attitude covariance matrix (states: roll, pitch, yaw; first three entries are the first ROW, next three entries are the second row, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return self.send(self.attitude_quaternion_cov_encode(time_usec, q, rollspeed, pitchspeed, yawspeed, covariance), force_mavlink1=force_mavlink1) def nav_controller_output_encode(self, nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error): ''' The state of the fixed wing navigation and position controller. nav_roll : Current desired roll [deg] (type:float) nav_pitch : Current desired pitch [deg] (type:float) nav_bearing : Current desired heading [deg] (type:int16_t) target_bearing : Bearing to current waypoint/target [deg] (type:int16_t) wp_dist : Distance to active waypoint [m] (type:uint16_t) alt_error : Current altitude error [m] (type:float) aspd_error : Current airspeed error [m/s] (type:float) xtrack_error : Current crosstrack error on x-y plane [m] (type:float) ''' return MAVLink_nav_controller_output_message(nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error) def nav_controller_output_send(self, nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error, force_mavlink1=False): ''' The state of the fixed wing navigation and position controller. nav_roll : Current desired roll [deg] (type:float) nav_pitch : Current desired pitch [deg] (type:float) nav_bearing : Current desired heading [deg] (type:int16_t) target_bearing : Bearing to current waypoint/target [deg] (type:int16_t) wp_dist : Distance to active waypoint [m] (type:uint16_t) alt_error : Current altitude error [m] (type:float) aspd_error : Current airspeed error [m/s] (type:float) xtrack_error : Current crosstrack error on x-y plane [m] (type:float) ''' return self.send(self.nav_controller_output_encode(nav_roll, nav_pitch, nav_bearing, target_bearing, wp_dist, alt_error, aspd_error, xtrack_error), force_mavlink1=force_mavlink1) def global_position_int_cov_encode(self, time_usec, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. NOTE: This message is intended for onboard networks / companion computers and higher-bandwidth links and optimized for accuracy and completeness. Please use the GLOBAL_POSITION_INT message for a minimal subset. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) estimator_type : Class id of the estimator this estimate originated from. (type:uint8_t, values:MAV_ESTIMATOR_TYPE) lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) alt : Altitude in meters above MSL [mm] (type:int32_t) relative_alt : Altitude above ground [mm] (type:int32_t) vx : Ground X Speed (Latitude) [m/s] (type:float) vy : Ground Y Speed (Longitude) [m/s] (type:float) vz : Ground Z Speed (Altitude) [m/s] (type:float) covariance : Row-major representation of a 6x6 position and velocity 6x6 cross-covariance matrix (states: lat, lon, alt, vx, vy, vz; first six entries are the first ROW, next six entries are the second row, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return MAVLink_global_position_int_cov_message(time_usec, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance) def global_position_int_cov_send(self, time_usec, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance, force_mavlink1=False): ''' The filtered global position (e.g. fused GPS and accelerometers). The position is in GPS-frame (right-handed, Z-up). It is designed as scaled integer message since the resolution of float is not sufficient. NOTE: This message is intended for onboard networks / companion computers and higher-bandwidth links and optimized for accuracy and completeness. Please use the GLOBAL_POSITION_INT message for a minimal subset. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) estimator_type : Class id of the estimator this estimate originated from. (type:uint8_t, values:MAV_ESTIMATOR_TYPE) lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) alt : Altitude in meters above MSL [mm] (type:int32_t) relative_alt : Altitude above ground [mm] (type:int32_t) vx : Ground X Speed (Latitude) [m/s] (type:float) vy : Ground Y Speed (Longitude) [m/s] (type:float) vz : Ground Z Speed (Altitude) [m/s] (type:float) covariance : Row-major representation of a 6x6 position and velocity 6x6 cross-covariance matrix (states: lat, lon, alt, vx, vy, vz; first six entries are the first ROW, next six entries are the second row, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return self.send(self.global_position_int_cov_encode(time_usec, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance), force_mavlink1=force_mavlink1) def local_position_ned_cov_encode(self, time_usec, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) estimator_type : Class id of the estimator this estimate originated from. (type:uint8_t, values:MAV_ESTIMATOR_TYPE) x : X Position [m] (type:float) y : Y Position [m] (type:float) z : Z Position [m] (type:float) vx : X Speed [m/s] (type:float) vy : Y Speed [m/s] (type:float) vz : Z Speed [m/s] (type:float) ax : X Acceleration [m/s/s] (type:float) ay : Y Acceleration [m/s/s] (type:float) az : Z Acceleration [m/s/s] (type:float) covariance : Row-major representation of position, velocity and acceleration 9x9 cross-covariance matrix upper right triangle (states: x, y, z, vx, vy, vz, ax, ay, az; first nine entries are the first ROW, next eight entries are the second row, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return MAVLink_local_position_ned_cov_message(time_usec, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance) def local_position_ned_cov_send(self, time_usec, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance, force_mavlink1=False): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) estimator_type : Class id of the estimator this estimate originated from. (type:uint8_t, values:MAV_ESTIMATOR_TYPE) x : X Position [m] (type:float) y : Y Position [m] (type:float) z : Z Position [m] (type:float) vx : X Speed [m/s] (type:float) vy : Y Speed [m/s] (type:float) vz : Z Speed [m/s] (type:float) ax : X Acceleration [m/s/s] (type:float) ay : Y Acceleration [m/s/s] (type:float) az : Z Acceleration [m/s/s] (type:float) covariance : Row-major representation of position, velocity and acceleration 9x9 cross-covariance matrix upper right triangle (states: x, y, z, vx, vy, vz, ax, ay, az; first nine entries are the first ROW, next eight entries are the second row, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return self.send(self.local_position_ned_cov_encode(time_usec, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance), force_mavlink1=force_mavlink1) def rc_channels_encode(self, time_boot_ms, chancount, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, chan13_raw, chan14_raw, chan15_raw, chan16_raw, chan17_raw, chan18_raw, rssi): ''' The PPM values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. A value of UINT16_MAX implies the channel is unused. Individual receivers/transmitters might violate this specification. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) chancount : Total number of RC channels being received. This can be larger than 18, indicating that more channels are available but not given in this message. This value should be 0 when no RC channels are available. (type:uint8_t) chan1_raw : RC channel 1 value. [us] (type:uint16_t) chan2_raw : RC channel 2 value. [us] (type:uint16_t) chan3_raw : RC channel 3 value. [us] (type:uint16_t) chan4_raw : RC channel 4 value. [us] (type:uint16_t) chan5_raw : RC channel 5 value. [us] (type:uint16_t) chan6_raw : RC channel 6 value. [us] (type:uint16_t) chan7_raw : RC channel 7 value. [us] (type:uint16_t) chan8_raw : RC channel 8 value. [us] (type:uint16_t) chan9_raw : RC channel 9 value. [us] (type:uint16_t) chan10_raw : RC channel 10 value. [us] (type:uint16_t) chan11_raw : RC channel 11 value. [us] (type:uint16_t) chan12_raw : RC channel 12 value. [us] (type:uint16_t) chan13_raw : RC channel 13 value. [us] (type:uint16_t) chan14_raw : RC channel 14 value. [us] (type:uint16_t) chan15_raw : RC channel 15 value. [us] (type:uint16_t) chan16_raw : RC channel 16 value. [us] (type:uint16_t) chan17_raw : RC channel 17 value. [us] (type:uint16_t) chan18_raw : RC channel 18 value. [us] (type:uint16_t) rssi : Receive signal strength indicator in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) ''' return MAVLink_rc_channels_message(time_boot_ms, chancount, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, chan13_raw, chan14_raw, chan15_raw, chan16_raw, chan17_raw, chan18_raw, rssi) def rc_channels_send(self, time_boot_ms, chancount, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, chan13_raw, chan14_raw, chan15_raw, chan16_raw, chan17_raw, chan18_raw, rssi, force_mavlink1=False): ''' The PPM values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. A value of UINT16_MAX implies the channel is unused. Individual receivers/transmitters might violate this specification. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) chancount : Total number of RC channels being received. This can be larger than 18, indicating that more channels are available but not given in this message. This value should be 0 when no RC channels are available. (type:uint8_t) chan1_raw : RC channel 1 value. [us] (type:uint16_t) chan2_raw : RC channel 2 value. [us] (type:uint16_t) chan3_raw : RC channel 3 value. [us] (type:uint16_t) chan4_raw : RC channel 4 value. [us] (type:uint16_t) chan5_raw : RC channel 5 value. [us] (type:uint16_t) chan6_raw : RC channel 6 value. [us] (type:uint16_t) chan7_raw : RC channel 7 value. [us] (type:uint16_t) chan8_raw : RC channel 8 value. [us] (type:uint16_t) chan9_raw : RC channel 9 value. [us] (type:uint16_t) chan10_raw : RC channel 10 value. [us] (type:uint16_t) chan11_raw : RC channel 11 value. [us] (type:uint16_t) chan12_raw : RC channel 12 value. [us] (type:uint16_t) chan13_raw : RC channel 13 value. [us] (type:uint16_t) chan14_raw : RC channel 14 value. [us] (type:uint16_t) chan15_raw : RC channel 15 value. [us] (type:uint16_t) chan16_raw : RC channel 16 value. [us] (type:uint16_t) chan17_raw : RC channel 17 value. [us] (type:uint16_t) chan18_raw : RC channel 18 value. [us] (type:uint16_t) rssi : Receive signal strength indicator in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) ''' return self.send(self.rc_channels_encode(time_boot_ms, chancount, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, chan13_raw, chan14_raw, chan15_raw, chan16_raw, chan17_raw, chan18_raw, rssi), force_mavlink1=force_mavlink1) def request_data_stream_encode(self, target_system, target_component, req_stream_id, req_message_rate, start_stop): ''' Request a data stream. target_system : The target requested to send the message stream. (type:uint8_t) target_component : The target requested to send the message stream. (type:uint8_t) req_stream_id : The ID of the requested data stream (type:uint8_t) req_message_rate : The requested message rate [Hz] (type:uint16_t) start_stop : 1 to start sending, 0 to stop sending. (type:uint8_t) ''' return MAVLink_request_data_stream_message(target_system, target_component, req_stream_id, req_message_rate, start_stop) def request_data_stream_send(self, target_system, target_component, req_stream_id, req_message_rate, start_stop, force_mavlink1=False): ''' Request a data stream. target_system : The target requested to send the message stream. (type:uint8_t) target_component : The target requested to send the message stream. (type:uint8_t) req_stream_id : The ID of the requested data stream (type:uint8_t) req_message_rate : The requested message rate [Hz] (type:uint16_t) start_stop : 1 to start sending, 0 to stop sending. (type:uint8_t) ''' return self.send(self.request_data_stream_encode(target_system, target_component, req_stream_id, req_message_rate, start_stop), force_mavlink1=force_mavlink1) def data_stream_encode(self, stream_id, message_rate, on_off): ''' Data stream status information. stream_id : The ID of the requested data stream (type:uint8_t) message_rate : The message rate [Hz] (type:uint16_t) on_off : 1 stream is enabled, 0 stream is stopped. (type:uint8_t) ''' return MAVLink_data_stream_message(stream_id, message_rate, on_off) def data_stream_send(self, stream_id, message_rate, on_off, force_mavlink1=False): ''' Data stream status information. stream_id : The ID of the requested data stream (type:uint8_t) message_rate : The message rate [Hz] (type:uint16_t) on_off : 1 stream is enabled, 0 stream is stopped. (type:uint8_t) ''' return self.send(self.data_stream_encode(stream_id, message_rate, on_off), force_mavlink1=force_mavlink1) def manual_control_encode(self, target, x, y, z, r, buttons): ''' This message provides an API for manually controlling the vehicle using standard joystick axes nomenclature, along with a joystick-like input device. Unused axes can be disabled an buttons are also transmit as boolean values of their target : The system to be controlled. (type:uint8_t) x : X-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to forward(1000)-backward(-1000) movement on a joystick and the pitch of a vehicle. (type:int16_t) y : Y-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to left(-1000)-right(1000) movement on a joystick and the roll of a vehicle. (type:int16_t) z : Z-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to a separate slider movement with maximum being 1000 and minimum being -1000 on a joystick and the thrust of a vehicle. Positive values are positive thrust, negative values are negative thrust. (type:int16_t) r : R-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to a twisting of the joystick, with counter-clockwise being 1000 and clockwise being -1000, and the yaw of a vehicle. (type:int16_t) buttons : A bitfield corresponding to the joystick buttons' current state, 1 for pressed, 0 for released. The lowest bit corresponds to Button 1. (type:uint16_t) ''' return MAVLink_manual_control_message(target, x, y, z, r, buttons) def manual_control_send(self, target, x, y, z, r, buttons, force_mavlink1=False): ''' This message provides an API for manually controlling the vehicle using standard joystick axes nomenclature, along with a joystick-like input device. Unused axes can be disabled an buttons are also transmit as boolean values of their target : The system to be controlled. (type:uint8_t) x : X-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to forward(1000)-backward(-1000) movement on a joystick and the pitch of a vehicle. (type:int16_t) y : Y-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to left(-1000)-right(1000) movement on a joystick and the roll of a vehicle. (type:int16_t) z : Z-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to a separate slider movement with maximum being 1000 and minimum being -1000 on a joystick and the thrust of a vehicle. Positive values are positive thrust, negative values are negative thrust. (type:int16_t) r : R-axis, normalized to the range [-1000,1000]. A value of INT16_MAX indicates that this axis is invalid. Generally corresponds to a twisting of the joystick, with counter-clockwise being 1000 and clockwise being -1000, and the yaw of a vehicle. (type:int16_t) buttons : A bitfield corresponding to the joystick buttons' current state, 1 for pressed, 0 for released. The lowest bit corresponds to Button 1. (type:uint16_t) ''' return self.send(self.manual_control_encode(target, x, y, z, r, buttons), force_mavlink1=force_mavlink1) def rc_channels_override_encode(self, target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw=0, chan10_raw=0, chan11_raw=0, chan12_raw=0, chan13_raw=0, chan14_raw=0, chan15_raw=0, chan16_raw=0, chan17_raw=0, chan18_raw=0): ''' The RAW values of the RC channels sent to the MAV to override info received from the RC radio. A value of UINT16_MAX means no change to that channel. A value of 0 means control of that channel should be released back to the RC radio. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) chan1_raw : RC channel 1 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan2_raw : RC channel 2 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan3_raw : RC channel 3 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan4_raw : RC channel 4 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan5_raw : RC channel 5 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan6_raw : RC channel 6 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan7_raw : RC channel 7 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan8_raw : RC channel 8 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan9_raw : RC channel 9 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan10_raw : RC channel 10 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan11_raw : RC channel 11 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan12_raw : RC channel 12 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan13_raw : RC channel 13 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan14_raw : RC channel 14 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan15_raw : RC channel 15 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan16_raw : RC channel 16 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan17_raw : RC channel 17 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan18_raw : RC channel 18 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) ''' return MAVLink_rc_channels_override_message(target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, chan13_raw, chan14_raw, chan15_raw, chan16_raw, chan17_raw, chan18_raw) def rc_channels_override_send(self, target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw=0, chan10_raw=0, chan11_raw=0, chan12_raw=0, chan13_raw=0, chan14_raw=0, chan15_raw=0, chan16_raw=0, chan17_raw=0, chan18_raw=0, force_mavlink1=False): ''' The RAW values of the RC channels sent to the MAV to override info received from the RC radio. A value of UINT16_MAX means no change to that channel. A value of 0 means control of that channel should be released back to the RC radio. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) chan1_raw : RC channel 1 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan2_raw : RC channel 2 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan3_raw : RC channel 3 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan4_raw : RC channel 4 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan5_raw : RC channel 5 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan6_raw : RC channel 6 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan7_raw : RC channel 7 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan8_raw : RC channel 8 value. A value of UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan9_raw : RC channel 9 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan10_raw : RC channel 10 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan11_raw : RC channel 11 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan12_raw : RC channel 12 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan13_raw : RC channel 13 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan14_raw : RC channel 14 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan15_raw : RC channel 15 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan16_raw : RC channel 16 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan17_raw : RC channel 17 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) chan18_raw : RC channel 18 value. A value of 0 or UINT16_MAX means to ignore this field. [us] (type:uint16_t) ''' return self.send(self.rc_channels_override_encode(target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, chan13_raw, chan14_raw, chan15_raw, chan16_raw, chan17_raw, chan18_raw), force_mavlink1=force_mavlink1) def mission_item_int_encode(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type=0): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also https://mavlink.io/en/services/mission.html. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Waypoint ID (sequence number). Starts at zero. Increases monotonically for each waypoint, no gaps in the sequence (0,1,2,3,4). (type:uint16_t) frame : The coordinate system of the waypoint. (type:uint8_t, values:MAV_FRAME) command : The scheduled action for the waypoint. (type:uint16_t, values:MAV_CMD) current : false:0, true:1 (type:uint8_t) autocontinue : Autocontinue to next waypoint (type:uint8_t) param1 : PARAM1, see MAV_CMD enum (type:float) param2 : PARAM2, see MAV_CMD enum (type:float) param3 : PARAM3, see MAV_CMD enum (type:float) param4 : PARAM4, see MAV_CMD enum (type:float) x : PARAM5 / local: x position in meters * 1e4, global: latitude in degrees * 10^7 (type:int32_t) y : PARAM6 / y position: local: x position in meters * 1e4, global: longitude in degrees *10^7 (type:int32_t) z : PARAM7 / z position: global: altitude in meters (relative or absolute, depending on frame. (type:float) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return MAVLink_mission_item_int_message(target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type) def mission_item_int_send(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type=0, force_mavlink1=False): ''' Message encoding a mission item. This message is emitted to announce the presence of a mission item and to set a mission item on the system. The mission item can be either in x, y, z meters (type: LOCAL) or x:lat, y:lon, z:altitude. Local frame is Z-down, right handed (NED), global frame is Z-up, right handed (ENU). See also https://mavlink.io/en/services/mission.html. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) seq : Waypoint ID (sequence number). Starts at zero. Increases monotonically for each waypoint, no gaps in the sequence (0,1,2,3,4). (type:uint16_t) frame : The coordinate system of the waypoint. (type:uint8_t, values:MAV_FRAME) command : The scheduled action for the waypoint. (type:uint16_t, values:MAV_CMD) current : false:0, true:1 (type:uint8_t) autocontinue : Autocontinue to next waypoint (type:uint8_t) param1 : PARAM1, see MAV_CMD enum (type:float) param2 : PARAM2, see MAV_CMD enum (type:float) param3 : PARAM3, see MAV_CMD enum (type:float) param4 : PARAM4, see MAV_CMD enum (type:float) x : PARAM5 / local: x position in meters * 1e4, global: latitude in degrees * 10^7 (type:int32_t) y : PARAM6 / y position: local: x position in meters * 1e4, global: longitude in degrees *10^7 (type:int32_t) z : PARAM7 / z position: global: altitude in meters (relative or absolute, depending on frame. (type:float) mission_type : Mission type. (type:uint8_t, values:MAV_MISSION_TYPE) ''' return self.send(self.mission_item_int_encode(target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, mission_type), force_mavlink1=force_mavlink1) def vfr_hud_encode(self, airspeed, groundspeed, heading, throttle, alt, climb): ''' Metrics typically displayed on a HUD for fixed wing aircraft. airspeed : Current indicated airspeed (IAS). [m/s] (type:float) groundspeed : Current ground speed. [m/s] (type:float) heading : Current heading in compass units (0-360, 0=north). [deg] (type:int16_t) throttle : Current throttle setting (0 to 100). [%] (type:uint16_t) alt : Current altitude (MSL). [m] (type:float) climb : Current climb rate. [m/s] (type:float) ''' return MAVLink_vfr_hud_message(airspeed, groundspeed, heading, throttle, alt, climb) def vfr_hud_send(self, airspeed, groundspeed, heading, throttle, alt, climb, force_mavlink1=False): ''' Metrics typically displayed on a HUD for fixed wing aircraft. airspeed : Current indicated airspeed (IAS). [m/s] (type:float) groundspeed : Current ground speed. [m/s] (type:float) heading : Current heading in compass units (0-360, 0=north). [deg] (type:int16_t) throttle : Current throttle setting (0 to 100). [%] (type:uint16_t) alt : Current altitude (MSL). [m] (type:float) climb : Current climb rate. [m/s] (type:float) ''' return self.send(self.vfr_hud_encode(airspeed, groundspeed, heading, throttle, alt, climb), force_mavlink1=force_mavlink1) def command_int_encode(self, target_system, target_component, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z): ''' Message encoding a command with parameters as scaled integers. Scaling depends on the actual command value. The command microservice is documented at https://mavlink.io/en/services/command.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) frame : The coordinate system of the COMMAND. (type:uint8_t, values:MAV_FRAME) command : The scheduled action for the mission item. (type:uint16_t, values:MAV_CMD) current : false:0, true:1 (type:uint8_t) autocontinue : autocontinue to next wp (type:uint8_t) param1 : PARAM1, see MAV_CMD enum (type:float) param2 : PARAM2, see MAV_CMD enum (type:float) param3 : PARAM3, see MAV_CMD enum (type:float) param4 : PARAM4, see MAV_CMD enum (type:float) x : PARAM5 / local: x position in meters * 1e4, global: latitude in degrees * 10^7 (type:int32_t) y : PARAM6 / local: y position in meters * 1e4, global: longitude in degrees * 10^7 (type:int32_t) z : PARAM7 / z position: global: altitude in meters (relative or absolute, depending on frame). (type:float) ''' return MAVLink_command_int_message(target_system, target_component, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z) def command_int_send(self, target_system, target_component, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z, force_mavlink1=False): ''' Message encoding a command with parameters as scaled integers. Scaling depends on the actual command value. The command microservice is documented at https://mavlink.io/en/services/command.html target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) frame : The coordinate system of the COMMAND. (type:uint8_t, values:MAV_FRAME) command : The scheduled action for the mission item. (type:uint16_t, values:MAV_CMD) current : false:0, true:1 (type:uint8_t) autocontinue : autocontinue to next wp (type:uint8_t) param1 : PARAM1, see MAV_CMD enum (type:float) param2 : PARAM2, see MAV_CMD enum (type:float) param3 : PARAM3, see MAV_CMD enum (type:float) param4 : PARAM4, see MAV_CMD enum (type:float) x : PARAM5 / local: x position in meters * 1e4, global: latitude in degrees * 10^7 (type:int32_t) y : PARAM6 / local: y position in meters * 1e4, global: longitude in degrees * 10^7 (type:int32_t) z : PARAM7 / z position: global: altitude in meters (relative or absolute, depending on frame). (type:float) ''' return self.send(self.command_int_encode(target_system, target_component, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z), force_mavlink1=force_mavlink1) def command_long_encode(self, target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7): ''' Send a command with up to seven parameters to the MAV. The command microservice is documented at https://mavlink.io/en/services/command.html target_system : System which should execute the command (type:uint8_t) target_component : Component which should execute the command, 0 for all components (type:uint8_t) command : Command ID (of command to send). (type:uint16_t, values:MAV_CMD) confirmation : 0: First transmission of this command. 1-255: Confirmation transmissions (e.g. for kill command) (type:uint8_t) param1 : Parameter 1 (for the specific command). (type:float) param2 : Parameter 2 (for the specific command). (type:float) param3 : Parameter 3 (for the specific command). (type:float) param4 : Parameter 4 (for the specific command). (type:float) param5 : Parameter 5 (for the specific command). (type:float) param6 : Parameter 6 (for the specific command). (type:float) param7 : Parameter 7 (for the specific command). (type:float) ''' return MAVLink_command_long_message(target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7) def command_long_send(self, target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7, force_mavlink1=False): ''' Send a command with up to seven parameters to the MAV. The command microservice is documented at https://mavlink.io/en/services/command.html target_system : System which should execute the command (type:uint8_t) target_component : Component which should execute the command, 0 for all components (type:uint8_t) command : Command ID (of command to send). (type:uint16_t, values:MAV_CMD) confirmation : 0: First transmission of this command. 1-255: Confirmation transmissions (e.g. for kill command) (type:uint8_t) param1 : Parameter 1 (for the specific command). (type:float) param2 : Parameter 2 (for the specific command). (type:float) param3 : Parameter 3 (for the specific command). (type:float) param4 : Parameter 4 (for the specific command). (type:float) param5 : Parameter 5 (for the specific command). (type:float) param6 : Parameter 6 (for the specific command). (type:float) param7 : Parameter 7 (for the specific command). (type:float) ''' return self.send(self.command_long_encode(target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7), force_mavlink1=force_mavlink1) def command_ack_encode(self, command, result): ''' Report status of a command. Includes feedback whether the command was executed. The command microservice is documented at https://mavlink.io/en/services/command.html command : Command ID (of acknowledged command). (type:uint16_t, values:MAV_CMD) result : Result of command. (type:uint8_t, values:MAV_RESULT) ''' return MAVLink_command_ack_message(command, result) def command_ack_send(self, command, result, force_mavlink1=False): ''' Report status of a command. Includes feedback whether the command was executed. The command microservice is documented at https://mavlink.io/en/services/command.html command : Command ID (of acknowledged command). (type:uint16_t, values:MAV_CMD) result : Result of command. (type:uint8_t, values:MAV_RESULT) ''' return self.send(self.command_ack_encode(command, result), force_mavlink1=force_mavlink1) def manual_setpoint_encode(self, time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch): ''' Setpoint in roll, pitch, yaw and thrust from the operator time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) roll : Desired roll rate [rad/s] (type:float) pitch : Desired pitch rate [rad/s] (type:float) yaw : Desired yaw rate [rad/s] (type:float) thrust : Collective thrust, normalized to 0 .. 1 (type:float) mode_switch : Flight mode switch position, 0.. 255 (type:uint8_t) manual_override_switch : Override mode switch position, 0.. 255 (type:uint8_t) ''' return MAVLink_manual_setpoint_message(time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch) def manual_setpoint_send(self, time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch, force_mavlink1=False): ''' Setpoint in roll, pitch, yaw and thrust from the operator time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) roll : Desired roll rate [rad/s] (type:float) pitch : Desired pitch rate [rad/s] (type:float) yaw : Desired yaw rate [rad/s] (type:float) thrust : Collective thrust, normalized to 0 .. 1 (type:float) mode_switch : Flight mode switch position, 0.. 255 (type:uint8_t) manual_override_switch : Override mode switch position, 0.. 255 (type:uint8_t) ''' return self.send(self.manual_setpoint_encode(time_boot_ms, roll, pitch, yaw, thrust, mode_switch, manual_override_switch), force_mavlink1=force_mavlink1) def set_attitude_target_encode(self, time_boot_ms, target_system, target_component, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust): ''' Sets a desired vehicle attitude. Used by an external controller to command the vehicle (manual controller or other system). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) type_mask : Mappings: If any of these bits are set, the corresponding input should be ignored: bit 1: body roll rate, bit 2: body pitch rate, bit 3: body yaw rate. bit 4-bit 6: reserved, bit 7: throttle, bit 8: attitude (type:uint8_t) q : Attitude quaternion (w, x, y, z order, zero-rotation is 1, 0, 0, 0) (type:float) body_roll_rate : Body roll rate [rad/s] (type:float) body_pitch_rate : Body pitch rate [rad/s] (type:float) body_yaw_rate : Body yaw rate [rad/s] (type:float) thrust : Collective thrust, normalized to 0 .. 1 (-1 .. 1 for vehicles capable of reverse trust) (type:float) ''' return MAVLink_set_attitude_target_message(time_boot_ms, target_system, target_component, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust) def set_attitude_target_send(self, time_boot_ms, target_system, target_component, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust, force_mavlink1=False): ''' Sets a desired vehicle attitude. Used by an external controller to command the vehicle (manual controller or other system). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) type_mask : Mappings: If any of these bits are set, the corresponding input should be ignored: bit 1: body roll rate, bit 2: body pitch rate, bit 3: body yaw rate. bit 4-bit 6: reserved, bit 7: throttle, bit 8: attitude (type:uint8_t) q : Attitude quaternion (w, x, y, z order, zero-rotation is 1, 0, 0, 0) (type:float) body_roll_rate : Body roll rate [rad/s] (type:float) body_pitch_rate : Body pitch rate [rad/s] (type:float) body_yaw_rate : Body yaw rate [rad/s] (type:float) thrust : Collective thrust, normalized to 0 .. 1 (-1 .. 1 for vehicles capable of reverse trust) (type:float) ''' return self.send(self.set_attitude_target_encode(time_boot_ms, target_system, target_component, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust), force_mavlink1=force_mavlink1) def attitude_target_encode(self, time_boot_ms, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust): ''' Reports the current commanded attitude of the vehicle as specified by the autopilot. This should match the commands sent in a SET_ATTITUDE_TARGET message if the vehicle is being controlled this way. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) type_mask : Mappings: If any of these bits are set, the corresponding input should be ignored: bit 1: body roll rate, bit 2: body pitch rate, bit 3: body yaw rate. bit 4-bit 7: reserved, bit 8: attitude (type:uint8_t) q : Attitude quaternion (w, x, y, z order, zero-rotation is 1, 0, 0, 0) (type:float) body_roll_rate : Body roll rate [rad/s] (type:float) body_pitch_rate : Body pitch rate [rad/s] (type:float) body_yaw_rate : Body yaw rate [rad/s] (type:float) thrust : Collective thrust, normalized to 0 .. 1 (-1 .. 1 for vehicles capable of reverse trust) (type:float) ''' return MAVLink_attitude_target_message(time_boot_ms, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust) def attitude_target_send(self, time_boot_ms, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust, force_mavlink1=False): ''' Reports the current commanded attitude of the vehicle as specified by the autopilot. This should match the commands sent in a SET_ATTITUDE_TARGET message if the vehicle is being controlled this way. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) type_mask : Mappings: If any of these bits are set, the corresponding input should be ignored: bit 1: body roll rate, bit 2: body pitch rate, bit 3: body yaw rate. bit 4-bit 7: reserved, bit 8: attitude (type:uint8_t) q : Attitude quaternion (w, x, y, z order, zero-rotation is 1, 0, 0, 0) (type:float) body_roll_rate : Body roll rate [rad/s] (type:float) body_pitch_rate : Body pitch rate [rad/s] (type:float) body_yaw_rate : Body yaw rate [rad/s] (type:float) thrust : Collective thrust, normalized to 0 .. 1 (-1 .. 1 for vehicles capable of reverse trust) (type:float) ''' return self.send(self.attitude_target_encode(time_boot_ms, type_mask, q, body_roll_rate, body_pitch_rate, body_yaw_rate, thrust), force_mavlink1=force_mavlink1) def set_position_target_local_ned_encode(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Sets a desired vehicle position in a local north-east-down coordinate frame. Used by an external controller to command the vehicle (manual controller or other system). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) coordinate_frame : Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7, MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9 (type:uint8_t, values:MAV_FRAME) type_mask : Bitmap to indicate which dimensions should be ignored by the vehicle. (type:uint16_t, values:POSITION_TARGET_TYPEMASK) x : X Position in NED frame [m] (type:float) y : Y Position in NED frame [m] (type:float) z : Z Position in NED frame (note, altitude is negative in NED) [m] (type:float) vx : X velocity in NED frame [m/s] (type:float) vy : Y velocity in NED frame [m/s] (type:float) vz : Z velocity in NED frame [m/s] (type:float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) yaw : yaw setpoint [rad] (type:float) yaw_rate : yaw rate setpoint [rad/s] (type:float) ''' return MAVLink_set_position_target_local_ned_message(time_boot_ms, target_system, target_component, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate) def set_position_target_local_ned_send(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate, force_mavlink1=False): ''' Sets a desired vehicle position in a local north-east-down coordinate frame. Used by an external controller to command the vehicle (manual controller or other system). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) coordinate_frame : Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7, MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9 (type:uint8_t, values:MAV_FRAME) type_mask : Bitmap to indicate which dimensions should be ignored by the vehicle. (type:uint16_t, values:POSITION_TARGET_TYPEMASK) x : X Position in NED frame [m] (type:float) y : Y Position in NED frame [m] (type:float) z : Z Position in NED frame (note, altitude is negative in NED) [m] (type:float) vx : X velocity in NED frame [m/s] (type:float) vy : Y velocity in NED frame [m/s] (type:float) vz : Z velocity in NED frame [m/s] (type:float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) yaw : yaw setpoint [rad] (type:float) yaw_rate : yaw rate setpoint [rad/s] (type:float) ''' return self.send(self.set_position_target_local_ned_encode(time_boot_ms, target_system, target_component, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate), force_mavlink1=force_mavlink1) def position_target_local_ned_encode(self, time_boot_ms, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_LOCAL_NED if the vehicle is being controlled this way. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) coordinate_frame : Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7, MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9 (type:uint8_t, values:MAV_FRAME) type_mask : Bitmap to indicate which dimensions should be ignored by the vehicle. (type:uint16_t, values:POSITION_TARGET_TYPEMASK) x : X Position in NED frame [m] (type:float) y : Y Position in NED frame [m] (type:float) z : Z Position in NED frame (note, altitude is negative in NED) [m] (type:float) vx : X velocity in NED frame [m/s] (type:float) vy : Y velocity in NED frame [m/s] (type:float) vz : Z velocity in NED frame [m/s] (type:float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) yaw : yaw setpoint [rad] (type:float) yaw_rate : yaw rate setpoint [rad/s] (type:float) ''' return MAVLink_position_target_local_ned_message(time_boot_ms, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate) def position_target_local_ned_send(self, time_boot_ms, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate, force_mavlink1=False): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_LOCAL_NED if the vehicle is being controlled this way. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) coordinate_frame : Valid options are: MAV_FRAME_LOCAL_NED = 1, MAV_FRAME_LOCAL_OFFSET_NED = 7, MAV_FRAME_BODY_NED = 8, MAV_FRAME_BODY_OFFSET_NED = 9 (type:uint8_t, values:MAV_FRAME) type_mask : Bitmap to indicate which dimensions should be ignored by the vehicle. (type:uint16_t, values:POSITION_TARGET_TYPEMASK) x : X Position in NED frame [m] (type:float) y : Y Position in NED frame [m] (type:float) z : Z Position in NED frame (note, altitude is negative in NED) [m] (type:float) vx : X velocity in NED frame [m/s] (type:float) vy : Y velocity in NED frame [m/s] (type:float) vz : Z velocity in NED frame [m/s] (type:float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) yaw : yaw setpoint [rad] (type:float) yaw_rate : yaw rate setpoint [rad/s] (type:float) ''' return self.send(self.position_target_local_ned_encode(time_boot_ms, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate), force_mavlink1=force_mavlink1) def set_position_target_global_int_encode(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Sets a desired vehicle position, velocity, and/or acceleration in a global coordinate system (WGS84). Used by an external controller to command the vehicle (manual controller or other system). time_boot_ms : Timestamp (time since system boot). The rationale for the timestamp in the setpoint is to allow the system to compensate for the transport delay of the setpoint. This allows the system to compensate processing latency. [ms] (type:uint32_t) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) coordinate_frame : Valid options are: MAV_FRAME_GLOBAL_INT = 5, MAV_FRAME_GLOBAL_RELATIVE_ALT_INT = 6, MAV_FRAME_GLOBAL_TERRAIN_ALT_INT = 11 (type:uint8_t, values:MAV_FRAME) type_mask : Bitmap to indicate which dimensions should be ignored by the vehicle. (type:uint16_t, values:POSITION_TARGET_TYPEMASK) lat_int : X Position in WGS84 frame [degE7] (type:int32_t) lon_int : Y Position in WGS84 frame [degE7] (type:int32_t) alt : Altitude (MSL, Relative to home, or AGL - depending on frame) [m] (type:float) vx : X velocity in NED frame [m/s] (type:float) vy : Y velocity in NED frame [m/s] (type:float) vz : Z velocity in NED frame [m/s] (type:float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) yaw : yaw setpoint [rad] (type:float) yaw_rate : yaw rate setpoint [rad/s] (type:float) ''' return MAVLink_set_position_target_global_int_message(time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate) def set_position_target_global_int_send(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate, force_mavlink1=False): ''' Sets a desired vehicle position, velocity, and/or acceleration in a global coordinate system (WGS84). Used by an external controller to command the vehicle (manual controller or other system). time_boot_ms : Timestamp (time since system boot). The rationale for the timestamp in the setpoint is to allow the system to compensate for the transport delay of the setpoint. This allows the system to compensate processing latency. [ms] (type:uint32_t) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) coordinate_frame : Valid options are: MAV_FRAME_GLOBAL_INT = 5, MAV_FRAME_GLOBAL_RELATIVE_ALT_INT = 6, MAV_FRAME_GLOBAL_TERRAIN_ALT_INT = 11 (type:uint8_t, values:MAV_FRAME) type_mask : Bitmap to indicate which dimensions should be ignored by the vehicle. (type:uint16_t, values:POSITION_TARGET_TYPEMASK) lat_int : X Position in WGS84 frame [degE7] (type:int32_t) lon_int : Y Position in WGS84 frame [degE7] (type:int32_t) alt : Altitude (MSL, Relative to home, or AGL - depending on frame) [m] (type:float) vx : X velocity in NED frame [m/s] (type:float) vy : Y velocity in NED frame [m/s] (type:float) vz : Z velocity in NED frame [m/s] (type:float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) yaw : yaw setpoint [rad] (type:float) yaw_rate : yaw rate setpoint [rad/s] (type:float) ''' return self.send(self.set_position_target_global_int_encode(time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate), force_mavlink1=force_mavlink1) def position_target_global_int_encode(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_GLOBAL_INT if the vehicle is being controlled this way. time_boot_ms : Timestamp (time since system boot). The rationale for the timestamp in the setpoint is to allow the system to compensate for the transport delay of the setpoint. This allows the system to compensate processing latency. [ms] (type:uint32_t) coordinate_frame : Valid options are: MAV_FRAME_GLOBAL_INT = 5, MAV_FRAME_GLOBAL_RELATIVE_ALT_INT = 6, MAV_FRAME_GLOBAL_TERRAIN_ALT_INT = 11 (type:uint8_t, values:MAV_FRAME) type_mask : Bitmap to indicate which dimensions should be ignored by the vehicle. (type:uint16_t, values:POSITION_TARGET_TYPEMASK) lat_int : X Position in WGS84 frame [degE7] (type:int32_t) lon_int : Y Position in WGS84 frame [degE7] (type:int32_t) alt : Altitude (MSL, AGL or relative to home altitude, depending on frame) [m] (type:float) vx : X velocity in NED frame [m/s] (type:float) vy : Y velocity in NED frame [m/s] (type:float) vz : Z velocity in NED frame [m/s] (type:float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) yaw : yaw setpoint [rad] (type:float) yaw_rate : yaw rate setpoint [rad/s] (type:float) ''' return MAVLink_position_target_global_int_message(time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate) def position_target_global_int_send(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate, force_mavlink1=False): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_GLOBAL_INT if the vehicle is being controlled this way. time_boot_ms : Timestamp (time since system boot). The rationale for the timestamp in the setpoint is to allow the system to compensate for the transport delay of the setpoint. This allows the system to compensate processing latency. [ms] (type:uint32_t) coordinate_frame : Valid options are: MAV_FRAME_GLOBAL_INT = 5, MAV_FRAME_GLOBAL_RELATIVE_ALT_INT = 6, MAV_FRAME_GLOBAL_TERRAIN_ALT_INT = 11 (type:uint8_t, values:MAV_FRAME) type_mask : Bitmap to indicate which dimensions should be ignored by the vehicle. (type:uint16_t, values:POSITION_TARGET_TYPEMASK) lat_int : X Position in WGS84 frame [degE7] (type:int32_t) lon_int : Y Position in WGS84 frame [degE7] (type:int32_t) alt : Altitude (MSL, AGL or relative to home altitude, depending on frame) [m] (type:float) vx : X velocity in NED frame [m/s] (type:float) vy : Y velocity in NED frame [m/s] (type:float) vz : Z velocity in NED frame [m/s] (type:float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N [m/s/s] (type:float) yaw : yaw setpoint [rad] (type:float) yaw_rate : yaw rate setpoint [rad/s] (type:float) ''' return self.send(self.position_target_global_int_encode(time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate), force_mavlink1=force_mavlink1) def local_position_ned_system_global_offset_encode(self, time_boot_ms, x, y, z, roll, pitch, yaw): ''' The offset in X, Y, Z and yaw between the LOCAL_POSITION_NED messages of MAV X and the global coordinate frame in NED coordinates. Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) x : X Position [m] (type:float) y : Y Position [m] (type:float) z : Z Position [m] (type:float) roll : Roll [rad] (type:float) pitch : Pitch [rad] (type:float) yaw : Yaw [rad] (type:float) ''' return MAVLink_local_position_ned_system_global_offset_message(time_boot_ms, x, y, z, roll, pitch, yaw) def local_position_ned_system_global_offset_send(self, time_boot_ms, x, y, z, roll, pitch, yaw, force_mavlink1=False): ''' The offset in X, Y, Z and yaw between the LOCAL_POSITION_NED messages of MAV X and the global coordinate frame in NED coordinates. Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) x : X Position [m] (type:float) y : Y Position [m] (type:float) z : Z Position [m] (type:float) roll : Roll [rad] (type:float) pitch : Pitch [rad] (type:float) yaw : Yaw [rad] (type:float) ''' return self.send(self.local_position_ned_system_global_offset_encode(time_boot_ms, x, y, z, roll, pitch, yaw), force_mavlink1=force_mavlink1) def hil_state_encode(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc): ''' Sent from simulation to autopilot. This packet is useful for high throughput applications such as hardware in the loop simulations. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) roll : Roll angle [rad] (type:float) pitch : Pitch angle [rad] (type:float) yaw : Yaw angle [rad] (type:float) rollspeed : Body frame roll / phi angular speed [rad/s] (type:float) pitchspeed : Body frame pitch / theta angular speed [rad/s] (type:float) yawspeed : Body frame yaw / psi angular speed [rad/s] (type:float) lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) alt : Altitude [mm] (type:int32_t) vx : Ground X Speed (Latitude) [cm/s] (type:int16_t) vy : Ground Y Speed (Longitude) [cm/s] (type:int16_t) vz : Ground Z Speed (Altitude) [cm/s] (type:int16_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) ''' return MAVLink_hil_state_message(time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc) def hil_state_send(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc, force_mavlink1=False): ''' Sent from simulation to autopilot. This packet is useful for high throughput applications such as hardware in the loop simulations. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) roll : Roll angle [rad] (type:float) pitch : Pitch angle [rad] (type:float) yaw : Yaw angle [rad] (type:float) rollspeed : Body frame roll / phi angular speed [rad/s] (type:float) pitchspeed : Body frame pitch / theta angular speed [rad/s] (type:float) yawspeed : Body frame yaw / psi angular speed [rad/s] (type:float) lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) alt : Altitude [mm] (type:int32_t) vx : Ground X Speed (Latitude) [cm/s] (type:int16_t) vy : Ground Y Speed (Longitude) [cm/s] (type:int16_t) vz : Ground Z Speed (Altitude) [cm/s] (type:int16_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) ''' return self.send(self.hil_state_encode(time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc), force_mavlink1=force_mavlink1) def hil_controls_encode(self, time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode): ''' Sent from autopilot to simulation. Hardware in the loop control outputs time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) roll_ailerons : Control output -1 .. 1 (type:float) pitch_elevator : Control output -1 .. 1 (type:float) yaw_rudder : Control output -1 .. 1 (type:float) throttle : Throttle 0 .. 1 (type:float) aux1 : Aux 1, -1 .. 1 (type:float) aux2 : Aux 2, -1 .. 1 (type:float) aux3 : Aux 3, -1 .. 1 (type:float) aux4 : Aux 4, -1 .. 1 (type:float) mode : System mode. (type:uint8_t, values:MAV_MODE) nav_mode : Navigation mode (MAV_NAV_MODE) (type:uint8_t) ''' return MAVLink_hil_controls_message(time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode) def hil_controls_send(self, time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode, force_mavlink1=False): ''' Sent from autopilot to simulation. Hardware in the loop control outputs time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) roll_ailerons : Control output -1 .. 1 (type:float) pitch_elevator : Control output -1 .. 1 (type:float) yaw_rudder : Control output -1 .. 1 (type:float) throttle : Throttle 0 .. 1 (type:float) aux1 : Aux 1, -1 .. 1 (type:float) aux2 : Aux 2, -1 .. 1 (type:float) aux3 : Aux 3, -1 .. 1 (type:float) aux4 : Aux 4, -1 .. 1 (type:float) mode : System mode. (type:uint8_t, values:MAV_MODE) nav_mode : Navigation mode (MAV_NAV_MODE) (type:uint8_t) ''' return self.send(self.hil_controls_encode(time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode), force_mavlink1=force_mavlink1) def hil_rc_inputs_raw_encode(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi): ''' Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) chan1_raw : RC channel 1 value [us] (type:uint16_t) chan2_raw : RC channel 2 value [us] (type:uint16_t) chan3_raw : RC channel 3 value [us] (type:uint16_t) chan4_raw : RC channel 4 value [us] (type:uint16_t) chan5_raw : RC channel 5 value [us] (type:uint16_t) chan6_raw : RC channel 6 value [us] (type:uint16_t) chan7_raw : RC channel 7 value [us] (type:uint16_t) chan8_raw : RC channel 8 value [us] (type:uint16_t) chan9_raw : RC channel 9 value [us] (type:uint16_t) chan10_raw : RC channel 10 value [us] (type:uint16_t) chan11_raw : RC channel 11 value [us] (type:uint16_t) chan12_raw : RC channel 12 value [us] (type:uint16_t) rssi : Receive signal strength indicator in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) ''' return MAVLink_hil_rc_inputs_raw_message(time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi) def hil_rc_inputs_raw_send(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi, force_mavlink1=False): ''' Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) chan1_raw : RC channel 1 value [us] (type:uint16_t) chan2_raw : RC channel 2 value [us] (type:uint16_t) chan3_raw : RC channel 3 value [us] (type:uint16_t) chan4_raw : RC channel 4 value [us] (type:uint16_t) chan5_raw : RC channel 5 value [us] (type:uint16_t) chan6_raw : RC channel 6 value [us] (type:uint16_t) chan7_raw : RC channel 7 value [us] (type:uint16_t) chan8_raw : RC channel 8 value [us] (type:uint16_t) chan9_raw : RC channel 9 value [us] (type:uint16_t) chan10_raw : RC channel 10 value [us] (type:uint16_t) chan11_raw : RC channel 11 value [us] (type:uint16_t) chan12_raw : RC channel 12 value [us] (type:uint16_t) rssi : Receive signal strength indicator in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) ''' return self.send(self.hil_rc_inputs_raw_encode(time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi), force_mavlink1=force_mavlink1) def hil_actuator_controls_encode(self, time_usec, controls, mode, flags): ''' Sent from autopilot to simulation. Hardware in the loop control outputs (replacement for HIL_CONTROLS) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) controls : Control outputs -1 .. 1. Channel assignment depends on the simulated hardware. (type:float) mode : System mode. Includes arming state. (type:uint8_t, values:MAV_MODE_FLAG) flags : Flags as bitfield, reserved for future use. (type:uint64_t) ''' return MAVLink_hil_actuator_controls_message(time_usec, controls, mode, flags) def hil_actuator_controls_send(self, time_usec, controls, mode, flags, force_mavlink1=False): ''' Sent from autopilot to simulation. Hardware in the loop control outputs (replacement for HIL_CONTROLS) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) controls : Control outputs -1 .. 1. Channel assignment depends on the simulated hardware. (type:float) mode : System mode. Includes arming state. (type:uint8_t, values:MAV_MODE_FLAG) flags : Flags as bitfield, reserved for future use. (type:uint64_t) ''' return self.send(self.hil_actuator_controls_encode(time_usec, controls, mode, flags), force_mavlink1=force_mavlink1) def optical_flow_encode(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance, flow_rate_x=0, flow_rate_y=0): ''' Optical flow from a flow sensor (e.g. optical mouse sensor) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) sensor_id : Sensor ID (type:uint8_t) flow_x : Flow in x-sensor direction [dpix] (type:int16_t) flow_y : Flow in y-sensor direction [dpix] (type:int16_t) flow_comp_m_x : Flow in x-sensor direction, angular-speed compensated [m/s] (type:float) flow_comp_m_y : Flow in y-sensor direction, angular-speed compensated [m/s] (type:float) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (type:uint8_t) ground_distance : Ground distance. Positive value: distance known. Negative value: Unknown distance [m] (type:float) flow_rate_x : Flow rate about X axis [rad/s] (type:float) flow_rate_y : Flow rate about Y axis [rad/s] (type:float) ''' return MAVLink_optical_flow_message(time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance, flow_rate_x, flow_rate_y) def optical_flow_send(self, time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance, flow_rate_x=0, flow_rate_y=0, force_mavlink1=False): ''' Optical flow from a flow sensor (e.g. optical mouse sensor) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) sensor_id : Sensor ID (type:uint8_t) flow_x : Flow in x-sensor direction [dpix] (type:int16_t) flow_y : Flow in y-sensor direction [dpix] (type:int16_t) flow_comp_m_x : Flow in x-sensor direction, angular-speed compensated [m/s] (type:float) flow_comp_m_y : Flow in y-sensor direction, angular-speed compensated [m/s] (type:float) quality : Optical flow quality / confidence. 0: bad, 255: maximum quality (type:uint8_t) ground_distance : Ground distance. Positive value: distance known. Negative value: Unknown distance [m] (type:float) flow_rate_x : Flow rate about X axis [rad/s] (type:float) flow_rate_y : Flow rate about Y axis [rad/s] (type:float) ''' return self.send(self.optical_flow_encode(time_usec, sensor_id, flow_x, flow_y, flow_comp_m_x, flow_comp_m_y, quality, ground_distance, flow_rate_x, flow_rate_y), force_mavlink1=force_mavlink1) def global_vision_position_estimate_encode(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], reset_counter=0): ''' Global position/attitude estimate from a vision source. usec : Timestamp (UNIX time or since system boot) [us] (type:uint64_t) x : Global X position [m] (type:float) y : Global Y position [m] (type:float) z : Global Z position [m] (type:float) roll : Roll angle [rad] (type:float) pitch : Pitch angle [rad] (type:float) yaw : Yaw angle [rad] (type:float) covariance : Row-major representation of pose 6x6 cross-covariance matrix upper right triangle (states: x_global, y_global, z_global, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) reset_counter : Estimate reset counter. This should be incremented when the estimate resets in any of the dimensions (position, velocity, attitude, angular speed). This is designed to be used when e.g an external SLAM system detects a loop-closure and the estimate jumps. (type:uint8_t) ''' return MAVLink_global_vision_position_estimate_message(usec, x, y, z, roll, pitch, yaw, covariance, reset_counter) def global_vision_position_estimate_send(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], reset_counter=0, force_mavlink1=False): ''' Global position/attitude estimate from a vision source. usec : Timestamp (UNIX time or since system boot) [us] (type:uint64_t) x : Global X position [m] (type:float) y : Global Y position [m] (type:float) z : Global Z position [m] (type:float) roll : Roll angle [rad] (type:float) pitch : Pitch angle [rad] (type:float) yaw : Yaw angle [rad] (type:float) covariance : Row-major representation of pose 6x6 cross-covariance matrix upper right triangle (states: x_global, y_global, z_global, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) reset_counter : Estimate reset counter. This should be incremented when the estimate resets in any of the dimensions (position, velocity, attitude, angular speed). This is designed to be used when e.g an external SLAM system detects a loop-closure and the estimate jumps. (type:uint8_t) ''' return self.send(self.global_vision_position_estimate_encode(usec, x, y, z, roll, pitch, yaw, covariance, reset_counter), force_mavlink1=force_mavlink1) def vision_position_estimate_encode(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], reset_counter=0): ''' Global position/attitude estimate from a vision source. usec : Timestamp (UNIX time or time since system boot) [us] (type:uint64_t) x : Global X position [m] (type:float) y : Global Y position [m] (type:float) z : Global Z position [m] (type:float) roll : Roll angle [rad] (type:float) pitch : Pitch angle [rad] (type:float) yaw : Yaw angle [rad] (type:float) covariance : Row-major representation of pose 6x6 cross-covariance matrix upper right triangle (states: x, y, z, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) reset_counter : Estimate reset counter. This should be incremented when the estimate resets in any of the dimensions (position, velocity, attitude, angular speed). This is designed to be used when e.g an external SLAM system detects a loop-closure and the estimate jumps. (type:uint8_t) ''' return MAVLink_vision_position_estimate_message(usec, x, y, z, roll, pitch, yaw, covariance, reset_counter) def vision_position_estimate_send(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], reset_counter=0, force_mavlink1=False): ''' Global position/attitude estimate from a vision source. usec : Timestamp (UNIX time or time since system boot) [us] (type:uint64_t) x : Global X position [m] (type:float) y : Global Y position [m] (type:float) z : Global Z position [m] (type:float) roll : Roll angle [rad] (type:float) pitch : Pitch angle [rad] (type:float) yaw : Yaw angle [rad] (type:float) covariance : Row-major representation of pose 6x6 cross-covariance matrix upper right triangle (states: x, y, z, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) reset_counter : Estimate reset counter. This should be incremented when the estimate resets in any of the dimensions (position, velocity, attitude, angular speed). This is designed to be used when e.g an external SLAM system detects a loop-closure and the estimate jumps. (type:uint8_t) ''' return self.send(self.vision_position_estimate_encode(usec, x, y, z, roll, pitch, yaw, covariance, reset_counter), force_mavlink1=force_mavlink1) def vision_speed_estimate_encode(self, usec, x, y, z, covariance=[0,0,0,0,0,0,0,0,0], reset_counter=0): ''' Speed estimate from a vision source. usec : Timestamp (UNIX time or time since system boot) [us] (type:uint64_t) x : Global X speed [m/s] (type:float) y : Global Y speed [m/s] (type:float) z : Global Z speed [m/s] (type:float) covariance : Row-major representation of 3x3 linear velocity covariance matrix (states: vx, vy, vz; 1st three entries - 1st row, etc.). If unknown, assign NaN value to first element in the array. (type:float) reset_counter : Estimate reset counter. This should be incremented when the estimate resets in any of the dimensions (position, velocity, attitude, angular speed). This is designed to be used when e.g an external SLAM system detects a loop-closure and the estimate jumps. (type:uint8_t) ''' return MAVLink_vision_speed_estimate_message(usec, x, y, z, covariance, reset_counter) def vision_speed_estimate_send(self, usec, x, y, z, covariance=[0,0,0,0,0,0,0,0,0], reset_counter=0, force_mavlink1=False): ''' Speed estimate from a vision source. usec : Timestamp (UNIX time or time since system boot) [us] (type:uint64_t) x : Global X speed [m/s] (type:float) y : Global Y speed [m/s] (type:float) z : Global Z speed [m/s] (type:float) covariance : Row-major representation of 3x3 linear velocity covariance matrix (states: vx, vy, vz; 1st three entries - 1st row, etc.). If unknown, assign NaN value to first element in the array. (type:float) reset_counter : Estimate reset counter. This should be incremented when the estimate resets in any of the dimensions (position, velocity, attitude, angular speed). This is designed to be used when e.g an external SLAM system detects a loop-closure and the estimate jumps. (type:uint8_t) ''' return self.send(self.vision_speed_estimate_encode(usec, x, y, z, covariance, reset_counter), force_mavlink1=force_mavlink1) def vicon_position_estimate_encode(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]): ''' Global position estimate from a Vicon motion system source. usec : Timestamp (UNIX time or time since system boot) [us] (type:uint64_t) x : Global X position [m] (type:float) y : Global Y position [m] (type:float) z : Global Z position [m] (type:float) roll : Roll angle [rad] (type:float) pitch : Pitch angle [rad] (type:float) yaw : Yaw angle [rad] (type:float) covariance : Row-major representation of 6x6 pose cross-covariance matrix upper right triangle (states: x, y, z, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return MAVLink_vicon_position_estimate_message(usec, x, y, z, roll, pitch, yaw, covariance) def vicon_position_estimate_send(self, usec, x, y, z, roll, pitch, yaw, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], force_mavlink1=False): ''' Global position estimate from a Vicon motion system source. usec : Timestamp (UNIX time or time since system boot) [us] (type:uint64_t) x : Global X position [m] (type:float) y : Global Y position [m] (type:float) z : Global Z position [m] (type:float) roll : Roll angle [rad] (type:float) pitch : Pitch angle [rad] (type:float) yaw : Yaw angle [rad] (type:float) covariance : Row-major representation of 6x6 pose cross-covariance matrix upper right triangle (states: x, y, z, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return self.send(self.vicon_position_estimate_encode(usec, x, y, z, roll, pitch, yaw, covariance), force_mavlink1=force_mavlink1) def highres_imu_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated, id=0): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) xacc : X acceleration [m/s/s] (type:float) yacc : Y acceleration [m/s/s] (type:float) zacc : Z acceleration [m/s/s] (type:float) xgyro : Angular speed around X axis [rad/s] (type:float) ygyro : Angular speed around Y axis [rad/s] (type:float) zgyro : Angular speed around Z axis [rad/s] (type:float) xmag : X Magnetic field [gauss] (type:float) ymag : Y Magnetic field [gauss] (type:float) zmag : Z Magnetic field [gauss] (type:float) abs_pressure : Absolute pressure [mbar] (type:float) diff_pressure : Differential pressure [mbar] (type:float) pressure_alt : Altitude calculated from pressure (type:float) temperature : Temperature [degC] (type:float) fields_updated : Bitmap for fields that have updated since last message, bit 0 = xacc, bit 12: temperature (type:uint16_t) id : Id. Ids are numbered from 0 and map to IMUs numbered from 1 (e.g. IMU1 will have a message with id=0) (type:uint8_t) ''' return MAVLink_highres_imu_message(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated, id) def highres_imu_send(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated, id=0, force_mavlink1=False): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) xacc : X acceleration [m/s/s] (type:float) yacc : Y acceleration [m/s/s] (type:float) zacc : Z acceleration [m/s/s] (type:float) xgyro : Angular speed around X axis [rad/s] (type:float) ygyro : Angular speed around Y axis [rad/s] (type:float) zgyro : Angular speed around Z axis [rad/s] (type:float) xmag : X Magnetic field [gauss] (type:float) ymag : Y Magnetic field [gauss] (type:float) zmag : Z Magnetic field [gauss] (type:float) abs_pressure : Absolute pressure [mbar] (type:float) diff_pressure : Differential pressure [mbar] (type:float) pressure_alt : Altitude calculated from pressure (type:float) temperature : Temperature [degC] (type:float) fields_updated : Bitmap for fields that have updated since last message, bit 0 = xacc, bit 12: temperature (type:uint16_t) id : Id. Ids are numbered from 0 and map to IMUs numbered from 1 (e.g. IMU1 will have a message with id=0) (type:uint8_t) ''' return self.send(self.highres_imu_encode(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated, id), force_mavlink1=force_mavlink1) def optical_flow_rad_encode(self, time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance): ''' Optical flow from an angular rate flow sensor (e.g. PX4FLOW or mouse sensor) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) sensor_id : Sensor ID (type:uint8_t) integration_time_us : Integration time. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the. [us] (type:uint32_t) integrated_x : Flow around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.) [rad] (type:float) integrated_y : Flow around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.) [rad] (type:float) integrated_xgyro : RH rotation around X axis [rad] (type:float) integrated_ygyro : RH rotation around Y axis [rad] (type:float) integrated_zgyro : RH rotation around Z axis [rad] (type:float) temperature : Temperature [cdegC] (type:int16_t) quality : Optical flow quality / confidence. 0: no valid flow, 255: maximum quality (type:uint8_t) time_delta_distance_us : Time since the distance was sampled. [us] (type:uint32_t) distance : Distance to the center of the flow field. Positive value (including zero): distance known. Negative value: Unknown distance. [m] (type:float) ''' return MAVLink_optical_flow_rad_message(time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance) def optical_flow_rad_send(self, time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance, force_mavlink1=False): ''' Optical flow from an angular rate flow sensor (e.g. PX4FLOW or mouse sensor) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) sensor_id : Sensor ID (type:uint8_t) integration_time_us : Integration time. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the. [us] (type:uint32_t) integrated_x : Flow around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.) [rad] (type:float) integrated_y : Flow around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.) [rad] (type:float) integrated_xgyro : RH rotation around X axis [rad] (type:float) integrated_ygyro : RH rotation around Y axis [rad] (type:float) integrated_zgyro : RH rotation around Z axis [rad] (type:float) temperature : Temperature [cdegC] (type:int16_t) quality : Optical flow quality / confidence. 0: no valid flow, 255: maximum quality (type:uint8_t) time_delta_distance_us : Time since the distance was sampled. [us] (type:uint32_t) distance : Distance to the center of the flow field. Positive value (including zero): distance known. Negative value: Unknown distance. [m] (type:float) ''' return self.send(self.optical_flow_rad_encode(time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance), force_mavlink1=force_mavlink1) def hil_sensor_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) xacc : X acceleration [m/s/s] (type:float) yacc : Y acceleration [m/s/s] (type:float) zacc : Z acceleration [m/s/s] (type:float) xgyro : Angular speed around X axis in body frame [rad/s] (type:float) ygyro : Angular speed around Y axis in body frame [rad/s] (type:float) zgyro : Angular speed around Z axis in body frame [rad/s] (type:float) xmag : X Magnetic field [gauss] (type:float) ymag : Y Magnetic field [gauss] (type:float) zmag : Z Magnetic field [gauss] (type:float) abs_pressure : Absolute pressure [mbar] (type:float) diff_pressure : Differential pressure (airspeed) [mbar] (type:float) pressure_alt : Altitude calculated from pressure (type:float) temperature : Temperature [degC] (type:float) fields_updated : Bitmap for fields that have updated since last message, bit 0 = xacc, bit 12: temperature, bit 31: full reset of attitude/position/velocities/etc was performed in sim. (type:uint32_t) ''' return MAVLink_hil_sensor_message(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated) def hil_sensor_send(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated, force_mavlink1=False): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) xacc : X acceleration [m/s/s] (type:float) yacc : Y acceleration [m/s/s] (type:float) zacc : Z acceleration [m/s/s] (type:float) xgyro : Angular speed around X axis in body frame [rad/s] (type:float) ygyro : Angular speed around Y axis in body frame [rad/s] (type:float) zgyro : Angular speed around Z axis in body frame [rad/s] (type:float) xmag : X Magnetic field [gauss] (type:float) ymag : Y Magnetic field [gauss] (type:float) zmag : Z Magnetic field [gauss] (type:float) abs_pressure : Absolute pressure [mbar] (type:float) diff_pressure : Differential pressure (airspeed) [mbar] (type:float) pressure_alt : Altitude calculated from pressure (type:float) temperature : Temperature [degC] (type:float) fields_updated : Bitmap for fields that have updated since last message, bit 0 = xacc, bit 12: temperature, bit 31: full reset of attitude/position/velocities/etc was performed in sim. (type:uint32_t) ''' return self.send(self.hil_sensor_encode(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated), force_mavlink1=force_mavlink1) def sim_state_encode(self, q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd): ''' Status of simulation environment, if used q1 : True attitude quaternion component 1, w (1 in null-rotation) (type:float) q2 : True attitude quaternion component 2, x (0 in null-rotation) (type:float) q3 : True attitude quaternion component 3, y (0 in null-rotation) (type:float) q4 : True attitude quaternion component 4, z (0 in null-rotation) (type:float) roll : Attitude roll expressed as Euler angles, not recommended except for human-readable outputs (type:float) pitch : Attitude pitch expressed as Euler angles, not recommended except for human-readable outputs (type:float) yaw : Attitude yaw expressed as Euler angles, not recommended except for human-readable outputs (type:float) xacc : X acceleration [m/s/s] (type:float) yacc : Y acceleration [m/s/s] (type:float) zacc : Z acceleration [m/s/s] (type:float) xgyro : Angular speed around X axis [rad/s] (type:float) ygyro : Angular speed around Y axis [rad/s] (type:float) zgyro : Angular speed around Z axis [rad/s] (type:float) lat : Latitude [deg] (type:float) lon : Longitude [deg] (type:float) alt : Altitude [m] (type:float) std_dev_horz : Horizontal position standard deviation (type:float) std_dev_vert : Vertical position standard deviation (type:float) vn : True velocity in NORTH direction in earth-fixed NED frame [m/s] (type:float) ve : True velocity in EAST direction in earth-fixed NED frame [m/s] (type:float) vd : True velocity in DOWN direction in earth-fixed NED frame [m/s] (type:float) ''' return MAVLink_sim_state_message(q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd) def sim_state_send(self, q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd, force_mavlink1=False): ''' Status of simulation environment, if used q1 : True attitude quaternion component 1, w (1 in null-rotation) (type:float) q2 : True attitude quaternion component 2, x (0 in null-rotation) (type:float) q3 : True attitude quaternion component 3, y (0 in null-rotation) (type:float) q4 : True attitude quaternion component 4, z (0 in null-rotation) (type:float) roll : Attitude roll expressed as Euler angles, not recommended except for human-readable outputs (type:float) pitch : Attitude pitch expressed as Euler angles, not recommended except for human-readable outputs (type:float) yaw : Attitude yaw expressed as Euler angles, not recommended except for human-readable outputs (type:float) xacc : X acceleration [m/s/s] (type:float) yacc : Y acceleration [m/s/s] (type:float) zacc : Z acceleration [m/s/s] (type:float) xgyro : Angular speed around X axis [rad/s] (type:float) ygyro : Angular speed around Y axis [rad/s] (type:float) zgyro : Angular speed around Z axis [rad/s] (type:float) lat : Latitude [deg] (type:float) lon : Longitude [deg] (type:float) alt : Altitude [m] (type:float) std_dev_horz : Horizontal position standard deviation (type:float) std_dev_vert : Vertical position standard deviation (type:float) vn : True velocity in NORTH direction in earth-fixed NED frame [m/s] (type:float) ve : True velocity in EAST direction in earth-fixed NED frame [m/s] (type:float) vd : True velocity in DOWN direction in earth-fixed NED frame [m/s] (type:float) ''' return self.send(self.sim_state_encode(q1, q2, q3, q4, roll, pitch, yaw, xacc, yacc, zacc, xgyro, ygyro, zgyro, lat, lon, alt, std_dev_horz, std_dev_vert, vn, ve, vd), force_mavlink1=force_mavlink1) def radio_status_encode(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed): ''' Status generated by radio and injected into MAVLink stream. rssi : Local (message sender) recieved signal strength indication in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) remrssi : Remote (message receiver) signal strength indication in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) txbuf : Remaining free transmitter buffer space. [%] (type:uint8_t) noise : Local background noise level. These are device dependent RSSI values (scale as approx 2x dB on SiK radios). Values: [0-254], 255: invalid/unknown. (type:uint8_t) remnoise : Remote background noise level. These are device dependent RSSI values (scale as approx 2x dB on SiK radios). Values: [0-254], 255: invalid/unknown. (type:uint8_t) rxerrors : Count of radio packet receive errors (since boot). (type:uint16_t) fixed : Count of error corrected radio packets (since boot). (type:uint16_t) ''' return MAVLink_radio_status_message(rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed) def radio_status_send(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed, force_mavlink1=False): ''' Status generated by radio and injected into MAVLink stream. rssi : Local (message sender) recieved signal strength indication in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) remrssi : Remote (message receiver) signal strength indication in device-dependent units/scale. Values: [0-254], 255: invalid/unknown. (type:uint8_t) txbuf : Remaining free transmitter buffer space. [%] (type:uint8_t) noise : Local background noise level. These are device dependent RSSI values (scale as approx 2x dB on SiK radios). Values: [0-254], 255: invalid/unknown. (type:uint8_t) remnoise : Remote background noise level. These are device dependent RSSI values (scale as approx 2x dB on SiK radios). Values: [0-254], 255: invalid/unknown. (type:uint8_t) rxerrors : Count of radio packet receive errors (since boot). (type:uint16_t) fixed : Count of error corrected radio packets (since boot). (type:uint16_t) ''' return self.send(self.radio_status_encode(rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed), force_mavlink1=force_mavlink1) def file_transfer_protocol_encode(self, target_network, target_system, target_component, payload): ''' File transfer message target_network : Network ID (0 for broadcast) (type:uint8_t) target_system : System ID (0 for broadcast) (type:uint8_t) target_component : Component ID (0 for broadcast) (type:uint8_t) payload : Variable length payload. The length is defined by the remaining message length when subtracting the header and other fields. The entire content of this block is opaque unless you understand any the encoding message_type. The particular encoding used can be extension specific and might not always be documented as part of the mavlink specification. (type:uint8_t) ''' return MAVLink_file_transfer_protocol_message(target_network, target_system, target_component, payload) def file_transfer_protocol_send(self, target_network, target_system, target_component, payload, force_mavlink1=False): ''' File transfer message target_network : Network ID (0 for broadcast) (type:uint8_t) target_system : System ID (0 for broadcast) (type:uint8_t) target_component : Component ID (0 for broadcast) (type:uint8_t) payload : Variable length payload. The length is defined by the remaining message length when subtracting the header and other fields. The entire content of this block is opaque unless you understand any the encoding message_type. The particular encoding used can be extension specific and might not always be documented as part of the mavlink specification. (type:uint8_t) ''' return self.send(self.file_transfer_protocol_encode(target_network, target_system, target_component, payload), force_mavlink1=force_mavlink1) def timesync_encode(self, tc1, ts1): ''' Time synchronization message. tc1 : Time sync timestamp 1 (type:int64_t) ts1 : Time sync timestamp 2 (type:int64_t) ''' return MAVLink_timesync_message(tc1, ts1) def timesync_send(self, tc1, ts1, force_mavlink1=False): ''' Time synchronization message. tc1 : Time sync timestamp 1 (type:int64_t) ts1 : Time sync timestamp 2 (type:int64_t) ''' return self.send(self.timesync_encode(tc1, ts1), force_mavlink1=force_mavlink1) def camera_trigger_encode(self, time_usec, seq): ''' Camera-IMU triggering and synchronisation message. time_usec : Timestamp for image frame (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) seq : Image frame sequence (type:uint32_t) ''' return MAVLink_camera_trigger_message(time_usec, seq) def camera_trigger_send(self, time_usec, seq, force_mavlink1=False): ''' Camera-IMU triggering and synchronisation message. time_usec : Timestamp for image frame (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) seq : Image frame sequence (type:uint32_t) ''' return self.send(self.camera_trigger_encode(time_usec, seq), force_mavlink1=force_mavlink1) def hil_gps_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. Some applications will not use the value of this field unless it is at least two, so always correctly fill in the fix. (type:uint8_t) lat : Latitude (WGS84) [degE7] (type:int32_t) lon : Longitude (WGS84) [degE7] (type:int32_t) alt : Altitude (MSL). Positive for up. [mm] (type:int32_t) eph : GPS HDOP horizontal dilution of position. If unknown, set to: 65535 [cm] (type:uint16_t) epv : GPS VDOP vertical dilution of position. If unknown, set to: 65535 [cm] (type:uint16_t) vel : GPS ground speed. If unknown, set to: 65535 [cm/s] (type:uint16_t) vn : GPS velocity in NORTH direction in earth-fixed NED frame [cm/s] (type:int16_t) ve : GPS velocity in EAST direction in earth-fixed NED frame [cm/s] (type:int16_t) vd : GPS velocity in DOWN direction in earth-fixed NED frame [cm/s] (type:int16_t) cog : Course over ground (NOT heading, but direction of movement), 0.0..359.99 degrees. If unknown, set to: 65535 [cdeg] (type:uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (type:uint8_t) ''' return MAVLink_hil_gps_message(time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible) def hil_gps_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible, force_mavlink1=False): ''' The global position, as returned by the Global Positioning System (GPS). This is NOT the global position estimate of the sytem, but rather a RAW sensor value. See message GLOBAL_POSITION for the global position estimate. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. Some applications will not use the value of this field unless it is at least two, so always correctly fill in the fix. (type:uint8_t) lat : Latitude (WGS84) [degE7] (type:int32_t) lon : Longitude (WGS84) [degE7] (type:int32_t) alt : Altitude (MSL). Positive for up. [mm] (type:int32_t) eph : GPS HDOP horizontal dilution of position. If unknown, set to: 65535 [cm] (type:uint16_t) epv : GPS VDOP vertical dilution of position. If unknown, set to: 65535 [cm] (type:uint16_t) vel : GPS ground speed. If unknown, set to: 65535 [cm/s] (type:uint16_t) vn : GPS velocity in NORTH direction in earth-fixed NED frame [cm/s] (type:int16_t) ve : GPS velocity in EAST direction in earth-fixed NED frame [cm/s] (type:int16_t) vd : GPS velocity in DOWN direction in earth-fixed NED frame [cm/s] (type:int16_t) cog : Course over ground (NOT heading, but direction of movement), 0.0..359.99 degrees. If unknown, set to: 65535 [cdeg] (type:uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (type:uint8_t) ''' return self.send(self.hil_gps_encode(time_usec, fix_type, lat, lon, alt, eph, epv, vel, vn, ve, vd, cog, satellites_visible), force_mavlink1=force_mavlink1) def hil_optical_flow_encode(self, time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance): ''' Simulated optical flow from a flow sensor (e.g. PX4FLOW or optical mouse sensor) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) sensor_id : Sensor ID (type:uint8_t) integration_time_us : Integration time. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the. [us] (type:uint32_t) integrated_x : Flow in radians around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.) [rad] (type:float) integrated_y : Flow in radians around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.) [rad] (type:float) integrated_xgyro : RH rotation around X axis [rad] (type:float) integrated_ygyro : RH rotation around Y axis [rad] (type:float) integrated_zgyro : RH rotation around Z axis [rad] (type:float) temperature : Temperature [cdegC] (type:int16_t) quality : Optical flow quality / confidence. 0: no valid flow, 255: maximum quality (type:uint8_t) time_delta_distance_us : Time since the distance was sampled. [us] (type:uint32_t) distance : Distance to the center of the flow field. Positive value (including zero): distance known. Negative value: Unknown distance. [m] (type:float) ''' return MAVLink_hil_optical_flow_message(time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance) def hil_optical_flow_send(self, time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance, force_mavlink1=False): ''' Simulated optical flow from a flow sensor (e.g. PX4FLOW or optical mouse sensor) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) sensor_id : Sensor ID (type:uint8_t) integration_time_us : Integration time. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the. [us] (type:uint32_t) integrated_x : Flow in radians around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.) [rad] (type:float) integrated_y : Flow in radians around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.) [rad] (type:float) integrated_xgyro : RH rotation around X axis [rad] (type:float) integrated_ygyro : RH rotation around Y axis [rad] (type:float) integrated_zgyro : RH rotation around Z axis [rad] (type:float) temperature : Temperature [cdegC] (type:int16_t) quality : Optical flow quality / confidence. 0: no valid flow, 255: maximum quality (type:uint8_t) time_delta_distance_us : Time since the distance was sampled. [us] (type:uint32_t) distance : Distance to the center of the flow field. Positive value (including zero): distance known. Negative value: Unknown distance. [m] (type:float) ''' return self.send(self.hil_optical_flow_encode(time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance), force_mavlink1=force_mavlink1) def hil_state_quaternion_encode(self, time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc): ''' Sent from simulation to autopilot, avoids in contrast to HIL_STATE singularities. This packet is useful for high throughput applications such as hardware in the loop simulations. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) attitude_quaternion : Vehicle attitude expressed as normalized quaternion in w, x, y, z order (with 1 0 0 0 being the null-rotation) (type:float) rollspeed : Body frame roll / phi angular speed [rad/s] (type:float) pitchspeed : Body frame pitch / theta angular speed [rad/s] (type:float) yawspeed : Body frame yaw / psi angular speed [rad/s] (type:float) lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) alt : Altitude [mm] (type:int32_t) vx : Ground X Speed (Latitude) [cm/s] (type:int16_t) vy : Ground Y Speed (Longitude) [cm/s] (type:int16_t) vz : Ground Z Speed (Altitude) [cm/s] (type:int16_t) ind_airspeed : Indicated airspeed [cm/s] (type:uint16_t) true_airspeed : True airspeed [cm/s] (type:uint16_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) ''' return MAVLink_hil_state_quaternion_message(time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc) def hil_state_quaternion_send(self, time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc, force_mavlink1=False): ''' Sent from simulation to autopilot, avoids in contrast to HIL_STATE singularities. This packet is useful for high throughput applications such as hardware in the loop simulations. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) attitude_quaternion : Vehicle attitude expressed as normalized quaternion in w, x, y, z order (with 1 0 0 0 being the null-rotation) (type:float) rollspeed : Body frame roll / phi angular speed [rad/s] (type:float) pitchspeed : Body frame pitch / theta angular speed [rad/s] (type:float) yawspeed : Body frame yaw / psi angular speed [rad/s] (type:float) lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) alt : Altitude [mm] (type:int32_t) vx : Ground X Speed (Latitude) [cm/s] (type:int16_t) vy : Ground Y Speed (Longitude) [cm/s] (type:int16_t) vz : Ground Z Speed (Altitude) [cm/s] (type:int16_t) ind_airspeed : Indicated airspeed [cm/s] (type:uint16_t) true_airspeed : True airspeed [cm/s] (type:uint16_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) ''' return self.send(self.hil_state_quaternion_encode(time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc), force_mavlink1=force_mavlink1) def scaled_imu2_encode(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0): ''' The RAW IMU readings for secondary 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) xgyro : Angular speed around X axis [mrad/s] (type:int16_t) ygyro : Angular speed around Y axis [mrad/s] (type:int16_t) zgyro : Angular speed around Z axis [mrad/s] (type:int16_t) xmag : X Magnetic field [mgauss] (type:int16_t) ymag : Y Magnetic field [mgauss] (type:int16_t) zmag : Z Magnetic field [mgauss] (type:int16_t) temperature : Temperature, 0: IMU does not provide temperature values. If the IMU is at 0C it must send 1 (0.01C). [cdegC] (type:int16_t) ''' return MAVLink_scaled_imu2_message(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature) def scaled_imu2_send(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0, force_mavlink1=False): ''' The RAW IMU readings for secondary 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) xgyro : Angular speed around X axis [mrad/s] (type:int16_t) ygyro : Angular speed around Y axis [mrad/s] (type:int16_t) zgyro : Angular speed around Z axis [mrad/s] (type:int16_t) xmag : X Magnetic field [mgauss] (type:int16_t) ymag : Y Magnetic field [mgauss] (type:int16_t) zmag : Z Magnetic field [mgauss] (type:int16_t) temperature : Temperature, 0: IMU does not provide temperature values. If the IMU is at 0C it must send 1 (0.01C). [cdegC] (type:int16_t) ''' return self.send(self.scaled_imu2_encode(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature), force_mavlink1=force_mavlink1) def log_request_list_encode(self, target_system, target_component, start, end): ''' Request a list of available logs. On some systems calling this may stop on-board logging until LOG_REQUEST_END is called. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) start : First log id (0 for first available) (type:uint16_t) end : Last log id (0xffff for last available) (type:uint16_t) ''' return MAVLink_log_request_list_message(target_system, target_component, start, end) def log_request_list_send(self, target_system, target_component, start, end, force_mavlink1=False): ''' Request a list of available logs. On some systems calling this may stop on-board logging until LOG_REQUEST_END is called. target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) start : First log id (0 for first available) (type:uint16_t) end : Last log id (0xffff for last available) (type:uint16_t) ''' return self.send(self.log_request_list_encode(target_system, target_component, start, end), force_mavlink1=force_mavlink1) def log_entry_encode(self, id, num_logs, last_log_num, time_utc, size): ''' Reply to LOG_REQUEST_LIST id : Log id (type:uint16_t) num_logs : Total number of logs (type:uint16_t) last_log_num : High log number (type:uint16_t) time_utc : UTC timestamp of log since 1970, or 0 if not available [s] (type:uint32_t) size : Size of the log (may be approximate) [bytes] (type:uint32_t) ''' return MAVLink_log_entry_message(id, num_logs, last_log_num, time_utc, size) def log_entry_send(self, id, num_logs, last_log_num, time_utc, size, force_mavlink1=False): ''' Reply to LOG_REQUEST_LIST id : Log id (type:uint16_t) num_logs : Total number of logs (type:uint16_t) last_log_num : High log number (type:uint16_t) time_utc : UTC timestamp of log since 1970, or 0 if not available [s] (type:uint32_t) size : Size of the log (may be approximate) [bytes] (type:uint32_t) ''' return self.send(self.log_entry_encode(id, num_logs, last_log_num, time_utc, size), force_mavlink1=force_mavlink1) def log_request_data_encode(self, target_system, target_component, id, ofs, count): ''' Request a chunk of a log target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) id : Log id (from LOG_ENTRY reply) (type:uint16_t) ofs : Offset into the log (type:uint32_t) count : Number of bytes [bytes] (type:uint32_t) ''' return MAVLink_log_request_data_message(target_system, target_component, id, ofs, count) def log_request_data_send(self, target_system, target_component, id, ofs, count, force_mavlink1=False): ''' Request a chunk of a log target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) id : Log id (from LOG_ENTRY reply) (type:uint16_t) ofs : Offset into the log (type:uint32_t) count : Number of bytes [bytes] (type:uint32_t) ''' return self.send(self.log_request_data_encode(target_system, target_component, id, ofs, count), force_mavlink1=force_mavlink1) def log_data_encode(self, id, ofs, count, data): ''' Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (type:uint16_t) ofs : Offset into the log (type:uint32_t) count : Number of bytes (zero for end of log) [bytes] (type:uint8_t) data : log data (type:uint8_t) ''' return MAVLink_log_data_message(id, ofs, count, data) def log_data_send(self, id, ofs, count, data, force_mavlink1=False): ''' Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (type:uint16_t) ofs : Offset into the log (type:uint32_t) count : Number of bytes (zero for end of log) [bytes] (type:uint8_t) data : log data (type:uint8_t) ''' return self.send(self.log_data_encode(id, ofs, count, data), force_mavlink1=force_mavlink1) def log_erase_encode(self, target_system, target_component): ''' Erase all logs target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return MAVLink_log_erase_message(target_system, target_component) def log_erase_send(self, target_system, target_component, force_mavlink1=False): ''' Erase all logs target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return self.send(self.log_erase_encode(target_system, target_component), force_mavlink1=force_mavlink1) def log_request_end_encode(self, target_system, target_component): ''' Stop log transfer and resume normal logging target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return MAVLink_log_request_end_message(target_system, target_component) def log_request_end_send(self, target_system, target_component, force_mavlink1=False): ''' Stop log transfer and resume normal logging target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) ''' return self.send(self.log_request_end_encode(target_system, target_component), force_mavlink1=force_mavlink1) def gps_inject_data_encode(self, target_system, target_component, len, data): ''' Data for injecting into the onboard GPS (used for DGPS) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) len : Data length [bytes] (type:uint8_t) data : Raw data (110 is enough for 12 satellites of RTCMv2) (type:uint8_t) ''' return MAVLink_gps_inject_data_message(target_system, target_component, len, data) def gps_inject_data_send(self, target_system, target_component, len, data, force_mavlink1=False): ''' Data for injecting into the onboard GPS (used for DGPS) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) len : Data length [bytes] (type:uint8_t) data : Raw data (110 is enough for 12 satellites of RTCMv2) (type:uint8_t) ''' return self.send(self.gps_inject_data_encode(target_system, target_component, len, data), force_mavlink1=force_mavlink1) def gps2_raw_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age): ''' Second GPS data. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) fix_type : GPS fix type. (type:uint8_t, values:GPS_FIX_TYPE) lat : Latitude (WGS84) [degE7] (type:int32_t) lon : Longitude (WGS84) [degE7] (type:int32_t) alt : Altitude (MSL). Positive for up. [mm] (type:int32_t) eph : GPS HDOP horizontal dilution of position. If unknown, set to: UINT16_MAX [cm] (type:uint16_t) epv : GPS VDOP vertical dilution of position. If unknown, set to: UINT16_MAX [cm] (type:uint16_t) vel : GPS ground speed. If unknown, set to: UINT16_MAX [cm/s] (type:uint16_t) cog : Course over ground (NOT heading, but direction of movement): 0.0..359.99 degrees. If unknown, set to: UINT16_MAX [cdeg] (type:uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (type:uint8_t) dgps_numch : Number of DGPS satellites (type:uint8_t) dgps_age : Age of DGPS info [ms] (type:uint32_t) ''' return MAVLink_gps2_raw_message(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age) def gps2_raw_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age, force_mavlink1=False): ''' Second GPS data. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) fix_type : GPS fix type. (type:uint8_t, values:GPS_FIX_TYPE) lat : Latitude (WGS84) [degE7] (type:int32_t) lon : Longitude (WGS84) [degE7] (type:int32_t) alt : Altitude (MSL). Positive for up. [mm] (type:int32_t) eph : GPS HDOP horizontal dilution of position. If unknown, set to: UINT16_MAX [cm] (type:uint16_t) epv : GPS VDOP vertical dilution of position. If unknown, set to: UINT16_MAX [cm] (type:uint16_t) vel : GPS ground speed. If unknown, set to: UINT16_MAX [cm/s] (type:uint16_t) cog : Course over ground (NOT heading, but direction of movement): 0.0..359.99 degrees. If unknown, set to: UINT16_MAX [cdeg] (type:uint16_t) satellites_visible : Number of satellites visible. If unknown, set to 255 (type:uint8_t) dgps_numch : Number of DGPS satellites (type:uint8_t) dgps_age : Age of DGPS info [ms] (type:uint32_t) ''' return self.send(self.gps2_raw_encode(time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age), force_mavlink1=force_mavlink1) def power_status_encode(self, Vcc, Vservo, flags): ''' Power supply status Vcc : 5V rail voltage. [mV] (type:uint16_t) Vservo : Servo rail voltage. [mV] (type:uint16_t) flags : Bitmap of power supply status flags. (type:uint16_t, values:MAV_POWER_STATUS) ''' return MAVLink_power_status_message(Vcc, Vservo, flags) def power_status_send(self, Vcc, Vservo, flags, force_mavlink1=False): ''' Power supply status Vcc : 5V rail voltage. [mV] (type:uint16_t) Vservo : Servo rail voltage. [mV] (type:uint16_t) flags : Bitmap of power supply status flags. (type:uint16_t, values:MAV_POWER_STATUS) ''' return self.send(self.power_status_encode(Vcc, Vservo, flags), force_mavlink1=force_mavlink1) def serial_control_encode(self, device, flags, timeout, baudrate, count, data): ''' Control a serial port. This can be used for raw access to an onboard serial peripheral such as a GPS or telemetry radio. It is designed to make it possible to update the devices firmware via MAVLink messages or change the devices settings. A message with zero bytes can be used to change just the baudrate. device : Serial control device type. (type:uint8_t, values:SERIAL_CONTROL_DEV) flags : Bitmap of serial control flags. (type:uint8_t, values:SERIAL_CONTROL_FLAG) timeout : Timeout for reply data [ms] (type:uint16_t) baudrate : Baudrate of transfer. Zero means no change. [bits/s] (type:uint32_t) count : how many bytes in this transfer [bytes] (type:uint8_t) data : serial data (type:uint8_t) ''' return MAVLink_serial_control_message(device, flags, timeout, baudrate, count, data) def serial_control_send(self, device, flags, timeout, baudrate, count, data, force_mavlink1=False): ''' Control a serial port. This can be used for raw access to an onboard serial peripheral such as a GPS or telemetry radio. It is designed to make it possible to update the devices firmware via MAVLink messages or change the devices settings. A message with zero bytes can be used to change just the baudrate. device : Serial control device type. (type:uint8_t, values:SERIAL_CONTROL_DEV) flags : Bitmap of serial control flags. (type:uint8_t, values:SERIAL_CONTROL_FLAG) timeout : Timeout for reply data [ms] (type:uint16_t) baudrate : Baudrate of transfer. Zero means no change. [bits/s] (type:uint32_t) count : how many bytes in this transfer [bytes] (type:uint8_t) data : serial data (type:uint8_t) ''' return self.send(self.serial_control_encode(device, flags, timeout, baudrate, count, data), force_mavlink1=force_mavlink1) def gps_rtk_encode(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses): ''' RTK GPS data. Gives information on the relative baseline calculation the GPS is reporting time_last_baseline_ms : Time since boot of last baseline message received. [ms] (type:uint32_t) rtk_receiver_id : Identification of connected RTK receiver. (type:uint8_t) wn : GPS Week Number of last baseline (type:uint16_t) tow : GPS Time of Week of last baseline [ms] (type:uint32_t) rtk_health : GPS-specific health report for RTK data. (type:uint8_t) rtk_rate : Rate of baseline messages being received by GPS [Hz] (type:uint8_t) nsats : Current number of sats used for RTK calculation. (type:uint8_t) baseline_coords_type : Coordinate system of baseline (type:uint8_t, values:RTK_BASELINE_COORDINATE_SYSTEM) baseline_a_mm : Current baseline in ECEF x or NED north component. [mm] (type:int32_t) baseline_b_mm : Current baseline in ECEF y or NED east component. [mm] (type:int32_t) baseline_c_mm : Current baseline in ECEF z or NED down component. [mm] (type:int32_t) accuracy : Current estimate of baseline accuracy. (type:uint32_t) iar_num_hypotheses : Current number of integer ambiguity hypotheses. (type:int32_t) ''' return MAVLink_gps_rtk_message(time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses) def gps_rtk_send(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses, force_mavlink1=False): ''' RTK GPS data. Gives information on the relative baseline calculation the GPS is reporting time_last_baseline_ms : Time since boot of last baseline message received. [ms] (type:uint32_t) rtk_receiver_id : Identification of connected RTK receiver. (type:uint8_t) wn : GPS Week Number of last baseline (type:uint16_t) tow : GPS Time of Week of last baseline [ms] (type:uint32_t) rtk_health : GPS-specific health report for RTK data. (type:uint8_t) rtk_rate : Rate of baseline messages being received by GPS [Hz] (type:uint8_t) nsats : Current number of sats used for RTK calculation. (type:uint8_t) baseline_coords_type : Coordinate system of baseline (type:uint8_t, values:RTK_BASELINE_COORDINATE_SYSTEM) baseline_a_mm : Current baseline in ECEF x or NED north component. [mm] (type:int32_t) baseline_b_mm : Current baseline in ECEF y or NED east component. [mm] (type:int32_t) baseline_c_mm : Current baseline in ECEF z or NED down component. [mm] (type:int32_t) accuracy : Current estimate of baseline accuracy. (type:uint32_t) iar_num_hypotheses : Current number of integer ambiguity hypotheses. (type:int32_t) ''' return self.send(self.gps_rtk_encode(time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses), force_mavlink1=force_mavlink1) def gps2_rtk_encode(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses): ''' RTK GPS data. Gives information on the relative baseline calculation the GPS is reporting time_last_baseline_ms : Time since boot of last baseline message received. [ms] (type:uint32_t) rtk_receiver_id : Identification of connected RTK receiver. (type:uint8_t) wn : GPS Week Number of last baseline (type:uint16_t) tow : GPS Time of Week of last baseline [ms] (type:uint32_t) rtk_health : GPS-specific health report for RTK data. (type:uint8_t) rtk_rate : Rate of baseline messages being received by GPS [Hz] (type:uint8_t) nsats : Current number of sats used for RTK calculation. (type:uint8_t) baseline_coords_type : Coordinate system of baseline (type:uint8_t, values:RTK_BASELINE_COORDINATE_SYSTEM) baseline_a_mm : Current baseline in ECEF x or NED north component. [mm] (type:int32_t) baseline_b_mm : Current baseline in ECEF y or NED east component. [mm] (type:int32_t) baseline_c_mm : Current baseline in ECEF z or NED down component. [mm] (type:int32_t) accuracy : Current estimate of baseline accuracy. (type:uint32_t) iar_num_hypotheses : Current number of integer ambiguity hypotheses. (type:int32_t) ''' return MAVLink_gps2_rtk_message(time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses) def gps2_rtk_send(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses, force_mavlink1=False): ''' RTK GPS data. Gives information on the relative baseline calculation the GPS is reporting time_last_baseline_ms : Time since boot of last baseline message received. [ms] (type:uint32_t) rtk_receiver_id : Identification of connected RTK receiver. (type:uint8_t) wn : GPS Week Number of last baseline (type:uint16_t) tow : GPS Time of Week of last baseline [ms] (type:uint32_t) rtk_health : GPS-specific health report for RTK data. (type:uint8_t) rtk_rate : Rate of baseline messages being received by GPS [Hz] (type:uint8_t) nsats : Current number of sats used for RTK calculation. (type:uint8_t) baseline_coords_type : Coordinate system of baseline (type:uint8_t, values:RTK_BASELINE_COORDINATE_SYSTEM) baseline_a_mm : Current baseline in ECEF x or NED north component. [mm] (type:int32_t) baseline_b_mm : Current baseline in ECEF y or NED east component. [mm] (type:int32_t) baseline_c_mm : Current baseline in ECEF z or NED down component. [mm] (type:int32_t) accuracy : Current estimate of baseline accuracy. (type:uint32_t) iar_num_hypotheses : Current number of integer ambiguity hypotheses. (type:int32_t) ''' return self.send(self.gps2_rtk_encode(time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses), force_mavlink1=force_mavlink1) def scaled_imu3_encode(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0): ''' The RAW IMU readings for 3rd 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) xgyro : Angular speed around X axis [mrad/s] (type:int16_t) ygyro : Angular speed around Y axis [mrad/s] (type:int16_t) zgyro : Angular speed around Z axis [mrad/s] (type:int16_t) xmag : X Magnetic field [mgauss] (type:int16_t) ymag : Y Magnetic field [mgauss] (type:int16_t) zmag : Z Magnetic field [mgauss] (type:int16_t) temperature : Temperature, 0: IMU does not provide temperature values. If the IMU is at 0C it must send 1 (0.01C). [cdegC] (type:int16_t) ''' return MAVLink_scaled_imu3_message(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature) def scaled_imu3_send(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature=0, force_mavlink1=False): ''' The RAW IMU readings for 3rd 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) xacc : X acceleration [mG] (type:int16_t) yacc : Y acceleration [mG] (type:int16_t) zacc : Z acceleration [mG] (type:int16_t) xgyro : Angular speed around X axis [mrad/s] (type:int16_t) ygyro : Angular speed around Y axis [mrad/s] (type:int16_t) zgyro : Angular speed around Z axis [mrad/s] (type:int16_t) xmag : X Magnetic field [mgauss] (type:int16_t) ymag : Y Magnetic field [mgauss] (type:int16_t) zmag : Z Magnetic field [mgauss] (type:int16_t) temperature : Temperature, 0: IMU does not provide temperature values. If the IMU is at 0C it must send 1 (0.01C). [cdegC] (type:int16_t) ''' return self.send(self.scaled_imu3_encode(time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, temperature), force_mavlink1=force_mavlink1) def data_transmission_handshake_encode(self, type, size, width, height, packets, payload, jpg_quality): ''' Handshake message to initiate, control and stop image streaming when using the Image Transmission Protocol: https://mavlink .io/en/services/image_transmission.html. type : Type of requested/acknowledged data. (type:uint8_t, values:MAVLINK_DATA_STREAM_TYPE) size : total data size (set on ACK only). [bytes] (type:uint32_t) width : Width of a matrix or image. (type:uint16_t) height : Height of a matrix or image. (type:uint16_t) packets : Number of packets being sent (set on ACK only). (type:uint16_t) payload : Payload size per packet (normally 253 byte, see DATA field size in message ENCAPSULATED_DATA) (set on ACK only). [bytes] (type:uint8_t) jpg_quality : JPEG quality. Values: [1-100]. [%] (type:uint8_t) ''' return MAVLink_data_transmission_handshake_message(type, size, width, height, packets, payload, jpg_quality) def data_transmission_handshake_send(self, type, size, width, height, packets, payload, jpg_quality, force_mavlink1=False): ''' Handshake message to initiate, control and stop image streaming when using the Image Transmission Protocol: https://mavlink .io/en/services/image_transmission.html. type : Type of requested/acknowledged data. (type:uint8_t, values:MAVLINK_DATA_STREAM_TYPE) size : total data size (set on ACK only). [bytes] (type:uint32_t) width : Width of a matrix or image. (type:uint16_t) height : Height of a matrix or image. (type:uint16_t) packets : Number of packets being sent (set on ACK only). (type:uint16_t) payload : Payload size per packet (normally 253 byte, see DATA field size in message ENCAPSULATED_DATA) (set on ACK only). [bytes] (type:uint8_t) jpg_quality : JPEG quality. Values: [1-100]. [%] (type:uint8_t) ''' return self.send(self.data_transmission_handshake_encode(type, size, width, height, packets, payload, jpg_quality), force_mavlink1=force_mavlink1) def encapsulated_data_encode(self, seqnr, data): ''' Data packet for images sent using the Image Transmission Protocol: https://mavlink.io/en/services/image_transmission.html . seqnr : sequence number (starting with 0 on every transmission) (type:uint16_t) data : image data bytes (type:uint8_t) ''' return MAVLink_encapsulated_data_message(seqnr, data) def encapsulated_data_send(self, seqnr, data, force_mavlink1=False): ''' Data packet for images sent using the Image Transmission Protocol: https://mavlink.io/en/services/image_transmission.html . seqnr : sequence number (starting with 0 on every transmission) (type:uint16_t) data : image data bytes (type:uint8_t) ''' return self.send(self.encapsulated_data_encode(seqnr, data), force_mavlink1=force_mavlink1) def distance_sensor_encode(self, time_boot_ms, min_distance, max_distance, current_distance, type, id, orientation, covariance, horizontal_fov=0, vertical_fov=0, quaternion=[0,0,0,0]): ''' Distance sensor information for an onboard rangefinder. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) min_distance : Minimum distance the sensor can measure [cm] (type:uint16_t) max_distance : Maximum distance the sensor can measure [cm] (type:uint16_t) current_distance : Current distance reading [cm] (type:uint16_t) type : Type of distance sensor. (type:uint8_t, values:MAV_DISTANCE_SENSOR) id : Onboard ID of the sensor (type:uint8_t) orientation : Direction the sensor faces. downward-facing: ROTATION_PITCH_270, upward-facing: ROTATION_PITCH_90, backward-facing: ROTATION_PITCH_180, forward-facing: ROTATION_NONE, left-facing: ROTATION_YAW_90, right-facing: ROTATION_YAW_270 (type:uint8_t, values:MAV_SENSOR_ORIENTATION) covariance : Measurement variance. Max standard deviation is 6cm. 255 if unknown. [cm^2] (type:uint8_t) horizontal_fov : Horizontal Field of View (angle) where the distance measurement is valid and the field of view is known. Otherwise this is set to 0. [rad] (type:float) vertical_fov : Vertical Field of View (angle) where the distance measurement is valid and the field of view is known. Otherwise this is set to 0. [rad] (type:float) quaternion : Quaternion of the sensor orientation in vehicle body frame (w, x, y, z order, zero-rotation is 1, 0, 0, 0). Zero-rotation is along the vehicle body x-axis. This field is required if the orientation is set to MAV_SENSOR_ROTATION_CUSTOM. Set it to 0 if invalid." (type:float) ''' return MAVLink_distance_sensor_message(time_boot_ms, min_distance, max_distance, current_distance, type, id, orientation, covariance, horizontal_fov, vertical_fov, quaternion) def distance_sensor_send(self, time_boot_ms, min_distance, max_distance, current_distance, type, id, orientation, covariance, horizontal_fov=0, vertical_fov=0, quaternion=[0,0,0,0], force_mavlink1=False): ''' Distance sensor information for an onboard rangefinder. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) min_distance : Minimum distance the sensor can measure [cm] (type:uint16_t) max_distance : Maximum distance the sensor can measure [cm] (type:uint16_t) current_distance : Current distance reading [cm] (type:uint16_t) type : Type of distance sensor. (type:uint8_t, values:MAV_DISTANCE_SENSOR) id : Onboard ID of the sensor (type:uint8_t) orientation : Direction the sensor faces. downward-facing: ROTATION_PITCH_270, upward-facing: ROTATION_PITCH_90, backward-facing: ROTATION_PITCH_180, forward-facing: ROTATION_NONE, left-facing: ROTATION_YAW_90, right-facing: ROTATION_YAW_270 (type:uint8_t, values:MAV_SENSOR_ORIENTATION) covariance : Measurement variance. Max standard deviation is 6cm. 255 if unknown. [cm^2] (type:uint8_t) horizontal_fov : Horizontal Field of View (angle) where the distance measurement is valid and the field of view is known. Otherwise this is set to 0. [rad] (type:float) vertical_fov : Vertical Field of View (angle) where the distance measurement is valid and the field of view is known. Otherwise this is set to 0. [rad] (type:float) quaternion : Quaternion of the sensor orientation in vehicle body frame (w, x, y, z order, zero-rotation is 1, 0, 0, 0). Zero-rotation is along the vehicle body x-axis. This field is required if the orientation is set to MAV_SENSOR_ROTATION_CUSTOM. Set it to 0 if invalid." (type:float) ''' return self.send(self.distance_sensor_encode(time_boot_ms, min_distance, max_distance, current_distance, type, id, orientation, covariance, horizontal_fov, vertical_fov, quaternion), force_mavlink1=force_mavlink1) def terrain_request_encode(self, lat, lon, grid_spacing, mask): ''' Request for terrain data and terrain status lat : Latitude of SW corner of first grid [degE7] (type:int32_t) lon : Longitude of SW corner of first grid [degE7] (type:int32_t) grid_spacing : Grid spacing [m] (type:uint16_t) mask : Bitmask of requested 4x4 grids (row major 8x7 array of grids, 56 bits) (type:uint64_t) ''' return MAVLink_terrain_request_message(lat, lon, grid_spacing, mask) def terrain_request_send(self, lat, lon, grid_spacing, mask, force_mavlink1=False): ''' Request for terrain data and terrain status lat : Latitude of SW corner of first grid [degE7] (type:int32_t) lon : Longitude of SW corner of first grid [degE7] (type:int32_t) grid_spacing : Grid spacing [m] (type:uint16_t) mask : Bitmask of requested 4x4 grids (row major 8x7 array of grids, 56 bits) (type:uint64_t) ''' return self.send(self.terrain_request_encode(lat, lon, grid_spacing, mask), force_mavlink1=force_mavlink1) def terrain_data_encode(self, lat, lon, grid_spacing, gridbit, data): ''' Terrain data sent from GCS. The lat/lon and grid_spacing must be the same as a lat/lon from a TERRAIN_REQUEST lat : Latitude of SW corner of first grid [degE7] (type:int32_t) lon : Longitude of SW corner of first grid [degE7] (type:int32_t) grid_spacing : Grid spacing [m] (type:uint16_t) gridbit : bit within the terrain request mask (type:uint8_t) data : Terrain data MSL [m] (type:int16_t) ''' return MAVLink_terrain_data_message(lat, lon, grid_spacing, gridbit, data) def terrain_data_send(self, lat, lon, grid_spacing, gridbit, data, force_mavlink1=False): ''' Terrain data sent from GCS. The lat/lon and grid_spacing must be the same as a lat/lon from a TERRAIN_REQUEST lat : Latitude of SW corner of first grid [degE7] (type:int32_t) lon : Longitude of SW corner of first grid [degE7] (type:int32_t) grid_spacing : Grid spacing [m] (type:uint16_t) gridbit : bit within the terrain request mask (type:uint8_t) data : Terrain data MSL [m] (type:int16_t) ''' return self.send(self.terrain_data_encode(lat, lon, grid_spacing, gridbit, data), force_mavlink1=force_mavlink1) def terrain_check_encode(self, lat, lon): ''' Request that the vehicle report terrain height at the given location. Used by GCS to check if vehicle has all terrain data needed for a mission. lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) ''' return MAVLink_terrain_check_message(lat, lon) def terrain_check_send(self, lat, lon, force_mavlink1=False): ''' Request that the vehicle report terrain height at the given location. Used by GCS to check if vehicle has all terrain data needed for a mission. lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) ''' return self.send(self.terrain_check_encode(lat, lon), force_mavlink1=force_mavlink1) def terrain_report_encode(self, lat, lon, spacing, terrain_height, current_height, pending, loaded): ''' Response from a TERRAIN_CHECK request lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) spacing : grid spacing (zero if terrain at this location unavailable) (type:uint16_t) terrain_height : Terrain height MSL [m] (type:float) current_height : Current vehicle height above lat/lon terrain height [m] (type:float) pending : Number of 4x4 terrain blocks waiting to be received or read from disk (type:uint16_t) loaded : Number of 4x4 terrain blocks in memory (type:uint16_t) ''' return MAVLink_terrain_report_message(lat, lon, spacing, terrain_height, current_height, pending, loaded) def terrain_report_send(self, lat, lon, spacing, terrain_height, current_height, pending, loaded, force_mavlink1=False): ''' Response from a TERRAIN_CHECK request lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) spacing : grid spacing (zero if terrain at this location unavailable) (type:uint16_t) terrain_height : Terrain height MSL [m] (type:float) current_height : Current vehicle height above lat/lon terrain height [m] (type:float) pending : Number of 4x4 terrain blocks waiting to be received or read from disk (type:uint16_t) loaded : Number of 4x4 terrain blocks in memory (type:uint16_t) ''' return self.send(self.terrain_report_encode(lat, lon, spacing, terrain_height, current_height, pending, loaded), force_mavlink1=force_mavlink1) def scaled_pressure2_encode(self, time_boot_ms, press_abs, press_diff, temperature): ''' Barometer readings for 2nd barometer time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) press_abs : Absolute pressure [hPa] (type:float) press_diff : Differential pressure [hPa] (type:float) temperature : Temperature measurement [cdegC] (type:int16_t) ''' return MAVLink_scaled_pressure2_message(time_boot_ms, press_abs, press_diff, temperature) def scaled_pressure2_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False): ''' Barometer readings for 2nd barometer time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) press_abs : Absolute pressure [hPa] (type:float) press_diff : Differential pressure [hPa] (type:float) temperature : Temperature measurement [cdegC] (type:int16_t) ''' return self.send(self.scaled_pressure2_encode(time_boot_ms, press_abs, press_diff, temperature), force_mavlink1=force_mavlink1) def att_pos_mocap_encode(self, time_usec, q, x, y, z, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]): ''' Motion capture attitude and position time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) q : Attitude quaternion (w, x, y, z order, zero-rotation is 1, 0, 0, 0) (type:float) x : X position (NED) [m] (type:float) y : Y position (NED) [m] (type:float) z : Z position (NED) [m] (type:float) covariance : Row-major representation of a pose 6x6 cross-covariance matrix upper right triangle (states: x, y, z, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return MAVLink_att_pos_mocap_message(time_usec, q, x, y, z, covariance) def att_pos_mocap_send(self, time_usec, q, x, y, z, covariance=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], force_mavlink1=False): ''' Motion capture attitude and position time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) q : Attitude quaternion (w, x, y, z order, zero-rotation is 1, 0, 0, 0) (type:float) x : X position (NED) [m] (type:float) y : Y position (NED) [m] (type:float) z : Z position (NED) [m] (type:float) covariance : Row-major representation of a pose 6x6 cross-covariance matrix upper right triangle (states: x, y, z, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) ''' return self.send(self.att_pos_mocap_encode(time_usec, q, x, y, z, covariance), force_mavlink1=force_mavlink1) def set_actuator_control_target_encode(self, time_usec, group_mlx, target_system, target_component, controls): ''' Set the vehicle attitude and body angular rates. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) group_mlx : Actuator group. The "_mlx" indicates this is a multi-instance message and a MAVLink parser should use this field to difference between instances. (type:uint8_t) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) controls : Actuator controls. Normed to -1..+1 where 0 is neutral position. Throttle for single rotation direction motors is 0..1, negative range for reverse direction. Standard mapping for attitude controls (group 0): (index 0-7): roll, pitch, yaw, throttle, flaps, spoilers, airbrakes, landing gear. Load a pass-through mixer to repurpose them as generic outputs. (type:float) ''' return MAVLink_set_actuator_control_target_message(time_usec, group_mlx, target_system, target_component, controls) def set_actuator_control_target_send(self, time_usec, group_mlx, target_system, target_component, controls, force_mavlink1=False): ''' Set the vehicle attitude and body angular rates. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) group_mlx : Actuator group. The "_mlx" indicates this is a multi-instance message and a MAVLink parser should use this field to difference between instances. (type:uint8_t) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) controls : Actuator controls. Normed to -1..+1 where 0 is neutral position. Throttle for single rotation direction motors is 0..1, negative range for reverse direction. Standard mapping for attitude controls (group 0): (index 0-7): roll, pitch, yaw, throttle, flaps, spoilers, airbrakes, landing gear. Load a pass-through mixer to repurpose them as generic outputs. (type:float) ''' return self.send(self.set_actuator_control_target_encode(time_usec, group_mlx, target_system, target_component, controls), force_mavlink1=force_mavlink1) def actuator_control_target_encode(self, time_usec, group_mlx, controls): ''' Set the vehicle attitude and body angular rates. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) group_mlx : Actuator group. The "_mlx" indicates this is a multi-instance message and a MAVLink parser should use this field to difference between instances. (type:uint8_t) controls : Actuator controls. Normed to -1..+1 where 0 is neutral position. Throttle for single rotation direction motors is 0..1, negative range for reverse direction. Standard mapping for attitude controls (group 0): (index 0-7): roll, pitch, yaw, throttle, flaps, spoilers, airbrakes, landing gear. Load a pass-through mixer to repurpose them as generic outputs. (type:float) ''' return MAVLink_actuator_control_target_message(time_usec, group_mlx, controls) def actuator_control_target_send(self, time_usec, group_mlx, controls, force_mavlink1=False): ''' Set the vehicle attitude and body angular rates. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) group_mlx : Actuator group. The "_mlx" indicates this is a multi-instance message and a MAVLink parser should use this field to difference between instances. (type:uint8_t) controls : Actuator controls. Normed to -1..+1 where 0 is neutral position. Throttle for single rotation direction motors is 0..1, negative range for reverse direction. Standard mapping for attitude controls (group 0): (index 0-7): roll, pitch, yaw, throttle, flaps, spoilers, airbrakes, landing gear. Load a pass-through mixer to repurpose them as generic outputs. (type:float) ''' return self.send(self.actuator_control_target_encode(time_usec, group_mlx, controls), force_mavlink1=force_mavlink1) def altitude_encode(self, time_usec, altitude_monotonic, altitude_amsl, altitude_local, altitude_relative, altitude_terrain, bottom_clearance): ''' The current system altitude. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) altitude_monotonic : This altitude measure is initialized on system boot and monotonic (it is never reset, but represents the local altitude change). The only guarantee on this field is that it will never be reset and is consistent within a flight. The recommended value for this field is the uncorrected barometric altitude at boot time. This altitude will also drift and vary between flights. [m] (type:float) altitude_amsl : This altitude measure is strictly above mean sea level and might be non-monotonic (it might reset on events like GPS lock or when a new QNH value is set). It should be the altitude to which global altitude waypoints are compared to. Note that it is *not* the GPS altitude, however, most GPS modules already output MSL by default and not the WGS84 altitude. [m] (type:float) altitude_local : This is the local altitude in the local coordinate frame. It is not the altitude above home, but in reference to the coordinate origin (0, 0, 0). It is up-positive. [m] (type:float) altitude_relative : This is the altitude above the home position. It resets on each change of the current home position. [m] (type:float) altitude_terrain : This is the altitude above terrain. It might be fed by a terrain database or an altimeter. Values smaller than -1000 should be interpreted as unknown. [m] (type:float) bottom_clearance : This is not the altitude, but the clear space below the system according to the fused clearance estimate. It generally should max out at the maximum range of e.g. the laser altimeter. It is generally a moving target. A negative value indicates no measurement available. [m] (type:float) ''' return MAVLink_altitude_message(time_usec, altitude_monotonic, altitude_amsl, altitude_local, altitude_relative, altitude_terrain, bottom_clearance) def altitude_send(self, time_usec, altitude_monotonic, altitude_amsl, altitude_local, altitude_relative, altitude_terrain, bottom_clearance, force_mavlink1=False): ''' The current system altitude. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) altitude_monotonic : This altitude measure is initialized on system boot and monotonic (it is never reset, but represents the local altitude change). The only guarantee on this field is that it will never be reset and is consistent within a flight. The recommended value for this field is the uncorrected barometric altitude at boot time. This altitude will also drift and vary between flights. [m] (type:float) altitude_amsl : This altitude measure is strictly above mean sea level and might be non-monotonic (it might reset on events like GPS lock or when a new QNH value is set). It should be the altitude to which global altitude waypoints are compared to. Note that it is *not* the GPS altitude, however, most GPS modules already output MSL by default and not the WGS84 altitude. [m] (type:float) altitude_local : This is the local altitude in the local coordinate frame. It is not the altitude above home, but in reference to the coordinate origin (0, 0, 0). It is up-positive. [m] (type:float) altitude_relative : This is the altitude above the home position. It resets on each change of the current home position. [m] (type:float) altitude_terrain : This is the altitude above terrain. It might be fed by a terrain database or an altimeter. Values smaller than -1000 should be interpreted as unknown. [m] (type:float) bottom_clearance : This is not the altitude, but the clear space below the system according to the fused clearance estimate. It generally should max out at the maximum range of e.g. the laser altimeter. It is generally a moving target. A negative value indicates no measurement available. [m] (type:float) ''' return self.send(self.altitude_encode(time_usec, altitude_monotonic, altitude_amsl, altitude_local, altitude_relative, altitude_terrain, bottom_clearance), force_mavlink1=force_mavlink1) def resource_request_encode(self, request_id, uri_type, uri, transfer_type, storage): ''' The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI contents (type:uint8_t) uri_type : The type of requested URI. 0 = a file via URL. 1 = a UAVCAN binary (type:uint8_t) uri : The requested unique resource identifier (URI). It is not necessarily a straight domain name (depends on the URI type enum) (type:uint8_t) transfer_type : The way the autopilot wants to receive the URI. 0 = MAVLink FTP. 1 = binary stream. (type:uint8_t) storage : The storage path the autopilot wants the URI to be stored in. Will only be valid if the transfer_type has a storage associated (e.g. MAVLink FTP). (type:uint8_t) ''' return MAVLink_resource_request_message(request_id, uri_type, uri, transfer_type, storage) def resource_request_send(self, request_id, uri_type, uri, transfer_type, storage, force_mavlink1=False): ''' The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI contents (type:uint8_t) uri_type : The type of requested URI. 0 = a file via URL. 1 = a UAVCAN binary (type:uint8_t) uri : The requested unique resource identifier (URI). It is not necessarily a straight domain name (depends on the URI type enum) (type:uint8_t) transfer_type : The way the autopilot wants to receive the URI. 0 = MAVLink FTP. 1 = binary stream. (type:uint8_t) storage : The storage path the autopilot wants the URI to be stored in. Will only be valid if the transfer_type has a storage associated (e.g. MAVLink FTP). (type:uint8_t) ''' return self.send(self.resource_request_encode(request_id, uri_type, uri, transfer_type, storage), force_mavlink1=force_mavlink1) def scaled_pressure3_encode(self, time_boot_ms, press_abs, press_diff, temperature): ''' Barometer readings for 3rd barometer time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) press_abs : Absolute pressure [hPa] (type:float) press_diff : Differential pressure [hPa] (type:float) temperature : Temperature measurement [cdegC] (type:int16_t) ''' return MAVLink_scaled_pressure3_message(time_boot_ms, press_abs, press_diff, temperature) def scaled_pressure3_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False): ''' Barometer readings for 3rd barometer time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) press_abs : Absolute pressure [hPa] (type:float) press_diff : Differential pressure [hPa] (type:float) temperature : Temperature measurement [cdegC] (type:int16_t) ''' return self.send(self.scaled_pressure3_encode(time_boot_ms, press_abs, press_diff, temperature), force_mavlink1=force_mavlink1) def follow_target_encode(self, timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state): ''' Current motion information from a designated system timestamp : Timestamp (time since system boot). [ms] (type:uint64_t) est_capabilities : bit positions for tracker reporting capabilities (POS = 0, VEL = 1, ACCEL = 2, ATT + RATES = 3) (type:uint8_t) lat : Latitude (WGS84) [degE7] (type:int32_t) lon : Longitude (WGS84) [degE7] (type:int32_t) alt : Altitude (MSL) [m] (type:float) vel : target velocity (0,0,0) for unknown [m/s] (type:float) acc : linear target acceleration (0,0,0) for unknown [m/s/s] (type:float) attitude_q : (1 0 0 0 for unknown) (type:float) rates : (0 0 0 for unknown) (type:float) position_cov : eph epv (type:float) custom_state : button states or switches of a tracker device (type:uint64_t) ''' return MAVLink_follow_target_message(timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state) def follow_target_send(self, timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state, force_mavlink1=False): ''' Current motion information from a designated system timestamp : Timestamp (time since system boot). [ms] (type:uint64_t) est_capabilities : bit positions for tracker reporting capabilities (POS = 0, VEL = 1, ACCEL = 2, ATT + RATES = 3) (type:uint8_t) lat : Latitude (WGS84) [degE7] (type:int32_t) lon : Longitude (WGS84) [degE7] (type:int32_t) alt : Altitude (MSL) [m] (type:float) vel : target velocity (0,0,0) for unknown [m/s] (type:float) acc : linear target acceleration (0,0,0) for unknown [m/s/s] (type:float) attitude_q : (1 0 0 0 for unknown) (type:float) rates : (0 0 0 for unknown) (type:float) position_cov : eph epv (type:float) custom_state : button states or switches of a tracker device (type:uint64_t) ''' return self.send(self.follow_target_encode(timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state), force_mavlink1=force_mavlink1) def control_system_state_encode(self, time_usec, x_acc, y_acc, z_acc, x_vel, y_vel, z_vel, x_pos, y_pos, z_pos, airspeed, vel_variance, pos_variance, q, roll_rate, pitch_rate, yaw_rate): ''' The smoothed, monotonic system state used to feed the control loops of the system. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) x_acc : X acceleration in body frame [m/s/s] (type:float) y_acc : Y acceleration in body frame [m/s/s] (type:float) z_acc : Z acceleration in body frame [m/s/s] (type:float) x_vel : X velocity in body frame [m/s] (type:float) y_vel : Y velocity in body frame [m/s] (type:float) z_vel : Z velocity in body frame [m/s] (type:float) x_pos : X position in local frame [m] (type:float) y_pos : Y position in local frame [m] (type:float) z_pos : Z position in local frame [m] (type:float) airspeed : Airspeed, set to -1 if unknown [m/s] (type:float) vel_variance : Variance of body velocity estimate (type:float) pos_variance : Variance in local position (type:float) q : The attitude, represented as Quaternion (type:float) roll_rate : Angular rate in roll axis [rad/s] (type:float) pitch_rate : Angular rate in pitch axis [rad/s] (type:float) yaw_rate : Angular rate in yaw axis [rad/s] (type:float) ''' return MAVLink_control_system_state_message(time_usec, x_acc, y_acc, z_acc, x_vel, y_vel, z_vel, x_pos, y_pos, z_pos, airspeed, vel_variance, pos_variance, q, roll_rate, pitch_rate, yaw_rate) def control_system_state_send(self, time_usec, x_acc, y_acc, z_acc, x_vel, y_vel, z_vel, x_pos, y_pos, z_pos, airspeed, vel_variance, pos_variance, q, roll_rate, pitch_rate, yaw_rate, force_mavlink1=False): ''' The smoothed, monotonic system state used to feed the control loops of the system. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) x_acc : X acceleration in body frame [m/s/s] (type:float) y_acc : Y acceleration in body frame [m/s/s] (type:float) z_acc : Z acceleration in body frame [m/s/s] (type:float) x_vel : X velocity in body frame [m/s] (type:float) y_vel : Y velocity in body frame [m/s] (type:float) z_vel : Z velocity in body frame [m/s] (type:float) x_pos : X position in local frame [m] (type:float) y_pos : Y position in local frame [m] (type:float) z_pos : Z position in local frame [m] (type:float) airspeed : Airspeed, set to -1 if unknown [m/s] (type:float) vel_variance : Variance of body velocity estimate (type:float) pos_variance : Variance in local position (type:float) q : The attitude, represented as Quaternion (type:float) roll_rate : Angular rate in roll axis [rad/s] (type:float) pitch_rate : Angular rate in pitch axis [rad/s] (type:float) yaw_rate : Angular rate in yaw axis [rad/s] (type:float) ''' return self.send(self.control_system_state_encode(time_usec, x_acc, y_acc, z_acc, x_vel, y_vel, z_vel, x_pos, y_pos, z_pos, airspeed, vel_variance, pos_variance, q, roll_rate, pitch_rate, yaw_rate), force_mavlink1=force_mavlink1) def battery_status_encode(self, id, battery_function, type, temperature, voltages, current_battery, current_consumed, energy_consumed, battery_remaining, time_remaining=0, charge_state=0): ''' Battery information id : Battery ID (type:uint8_t) battery_function : Function of the battery (type:uint8_t, values:MAV_BATTERY_FUNCTION) type : Type (chemistry) of the battery (type:uint8_t, values:MAV_BATTERY_TYPE) temperature : Temperature of the battery. INT16_MAX for unknown temperature. [cdegC] (type:int16_t) voltages : Battery voltage of cells. Cells above the valid cell count for this battery should have the UINT16_MAX value. [mV] (type:uint16_t) current_battery : Battery current, -1: autopilot does not measure the current [cA] (type:int16_t) current_consumed : Consumed charge, -1: autopilot does not provide consumption estimate [mAh] (type:int32_t) energy_consumed : Consumed energy, -1: autopilot does not provide energy consumption estimate [hJ] (type:int32_t) battery_remaining : Remaining battery energy. Values: [0-100], -1: autopilot does not estimate the remaining battery. [%] (type:int8_t) time_remaining : Remaining battery time, 0: autopilot does not provide remaining battery time estimate [s] (type:int32_t) charge_state : State for extent of discharge, provided by autopilot for warning or external reactions (type:uint8_t, values:MAV_BATTERY_CHARGE_STATE) ''' return MAVLink_battery_status_message(id, battery_function, type, temperature, voltages, current_battery, current_consumed, energy_consumed, battery_remaining, time_remaining, charge_state) def battery_status_send(self, id, battery_function, type, temperature, voltages, current_battery, current_consumed, energy_consumed, battery_remaining, time_remaining=0, charge_state=0, force_mavlink1=False): ''' Battery information id : Battery ID (type:uint8_t) battery_function : Function of the battery (type:uint8_t, values:MAV_BATTERY_FUNCTION) type : Type (chemistry) of the battery (type:uint8_t, values:MAV_BATTERY_TYPE) temperature : Temperature of the battery. INT16_MAX for unknown temperature. [cdegC] (type:int16_t) voltages : Battery voltage of cells. Cells above the valid cell count for this battery should have the UINT16_MAX value. [mV] (type:uint16_t) current_battery : Battery current, -1: autopilot does not measure the current [cA] (type:int16_t) current_consumed : Consumed charge, -1: autopilot does not provide consumption estimate [mAh] (type:int32_t) energy_consumed : Consumed energy, -1: autopilot does not provide energy consumption estimate [hJ] (type:int32_t) battery_remaining : Remaining battery energy. Values: [0-100], -1: autopilot does not estimate the remaining battery. [%] (type:int8_t) time_remaining : Remaining battery time, 0: autopilot does not provide remaining battery time estimate [s] (type:int32_t) charge_state : State for extent of discharge, provided by autopilot for warning or external reactions (type:uint8_t, values:MAV_BATTERY_CHARGE_STATE) ''' return self.send(self.battery_status_encode(id, battery_function, type, temperature, voltages, current_battery, current_consumed, energy_consumed, battery_remaining, time_remaining, charge_state), force_mavlink1=force_mavlink1) def autopilot_version_encode(self, capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid, uid2=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]): ''' Version and capability of autopilot software. This should be emitted in response to a MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES command. capabilities : Bitmap of capabilities (type:uint64_t, values:MAV_PROTOCOL_CAPABILITY) flight_sw_version : Firmware version number (type:uint32_t) middleware_sw_version : Middleware version number (type:uint32_t) os_sw_version : Operating system version number (type:uint32_t) board_version : HW / board version (last 8 bytes should be silicon ID, if any) (type:uint32_t) flight_custom_version : Custom version field, commonly the first 8 bytes of the git hash. This is not an unique identifier, but should allow to identify the commit using the main version number even for very large code bases. (type:uint8_t) middleware_custom_version : Custom version field, commonly the first 8 bytes of the git hash. This is not an unique identifier, but should allow to identify the commit using the main version number even for very large code bases. (type:uint8_t) os_custom_version : Custom version field, commonly the first 8 bytes of the git hash. This is not an unique identifier, but should allow to identify the commit using the main version number even for very large code bases. (type:uint8_t) vendor_id : ID of the board vendor (type:uint16_t) product_id : ID of the product (type:uint16_t) uid : UID if provided by hardware (see uid2) (type:uint64_t) uid2 : UID if provided by hardware (supersedes the uid field. If this is non-zero, use this field, otherwise use uid) (type:uint8_t) ''' return MAVLink_autopilot_version_message(capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid, uid2) def autopilot_version_send(self, capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid, uid2=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], force_mavlink1=False): ''' Version and capability of autopilot software. This should be emitted in response to a MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES command. capabilities : Bitmap of capabilities (type:uint64_t, values:MAV_PROTOCOL_CAPABILITY) flight_sw_version : Firmware version number (type:uint32_t) middleware_sw_version : Middleware version number (type:uint32_t) os_sw_version : Operating system version number (type:uint32_t) board_version : HW / board version (last 8 bytes should be silicon ID, if any) (type:uint32_t) flight_custom_version : Custom version field, commonly the first 8 bytes of the git hash. This is not an unique identifier, but should allow to identify the commit using the main version number even for very large code bases. (type:uint8_t) middleware_custom_version : Custom version field, commonly the first 8 bytes of the git hash. This is not an unique identifier, but should allow to identify the commit using the main version number even for very large code bases. (type:uint8_t) os_custom_version : Custom version field, commonly the first 8 bytes of the git hash. This is not an unique identifier, but should allow to identify the commit using the main version number even for very large code bases. (type:uint8_t) vendor_id : ID of the board vendor (type:uint16_t) product_id : ID of the product (type:uint16_t) uid : UID if provided by hardware (see uid2) (type:uint64_t) uid2 : UID if provided by hardware (supersedes the uid field. If this is non-zero, use this field, otherwise use uid) (type:uint8_t) ''' return self.send(self.autopilot_version_encode(capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid, uid2), force_mavlink1=force_mavlink1) def landing_target_encode(self, time_usec, target_num, frame, angle_x, angle_y, distance, size_x, size_y, x=0, y=0, z=0, q=[0,0,0,0], type=0, position_valid=0): ''' The location of a landing target. See: https://mavlink.io/en/services/landing_target.html time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) target_num : The ID of the target if multiple targets are present (type:uint8_t) frame : Coordinate frame used for following fields. (type:uint8_t, values:MAV_FRAME) angle_x : X-axis angular offset of the target from the center of the image [rad] (type:float) angle_y : Y-axis angular offset of the target from the center of the image [rad] (type:float) distance : Distance to the target from the vehicle [m] (type:float) size_x : Size of target along x-axis [rad] (type:float) size_y : Size of target along y-axis [rad] (type:float) x : X Position of the landing target in MAV_FRAME [m] (type:float) y : Y Position of the landing target in MAV_FRAME [m] (type:float) z : Z Position of the landing target in MAV_FRAME [m] (type:float) q : Quaternion of landing target orientation (w, x, y, z order, zero-rotation is 1, 0, 0, 0) (type:float) type : Type of landing target (type:uint8_t, values:LANDING_TARGET_TYPE) position_valid : Boolean indicating whether the position fields (x, y, z, q, type) contain valid target position information (valid: 1, invalid: 0). Default is 0 (invalid). (type:uint8_t) ''' return MAVLink_landing_target_message(time_usec, target_num, frame, angle_x, angle_y, distance, size_x, size_y, x, y, z, q, type, position_valid) def landing_target_send(self, time_usec, target_num, frame, angle_x, angle_y, distance, size_x, size_y, x=0, y=0, z=0, q=[0,0,0,0], type=0, position_valid=0, force_mavlink1=False): ''' The location of a landing target. See: https://mavlink.io/en/services/landing_target.html time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) target_num : The ID of the target if multiple targets are present (type:uint8_t) frame : Coordinate frame used for following fields. (type:uint8_t, values:MAV_FRAME) angle_x : X-axis angular offset of the target from the center of the image [rad] (type:float) angle_y : Y-axis angular offset of the target from the center of the image [rad] (type:float) distance : Distance to the target from the vehicle [m] (type:float) size_x : Size of target along x-axis [rad] (type:float) size_y : Size of target along y-axis [rad] (type:float) x : X Position of the landing target in MAV_FRAME [m] (type:float) y : Y Position of the landing target in MAV_FRAME [m] (type:float) z : Z Position of the landing target in MAV_FRAME [m] (type:float) q : Quaternion of landing target orientation (w, x, y, z order, zero-rotation is 1, 0, 0, 0) (type:float) type : Type of landing target (type:uint8_t, values:LANDING_TARGET_TYPE) position_valid : Boolean indicating whether the position fields (x, y, z, q, type) contain valid target position information (valid: 1, invalid: 0). Default is 0 (invalid). (type:uint8_t) ''' return self.send(self.landing_target_encode(time_usec, target_num, frame, angle_x, angle_y, distance, size_x, size_y, x, y, z, q, type, position_valid), force_mavlink1=force_mavlink1) def fence_status_encode(self, breach_status, breach_count, breach_type, breach_time): ''' Status of geo-fencing. Sent in extended status stream when fencing enabled. breach_status : Breach status (0 if currently inside fence, 1 if outside). (type:uint8_t) breach_count : Number of fence breaches. (type:uint16_t) breach_type : Last breach type. (type:uint8_t, values:FENCE_BREACH) breach_time : Time (since boot) of last breach. [ms] (type:uint32_t) ''' return MAVLink_fence_status_message(breach_status, breach_count, breach_type, breach_time) def fence_status_send(self, breach_status, breach_count, breach_type, breach_time, force_mavlink1=False): ''' Status of geo-fencing. Sent in extended status stream when fencing enabled. breach_status : Breach status (0 if currently inside fence, 1 if outside). (type:uint8_t) breach_count : Number of fence breaches. (type:uint16_t) breach_type : Last breach type. (type:uint8_t, values:FENCE_BREACH) breach_time : Time (since boot) of last breach. [ms] (type:uint32_t) ''' return self.send(self.fence_status_encode(breach_status, breach_count, breach_type, breach_time), force_mavlink1=force_mavlink1) def estimator_status_encode(self, time_usec, flags, vel_ratio, pos_horiz_ratio, pos_vert_ratio, mag_ratio, hagl_ratio, tas_ratio, pos_horiz_accuracy, pos_vert_accuracy): ''' Estimator status message including flags, innovation test ratios and estimated accuracies. The flags message is an integer bitmask containing information on which EKF outputs are valid. See the ESTIMATOR_STATUS_FLAGS enum definition for further information. The innovation test ratios show the magnitude of the sensor innovation divided by the innovation check threshold. Under normal operation the innovation test ratios should be below 0.5 with occasional values up to 1.0. Values greater than 1.0 should be rare under normal operation and indicate that a measurement has been rejected by the filter. The user should be notified if an innovation test ratio greater than 1.0 is recorded. Notifications for values in the range between 0.5 and 1.0 should be optional and controllable by the user. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) flags : Bitmap indicating which EKF outputs are valid. (type:uint16_t, values:ESTIMATOR_STATUS_FLAGS) vel_ratio : Velocity innovation test ratio (type:float) pos_horiz_ratio : Horizontal position innovation test ratio (type:float) pos_vert_ratio : Vertical position innovation test ratio (type:float) mag_ratio : Magnetometer innovation test ratio (type:float) hagl_ratio : Height above terrain innovation test ratio (type:float) tas_ratio : True airspeed innovation test ratio (type:float) pos_horiz_accuracy : Horizontal position 1-STD accuracy relative to the EKF local origin [m] (type:float) pos_vert_accuracy : Vertical position 1-STD accuracy relative to the EKF local origin [m] (type:float) ''' return MAVLink_estimator_status_message(time_usec, flags, vel_ratio, pos_horiz_ratio, pos_vert_ratio, mag_ratio, hagl_ratio, tas_ratio, pos_horiz_accuracy, pos_vert_accuracy) def estimator_status_send(self, time_usec, flags, vel_ratio, pos_horiz_ratio, pos_vert_ratio, mag_ratio, hagl_ratio, tas_ratio, pos_horiz_accuracy, pos_vert_accuracy, force_mavlink1=False): ''' Estimator status message including flags, innovation test ratios and estimated accuracies. The flags message is an integer bitmask containing information on which EKF outputs are valid. See the ESTIMATOR_STATUS_FLAGS enum definition for further information. The innovation test ratios show the magnitude of the sensor innovation divided by the innovation check threshold. Under normal operation the innovation test ratios should be below 0.5 with occasional values up to 1.0. Values greater than 1.0 should be rare under normal operation and indicate that a measurement has been rejected by the filter. The user should be notified if an innovation test ratio greater than 1.0 is recorded. Notifications for values in the range between 0.5 and 1.0 should be optional and controllable by the user. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) flags : Bitmap indicating which EKF outputs are valid. (type:uint16_t, values:ESTIMATOR_STATUS_FLAGS) vel_ratio : Velocity innovation test ratio (type:float) pos_horiz_ratio : Horizontal position innovation test ratio (type:float) pos_vert_ratio : Vertical position innovation test ratio (type:float) mag_ratio : Magnetometer innovation test ratio (type:float) hagl_ratio : Height above terrain innovation test ratio (type:float) tas_ratio : True airspeed innovation test ratio (type:float) pos_horiz_accuracy : Horizontal position 1-STD accuracy relative to the EKF local origin [m] (type:float) pos_vert_accuracy : Vertical position 1-STD accuracy relative to the EKF local origin [m] (type:float) ''' return self.send(self.estimator_status_encode(time_usec, flags, vel_ratio, pos_horiz_ratio, pos_vert_ratio, mag_ratio, hagl_ratio, tas_ratio, pos_horiz_accuracy, pos_vert_accuracy), force_mavlink1=force_mavlink1) def wind_cov_encode(self, time_usec, wind_x, wind_y, wind_z, var_horiz, var_vert, wind_alt, horiz_accuracy, vert_accuracy): ''' Wind covariance estimate from vehicle. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) wind_x : Wind in X (NED) direction [m/s] (type:float) wind_y : Wind in Y (NED) direction [m/s] (type:float) wind_z : Wind in Z (NED) direction [m/s] (type:float) var_horiz : Variability of the wind in XY. RMS of a 1 Hz lowpassed wind estimate. [m/s] (type:float) var_vert : Variability of the wind in Z. RMS of a 1 Hz lowpassed wind estimate. [m/s] (type:float) wind_alt : Altitude (MSL) that this measurement was taken at [m] (type:float) horiz_accuracy : Horizontal speed 1-STD accuracy [m] (type:float) vert_accuracy : Vertical speed 1-STD accuracy [m] (type:float) ''' return MAVLink_wind_cov_message(time_usec, wind_x, wind_y, wind_z, var_horiz, var_vert, wind_alt, horiz_accuracy, vert_accuracy) def wind_cov_send(self, time_usec, wind_x, wind_y, wind_z, var_horiz, var_vert, wind_alt, horiz_accuracy, vert_accuracy, force_mavlink1=False): ''' Wind covariance estimate from vehicle. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) wind_x : Wind in X (NED) direction [m/s] (type:float) wind_y : Wind in Y (NED) direction [m/s] (type:float) wind_z : Wind in Z (NED) direction [m/s] (type:float) var_horiz : Variability of the wind in XY. RMS of a 1 Hz lowpassed wind estimate. [m/s] (type:float) var_vert : Variability of the wind in Z. RMS of a 1 Hz lowpassed wind estimate. [m/s] (type:float) wind_alt : Altitude (MSL) that this measurement was taken at [m] (type:float) horiz_accuracy : Horizontal speed 1-STD accuracy [m] (type:float) vert_accuracy : Vertical speed 1-STD accuracy [m] (type:float) ''' return self.send(self.wind_cov_encode(time_usec, wind_x, wind_y, wind_z, var_horiz, var_vert, wind_alt, horiz_accuracy, vert_accuracy), force_mavlink1=force_mavlink1) def gps_input_encode(self, time_usec, gps_id, ignore_flags, time_week_ms, time_week, fix_type, lat, lon, alt, hdop, vdop, vn, ve, vd, speed_accuracy, horiz_accuracy, vert_accuracy, satellites_visible, yaw=0): ''' GPS sensor input message. This is a raw sensor value sent by the GPS. This is NOT the global position estimate of the system. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) gps_id : ID of the GPS for multiple GPS inputs (type:uint8_t) ignore_flags : Bitmap indicating which GPS input flags fields to ignore. All other fields must be provided. (type:uint16_t, values:GPS_INPUT_IGNORE_FLAGS) time_week_ms : GPS time (from start of GPS week) [ms] (type:uint32_t) time_week : GPS week number (type:uint16_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. 4: 3D with DGPS. 5: 3D with RTK (type:uint8_t) lat : Latitude (WGS84) [degE7] (type:int32_t) lon : Longitude (WGS84) [degE7] (type:int32_t) alt : Altitude (MSL). Positive for up. [m] (type:float) hdop : GPS HDOP horizontal dilution of position [m] (type:float) vdop : GPS VDOP vertical dilution of position [m] (type:float) vn : GPS velocity in NORTH direction in earth-fixed NED frame [m/s] (type:float) ve : GPS velocity in EAST direction in earth-fixed NED frame [m/s] (type:float) vd : GPS velocity in DOWN direction in earth-fixed NED frame [m/s] (type:float) speed_accuracy : GPS speed accuracy [m/s] (type:float) horiz_accuracy : GPS horizontal accuracy [m] (type:float) vert_accuracy : GPS vertical accuracy [m] (type:float) satellites_visible : Number of satellites visible. (type:uint8_t) yaw : Yaw of vehicle, zero means not available, use 36000 for north [cdeg] (type:uint16_t) ''' return MAVLink_gps_input_message(time_usec, gps_id, ignore_flags, time_week_ms, time_week, fix_type, lat, lon, alt, hdop, vdop, vn, ve, vd, speed_accuracy, horiz_accuracy, vert_accuracy, satellites_visible, yaw) def gps_input_send(self, time_usec, gps_id, ignore_flags, time_week_ms, time_week, fix_type, lat, lon, alt, hdop, vdop, vn, ve, vd, speed_accuracy, horiz_accuracy, vert_accuracy, satellites_visible, yaw=0, force_mavlink1=False): ''' GPS sensor input message. This is a raw sensor value sent by the GPS. This is NOT the global position estimate of the system. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) gps_id : ID of the GPS for multiple GPS inputs (type:uint8_t) ignore_flags : Bitmap indicating which GPS input flags fields to ignore. All other fields must be provided. (type:uint16_t, values:GPS_INPUT_IGNORE_FLAGS) time_week_ms : GPS time (from start of GPS week) [ms] (type:uint32_t) time_week : GPS week number (type:uint16_t) fix_type : 0-1: no fix, 2: 2D fix, 3: 3D fix. 4: 3D with DGPS. 5: 3D with RTK (type:uint8_t) lat : Latitude (WGS84) [degE7] (type:int32_t) lon : Longitude (WGS84) [degE7] (type:int32_t) alt : Altitude (MSL). Positive for up. [m] (type:float) hdop : GPS HDOP horizontal dilution of position [m] (type:float) vdop : GPS VDOP vertical dilution of position [m] (type:float) vn : GPS velocity in NORTH direction in earth-fixed NED frame [m/s] (type:float) ve : GPS velocity in EAST direction in earth-fixed NED frame [m/s] (type:float) vd : GPS velocity in DOWN direction in earth-fixed NED frame [m/s] (type:float) speed_accuracy : GPS speed accuracy [m/s] (type:float) horiz_accuracy : GPS horizontal accuracy [m] (type:float) vert_accuracy : GPS vertical accuracy [m] (type:float) satellites_visible : Number of satellites visible. (type:uint8_t) yaw : Yaw of vehicle, zero means not available, use 36000 for north [cdeg] (type:uint16_t) ''' return self.send(self.gps_input_encode(time_usec, gps_id, ignore_flags, time_week_ms, time_week, fix_type, lat, lon, alt, hdop, vdop, vn, ve, vd, speed_accuracy, horiz_accuracy, vert_accuracy, satellites_visible, yaw), force_mavlink1=force_mavlink1) def gps_rtcm_data_encode(self, flags, len, data): ''' RTCM message for injecting into the onboard GPS (used for DGPS) flags : LSB: 1 means message is fragmented, next 2 bits are the fragment ID, the remaining 5 bits are used for the sequence ID. Messages are only to be flushed to the GPS when the entire message has been reconstructed on the autopilot. The fragment ID specifies which order the fragments should be assembled into a buffer, while the sequence ID is used to detect a mismatch between different buffers. The buffer is considered fully reconstructed when either all 4 fragments are present, or all the fragments before the first fragment with a non full payload is received. This management is used to ensure that normal GPS operation doesn't corrupt RTCM data, and to recover from a unreliable transport delivery order. (type:uint8_t) len : data length [bytes] (type:uint8_t) data : RTCM message (may be fragmented) (type:uint8_t) ''' return MAVLink_gps_rtcm_data_message(flags, len, data) def gps_rtcm_data_send(self, flags, len, data, force_mavlink1=False): ''' RTCM message for injecting into the onboard GPS (used for DGPS) flags : LSB: 1 means message is fragmented, next 2 bits are the fragment ID, the remaining 5 bits are used for the sequence ID. Messages are only to be flushed to the GPS when the entire message has been reconstructed on the autopilot. The fragment ID specifies which order the fragments should be assembled into a buffer, while the sequence ID is used to detect a mismatch between different buffers. The buffer is considered fully reconstructed when either all 4 fragments are present, or all the fragments before the first fragment with a non full payload is received. This management is used to ensure that normal GPS operation doesn't corrupt RTCM data, and to recover from a unreliable transport delivery order. (type:uint8_t) len : data length [bytes] (type:uint8_t) data : RTCM message (may be fragmented) (type:uint8_t) ''' return self.send(self.gps_rtcm_data_encode(flags, len, data), force_mavlink1=force_mavlink1) def high_latency_encode(self, base_mode, custom_mode, landed_state, roll, pitch, heading, throttle, heading_sp, latitude, longitude, altitude_amsl, altitude_sp, airspeed, airspeed_sp, groundspeed, climb_rate, gps_nsat, gps_fix_type, battery_remaining, temperature, temperature_air, failsafe, wp_num, wp_distance): ''' Message appropriate for high latency connections like Iridium base_mode : Bitmap of enabled system modes. (type:uint8_t, values:MAV_MODE_FLAG) custom_mode : A bitfield for use for autopilot-specific flags. (type:uint32_t) landed_state : The landed state. Is set to MAV_LANDED_STATE_UNDEFINED if landed state is unknown. (type:uint8_t, values:MAV_LANDED_STATE) roll : roll [cdeg] (type:int16_t) pitch : pitch [cdeg] (type:int16_t) heading : heading [cdeg] (type:uint16_t) throttle : throttle (percentage) [%] (type:int8_t) heading_sp : heading setpoint [cdeg] (type:int16_t) latitude : Latitude [degE7] (type:int32_t) longitude : Longitude [degE7] (type:int32_t) altitude_amsl : Altitude above mean sea level [m] (type:int16_t) altitude_sp : Altitude setpoint relative to the home position [m] (type:int16_t) airspeed : airspeed [m/s] (type:uint8_t) airspeed_sp : airspeed setpoint [m/s] (type:uint8_t) groundspeed : groundspeed [m/s] (type:uint8_t) climb_rate : climb rate [m/s] (type:int8_t) gps_nsat : Number of satellites visible. If unknown, set to 255 (type:uint8_t) gps_fix_type : GPS Fix type. (type:uint8_t, values:GPS_FIX_TYPE) battery_remaining : Remaining battery (percentage) [%] (type:uint8_t) temperature : Autopilot temperature (degrees C) [degC] (type:int8_t) temperature_air : Air temperature (degrees C) from airspeed sensor [degC] (type:int8_t) failsafe : failsafe (each bit represents a failsafe where 0=ok, 1=failsafe active (bit0:RC, bit1:batt, bit2:GPS, bit3:GCS, bit4:fence) (type:uint8_t) wp_num : current waypoint number (type:uint8_t) wp_distance : distance to target [m] (type:uint16_t) ''' return MAVLink_high_latency_message(base_mode, custom_mode, landed_state, roll, pitch, heading, throttle, heading_sp, latitude, longitude, altitude_amsl, altitude_sp, airspeed, airspeed_sp, groundspeed, climb_rate, gps_nsat, gps_fix_type, battery_remaining, temperature, temperature_air, failsafe, wp_num, wp_distance) def high_latency_send(self, base_mode, custom_mode, landed_state, roll, pitch, heading, throttle, heading_sp, latitude, longitude, altitude_amsl, altitude_sp, airspeed, airspeed_sp, groundspeed, climb_rate, gps_nsat, gps_fix_type, battery_remaining, temperature, temperature_air, failsafe, wp_num, wp_distance, force_mavlink1=False): ''' Message appropriate for high latency connections like Iridium base_mode : Bitmap of enabled system modes. (type:uint8_t, values:MAV_MODE_FLAG) custom_mode : A bitfield for use for autopilot-specific flags. (type:uint32_t) landed_state : The landed state. Is set to MAV_LANDED_STATE_UNDEFINED if landed state is unknown. (type:uint8_t, values:MAV_LANDED_STATE) roll : roll [cdeg] (type:int16_t) pitch : pitch [cdeg] (type:int16_t) heading : heading [cdeg] (type:uint16_t) throttle : throttle (percentage) [%] (type:int8_t) heading_sp : heading setpoint [cdeg] (type:int16_t) latitude : Latitude [degE7] (type:int32_t) longitude : Longitude [degE7] (type:int32_t) altitude_amsl : Altitude above mean sea level [m] (type:int16_t) altitude_sp : Altitude setpoint relative to the home position [m] (type:int16_t) airspeed : airspeed [m/s] (type:uint8_t) airspeed_sp : airspeed setpoint [m/s] (type:uint8_t) groundspeed : groundspeed [m/s] (type:uint8_t) climb_rate : climb rate [m/s] (type:int8_t) gps_nsat : Number of satellites visible. If unknown, set to 255 (type:uint8_t) gps_fix_type : GPS Fix type. (type:uint8_t, values:GPS_FIX_TYPE) battery_remaining : Remaining battery (percentage) [%] (type:uint8_t) temperature : Autopilot temperature (degrees C) [degC] (type:int8_t) temperature_air : Air temperature (degrees C) from airspeed sensor [degC] (type:int8_t) failsafe : failsafe (each bit represents a failsafe where 0=ok, 1=failsafe active (bit0:RC, bit1:batt, bit2:GPS, bit3:GCS, bit4:fence) (type:uint8_t) wp_num : current waypoint number (type:uint8_t) wp_distance : distance to target [m] (type:uint16_t) ''' return self.send(self.high_latency_encode(base_mode, custom_mode, landed_state, roll, pitch, heading, throttle, heading_sp, latitude, longitude, altitude_amsl, altitude_sp, airspeed, airspeed_sp, groundspeed, climb_rate, gps_nsat, gps_fix_type, battery_remaining, temperature, temperature_air, failsafe, wp_num, wp_distance), force_mavlink1=force_mavlink1) def vibration_encode(self, time_usec, vibration_x, vibration_y, vibration_z, clipping_0, clipping_1, clipping_2): ''' Vibration levels and accelerometer clipping time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) vibration_x : Vibration levels on X-axis (type:float) vibration_y : Vibration levels on Y-axis (type:float) vibration_z : Vibration levels on Z-axis (type:float) clipping_0 : first accelerometer clipping count (type:uint32_t) clipping_1 : second accelerometer clipping count (type:uint32_t) clipping_2 : third accelerometer clipping count (type:uint32_t) ''' return MAVLink_vibration_message(time_usec, vibration_x, vibration_y, vibration_z, clipping_0, clipping_1, clipping_2) def vibration_send(self, time_usec, vibration_x, vibration_y, vibration_z, clipping_0, clipping_1, clipping_2, force_mavlink1=False): ''' Vibration levels and accelerometer clipping time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) vibration_x : Vibration levels on X-axis (type:float) vibration_y : Vibration levels on Y-axis (type:float) vibration_z : Vibration levels on Z-axis (type:float) clipping_0 : first accelerometer clipping count (type:uint32_t) clipping_1 : second accelerometer clipping count (type:uint32_t) clipping_2 : third accelerometer clipping count (type:uint32_t) ''' return self.send(self.vibration_encode(time_usec, vibration_x, vibration_y, vibration_z, clipping_0, clipping_1, clipping_2), force_mavlink1=force_mavlink1) def home_position_encode(self, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec=0): ''' This message can be requested by sending the MAV_CMD_GET_HOME_POSITION command. The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitly set by the operator before or after. The position the system will return to and land on. The global and local positions encode the position in the respective coordinate frames, while the q parameter encodes the orientation of the surface. Under normal conditions it describes the heading and terrain slope, which can be used by the aircraft to adjust the approach. The approach 3D vector describes the point to which the system should fly in normal flight mode and then perform a landing sequence along the vector. latitude : Latitude (WGS84) [degE7] (type:int32_t) longitude : Longitude (WGS84) [degE7] (type:int32_t) altitude : Altitude (MSL). Positive for up. [mm] (type:int32_t) x : Local X position of this position in the local coordinate frame [m] (type:float) y : Local Y position of this position in the local coordinate frame [m] (type:float) z : Local Z position of this position in the local coordinate frame [m] (type:float) q : World to surface normal and heading transformation of the takeoff position. Used to indicate the heading and slope of the ground (type:float) approach_x : Local X position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) approach_y : Local Y position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) approach_z : Local Z position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) ''' return MAVLink_home_position_message(latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec) def home_position_send(self, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec=0, force_mavlink1=False): ''' This message can be requested by sending the MAV_CMD_GET_HOME_POSITION command. The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitly set by the operator before or after. The position the system will return to and land on. The global and local positions encode the position in the respective coordinate frames, while the q parameter encodes the orientation of the surface. Under normal conditions it describes the heading and terrain slope, which can be used by the aircraft to adjust the approach. The approach 3D vector describes the point to which the system should fly in normal flight mode and then perform a landing sequence along the vector. latitude : Latitude (WGS84) [degE7] (type:int32_t) longitude : Longitude (WGS84) [degE7] (type:int32_t) altitude : Altitude (MSL). Positive for up. [mm] (type:int32_t) x : Local X position of this position in the local coordinate frame [m] (type:float) y : Local Y position of this position in the local coordinate frame [m] (type:float) z : Local Z position of this position in the local coordinate frame [m] (type:float) q : World to surface normal and heading transformation of the takeoff position. Used to indicate the heading and slope of the ground (type:float) approach_x : Local X position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) approach_y : Local Y position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) approach_z : Local Z position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) ''' return self.send(self.home_position_encode(latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec), force_mavlink1=force_mavlink1) def set_home_position_encode(self, target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec=0): ''' The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitly set by the operator before or after. The global and local positions encode the position in the respective coordinate frames, while the q parameter encodes the orientation of the surface. Under normal conditions it describes the heading and terrain slope, which can be used by the aircraft to adjust the approach. The approach 3D vector describes the point to which the system should fly in normal flight mode and then perform a landing sequence along the vector. target_system : System ID. (type:uint8_t) latitude : Latitude (WGS84) [degE7] (type:int32_t) longitude : Longitude (WGS84) [degE7] (type:int32_t) altitude : Altitude (MSL). Positive for up. [mm] (type:int32_t) x : Local X position of this position in the local coordinate frame [m] (type:float) y : Local Y position of this position in the local coordinate frame [m] (type:float) z : Local Z position of this position in the local coordinate frame [m] (type:float) q : World to surface normal and heading transformation of the takeoff position. Used to indicate the heading and slope of the ground (type:float) approach_x : Local X position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) approach_y : Local Y position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) approach_z : Local Z position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) ''' return MAVLink_set_home_position_message(target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec) def set_home_position_send(self, target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec=0, force_mavlink1=False): ''' The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitly set by the operator before or after. The global and local positions encode the position in the respective coordinate frames, while the q parameter encodes the orientation of the surface. Under normal conditions it describes the heading and terrain slope, which can be used by the aircraft to adjust the approach. The approach 3D vector describes the point to which the system should fly in normal flight mode and then perform a landing sequence along the vector. target_system : System ID. (type:uint8_t) latitude : Latitude (WGS84) [degE7] (type:int32_t) longitude : Longitude (WGS84) [degE7] (type:int32_t) altitude : Altitude (MSL). Positive for up. [mm] (type:int32_t) x : Local X position of this position in the local coordinate frame [m] (type:float) y : Local Y position of this position in the local coordinate frame [m] (type:float) z : Local Z position of this position in the local coordinate frame [m] (type:float) q : World to surface normal and heading transformation of the takeoff position. Used to indicate the heading and slope of the ground (type:float) approach_x : Local X position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) approach_y : Local Y position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) approach_z : Local Z position of the end of the approach vector. Multicopters should set this position based on their takeoff path. Grass-landing fixed wing aircraft should set it the same way as multicopters. Runway-landing fixed wing aircraft should set it to the opposite direction of the takeoff, assuming the takeoff happened from the threshold / touchdown zone. [m] (type:float) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) ''' return self.send(self.set_home_position_encode(target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec), force_mavlink1=force_mavlink1) def message_interval_encode(self, message_id, interval_us): ''' The interval between messages for a particular MAVLink message ID. This message is the response to the MAV_CMD_GET_MESSAGE_INTERVAL command. This interface replaces DATA_STREAM. message_id : The ID of the requested MAVLink message. v1.0 is limited to 254 messages. (type:uint16_t) interval_us : The interval between two messages. A value of -1 indicates this stream is disabled, 0 indicates it is not available, > 0 indicates the interval at which it is sent. [us] (type:int32_t) ''' return MAVLink_message_interval_message(message_id, interval_us) def message_interval_send(self, message_id, interval_us, force_mavlink1=False): ''' The interval between messages for a particular MAVLink message ID. This message is the response to the MAV_CMD_GET_MESSAGE_INTERVAL command. This interface replaces DATA_STREAM. message_id : The ID of the requested MAVLink message. v1.0 is limited to 254 messages. (type:uint16_t) interval_us : The interval between two messages. A value of -1 indicates this stream is disabled, 0 indicates it is not available, > 0 indicates the interval at which it is sent. [us] (type:int32_t) ''' return self.send(self.message_interval_encode(message_id, interval_us), force_mavlink1=force_mavlink1) def extended_sys_state_encode(self, vtol_state, landed_state): ''' Provides state for additional features vtol_state : The VTOL state if applicable. Is set to MAV_VTOL_STATE_UNDEFINED if UAV is not in VTOL configuration. (type:uint8_t, values:MAV_VTOL_STATE) landed_state : The landed state. Is set to MAV_LANDED_STATE_UNDEFINED if landed state is unknown. (type:uint8_t, values:MAV_LANDED_STATE) ''' return MAVLink_extended_sys_state_message(vtol_state, landed_state) def extended_sys_state_send(self, vtol_state, landed_state, force_mavlink1=False): ''' Provides state for additional features vtol_state : The VTOL state if applicable. Is set to MAV_VTOL_STATE_UNDEFINED if UAV is not in VTOL configuration. (type:uint8_t, values:MAV_VTOL_STATE) landed_state : The landed state. Is set to MAV_LANDED_STATE_UNDEFINED if landed state is unknown. (type:uint8_t, values:MAV_LANDED_STATE) ''' return self.send(self.extended_sys_state_encode(vtol_state, landed_state), force_mavlink1=force_mavlink1) def adsb_vehicle_encode(self, ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, callsign, emitter_type, tslc, flags, squawk): ''' The location and information of an ADSB vehicle ICAO_address : ICAO address (type:uint32_t) lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) altitude_type : ADSB altitude type. (type:uint8_t, values:ADSB_ALTITUDE_TYPE) altitude : Altitude(ASL) [mm] (type:int32_t) heading : Course over ground [cdeg] (type:uint16_t) hor_velocity : The horizontal velocity [cm/s] (type:uint16_t) ver_velocity : The vertical velocity. Positive is up [cm/s] (type:int16_t) callsign : The callsign, 8+null (type:char) emitter_type : ADSB emitter type. (type:uint8_t, values:ADSB_EMITTER_TYPE) tslc : Time since last communication in seconds [s] (type:uint8_t) flags : Bitmap to indicate various statuses including valid data fields (type:uint16_t, values:ADSB_FLAGS) squawk : Squawk code (type:uint16_t) ''' return MAVLink_adsb_vehicle_message(ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, callsign, emitter_type, tslc, flags, squawk) def adsb_vehicle_send(self, ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, callsign, emitter_type, tslc, flags, squawk, force_mavlink1=False): ''' The location and information of an ADSB vehicle ICAO_address : ICAO address (type:uint32_t) lat : Latitude [degE7] (type:int32_t) lon : Longitude [degE7] (type:int32_t) altitude_type : ADSB altitude type. (type:uint8_t, values:ADSB_ALTITUDE_TYPE) altitude : Altitude(ASL) [mm] (type:int32_t) heading : Course over ground [cdeg] (type:uint16_t) hor_velocity : The horizontal velocity [cm/s] (type:uint16_t) ver_velocity : The vertical velocity. Positive is up [cm/s] (type:int16_t) callsign : The callsign, 8+null (type:char) emitter_type : ADSB emitter type. (type:uint8_t, values:ADSB_EMITTER_TYPE) tslc : Time since last communication in seconds [s] (type:uint8_t) flags : Bitmap to indicate various statuses including valid data fields (type:uint16_t, values:ADSB_FLAGS) squawk : Squawk code (type:uint16_t) ''' return self.send(self.adsb_vehicle_encode(ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, callsign, emitter_type, tslc, flags, squawk), force_mavlink1=force_mavlink1) def collision_encode(self, src, id, action, threat_level, time_to_minimum_delta, altitude_minimum_delta, horizontal_minimum_delta): ''' Information about a potential collision src : Collision data source (type:uint8_t, values:MAV_COLLISION_SRC) id : Unique identifier, domain based on src field (type:uint32_t) action : Action that is being taken to avoid this collision (type:uint8_t, values:MAV_COLLISION_ACTION) threat_level : How concerned the aircraft is about this collision (type:uint8_t, values:MAV_COLLISION_THREAT_LEVEL) time_to_minimum_delta : Estimated time until collision occurs [s] (type:float) altitude_minimum_delta : Closest vertical distance between vehicle and object [m] (type:float) horizontal_minimum_delta : Closest horizontal distance between vehicle and object [m] (type:float) ''' return MAVLink_collision_message(src, id, action, threat_level, time_to_minimum_delta, altitude_minimum_delta, horizontal_minimum_delta) def collision_send(self, src, id, action, threat_level, time_to_minimum_delta, altitude_minimum_delta, horizontal_minimum_delta, force_mavlink1=False): ''' Information about a potential collision src : Collision data source (type:uint8_t, values:MAV_COLLISION_SRC) id : Unique identifier, domain based on src field (type:uint32_t) action : Action that is being taken to avoid this collision (type:uint8_t, values:MAV_COLLISION_ACTION) threat_level : How concerned the aircraft is about this collision (type:uint8_t, values:MAV_COLLISION_THREAT_LEVEL) time_to_minimum_delta : Estimated time until collision occurs [s] (type:float) altitude_minimum_delta : Closest vertical distance between vehicle and object [m] (type:float) horizontal_minimum_delta : Closest horizontal distance between vehicle and object [m] (type:float) ''' return self.send(self.collision_encode(src, id, action, threat_level, time_to_minimum_delta, altitude_minimum_delta, horizontal_minimum_delta), force_mavlink1=force_mavlink1) def v2_extension_encode(self, target_network, target_system, target_component, message_type, payload): ''' Message implementing parts of the V2 payload specs in V1 frames for transitional support. target_network : Network ID (0 for broadcast) (type:uint8_t) target_system : System ID (0 for broadcast) (type:uint8_t) target_component : Component ID (0 for broadcast) (type:uint8_t) message_type : A code that identifies the software component that understands this message (analogous to USB device classes or mime type strings). If this code is less than 32768, it is considered a 'registered' protocol extension and the corresponding entry should be added to https://github.com/mavlink/mavlink/definition_files/extension_message_ids.xml. Software creators can register blocks of message IDs as needed (useful for GCS specific metadata, etc...). Message_types greater than 32767 are considered local experiments and should not be checked in to any widely distributed codebase. (type:uint16_t) payload : Variable length payload. The length must be encoded in the payload as part of the message_type protocol, e.g. by including the length as payload data, or by terminating the payload data with a non-zero marker. This is required in order to reconstruct zero-terminated payloads that are (or otherwise would be) trimmed by MAVLink 2 empty-byte truncation. The entire content of the payload block is opaque unless you understand the encoding message_type. The particular encoding used can be extension specific and might not always be documented as part of the MAVLink specification. (type:uint8_t) ''' return MAVLink_v2_extension_message(target_network, target_system, target_component, message_type, payload) def v2_extension_send(self, target_network, target_system, target_component, message_type, payload, force_mavlink1=False): ''' Message implementing parts of the V2 payload specs in V1 frames for transitional support. target_network : Network ID (0 for broadcast) (type:uint8_t) target_system : System ID (0 for broadcast) (type:uint8_t) target_component : Component ID (0 for broadcast) (type:uint8_t) message_type : A code that identifies the software component that understands this message (analogous to USB device classes or mime type strings). If this code is less than 32768, it is considered a 'registered' protocol extension and the corresponding entry should be added to https://github.com/mavlink/mavlink/definition_files/extension_message_ids.xml. Software creators can register blocks of message IDs as needed (useful for GCS specific metadata, etc...). Message_types greater than 32767 are considered local experiments and should not be checked in to any widely distributed codebase. (type:uint16_t) payload : Variable length payload. The length must be encoded in the payload as part of the message_type protocol, e.g. by including the length as payload data, or by terminating the payload data with a non-zero marker. This is required in order to reconstruct zero-terminated payloads that are (or otherwise would be) trimmed by MAVLink 2 empty-byte truncation. The entire content of the payload block is opaque unless you understand the encoding message_type. The particular encoding used can be extension specific and might not always be documented as part of the MAVLink specification. (type:uint8_t) ''' return self.send(self.v2_extension_encode(target_network, target_system, target_component, message_type, payload), force_mavlink1=force_mavlink1) def memory_vect_encode(self, address, ver, type, value): ''' Send raw controller memory. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. address : Starting address of the debug variables (type:uint16_t) ver : Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below (type:uint8_t) type : Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14 (type:uint8_t) value : Memory contents at specified address (type:int8_t) ''' return MAVLink_memory_vect_message(address, ver, type, value) def memory_vect_send(self, address, ver, type, value, force_mavlink1=False): ''' Send raw controller memory. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. address : Starting address of the debug variables (type:uint16_t) ver : Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below (type:uint8_t) type : Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14 (type:uint8_t) value : Memory contents at specified address (type:int8_t) ''' return self.send(self.memory_vect_encode(address, ver, type, value), force_mavlink1=force_mavlink1) def debug_vect_encode(self, name, time_usec, x, y, z): ''' To debug something using a named 3D vector. name : Name (type:char) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) x : x (type:float) y : y (type:float) z : z (type:float) ''' return MAVLink_debug_vect_message(name, time_usec, x, y, z) def debug_vect_send(self, name, time_usec, x, y, z, force_mavlink1=False): ''' To debug something using a named 3D vector. name : Name (type:char) time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) x : x (type:float) y : y (type:float) z : z (type:float) ''' return self.send(self.debug_vect_encode(name, time_usec, x, y, z), force_mavlink1=force_mavlink1) def named_value_float_encode(self, time_boot_ms, name, value): ''' Send a key-value pair as float. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) name : Name of the debug variable (type:char) value : Floating point value (type:float) ''' return MAVLink_named_value_float_message(time_boot_ms, name, value) def named_value_float_send(self, time_boot_ms, name, value, force_mavlink1=False): ''' Send a key-value pair as float. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) name : Name of the debug variable (type:char) value : Floating point value (type:float) ''' return self.send(self.named_value_float_encode(time_boot_ms, name, value), force_mavlink1=force_mavlink1) def named_value_int_encode(self, time_boot_ms, name, value): ''' Send a key-value pair as integer. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) name : Name of the debug variable (type:char) value : Signed integer value (type:int32_t) ''' return MAVLink_named_value_int_message(time_boot_ms, name, value) def named_value_int_send(self, time_boot_ms, name, value, force_mavlink1=False): ''' Send a key-value pair as integer. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental debug output. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) name : Name of the debug variable (type:char) value : Signed integer value (type:int32_t) ''' return self.send(self.named_value_int_encode(time_boot_ms, name, value), force_mavlink1=force_mavlink1) def statustext_encode(self, severity, text): ''' Status text message. These messages are printed in yellow in the COMM console of QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status and error messages. If implemented wisely, these messages are buffered on the MCU and sent only at a limited rate (e.g. 10 Hz). severity : Severity of status. Relies on the definitions within RFC-5424. (type:uint8_t, values:MAV_SEVERITY) text : Status text message, without null termination character (type:char) ''' return MAVLink_statustext_message(severity, text) def statustext_send(self, severity, text, force_mavlink1=False): ''' Status text message. These messages are printed in yellow in the COMM console of QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status and error messages. If implemented wisely, these messages are buffered on the MCU and sent only at a limited rate (e.g. 10 Hz). severity : Severity of status. Relies on the definitions within RFC-5424. (type:uint8_t, values:MAV_SEVERITY) text : Status text message, without null termination character (type:char) ''' return self.send(self.statustext_encode(severity, text), force_mavlink1=force_mavlink1) def debug_encode(self, time_boot_ms, ind, value): ''' Send a debug value. The index is used to discriminate between values. These values show up in the plot of QGroundControl as DEBUG N. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) ind : index of debug variable (type:uint8_t) value : DEBUG value (type:float) ''' return MAVLink_debug_message(time_boot_ms, ind, value) def debug_send(self, time_boot_ms, ind, value, force_mavlink1=False): ''' Send a debug value. The index is used to discriminate between values. These values show up in the plot of QGroundControl as DEBUG N. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) ind : index of debug variable (type:uint8_t) value : DEBUG value (type:float) ''' return self.send(self.debug_encode(time_boot_ms, ind, value), force_mavlink1=force_mavlink1) def setup_signing_encode(self, target_system, target_component, secret_key, initial_timestamp): ''' Setup a MAVLink2 signing key. If called with secret_key of all zero and zero initial_timestamp will disable signing target_system : system id of the target (type:uint8_t) target_component : component ID of the target (type:uint8_t) secret_key : signing key (type:uint8_t) initial_timestamp : initial timestamp (type:uint64_t) ''' return MAVLink_setup_signing_message(target_system, target_component, secret_key, initial_timestamp) def setup_signing_send(self, target_system, target_component, secret_key, initial_timestamp, force_mavlink1=False): ''' Setup a MAVLink2 signing key. If called with secret_key of all zero and zero initial_timestamp will disable signing target_system : system id of the target (type:uint8_t) target_component : component ID of the target (type:uint8_t) secret_key : signing key (type:uint8_t) initial_timestamp : initial timestamp (type:uint64_t) ''' return self.send(self.setup_signing_encode(target_system, target_component, secret_key, initial_timestamp), force_mavlink1=force_mavlink1) def button_change_encode(self, time_boot_ms, last_change_ms, state): ''' Report button state change. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) last_change_ms : Time of last change of button state. [ms] (type:uint32_t) state : Bitmap for state of buttons. (type:uint8_t) ''' return MAVLink_button_change_message(time_boot_ms, last_change_ms, state) def button_change_send(self, time_boot_ms, last_change_ms, state, force_mavlink1=False): ''' Report button state change. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) last_change_ms : Time of last change of button state. [ms] (type:uint32_t) state : Bitmap for state of buttons. (type:uint8_t) ''' return self.send(self.button_change_encode(time_boot_ms, last_change_ms, state), force_mavlink1=force_mavlink1) def play_tune_encode(self, target_system, target_component, tune, tune2=['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','']): ''' Control vehicle tone generation (buzzer) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) tune : tune in board specific format (type:char) tune2 : tune extension (appended to tune) (type:char) ''' return MAVLink_play_tune_message(target_system, target_component, tune, tune2) def play_tune_send(self, target_system, target_component, tune, tune2=['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], force_mavlink1=False): ''' Control vehicle tone generation (buzzer) target_system : System ID (type:uint8_t) target_component : Component ID (type:uint8_t) tune : tune in board specific format (type:char) tune2 : tune extension (appended to tune) (type:char) ''' return self.send(self.play_tune_encode(target_system, target_component, tune, tune2), force_mavlink1=force_mavlink1) def camera_information_encode(self, time_boot_ms, vendor_name, model_name, firmware_version, focal_length, sensor_size_h, sensor_size_v, resolution_h, resolution_v, lens_id, flags, cam_definition_version, cam_definition_uri): ''' Information about a camera time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) vendor_name : Name of the camera vendor (type:uint8_t) model_name : Name of the camera model (type:uint8_t) firmware_version : Version of the camera firmware (v << 24 & 0xff = Dev, v << 16 & 0xff = Patch, v << 8 & 0xff = Minor, v & 0xff = Major) (type:uint32_t) focal_length : Focal length [mm] (type:float) sensor_size_h : Image sensor size horizontal [mm] (type:float) sensor_size_v : Image sensor size vertical [mm] (type:float) resolution_h : Horizontal image resolution [pix] (type:uint16_t) resolution_v : Vertical image resolution [pix] (type:uint16_t) lens_id : Reserved for a lens ID (type:uint8_t) flags : Bitmap of camera capability flags. (type:uint32_t, values:CAMERA_CAP_FLAGS) cam_definition_version : Camera definition version (iteration) (type:uint16_t) cam_definition_uri : Camera definition URI (if any, otherwise only basic functions will be available). HTTP- (http://) and MAVLink FTP- (mavlinkftp://) formatted URIs are allowed (and both must be supported by any GCS that implements the Camera Protocol). (type:char) ''' return MAVLink_camera_information_message(time_boot_ms, vendor_name, model_name, firmware_version, focal_length, sensor_size_h, sensor_size_v, resolution_h, resolution_v, lens_id, flags, cam_definition_version, cam_definition_uri) def camera_information_send(self, time_boot_ms, vendor_name, model_name, firmware_version, focal_length, sensor_size_h, sensor_size_v, resolution_h, resolution_v, lens_id, flags, cam_definition_version, cam_definition_uri, force_mavlink1=False): ''' Information about a camera time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) vendor_name : Name of the camera vendor (type:uint8_t) model_name : Name of the camera model (type:uint8_t) firmware_version : Version of the camera firmware (v << 24 & 0xff = Dev, v << 16 & 0xff = Patch, v << 8 & 0xff = Minor, v & 0xff = Major) (type:uint32_t) focal_length : Focal length [mm] (type:float) sensor_size_h : Image sensor size horizontal [mm] (type:float) sensor_size_v : Image sensor size vertical [mm] (type:float) resolution_h : Horizontal image resolution [pix] (type:uint16_t) resolution_v : Vertical image resolution [pix] (type:uint16_t) lens_id : Reserved for a lens ID (type:uint8_t) flags : Bitmap of camera capability flags. (type:uint32_t, values:CAMERA_CAP_FLAGS) cam_definition_version : Camera definition version (iteration) (type:uint16_t) cam_definition_uri : Camera definition URI (if any, otherwise only basic functions will be available). HTTP- (http://) and MAVLink FTP- (mavlinkftp://) formatted URIs are allowed (and both must be supported by any GCS that implements the Camera Protocol). (type:char) ''' return self.send(self.camera_information_encode(time_boot_ms, vendor_name, model_name, firmware_version, focal_length, sensor_size_h, sensor_size_v, resolution_h, resolution_v, lens_id, flags, cam_definition_version, cam_definition_uri), force_mavlink1=force_mavlink1) def camera_settings_encode(self, time_boot_ms, mode_id, zoomLevel=0, focusLevel=0): ''' Settings of a camera, can be requested using MAV_CMD_REQUEST_CAMERA_SETTINGS. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) mode_id : Camera mode (type:uint8_t, values:CAMERA_MODE) zoomLevel : Current zoom level (0.0 to 100.0, NaN if not known) (type:float) focusLevel : Current focus level (0.0 to 100.0, NaN if not known) (type:float) ''' return MAVLink_camera_settings_message(time_boot_ms, mode_id, zoomLevel, focusLevel) def camera_settings_send(self, time_boot_ms, mode_id, zoomLevel=0, focusLevel=0, force_mavlink1=False): ''' Settings of a camera, can be requested using MAV_CMD_REQUEST_CAMERA_SETTINGS. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) mode_id : Camera mode (type:uint8_t, values:CAMERA_MODE) zoomLevel : Current zoom level (0.0 to 100.0, NaN if not known) (type:float) focusLevel : Current focus level (0.0 to 100.0, NaN if not known) (type:float) ''' return self.send(self.camera_settings_encode(time_boot_ms, mode_id, zoomLevel, focusLevel), force_mavlink1=force_mavlink1) def storage_information_encode(self, time_boot_ms, storage_id, storage_count, status, total_capacity, used_capacity, available_capacity, read_speed, write_speed): ''' Information about a storage medium. This message is sent in response to a request and whenever the status of the storage changes (STORAGE_STATUS). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) storage_id : Storage ID (1 for first, 2 for second, etc.) (type:uint8_t) storage_count : Number of storage devices (type:uint8_t) status : Status of storage (type:uint8_t, values:STORAGE_STATUS) total_capacity : Total capacity. If storage is not ready (STORAGE_STATUS_READY) value will be ignored. [MiB] (type:float) used_capacity : Used capacity. If storage is not ready (STORAGE_STATUS_READY) value will be ignored. [MiB] (type:float) available_capacity : Available storage capacity. If storage is not ready (STORAGE_STATUS_READY) value will be ignored. [MiB] (type:float) read_speed : Read speed. [MiB/s] (type:float) write_speed : Write speed. [MiB/s] (type:float) ''' return MAVLink_storage_information_message(time_boot_ms, storage_id, storage_count, status, total_capacity, used_capacity, available_capacity, read_speed, write_speed) def storage_information_send(self, time_boot_ms, storage_id, storage_count, status, total_capacity, used_capacity, available_capacity, read_speed, write_speed, force_mavlink1=False): ''' Information about a storage medium. This message is sent in response to a request and whenever the status of the storage changes (STORAGE_STATUS). time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) storage_id : Storage ID (1 for first, 2 for second, etc.) (type:uint8_t) storage_count : Number of storage devices (type:uint8_t) status : Status of storage (type:uint8_t, values:STORAGE_STATUS) total_capacity : Total capacity. If storage is not ready (STORAGE_STATUS_READY) value will be ignored. [MiB] (type:float) used_capacity : Used capacity. If storage is not ready (STORAGE_STATUS_READY) value will be ignored. [MiB] (type:float) available_capacity : Available storage capacity. If storage is not ready (STORAGE_STATUS_READY) value will be ignored. [MiB] (type:float) read_speed : Read speed. [MiB/s] (type:float) write_speed : Write speed. [MiB/s] (type:float) ''' return self.send(self.storage_information_encode(time_boot_ms, storage_id, storage_count, status, total_capacity, used_capacity, available_capacity, read_speed, write_speed), force_mavlink1=force_mavlink1) def camera_capture_status_encode(self, time_boot_ms, image_status, video_status, image_interval, recording_time_ms, available_capacity): ''' Information about the status of a capture. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) image_status : Current status of image capturing (0: idle, 1: capture in progress, 2: interval set but idle, 3: interval set and capture in progress) (type:uint8_t) video_status : Current status of video capturing (0: idle, 1: capture in progress) (type:uint8_t) image_interval : Image capture interval [s] (type:float) recording_time_ms : Time since recording started [ms] (type:uint32_t) available_capacity : Available storage capacity. [MiB] (type:float) ''' return MAVLink_camera_capture_status_message(time_boot_ms, image_status, video_status, image_interval, recording_time_ms, available_capacity) def camera_capture_status_send(self, time_boot_ms, image_status, video_status, image_interval, recording_time_ms, available_capacity, force_mavlink1=False): ''' Information about the status of a capture. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) image_status : Current status of image capturing (0: idle, 1: capture in progress, 2: interval set but idle, 3: interval set and capture in progress) (type:uint8_t) video_status : Current status of video capturing (0: idle, 1: capture in progress) (type:uint8_t) image_interval : Image capture interval [s] (type:float) recording_time_ms : Time since recording started [ms] (type:uint32_t) available_capacity : Available storage capacity. [MiB] (type:float) ''' return self.send(self.camera_capture_status_encode(time_boot_ms, image_status, video_status, image_interval, recording_time_ms, available_capacity), force_mavlink1=force_mavlink1) def camera_image_captured_encode(self, time_boot_ms, time_utc, camera_id, lat, lon, alt, relative_alt, q, image_index, capture_result, file_url): ''' Information about a captured image time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) time_utc : Timestamp (time since UNIX epoch) in UTC. 0 for unknown. [us] (type:uint64_t) camera_id : Camera ID (1 for first, 2 for second, etc.) (type:uint8_t) lat : Latitude where image was taken [degE7] (type:int32_t) lon : Longitude where capture was taken [degE7] (type:int32_t) alt : Altitude (MSL) where image was taken [mm] (type:int32_t) relative_alt : Altitude above ground [mm] (type:int32_t) q : Quaternion of camera orientation (w, x, y, z order, zero-rotation is 0, 0, 0, 0) (type:float) image_index : Zero based index of this image (image count since armed -1) (type:int32_t) capture_result : Boolean indicating success (1) or failure (0) while capturing this image. (type:int8_t) file_url : URL of image taken. Either local storage or http://foo.jpg if camera provides an HTTP interface. (type:char) ''' return MAVLink_camera_image_captured_message(time_boot_ms, time_utc, camera_id, lat, lon, alt, relative_alt, q, image_index, capture_result, file_url) def camera_image_captured_send(self, time_boot_ms, time_utc, camera_id, lat, lon, alt, relative_alt, q, image_index, capture_result, file_url, force_mavlink1=False): ''' Information about a captured image time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) time_utc : Timestamp (time since UNIX epoch) in UTC. 0 for unknown. [us] (type:uint64_t) camera_id : Camera ID (1 for first, 2 for second, etc.) (type:uint8_t) lat : Latitude where image was taken [degE7] (type:int32_t) lon : Longitude where capture was taken [degE7] (type:int32_t) alt : Altitude (MSL) where image was taken [mm] (type:int32_t) relative_alt : Altitude above ground [mm] (type:int32_t) q : Quaternion of camera orientation (w, x, y, z order, zero-rotation is 0, 0, 0, 0) (type:float) image_index : Zero based index of this image (image count since armed -1) (type:int32_t) capture_result : Boolean indicating success (1) or failure (0) while capturing this image. (type:int8_t) file_url : URL of image taken. Either local storage or http://foo.jpg if camera provides an HTTP interface. (type:char) ''' return self.send(self.camera_image_captured_encode(time_boot_ms, time_utc, camera_id, lat, lon, alt, relative_alt, q, image_index, capture_result, file_url), force_mavlink1=force_mavlink1) def flight_information_encode(self, time_boot_ms, arming_time_utc, takeoff_time_utc, flight_uuid): ''' Information about flight since last arming. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) arming_time_utc : Timestamp at arming (time since UNIX epoch) in UTC, 0 for unknown [us] (type:uint64_t) takeoff_time_utc : Timestamp at takeoff (time since UNIX epoch) in UTC, 0 for unknown [us] (type:uint64_t) flight_uuid : Universally unique identifier (UUID) of flight, should correspond to name of log files (type:uint64_t) ''' return MAVLink_flight_information_message(time_boot_ms, arming_time_utc, takeoff_time_utc, flight_uuid) def flight_information_send(self, time_boot_ms, arming_time_utc, takeoff_time_utc, flight_uuid, force_mavlink1=False): ''' Information about flight since last arming. time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) arming_time_utc : Timestamp at arming (time since UNIX epoch) in UTC, 0 for unknown [us] (type:uint64_t) takeoff_time_utc : Timestamp at takeoff (time since UNIX epoch) in UTC, 0 for unknown [us] (type:uint64_t) flight_uuid : Universally unique identifier (UUID) of flight, should correspond to name of log files (type:uint64_t) ''' return self.send(self.flight_information_encode(time_boot_ms, arming_time_utc, takeoff_time_utc, flight_uuid), force_mavlink1=force_mavlink1) def mount_orientation_encode(self, time_boot_ms, roll, pitch, yaw, yaw_absolute=0): ''' Orientation of a mount time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) roll : Roll in global frame (set to NaN for invalid). [deg] (type:float) pitch : Pitch in global frame (set to NaN for invalid). [deg] (type:float) yaw : Yaw relative to vehicle(set to NaN for invalid). [deg] (type:float) yaw_absolute : Yaw in absolute frame, North is 0 (set to NaN for invalid). [deg] (type:float) ''' return MAVLink_mount_orientation_message(time_boot_ms, roll, pitch, yaw, yaw_absolute) def mount_orientation_send(self, time_boot_ms, roll, pitch, yaw, yaw_absolute=0, force_mavlink1=False): ''' Orientation of a mount time_boot_ms : Timestamp (time since system boot). [ms] (type:uint32_t) roll : Roll in global frame (set to NaN for invalid). [deg] (type:float) pitch : Pitch in global frame (set to NaN for invalid). [deg] (type:float) yaw : Yaw relative to vehicle(set to NaN for invalid). [deg] (type:float) yaw_absolute : Yaw in absolute frame, North is 0 (set to NaN for invalid). [deg] (type:float) ''' return self.send(self.mount_orientation_encode(time_boot_ms, roll, pitch, yaw, yaw_absolute), force_mavlink1=force_mavlink1) def logging_data_encode(self, target_system, target_component, sequence, length, first_message_offset, data): ''' A message containing logged data (see also MAV_CMD_LOGGING_START) target_system : system ID of the target (type:uint8_t) target_component : component ID of the target (type:uint8_t) sequence : sequence number (can wrap) (type:uint16_t) length : data length [bytes] (type:uint8_t) first_message_offset : offset into data where first message starts. This can be used for recovery, when a previous message got lost (set to 255 if no start exists). [bytes] (type:uint8_t) data : logged data (type:uint8_t) ''' return MAVLink_logging_data_message(target_system, target_component, sequence, length, first_message_offset, data) def logging_data_send(self, target_system, target_component, sequence, length, first_message_offset, data, force_mavlink1=False): ''' A message containing logged data (see also MAV_CMD_LOGGING_START) target_system : system ID of the target (type:uint8_t) target_component : component ID of the target (type:uint8_t) sequence : sequence number (can wrap) (type:uint16_t) length : data length [bytes] (type:uint8_t) first_message_offset : offset into data where first message starts. This can be used for recovery, when a previous message got lost (set to 255 if no start exists). [bytes] (type:uint8_t) data : logged data (type:uint8_t) ''' return self.send(self.logging_data_encode(target_system, target_component, sequence, length, first_message_offset, data), force_mavlink1=force_mavlink1) def logging_data_acked_encode(self, target_system, target_component, sequence, length, first_message_offset, data): ''' A message containing logged data which requires a LOGGING_ACK to be sent back target_system : system ID of the target (type:uint8_t) target_component : component ID of the target (type:uint8_t) sequence : sequence number (can wrap) (type:uint16_t) length : data length [bytes] (type:uint8_t) first_message_offset : offset into data where first message starts. This can be used for recovery, when a previous message got lost (set to 255 if no start exists). [bytes] (type:uint8_t) data : logged data (type:uint8_t) ''' return MAVLink_logging_data_acked_message(target_system, target_component, sequence, length, first_message_offset, data) def logging_data_acked_send(self, target_system, target_component, sequence, length, first_message_offset, data, force_mavlink1=False): ''' A message containing logged data which requires a LOGGING_ACK to be sent back target_system : system ID of the target (type:uint8_t) target_component : component ID of the target (type:uint8_t) sequence : sequence number (can wrap) (type:uint16_t) length : data length [bytes] (type:uint8_t) first_message_offset : offset into data where first message starts. This can be used for recovery, when a previous message got lost (set to 255 if no start exists). [bytes] (type:uint8_t) data : logged data (type:uint8_t) ''' return self.send(self.logging_data_acked_encode(target_system, target_component, sequence, length, first_message_offset, data), force_mavlink1=force_mavlink1) def logging_ack_encode(self, target_system, target_component, sequence): ''' An ack for a LOGGING_DATA_ACKED message target_system : system ID of the target (type:uint8_t) target_component : component ID of the target (type:uint8_t) sequence : sequence number (must match the one in LOGGING_DATA_ACKED) (type:uint16_t) ''' return MAVLink_logging_ack_message(target_system, target_component, sequence) def logging_ack_send(self, target_system, target_component, sequence, force_mavlink1=False): ''' An ack for a LOGGING_DATA_ACKED message target_system : system ID of the target (type:uint8_t) target_component : component ID of the target (type:uint8_t) sequence : sequence number (must match the one in LOGGING_DATA_ACKED) (type:uint16_t) ''' return self.send(self.logging_ack_encode(target_system, target_component, sequence), force_mavlink1=force_mavlink1) def wifi_config_ap_encode(self, ssid, password): ''' Configure AP SSID and Password. ssid : Name of Wi-Fi network (SSID). Leave it blank to leave it unchanged. (type:char) password : Password. Leave it blank for an open AP. (type:char) ''' return MAVLink_wifi_config_ap_message(ssid, password) def wifi_config_ap_send(self, ssid, password, force_mavlink1=False): ''' Configure AP SSID and Password. ssid : Name of Wi-Fi network (SSID). Leave it blank to leave it unchanged. (type:char) password : Password. Leave it blank for an open AP. (type:char) ''' return self.send(self.wifi_config_ap_encode(ssid, password), force_mavlink1=force_mavlink1) def uavcan_node_status_encode(self, time_usec, uptime_sec, health, mode, sub_mode, vendor_specific_status_code): ''' General status information of an UAVCAN node. Please refer to the definition of the UAVCAN message "uavcan.protocol.NodeStatus" for the background information. The UAVCAN specification is available at http://uavcan.org. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) uptime_sec : Time since the start-up of the node. [s] (type:uint32_t) health : Generalized node health status. (type:uint8_t, values:UAVCAN_NODE_HEALTH) mode : Generalized operating mode. (type:uint8_t, values:UAVCAN_NODE_MODE) sub_mode : Not used currently. (type:uint8_t) vendor_specific_status_code : Vendor-specific status information. (type:uint16_t) ''' return MAVLink_uavcan_node_status_message(time_usec, uptime_sec, health, mode, sub_mode, vendor_specific_status_code) def uavcan_node_status_send(self, time_usec, uptime_sec, health, mode, sub_mode, vendor_specific_status_code, force_mavlink1=False): ''' General status information of an UAVCAN node. Please refer to the definition of the UAVCAN message "uavcan.protocol.NodeStatus" for the background information. The UAVCAN specification is available at http://uavcan.org. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) uptime_sec : Time since the start-up of the node. [s] (type:uint32_t) health : Generalized node health status. (type:uint8_t, values:UAVCAN_NODE_HEALTH) mode : Generalized operating mode. (type:uint8_t, values:UAVCAN_NODE_MODE) sub_mode : Not used currently. (type:uint8_t) vendor_specific_status_code : Vendor-specific status information. (type:uint16_t) ''' return self.send(self.uavcan_node_status_encode(time_usec, uptime_sec, health, mode, sub_mode, vendor_specific_status_code), force_mavlink1=force_mavlink1) def uavcan_node_info_encode(self, time_usec, uptime_sec, name, hw_version_major, hw_version_minor, hw_unique_id, sw_version_major, sw_version_minor, sw_vcs_commit): ''' General information describing a particular UAVCAN node. Please refer to the definition of the UAVCAN service "uavcan.protocol.GetNodeInfo" for the background information. This message should be emitted by the system whenever a new node appears online, or an existing node reboots. Additionally, it can be emitted upon request from the other end of the MAVLink channel (see MAV_CMD_UAVCAN_GET_NODE_INFO). It is also not prohibited to emit this message unconditionally at a low frequency. The UAVCAN specification is available at http://uavcan.org. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) uptime_sec : Time since the start-up of the node. [s] (type:uint32_t) name : Node name string. For example, "sapog.px4.io". (type:char) hw_version_major : Hardware major version number. (type:uint8_t) hw_version_minor : Hardware minor version number. (type:uint8_t) hw_unique_id : Hardware unique 128-bit ID. (type:uint8_t) sw_version_major : Software major version number. (type:uint8_t) sw_version_minor : Software minor version number. (type:uint8_t) sw_vcs_commit : Version control system (VCS) revision identifier (e.g. git short commit hash). Zero if unknown. (type:uint32_t) ''' return MAVLink_uavcan_node_info_message(time_usec, uptime_sec, name, hw_version_major, hw_version_minor, hw_unique_id, sw_version_major, sw_version_minor, sw_vcs_commit) def uavcan_node_info_send(self, time_usec, uptime_sec, name, hw_version_major, hw_version_minor, hw_unique_id, sw_version_major, sw_version_minor, sw_vcs_commit, force_mavlink1=False): ''' General information describing a particular UAVCAN node. Please refer to the definition of the UAVCAN service "uavcan.protocol.GetNodeInfo" for the background information. This message should be emitted by the system whenever a new node appears online, or an existing node reboots. Additionally, it can be emitted upon request from the other end of the MAVLink channel (see MAV_CMD_UAVCAN_GET_NODE_INFO). It is also not prohibited to emit this message unconditionally at a low frequency. The UAVCAN specification is available at http://uavcan.org. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) uptime_sec : Time since the start-up of the node. [s] (type:uint32_t) name : Node name string. For example, "sapog.px4.io". (type:char) hw_version_major : Hardware major version number. (type:uint8_t) hw_version_minor : Hardware minor version number. (type:uint8_t) hw_unique_id : Hardware unique 128-bit ID. (type:uint8_t) sw_version_major : Software major version number. (type:uint8_t) sw_version_minor : Software minor version number. (type:uint8_t) sw_vcs_commit : Version control system (VCS) revision identifier (e.g. git short commit hash). Zero if unknown. (type:uint32_t) ''' return self.send(self.uavcan_node_info_encode(time_usec, uptime_sec, name, hw_version_major, hw_version_minor, hw_unique_id, sw_version_major, sw_version_minor, sw_vcs_commit), force_mavlink1=force_mavlink1) def obstacle_distance_encode(self, time_usec, sensor_type, distances, increment, min_distance, max_distance, increment_f=0, angle_offset=0, frame=0): ''' Obstacle distances in front of the sensor, starting from the left in increment degrees to the right time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) sensor_type : Class id of the distance sensor type. (type:uint8_t, values:MAV_DISTANCE_SENSOR) distances : Distance of obstacles around the vehicle with index 0 corresponding to North + angle_offset, unless otherwise specified in the frame. A value of 0 is valid and means that the obstacle is practically touching the sensor. A value of max_distance +1 means no obstacle is present. A value of UINT16_MAX for unknown/not used. In a array element, one unit corresponds to 1cm. [cm] (type:uint16_t) increment : Angular width in degrees of each array element. Increment direction is clockwise. This field is ignored if increment_f is non-zero. [deg] (type:uint8_t) min_distance : Minimum distance the sensor can measure. [cm] (type:uint16_t) max_distance : Maximum distance the sensor can measure. [cm] (type:uint16_t) increment_f : Angular width in degrees of each array element as a float. If non-zero then this value is used instead of the uint8_t increment field. Positive is clockwise direction, negative is counter-clockwise. [deg] (type:float) angle_offset : Relative angle offset of the 0-index element in the distances array. Value of 0 corresponds to forward. Positive is clockwise direction, negative is counter-clockwise. [deg] (type:float) frame : Coordinate frame of reference for the yaw rotation and offset of the sensor data. Defaults to MAV_FRAME_GLOBAL, which is North aligned. For body-mounted sensors use MAV_FRAME_BODY_FRD, which is vehicle front aligned. (type:uint8_t, values:MAV_FRAME) ''' return MAVLink_obstacle_distance_message(time_usec, sensor_type, distances, increment, min_distance, max_distance, increment_f, angle_offset, frame) def obstacle_distance_send(self, time_usec, sensor_type, distances, increment, min_distance, max_distance, increment_f=0, angle_offset=0, frame=0, force_mavlink1=False): ''' Obstacle distances in front of the sensor, starting from the left in increment degrees to the right time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) sensor_type : Class id of the distance sensor type. (type:uint8_t, values:MAV_DISTANCE_SENSOR) distances : Distance of obstacles around the vehicle with index 0 corresponding to North + angle_offset, unless otherwise specified in the frame. A value of 0 is valid and means that the obstacle is practically touching the sensor. A value of max_distance +1 means no obstacle is present. A value of UINT16_MAX for unknown/not used. In a array element, one unit corresponds to 1cm. [cm] (type:uint16_t) increment : Angular width in degrees of each array element. Increment direction is clockwise. This field is ignored if increment_f is non-zero. [deg] (type:uint8_t) min_distance : Minimum distance the sensor can measure. [cm] (type:uint16_t) max_distance : Maximum distance the sensor can measure. [cm] (type:uint16_t) increment_f : Angular width in degrees of each array element as a float. If non-zero then this value is used instead of the uint8_t increment field. Positive is clockwise direction, negative is counter-clockwise. [deg] (type:float) angle_offset : Relative angle offset of the 0-index element in the distances array. Value of 0 corresponds to forward. Positive is clockwise direction, negative is counter-clockwise. [deg] (type:float) frame : Coordinate frame of reference for the yaw rotation and offset of the sensor data. Defaults to MAV_FRAME_GLOBAL, which is North aligned. For body-mounted sensors use MAV_FRAME_BODY_FRD, which is vehicle front aligned. (type:uint8_t, values:MAV_FRAME) ''' return self.send(self.obstacle_distance_encode(time_usec, sensor_type, distances, increment, min_distance, max_distance, increment_f, angle_offset, frame), force_mavlink1=force_mavlink1) def odometry_encode(self, time_usec, frame_id, child_frame_id, x, y, z, q, vx, vy, vz, rollspeed, pitchspeed, yawspeed, pose_covariance, velocity_covariance, reset_counter=0, estimator_type=0): ''' Odometry message to communicate odometry information with an external interface. Fits ROS REP 147 standard for aerial vehicles (http://www.ros.org/reps/rep-0147.html). time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) frame_id : Coordinate frame of reference for the pose data. (type:uint8_t, values:MAV_FRAME) child_frame_id : Coordinate frame of reference for the velocity in free space (twist) data. (type:uint8_t, values:MAV_FRAME) x : X Position [m] (type:float) y : Y Position [m] (type:float) z : Z Position [m] (type:float) q : Quaternion components, w, x, y, z (1 0 0 0 is the null-rotation) (type:float) vx : X linear speed [m/s] (type:float) vy : Y linear speed [m/s] (type:float) vz : Z linear speed [m/s] (type:float) rollspeed : Roll angular speed [rad/s] (type:float) pitchspeed : Pitch angular speed [rad/s] (type:float) yawspeed : Yaw angular speed [rad/s] (type:float) pose_covariance : Row-major representation of a 6x6 pose cross-covariance matrix upper right triangle (states: x, y, z, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) velocity_covariance : Row-major representation of a 6x6 velocity cross-covariance matrix upper right triangle (states: vx, vy, vz, rollspeed, pitchspeed, yawspeed; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) reset_counter : Estimate reset counter. This should be incremented when the estimate resets in any of the dimensions (position, velocity, attitude, angular speed). This is designed to be used when e.g an external SLAM system detects a loop-closure and the estimate jumps. (type:uint8_t) estimator_type : Type of estimator that is providing the odometry. (type:uint8_t, values:MAV_ESTIMATOR_TYPE) ''' return MAVLink_odometry_message(time_usec, frame_id, child_frame_id, x, y, z, q, vx, vy, vz, rollspeed, pitchspeed, yawspeed, pose_covariance, velocity_covariance, reset_counter, estimator_type) def odometry_send(self, time_usec, frame_id, child_frame_id, x, y, z, q, vx, vy, vz, rollspeed, pitchspeed, yawspeed, pose_covariance, velocity_covariance, reset_counter=0, estimator_type=0, force_mavlink1=False): ''' Odometry message to communicate odometry information with an external interface. Fits ROS REP 147 standard for aerial vehicles (http://www.ros.org/reps/rep-0147.html). time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) frame_id : Coordinate frame of reference for the pose data. (type:uint8_t, values:MAV_FRAME) child_frame_id : Coordinate frame of reference for the velocity in free space (twist) data. (type:uint8_t, values:MAV_FRAME) x : X Position [m] (type:float) y : Y Position [m] (type:float) z : Z Position [m] (type:float) q : Quaternion components, w, x, y, z (1 0 0 0 is the null-rotation) (type:float) vx : X linear speed [m/s] (type:float) vy : Y linear speed [m/s] (type:float) vz : Z linear speed [m/s] (type:float) rollspeed : Roll angular speed [rad/s] (type:float) pitchspeed : Pitch angular speed [rad/s] (type:float) yawspeed : Yaw angular speed [rad/s] (type:float) pose_covariance : Row-major representation of a 6x6 pose cross-covariance matrix upper right triangle (states: x, y, z, roll, pitch, yaw; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) velocity_covariance : Row-major representation of a 6x6 velocity cross-covariance matrix upper right triangle (states: vx, vy, vz, rollspeed, pitchspeed, yawspeed; first six entries are the first ROW, next five entries are the second ROW, etc.). If unknown, assign NaN value to first element in the array. (type:float) reset_counter : Estimate reset counter. This should be incremented when the estimate resets in any of the dimensions (position, velocity, attitude, angular speed). This is designed to be used when e.g an external SLAM system detects a loop-closure and the estimate jumps. (type:uint8_t) estimator_type : Type of estimator that is providing the odometry. (type:uint8_t, values:MAV_ESTIMATOR_TYPE) ''' return self.send(self.odometry_encode(time_usec, frame_id, child_frame_id, x, y, z, q, vx, vy, vz, rollspeed, pitchspeed, yawspeed, pose_covariance, velocity_covariance, reset_counter, estimator_type), force_mavlink1=force_mavlink1) def isbd_link_status_encode(self, timestamp, last_heartbeat, failed_sessions, successful_sessions, signal_quality, ring_pending, tx_session_pending, rx_session_pending): ''' Status of the Iridium SBD link. timestamp : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) last_heartbeat : Timestamp of the last successful sbd session. The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) failed_sessions : Number of failed SBD sessions. (type:uint16_t) successful_sessions : Number of successful SBD sessions. (type:uint16_t) signal_quality : Signal quality equal to the number of bars displayed on the ISU signal strength indicator. Range is 0 to 5, where 0 indicates no signal and 5 indicates maximum signal strength. (type:uint8_t) ring_pending : 1: Ring call pending, 0: No call pending. (type:uint8_t) tx_session_pending : 1: Transmission session pending, 0: No transmission session pending. (type:uint8_t) rx_session_pending : 1: Receiving session pending, 0: No receiving session pending. (type:uint8_t) ''' return MAVLink_isbd_link_status_message(timestamp, last_heartbeat, failed_sessions, successful_sessions, signal_quality, ring_pending, tx_session_pending, rx_session_pending) def isbd_link_status_send(self, timestamp, last_heartbeat, failed_sessions, successful_sessions, signal_quality, ring_pending, tx_session_pending, rx_session_pending, force_mavlink1=False): ''' Status of the Iridium SBD link. timestamp : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) last_heartbeat : Timestamp of the last successful sbd session. The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) failed_sessions : Number of failed SBD sessions. (type:uint16_t) successful_sessions : Number of successful SBD sessions. (type:uint16_t) signal_quality : Signal quality equal to the number of bars displayed on the ISU signal strength indicator. Range is 0 to 5, where 0 indicates no signal and 5 indicates maximum signal strength. (type:uint8_t) ring_pending : 1: Ring call pending, 0: No call pending. (type:uint8_t) tx_session_pending : 1: Transmission session pending, 0: No transmission session pending. (type:uint8_t) rx_session_pending : 1: Receiving session pending, 0: No receiving session pending. (type:uint8_t) ''' return self.send(self.isbd_link_status_encode(timestamp, last_heartbeat, failed_sessions, successful_sessions, signal_quality, ring_pending, tx_session_pending, rx_session_pending), force_mavlink1=force_mavlink1) def debug_float_array_encode(self, time_usec, name, array_id, data=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]): ''' Large debug/prototyping array. The message uses the maximum available payload for data. The array_id and name fields are used to discriminate between messages in code and in user interfaces (respectively). Do not use in production code. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) name : Name, for human-friendly display in a Ground Control Station (type:char) array_id : Unique ID used to discriminate between arrays (type:uint16_t) data : data (type:float) ''' return MAVLink_debug_float_array_message(time_usec, name, array_id, data) def debug_float_array_send(self, time_usec, name, array_id, data=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], force_mavlink1=False): ''' Large debug/prototyping array. The message uses the maximum available payload for data. The array_id and name fields are used to discriminate between messages in code and in user interfaces (respectively). Do not use in production code. time_usec : Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number. [us] (type:uint64_t) name : Name, for human-friendly display in a Ground Control Station (type:char) array_id : Unique ID used to discriminate between arrays (type:uint16_t) data : data (type:float) ''' return self.send(self.debug_float_array_encode(time_usec, name, array_id, data), force_mavlink1=force_mavlink1) def statustext_long_encode(self, severity, text): ''' Status text message (use only for important status and error messages). The full message payload can be used for status text, but we recommend that updates be kept concise. Note: The message is intended as a less restrictive replacement for STATUSTEXT. severity : Severity of status. Relies on the definitions within RFC-5424. (type:uint8_t, values:MAV_SEVERITY) text : Status text message, without null termination character. (type:char) ''' return MAVLink_statustext_long_message(severity, text) def statustext_long_send(self, severity, text, force_mavlink1=False): ''' Status text message (use only for important status and error messages). The full message payload can be used for status text, but we recommend that updates be kept concise. Note: The message is intended as a less restrictive replacement for STATUSTEXT. severity : Severity of status. Relies on the definitions within RFC-5424. (type:uint8_t, values:MAV_SEVERITY) text : Status text message, without null termination character. (type:char) ''' return self.send(self.statustext_long_encode(severity, text), force_mavlink1=force_mavlink1) def actuator_output_status_encode(self, time_usec, active, actuator): ''' The raw values of the actuator outputs. time_usec : Timestamp (since system boot). [us] (type:uint64_t) active : Active outputs (type:uint32_t) actuator : Servo / motor output array values. Zero values indicate unused channels. (type:float) ''' return MAVLink_actuator_output_status_message(time_usec, active, actuator) def actuator_output_status_send(self, time_usec, active, actuator, force_mavlink1=False): ''' The raw values of the actuator outputs. time_usec : Timestamp (since system boot). [us] (type:uint64_t) active : Active outputs (type:uint32_t) actuator : Servo / motor output array values. Zero values indicate unused channels. (type:float) ''' return self.send(self.actuator_output_status_encode(time_usec, active, actuator), force_mavlink1=force_mavlink1) def wheel_distance_encode(self, time_usec, count, distance): ''' Cumulative distance traveled for each reported wheel. time_usec : Timestamp (synced to UNIX time or since system boot). [us] (type:uint64_t) count : Number of wheels reported. (type:uint8_t) distance : Distance reported by individual wheel encoders. Forward rotations increase values, reverse rotations decrease them. Not all wheels will necessarily have wheel encoders; the mapping of encoders to wheel positions must be agreed/understood by the endpoints. [m] (type:double) ''' return MAVLink_wheel_distance_message(time_usec, count, distance) def wheel_distance_send(self, time_usec, count, distance, force_mavlink1=False): ''' Cumulative distance traveled for each reported wheel. time_usec : Timestamp (synced to UNIX time or since system boot). [us] (type:uint64_t) count : Number of wheels reported. (type:uint8_t) distance : Distance reported by individual wheel encoders. Forward rotations increase values, reverse rotations decrease them. Not all wheels will necessarily have wheel encoders; the mapping of encoders to wheel positions must be agreed/understood by the endpoints. [m] (type:double) ''' return self.send(self.wheel_distance_encode(time_usec, count, distance), force_mavlink1=force_mavlink1)
[ "Miao@DESKTOP-AJA95IE" ]
Miao@DESKTOP-AJA95IE
40f34e2b13d2dbd43ddbbdfaace14b75eac30a92
e56214188faae8ebfb36a463e34fc8324935b3c2
/test/test_boot_pxe_ref.py
b14fd7196b588ad8b507fa7ab35924a40ec22fa7
[ "Apache-2.0" ]
permissive
CiscoUcs/intersight-python
866d6c63e0cb8c33440771efd93541d679bb1ecc
a92fccb1c8df4332ba1f05a0e784efbb4f2efdc4
refs/heads/master
2021-11-07T12:54:41.888973
2021-10-25T16:15:50
2021-10-25T16:15:50
115,440,875
25
18
Apache-2.0
2020-03-02T16:19:49
2017-12-26T17:14:03
Python
UTF-8
Python
false
false
1,851
py
# coding: utf-8 """ Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. # noqa: E501 The version of the OpenAPI document: 1.0.9-1295 Contact: intersight@cisco.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import intersight from intersight.models.boot_pxe_ref import BootPxeRef # noqa: E501 from intersight.rest import ApiException class TestBootPxeRef(unittest.TestCase): """BootPxeRef unit test stubs""" def setUp(self): pass def tearDown(self): pass def testBootPxeRef(self): """Test BootPxeRef""" # FIXME: construct object with mandatory attributes with example values # model = intersight.models.boot_pxe_ref.BootPxeRef() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "ucs-build@github.com" ]
ucs-build@github.com
a323096e6b7bd55f5063ce02e8880ffba43feb9e
aed0016db7f4d22e7d66e6fddb7bf4ef68a3c692
/neural_sp/bin/args_lm.py
451d32dd41cc03cd73b2501e5b1c8b81a479d483
[]
no_license
thanhkm/neural_sp
6a5575111c83d1fdd97edec21f90fe647965cb69
1a5a5ed54f4cb79436007593dbd0d782b246a0c7
refs/heads/master
2020-12-26T23:22:56.964151
2020-01-15T23:40:22
2020-01-15T23:40:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,678
py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2018 Kyoto University (Hirofumi Inaguma) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Args option for the LM task.""" import configargparse from distutils.util import strtobool def parse(): parser = configargparse.ArgumentParser( config_file_parser_class=configargparse.YAMLConfigFileParser, formatter_class=configargparse.ArgumentDefaultsHelpFormatter) parser.add('--config', is_config_file=True, help='config file path') # general parser.add_argument('--corpus', type=str, help='corpus name') parser.add_argument('--n_gpus', type=int, default=1, help='number of GPUs (0 indicates CPU)') parser.add_argument('--model_save_dir', type=str, default=False, help='directory to save a model') parser.add_argument('--resume', type=str, default=False, nargs='?', help='model path to resume training') parser.add_argument('--job_name', type=str, default=False, help='job name') parser.add_argument('--stdout', type=strtobool, default=False, help='print to standard output') parser.add_argument('--recog_stdout', type=strtobool, default=False, help='print to standard output during evaluation') # dataset parser.add_argument('--train_set', type=str, help='tsv file path for the training set') parser.add_argument('--dev_set', type=str, help='tsv file path for the development set') parser.add_argument('--eval_sets', type=str, default=[], nargs='+', help='tsv file paths for the evaluation sets') parser.add_argument('--nlsyms', type=str, default=False, nargs='?', help='non-linguistic symbols file path') parser.add_argument('--dict', type=str, help='dictionary file path') parser.add_argument('--unit', type=str, default='word', choices=['word', 'wp', 'char', 'word_char'], help='output unit') parser.add_argument('--wp_model', type=str, default=False, nargs='?', help='wordpiece model path') # features parser.add_argument('--min_n_tokens', type=int, default=1, help='minimum number of input tokens') parser.add_argument('--dynamic_batching', type=strtobool, default=False, help='') # topology parser.add_argument('--lm_type', type=str, default='lstm', choices=['lstm', 'gru', 'gated_conv_custom', 'gated_conv_8', 'gated_conv_8B', 'gated_conv_9', 'gated_conv_13', 'gated_conv_14', 'gated_conv_14B', 'transformer'], help='type of language model') parser.add_argument('--kernel_size', type=int, default=4, help='kernel size for GatedConvLM') parser.add_argument('--n_units', type=int, default=1024, help='number of units in each layer') parser.add_argument('--n_projs', type=int, default=0, help='number of units in the projection layer') parser.add_argument('--n_layers', type=int, default=5, help='number of layers') parser.add_argument('--emb_dim', type=int, default=1024, help='number of dimensions in the embedding layer') parser.add_argument('--n_units_null_context', type=int, default=0, nargs='?', help='') parser.add_argument('--tie_embedding', type=strtobool, default=False, nargs='?', help='tie input and output embedding') parser.add_argument('--residual', type=strtobool, default=False, nargs='?', help='') parser.add_argument('--use_glu', type=strtobool, default=False, nargs='?', help='use Gated Linear Unit (GLU) for fully-connected layers') # optimization parser.add_argument('--batch_size', type=int, default=256, help='mini-batch size') parser.add_argument('--bptt', type=int, default=100, help='BPTT length') parser.add_argument('--optimizer', type=str, default='adam', choices=['adam', 'adadelta', 'adagrad', 'sgd', 'momentum', 'nesterov', 'noam'], help='type of optimizer') parser.add_argument('--n_epochs', type=int, default=50, help='number of epochs to train the model') parser.add_argument('--convert_to_sgd_epoch', type=int, default=20, help='epoch to converto to SGD fine-tuning') parser.add_argument('--print_step', type=int, default=100, help='print log per this value') parser.add_argument('--lr', type=float, default=1e-3, help='initial learning rate') parser.add_argument('--lr_factor', type=float, default=10.0, help='factor of learning rate for Transformer') parser.add_argument('--eps', type=float, default=1e-6, help='epsilon parameter for Adadelta optimizer') parser.add_argument('--lr_decay_type', type=str, default='always', choices=['always', 'metric', 'warmup'], help='type of learning rate decay') parser.add_argument('--lr_decay_start_epoch', type=int, default=10, help='epoch to start to decay learning rate') parser.add_argument('--lr_decay_rate', type=float, default=0.9, help='decay rate of learning rate') parser.add_argument('--lr_decay_patient_n_epochs', type=int, default=0, help='number of epochs to tolerate learning rate decay when validation perfomance is not improved') parser.add_argument('--early_stop_patient_n_epochs', type=int, default=5, help='number of epochs to tolerate stopping training when validation perfomance is not improved') parser.add_argument('--sort_stop_epoch', type=int, default=10000, help='epoch to stop soring utterances by length') parser.add_argument('--eval_start_epoch', type=int, default=1, help='first epoch to start evalaution') parser.add_argument('--warmup_start_lr', type=float, default=0, help='initial learning rate for learning rate warm up') parser.add_argument('--warmup_n_steps', type=int, default=0, help='number of steps to warm up learing rate') parser.add_argument('--accum_grad_n_steps', type=int, default=1, help='total number of steps to accumulate gradients') # initialization parser.add_argument('--param_init', type=float, default=0.1, help='') parser.add_argument('--rec_weight_orthogonal', type=strtobool, default=False, help='') parser.add_argument('--pretrained_model', type=str, default=False, nargs='?', help='') # regularization parser.add_argument('--clip_grad_norm', type=float, default=5.0, help='') parser.add_argument('--dropout_in', type=float, default=0.0, help='dropout probability for the input embedding layer') parser.add_argument('--dropout_hidden', type=float, default=0.0, help='dropout probability for the hidden layers') parser.add_argument('--dropout_out', type=float, default=0.0, help='dropout probability for the output layer') parser.add_argument('--dropout_att', type=float, default=0.1, help='dropout probability for the attention weights (for Transformer)') parser.add_argument('--weight_decay', type=float, default=1e-6, help='') parser.add_argument('--lsm_prob', type=float, default=0.0, help='probability of label smoothing') parser.add_argument('--logits_temp', type=float, default=1.0, help='') parser.add_argument('--backward', type=strtobool, default=False, nargs='?', help='') parser.add_argument('--adaptive_softmax', type=strtobool, default=False, help='use adaptive softmax') # transformer parser.add_argument('--transformer_d_model', type=int, default=256, help='number of units in self-attention layers in Transformer') parser.add_argument('--transformer_d_ff', type=int, default=2048, help='number of units in feed-forward fully-conncected layers in Transformer') parser.add_argument('--transformer_attn_type', type=str, default='scaled_dot', choices=['scaled_dot', 'add', 'average'], help='type of attention for Transformer') parser.add_argument('--transformer_n_heads', type=int, default=4, help='number of heads in the attention layer for Transformer') parser.add_argument('--transformer_pe_type', type=str, default='add', choices=['add', 'concat', 'learned_add', 'learned_concat', 'none'], help='type of positional encoding') parser.add_argument('--transformer_layer_norm_eps', type=float, default=1e-12, help='epsilon value for layer narmalization') parser.add_argument('--transformer_ffn_activation', type=str, default='relu', choices=['relu', 'gelu', 'gelu_accurate', 'glu'], help='nonlinear activation for position wise feed-forward layer') parser.add_argument('--transformer_param_init', type=str, default='xavier_uniform', choices=['xavier_uniform', 'pytorch'], help='parameter initializatin for Transformer') # contextualization parser.add_argument('--shuffle', type=strtobool, default=False, nargs='?', help='shuffle utterances per epoch') parser.add_argument('--serialize', type=strtobool, default=False, nargs='?', help='serialize text according to onset in dialogue') # evaluation parameters parser.add_argument('--recog_sets', type=str, default=[], nargs='+', help='tsv file paths for the evaluation sets') parser.add_argument('--recog_model', type=str, default=False, nargs='+', help='model path') parser.add_argument('--recog_dir', type=str, default=False, help='directory to save decoding results') parser.add_argument('--recog_batch_size', type=int, default=1, help='size of mini-batch in evaluation') parser.add_argument('--recog_n_average', type=int, default=5, help='number of models for the model averaging of Transformer') # cache parameters parser.add_argument('--recog_n_caches', type=int, default=0, help='number of tokens for cache') parser.add_argument('--recog_cache_theta', type=float, default=0.2, help='theta paramter for cache') parser.add_argument('--recog_cache_lambda', type=float, default=0.2, help='lambda paramter for cache') args = parser.parse_args() # args, _ = parser.parse_known_args(parser) return args
[ "hiro.mhbc@gmail.com" ]
hiro.mhbc@gmail.com
057418d9203386866b6b7fbc6ffe76f306489dcc
bddc40a97f92fafb8cbbbfdbdfe6774996578bb0
/exercicioLista_funcoes/ex12.py
ee26987f60bcef8d32b6fc9a3cf3d93898187be6
[]
no_license
andrehmiguel/treinamento
8f83041bd51387dd3e5cafed09c4bb0a08d0e375
ed18e6a8cfba0baaa68757c12893c62a0938a67e
refs/heads/main
2023-01-31T13:15:58.113392
2020-12-16T02:47:44
2020-12-16T02:47:44
317,631,214
0
0
null
null
null
null
UTF-8
Python
false
false
680
py
# 12. Embaralha palavra . Construa uma função que receba uma string como parâmetro e # devolva outra string com os carateres embaralhados. Por exemplo: se função # receber a palavra python , pode retornar npthyo , ophtyn ou qualquer outra # combinação possível, de forma aleatória. Padronize em sua função que todos os # caracteres serão devolvidos em caixa alta ou caixa baixa, independentemente de # como foram digitados. from random import shuffle def embaralha(palavra): lista = list(palavra) shuffle(lista) lista = ''.join(lista) print(lista.upper()) palavra = input('Insira uma palavra ou frase para embaralhar: ').strip() embaralha(palavra)
[ "andrehmiguel@outlook.com" ]
andrehmiguel@outlook.com
4c3c0468f63cea5bff5bb6f7efcfb911f37463bf
d8fae39bcfdff1974c5fecd96ed156c4db80e280
/tensorflow/core/function/capture/capture_container.py
fc8bae0ddc34784edcf9c98d1fb7b1b3ad30d7d4
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
enowy/tensorflow
d2834bda2ff35995637acc55321fc00113d212c1
b4276073ea8e3bd51229c0726f052f79d8dd239d
refs/heads/master
2023-04-11T02:02:19.956400
2023-03-23T09:06:17
2023-03-23T09:10:43
62,356,730
0
0
null
2016-07-01T02:38:38
2016-07-01T02:38:38
null
UTF-8
Python
false
false
11,537
py
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """FuncGraph and related functionality.""" import collections as py_collections import dataclasses import functools import inspect from typing import Any, Callable, Hashable, Mapping, Union from tensorflow.core.function import trace_type from tensorflow.python import pywrap_tfe from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import type_spec from tensorflow.python.types import core from tensorflow.python.util import nest from tensorflow.python.util import object_identity _EAGER_CONST_THRESHOLD = 128 @dataclasses.dataclass(frozen=True) class CaptureContainer(): """A container for both by-reference and by-value captures. external: Used to record the tensor external to the func_graph. For by-value captures, it would be the original tensor. For by-reference captures, it would be the lambda function, which will be called later to get the capture's runtime value. internal: An internal placeholder for the capture, or a constant tensor. The external value of the capture will be fed to this internal placeholder when executing the func_graph as a side input. idf: A Hashable identifier for the capture. is_by_ref: A bool indicates if the capture is call by reference or value. This flag will determine how `CaptureContainer.internal` is used. """ external: Any internal: core.Tensor idf: Hashable is_by_ref: bool = False class CachedCaptureDict(py_collections.OrderedDict): """A dict like container for captures with cached tuples.""" def __init__(self, *args, **kwargs): self._tuple_cache = [] super().__init__(*args, **kwargs) def _recompute_tuple_cache(self): self._tuple_cache = [( c.external, c.internal) for c in self.values()] def pop(self, key, default=None): if key in self.keys(): ret = super().pop(key, default) self._recompute_tuple_cache() return ret else: return default def __setitem__(self, key, value): assert isinstance(value, CaptureContainer) if key in self.keys(): super().__setitem__(key, value) self._recompute_tuple_cache() else: super().__setitem__(key, value) self._tuple_cache.append((value.external, value.internal)) def __delitem__(self, key): super().__delitem__(key) self._recompute_tuple_cache() def clear(self): self._tuple_cache = [] super().clear() @property def tuple_cache(self): return self._tuple_cache class FunctionCaptures(object): """A container for all capture usages within FuncGraph.""" def __init__(self): # Dict that maps capture identifier -> CaptureContainer self._by_ref = py_collections.OrderedDict() self._by_val = CachedCaptureDict() # Set of external ops on which the graph has a control dependency self.control = object_identity.ObjectIdentitySet() def capture_by_value( self, graph: "FuncGraph", tensor: core.Tensor, name: str = None ) -> core.Tensor: """Captures `tensor` if it's external to this graph. If `tensor` is from a different graph, returns a placeholder for it. `tensor` and the placeholder will appear in self.captures, and the placeholder will appear in self.inputs. Multiple calls to this method with the same `tensor` argument will return the same placeholder. If `tensor` is from this graph, returns `tensor`. Args: graph: The FuncGraph that captures this tensor. tensor: Tensor. May be from this FuncGraph or a different graph. name: Optional name if a placeholder is created. Returns: Tensor from this FuncGraph. Raises: InaccessibleTensorError: if any tensors are accessed in a manner that bypasses the mechanisms required for the data dependencies to be correctly wired. """ if isinstance(tensor, core.Value): if name is None: # A unique (within the program execution) integer. name = str(pywrap_tfe.TFE_Py_UID()) # Small EagerTensors are captured with Const ops if (tensor.dtype in dtypes.TF_VALUE_DTYPES and functools.reduce(lambda a, b: a*b, tensor.shape, 1) <= _EAGER_CONST_THRESHOLD): capture = self.by_val_captures.get(id(tensor)) if capture is None: graph_const = tensor._capture_as_const(name) # pylint: disable=protected-access if graph_const is None: # Some eager tensors, e.g. parallel tensors, are not convertible to # a single constant. We'll use a placeholder for this case. graph_const = self._create_placeholder_helper(graph, tensor, name) self.add_or_replace(tensor, graph_const, id(tensor), False) graph.inputs.append(graph_const) else: graph_const = capture.internal graph_const._record_tape(tensor) # pylint: disable=protected-access return graph_const # Large EagerTensors and resources are captured with Placeholder ops return self._create_placeholder_helper(graph, tensor, name) if tensor.graph is not graph: graph._validate_in_scope(tensor) # pylint: disable=protected-access if name is None: name = tensor.op.name # cond/while graphs override _capture_helper() so cannot call # self.create_placeholder_helper() here directly. return graph._capture_helper(tensor, name) # pylint: disable=protected-access return tensor def add_or_replace( self, value: Any, placeholder: core.Tensor, idf: Hashable, is_by_ref: bool = False): """Replace a already exsiting capture, otherwise add it.""" capture = CaptureContainer(value, placeholder, idf, is_by_ref) if is_by_ref: self._by_ref[idf] = capture else: self._by_val[idf] = capture return capture def pop(self, idf: Hashable, is_by_ref: bool = False) -> Union[core.Tensor, None]: if is_by_ref: return self._by_ref.pop(idf, None) else: return self._by_val.pop(idf, None) def reset_captures(self, tensors, placeholders): """Set the captures with the provided list of captures & placeholder.""" self._by_val = CachedCaptureDict() for external, internal in zip(tensors, placeholders): idf = id(external) c = CaptureContainer(external, internal, idf) self._by_val[idf] = c def capture_by_ref(self, lam: Callable[[], Any], idf: Hashable = None): """Create a by-referece capture if not exists.""" # check if the capture exist in self._by_ref if idf is not None and idf in self._by_ref: capture = self._by_ref[idf] return capture.internal if idf is None: idf = len(self._by_ref) if context.executing_eagerly(): return lam() placeholder = self._create_capture_placeholder(lam) capture = CaptureContainer(lam, placeholder, idf, is_by_ref=True) self._by_ref[idf] = capture return capture.internal def merge_by_ref_with(self, other: "FunctionCaptures"): """Add by-ref captures from `other` to `self` if not exist.""" assert isinstance(other, FunctionCaptures) for key, capture in other.by_ref_captures.items(): if key not in self._by_ref: self._by_ref[key] = capture def get_by_ref_snapshot(self) -> Mapping[Hashable, Any]: """Get a snapshot of current values of by-ref captures.""" snapshot = {} for key, capture in self._by_ref.items(): func = capture.external snapshot[key] = func() return snapshot def _create_placeholder_helper( self, graph: "FuncGraph", tensor: core.Tensor, name: str): """A helper function to create capture placeholder.""" capture = self._by_val.get(id(tensor)) if capture is None: tracing_ctx = trace_type.InternalTracingContext() spec = trace_type.from_value(tensor, tracing_ctx) spec._name = name # pylint: disable=protected-access if isinstance(tensor, core.Value) and tensor.is_packed: composite_device_name = tensor.device else: composite_device_name = None placeholder_ctx = trace_type.InternalPlaceholderContext( graph, with_none_control_dependencies=True, composite_device_name=composite_device_name) placeholder_ctx._spec_id_to_handledata = ( # pylint: disable=protected-access tracing_ctx.get_handledata_mapping() ) placeholder = spec.placeholder_value(placeholder_ctx) self.add_or_replace(tensor, placeholder, id(tensor), False) graph.inputs.append(placeholder) else: placeholder = capture.internal placeholder._record_tape(tensor) # pylint: disable=protected-access return placeholder # TODO(panzf): Use FunctionType/TraceType to create placeholder here. def _create_capture_placeholder(self, func: Callable[[], Any]) -> ...: """Create placeholder if the input is tensor.""" values_nest = func() values_flat = nest.flatten(values_nest) # Return values in flat format. It consists of placeholders and non-tensor # values. return_flat = [] tensor_spec_flat = [] # Create return_flat and replace tensors with None. Later, each None is # replaced again by corresponding placeholders for value in values_flat: if isinstance(value, core.Tensor): return_flat.append(None) tensor_spec_flat.append(type_spec.type_spec_from_value(value)) elif isinstance(value, set) or isinstance(value, frozenset): raise NotImplementedError( (f"Side input returned by '{inspect.getsource(func).strip()}' " f"has element of {type(value)} type, which is currently not " "supported by tf.function.")) else: return_flat.append(value) if tensor_spec_flat: def tensor_func(): values = nest.flatten(func()) return [value for value in values if isinstance(value, core.Tensor)] # TODO(panzf): remove get_default_graph after moving # capture_call_time_value to this class. graph = ops.get_default_graph() placeholder_flat = graph.capture_call_time_value( tensor_func, tensor_spec_flat) # replace None that represents tensors with placehoders flat_ptr = 0 for idx, item in enumerate(return_flat): if item is None: return_flat[idx] = placeholder_flat[flat_ptr] flat_ptr += 1 return_nest = nest.pack_sequence_as(values_nest, return_flat) return return_nest @property def by_ref_captures(self): return self._by_ref @property def by_val_captures(self): return self._by_val @property def by_val_capture_tuples(self): return self._by_val.tuple_cache
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
3ba66f0eed8ec2ff6be93418deccfcb8dd27c404
ece0d321e48f182832252b23db1df0c21b78f20c
/engine/2.80/scripts/addons/rigify/rigs/limbs/rear_paw.py
74974bb632ee3d0b20de7f3eac7555dbf09bb20a
[ "Unlicense", "GPL-3.0-only", "Font-exception-2.0", "GPL-3.0-or-later", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain-disclaimer", "Bitstream-Vera", "LicenseRef-scancode-blender-2010", "LGPL-2.1-or-later", "GPL-2.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "PSF-2.0", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "BSD-2-Clause" ]
permissive
byteinc/Phasor
47d4e48a52fa562dfa1a2dbe493f8ec9e94625b9
f7d23a489c2b4bcc3c1961ac955926484ff8b8d9
refs/heads/master
2022-10-25T17:05:01.585032
2019-03-16T19:24:22
2019-03-16T19:24:22
175,723,233
3
1
Unlicense
2022-10-21T07:02:37
2019-03-15T00:58:08
Python
UTF-8
Python
false
false
13,123
py
import bpy from .paw import Rig as pawRig from .paw import parameters_ui from .paw import add_parameters IMPLEMENTATION = True # Include and set True if Rig is just an implementation for a wrapper class # add_parameters and parameters_ui are unused for implementation classes class Rig(pawRig): def __init__(self, obj, bone_name, params): super(Rig, self).__init__(obj, bone_name, params) def create_sample(obj): # generated by rigify.utils.write_metarig bpy.ops.object.mode_set(mode='EDIT') arm = obj.data bones = {} bone = arm.edit_bones.new('thigh.L') bone.head[:] = 0.0291, 0.1181, 0.2460 bone.tail[:] = 0.0293, 0.1107, 0.1682 bone.roll = 3.1383 bone.use_connect = False bones['thigh.L'] = bone.name bone = arm.edit_bones.new('shin.L') bone.head[:] = 0.0293, 0.1107, 0.1682 bone.tail[:] = 0.0293, 0.1684, 0.1073 bone.roll = 3.1416 bone.use_connect = True bone.parent = arm.edit_bones[bones['thigh.L']] bones['shin.L'] = bone.name bone = arm.edit_bones.new('foot.L') bone.head[:] = 0.0293, 0.1684, 0.1073 bone.tail[:] = 0.0293, 0.1530, 0.0167 bone.roll = 3.1416 bone.use_connect = True bone.parent = arm.edit_bones[bones['shin.L']] bones['foot.L'] = bone.name bone = arm.edit_bones.new('r_toe.L') bone.head[:] = 0.0293, 0.1530, 0.0167 bone.tail[:] = 0.0293, 0.1224, 0.0167 bone.roll = 0.0000 bone.use_connect = True bone.parent = arm.edit_bones[bones['foot.L']] bones['r_toe.L'] = bone.name bone = arm.edit_bones.new('r_palm.001.L') bone.head[:] = 0.0220, 0.1457, 0.0123 bone.tail[:] = 0.0215, 0.1401, 0.0123 bone.roll = 0.0014 bone.use_connect = False bone.parent = arm.edit_bones[bones['r_toe.L']] bones['r_palm.001.L'] = bone.name bone = arm.edit_bones.new('r_palm.002.L') bone.head[:] = 0.0297, 0.1458, 0.0123 bone.tail[:] = 0.0311, 0.1393, 0.0123 bone.roll = -0.0005 bone.use_connect = False bone.parent = arm.edit_bones[bones['r_toe.L']] bones['r_palm.002.L'] = bone.name bone = arm.edit_bones.new('r_palm.003.L') bone.head[:] = 0.0363, 0.1473, 0.0123 bone.tail[:] = 0.0376, 0.1407, 0.0123 bone.roll = 0.0000 bone.use_connect = False bone.parent = arm.edit_bones[bones['r_toe.L']] bones['r_palm.003.L'] = bone.name bone = arm.edit_bones.new('r_palm.004.L') bone.head[:] = 0.0449, 0.1501, 0.0123 bone.tail[:] = 0.0466, 0.1479, 0.0123 bone.roll = -0.0004 bone.use_connect = False bone.parent = arm.edit_bones[bones['r_toe.L']] bones['r_palm.004.L'] = bone.name bone = arm.edit_bones.new('r_index.001.L') bone.head[:] = 0.0215, 0.1367, 0.0087 bone.tail[:] = 0.0217, 0.1325, 0.0070 bone.roll = -0.3427 bone.use_connect = False bone.parent = arm.edit_bones[bones['r_palm.001.L']] bones['r_index.001.L'] = bone.name bone = arm.edit_bones.new('r_middle.001.L') bone.head[:] = 0.0311, 0.1358, 0.0117 bone.tail[:] = 0.0324, 0.1297, 0.0092 bone.roll = -1.0029 bone.use_connect = False bone.parent = arm.edit_bones[bones['r_palm.002.L']] bones['r_middle.001.L'] = bone.name bone = arm.edit_bones.new('r_ring.001.L') bone.head[:] = 0.0376, 0.1372, 0.0117 bone.tail[:] = 0.0389, 0.1311, 0.0092 bone.roll = -1.0029 bone.use_connect = False bone.parent = arm.edit_bones[bones['r_palm.003.L']] bones['r_ring.001.L'] = bone.name bone = arm.edit_bones.new('r_pinky.001.L') bone.head[:] = 0.0466, 0.1444, 0.0083 bone.tail[:] = 0.0476, 0.1412, 0.0074 bone.roll = -1.7551 bone.use_connect = False bone.parent = arm.edit_bones[bones['r_palm.004.L']] bones['r_pinky.001.L'] = bone.name bone = arm.edit_bones.new('r_index.002.L') bone.head[:] = 0.0217, 0.1325, 0.0070 bone.tail[:] = 0.0221, 0.1271, 0.0038 bone.roll = -0.2465 bone.use_connect = True bone.parent = arm.edit_bones[bones['r_index.001.L']] bones['r_index.002.L'] = bone.name bone = arm.edit_bones.new('r_middle.002.L') bone.head[:] = 0.0324, 0.1297, 0.0092 bone.tail[:] = 0.0343, 0.1210, 0.0039 bone.roll = -0.7479 bone.use_connect = True bone.parent = arm.edit_bones[bones['r_middle.001.L']] bones['r_middle.002.L'] = bone.name bone = arm.edit_bones.new('r_ring.002.L') bone.head[:] = 0.0389, 0.1311, 0.0092 bone.tail[:] = 0.0407, 0.1229, 0.0042 bone.roll = -0.7479 bone.use_connect = True bone.parent = arm.edit_bones[bones['r_ring.001.L']] bones['r_ring.002.L'] = bone.name bone = arm.edit_bones.new('r_pinky.002.L') bone.head[:] = 0.0476, 0.1412, 0.0074 bone.tail[:] = 0.0494, 0.1351, 0.0032 bone.roll = -0.8965 bone.use_connect = True bone.parent = arm.edit_bones[bones['r_pinky.001.L']] bones['r_pinky.002.L'] = bone.name bpy.ops.object.mode_set(mode='OBJECT') pbone = obj.pose.bones[bones['thigh.L']] pbone.rigify_type = 'limbs.super_limb' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' try: pbone.rigify_parameters.limb_type = "paw" except AttributeError: pass try: pbone.rigify_parameters.fk_layers = [False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False] except AttributeError: pass try: pbone.rigify_parameters.tweak_layers = [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False] except AttributeError: pass try: pbone.rigify_parameters.segments = 2 except AttributeError: pass pbone = obj.pose.bones[bones['shin.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['foot.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_toe.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_palm.001.L']] pbone.rigify_type = 'limbs.super_palm' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_palm.002.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_palm.003.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_palm.004.L']] pbone.rigify_type = 'limbs.super_palm' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_index.001.L']] pbone.rigify_type = 'limbs.simple_tentacle' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' try: pbone.rigify_parameters.tweak_layers = [False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False] except AttributeError: pass pbone = obj.pose.bones[bones['r_middle.001.L']] pbone.rigify_type = 'limbs.simple_tentacle' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' try: pbone.rigify_parameters.tweak_layers = [False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False] except AttributeError: pass pbone = obj.pose.bones[bones['r_ring.001.L']] pbone.rigify_type = 'limbs.simple_tentacle' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' try: pbone.rigify_parameters.tweak_layers = [False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False] except AttributeError: pass pbone = obj.pose.bones[bones['r_pinky.001.L']] pbone.rigify_type = 'limbs.simple_tentacle' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' try: pbone.rigify_parameters.tweak_layers = [False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False] except AttributeError: pass pbone = obj.pose.bones[bones['r_index.002.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_middle.002.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_ring.002.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' pbone = obj.pose.bones[bones['r_pinky.002.L']] pbone.rigify_type = '' pbone.lock_location = (False, False, False) pbone.lock_rotation = (False, False, False) pbone.lock_rotation_w = False pbone.lock_scale = (False, False, False) pbone.rotation_mode = 'QUATERNION' bpy.ops.object.mode_set(mode='EDIT') for bone in arm.edit_bones: bone.select = False bone.select_head = False bone.select_tail = False for b in bones: bone = arm.edit_bones[bones[b]] bone.select = True bone.select_head = True bone.select_tail = True arm.edit_bones.active = bone for eb in arm.edit_bones: if ('thigh' in eb.name) or ('shin' in eb.name) or ('foot' in eb.name) or ('toe' in eb.name): eb.layers = (False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False) else: eb.layers = (False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False) arm.layers = (False, False, False, False, False, True, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False) if __name__ == "__main__": create_sample(bpy.context.active_object)
[ "admin@irradiate.net" ]
admin@irradiate.net
c75536852e252b5c4f8293e45f4008fa0530ec2a
18b741084bda1f1500e9accd2a52b8e75b23c8be
/mootdx/tools/__init__.py
23308c243ebde3e3097759557232e2deaccfc518
[ "MIT" ]
permissive
adam1iu/mootdx
bd55baaf10a10c9862f81776a045a3ae3c1ee8ad
704e2d20d6d81a16b82c67e028de54e48a7cae9c
refs/heads/master
2023-08-25T09:33:54.619594
2021-10-29T06:21:05
2021-10-29T06:21:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
84
py
# -*- coding: utf-8 -*- # @Author : BoPo # @Time : 2021/9/18 10:00 # @Function:
[ "ibopo@126.com" ]
ibopo@126.com
5dd552a5a78b85cdb055b52651dfb140b36eca81
7255a09821deba655309b74927091ac9ab8b6075
/example/ROAD/code/reborn2.py
de7caa75976e48d03da9d5e55344d7728e2b4973
[]
no_license
summer1719/pytorchgo
2814141d6fc0b5c3369d2b9d37e1140e410b25ec
1ffd561a53d583ca4098297e585e786e472ddd1a
refs/heads/master
2020-04-25T20:45:04.203802
2019-01-10T15:03:31
2019-01-10T15:03:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
17,138
py
import argparse import torch from pytorchgo.utils.pytorch_utils import model_summary, optimizer_summary from pytorchgo.utils.weight_init import weights_init import torch.nn.functional as F from torch.utils import data, model_zoo import math import os import os.path as osp import shutil import numpy as np from torch.autograd import Variable import tqdm import itertools import torchfcn from util_fns import get_parameters from pytorchgo.loss.loss import CrossEntropyLoss2d_Seg, Diff2d,CrossEntropyLoss2d from pytorchgo.utils.pytorch_utils import step_scheduler from pytorchgo.utils import logger class_num = 16 image_size = [1024, 512] # [640, 320] max_epoch = 10 base_lr = 1e-5 dis_lr = 1e-5 base_lr_schedule = [(5, 1e-6), (8, 1e-7)] dis_lr_schedule = [(5, 1e-6), (8, 1e-7)] LOSS_PRINT_INTERVAL = 500 QUICK_VAL = 50000 L_LOSS_WEIGHT = 1 DISTILL_WEIGHT = 1 DIS_WEIGHT = 1 G_STEP = 1 D_STEP = 2 Deeplabv2_restore_from = 'http://vllab.ucmerced.edu/ytsai/CVPR18/DeepLab_resnet_pretrained_init-f81d91e8.pth' def main(): logger.auto_set_dir() global args parser = argparse.ArgumentParser() parser = argparse.ArgumentParser() parser.add_argument('--dataroot', default='/home/hutao/lab/pytorchgo/example/ROAD/data', help='Path to source dataset') parser.add_argument('--batchSize', type=int, default=1, help='input batch size') parser.add_argument('--max_epoch', type=int, default=max_epoch, help='Number of training iterations') parser.add_argument('--optimizer', type=str, default='SGD', help='Optimizer to use | SGD, Adam') parser.add_argument('--lr', type=float, default=base_lr, help='learning rate') parser.add_argument('--momentum', type=float, default=0.99, help='Momentum for SGD') parser.add_argument('--beta1', type=float, default=0.9, help='beta1 for adam. default=0.5') parser.add_argument('--weight_decay', type=float, default=0.0005, help='Weight decay') parser.add_argument('--model', type=str, default='vgg16') parser.add_argument('--gpu', type=int, default=3) args = parser.parse_args() print(args) gpu = args.gpu os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu) cuda = torch.cuda.is_available() torch.manual_seed(1337) if cuda: logger.info("random seed 1337") torch.cuda.manual_seed(1337) # Defining data loaders kwargs = {'num_workers': 4, 'pin_memory': True, 'drop_last': True} if cuda else {} train_loader = torch.utils.data.DataLoader( torchfcn.datasets.SYNTHIA('SYNTHIA', args.dataroot, split='train', transform=True, image_size=image_size), batch_size=args.batchSize, shuffle=True, **kwargs) val_loader = torch.utils.data.DataLoader( torchfcn.datasets.CityScapes('cityscapes', args.dataroot, split='val', transform=True, image_size=[2048,1024]), batch_size=1, shuffle=False) target_loader = torch.utils.data.DataLoader( torchfcn.datasets.CityScapes('cityscapes', args.dataroot, split='train', transform=True, image_size=image_size), batch_size=args.batchSize, shuffle=True) if cuda: torch.set_default_tensor_type('torch.cuda.FloatTensor') if args.model == "vgg16": model = origin_model = torchfcn.models.Seg_model(n_class=class_num) vgg16 = torchfcn.models.VGG16(pretrained=True) model.copy_params_from_vgg16(vgg16) model_fix = torchfcn.models.Seg_model(n_class=class_num) model_fix.copy_params_from_vgg16(vgg16) elif args.model == "deeplabv2": # TODO may have problem! model = origin_model = torchfcn.models.Res_Deeplab(num_classes=class_num, image_size=image_size) saved_state_dict = model_zoo.load_url(Deeplabv2_restore_from) new_params = model.state_dict().copy() for i in saved_state_dict: # Scale.layer5.conv2d_list.3.weight i_parts = i.split('.') # print i_parts if not class_num == 19 or not i_parts[1] == 'layer5': new_params['.'.join(i_parts[1:])] = saved_state_dict[i] # print i_parts model.load_state_dict(new_params) model_fix = torchfcn.models.Res_Deeplab(num_classes=class_num, image_size=image_size) model_fix.load_state_dict(new_params) else: raise ValueError("only support vgg16, deeplabv2!") for param in model_fix.parameters(): param.requires_grad = False netD = torchfcn.models.Domain_classifer_forAdapSegNet(n_class=class_num) netD.apply(weights_init) model_summary([model, netD]) if cuda: model = model.cuda() netD = netD.cuda() # Defining optimizer if args.optimizer == 'SGD': if args.model == "vgg16": optim = torch.optim.SGD( [ {'params': get_parameters(model, bias=False), 'weight_decay': args.weight_decay}, {'params': get_parameters(model, bias=True), 'lr': args.lr * 2, 'weight_decay': args.weight_decay}, ], lr=args.lr, momentum=args.momentum,) elif args.model == "deeplabv2": optim = torch.optim.SGD( origin_model.optim_parameters(args.lr), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) else: raise elif args.optimizer == 'Adam': if args.model == "vgg16": optim = torch.optim.Adam( [ {'params': get_parameters(model, bias=False), 'weight_decay': args.weight_decay}, {'params': get_parameters(model, bias=True), 'lr': args.lr * 2, 'weight_decay': args.weight_decay}, ], lr=args.lr, betas=(args.beta1, 0.999)) elif args.model == "deeplabv2": optim = torch.optim.Adam( origin_model.optim_parameters(args.lr), lr=args.lr, betas=(args.beta1, 0.999), weight_decay=args.weight_decay) else: raise else: raise ValueError('Invalid optmizer argument. Has to be SGD or Adam') optimD = torch.optim.Adam(netD.parameters(), lr=dis_lr, weight_decay=args.weight_decay, betas=(0.7, 0.999)) optimizer_summary([optim, optimD]) trainer = MyTrainer_ROAD( cuda=cuda, model=model, model_fix=model_fix, netD=netD, optimizer=optim, optimizerD=optimD, train_loader=train_loader, target_loader=target_loader, val_loader=val_loader, batch_size=args.batchSize, image_size=image_size, loss_print_interval=LOSS_PRINT_INTERVAL ) trainer.epoch = 0 trainer.iteration = 0 trainer.train() class MyTrainer_ROAD(object): def __init__(self, cuda, model, model_fix, netD, optimizer, optimizerD, train_loader, target_loader, val_loader, image_size, batch_size, size_average=True, loss_print_interval=500): self.cuda = cuda self.model = model self.model_fix = model_fix self.netD = netD self.optim = optimizer self.optimD = optimizerD self.batch_size = batch_size self.loss_print_interval = loss_print_interval self.train_loader = train_loader self.target_loader = target_loader self.val_loader = val_loader self.image_size = tuple(image_size) self.n_class = len(self.train_loader.dataset.class_names) self.size_average = size_average self.epoch = 0 self.iteration = 0 self.best_mean_iu = 0 def validate(self): """ Function to validate a training model on the val split. """ logger.info("start validation....") val_loss = 0 label_trues, label_preds = [], [] # Evaluation for batch_idx, (data, target) in tqdm.tqdm( enumerate(self.val_loader), total=len(self.val_loader), desc='Validation iteration = {},epoch={}'.format(self.iteration, self.epoch), leave=False): if batch_idx > QUICK_VAL: break if self.cuda: data, target = data.cuda(), target.cuda() data, target = Variable(data, volatile=True), Variable(target) score = self.model(data) loss = CrossEntropyLoss2d_Seg(score, target, class_num= class_num,size_average=self.size_average) if np.isnan(float(loss.data[0])): raise ValueError('loss is nan while validating') val_loss += float(loss.data[0]) / len(data) lbl_pred = score.data.max(1)[1].cpu().numpy()[:, :, :] lbl_true = target.data.cpu().numpy() label_trues.append(lbl_true) label_preds.append(lbl_pred) # Computing the metrics acc, acc_cls, mean_iu, _ = torchfcn.utils.label_accuracy_score( label_trues, label_preds, self.n_class) val_loss /= len(self.val_loader) logger.info("iteration={},epoch={},validation mIoU = {}".format(self.iteration, self.epoch, mean_iu)) is_best = mean_iu > self.best_mean_iu if is_best: self.best_mean_iu = mean_iu torch.save({ 'epoch': self.epoch, 'iteration': self.iteration, 'arch': self.model.__class__.__name__, 'optim_state_dict': self.optim.state_dict(), 'model_state_dict': self.model.state_dict(), 'best_mean_iu': self.best_mean_iu, }, osp.join(logger.get_logger_dir(), 'checkpoint.pth.tar')) if is_best: shutil.copy(osp.join(logger.get_logger_dir(), 'checkpoint.pth.tar'), osp.join(logger.get_logger_dir(), 'model_best.pth.tar')) def train_epoch(self): """ Function to train the model for one epoch """ def set_requires_grad(seg, dis): for param in self.model.parameters(): param.requires_grad = seg for param in self.netD.parameters(): param.requires_grad = dis import copy self.G_source_loader_iter = [enumerate(self.train_loader) for _ in range(G_STEP)] self.G_target_loader_iter = [enumerate(self.target_loader) for _ in range(G_STEP)] self.D_source_loader_iter = [enumerate(self.train_loader) for _ in range(D_STEP)] self.D_target_loader_iter = [enumerate(self.target_loader) for _ in range(D_STEP)] for batch_idx in tqdm.tqdm( range(self.iters_per_epoch), total=self.iters_per_epoch, desc='Train epoch = {}/{}'.format(self.epoch, self.max_epoch)): self.iteration = batch_idx + self.epoch * self.iters_per_epoch src_dis_label = 1 target_dis_label = 0 mse_loss = torch.nn.MSELoss() def get_data(source_iter, target_iter): _, source_batch = source_iter.next() source_data, source_labels = source_batch _, target_batch = target_iter.next() target_data, _ = target_batch if self.cuda: source_data, source_labels = source_data.cuda(), source_labels.cuda() target_data = target_data.cuda() source_data, source_labels = Variable(source_data), Variable(source_labels) target_data = Variable(target_data) return source_data,source_labels, target_data ##################################train D for _ in range(D_STEP): source_data, source_labels, target_data = get_data(self.D_source_loader_iter[_], self.D_target_loader_iter[_]) self.optimD.zero_grad() set_requires_grad(seg=False, dis=True) score = self.model(source_data) seg_target_score = self.model(target_data) src_discriminate_result = self.netD(F.softmax(score)) target_discriminate_result = self.netD(F.softmax(seg_target_score)) src_dis_loss = mse_loss(src_discriminate_result, Variable(torch.FloatTensor(src_discriminate_result.data.size()).fill_( src_dis_label)).cuda()) target_dis_loss = mse_loss(target_discriminate_result, Variable(torch.FloatTensor(target_discriminate_result.data.size()).fill_( target_dis_label)).cuda(), ) src_dis_loss = src_dis_loss * DIS_WEIGHT target_dis_loss = target_dis_loss * DIS_WEIGHT dis_loss = src_dis_loss + target_dis_loss dis_loss.backward() self.optimD.step() # https://ewanlee.github.io/2017/04/29/WGAN-implemented-by-PyTorch/ for p in self.netD.parameters(): p.data.clamp_(-0.01, 0.01) #####################train G, item1 for _ in range(G_STEP): source_data, source_labels, target_data = get_data(self.G_source_loader_iter[_], self.G_target_loader_iter[_]) self.optim.zero_grad() set_requires_grad(seg=True, dis=False) # Source domain score = self.model(source_data) l_seg = CrossEntropyLoss2d_Seg(score, source_labels, class_num=class_num, size_average=self.size_average) # target domain seg_target_score = self.model(target_data) modelfix_target_score = self.model_fix(target_data) diff2d = Diff2d() distill_loss = diff2d(seg_target_score, modelfix_target_score) l_seg = l_seg * L_LOSS_WEIGHT distill_loss = distill_loss * DISTILL_WEIGHT seg_loss = l_seg + distill_loss #######train G, item 2 src_discriminate_result = self.netD(F.softmax(score)) target_discriminate_result = self.netD(F.softmax(seg_target_score)) src_dis_loss = mse_loss(src_discriminate_result, Variable(torch.FloatTensor(src_discriminate_result.data.size()).fill_( src_dis_label)).cuda()) target_dis_loss = mse_loss(target_discriminate_result, Variable( torch.FloatTensor(target_discriminate_result.data.size()).fill_( src_dis_label)).cuda(), ) src_dis_loss = src_dis_loss*DIS_WEIGHT target_dis_loss = target_dis_loss*DIS_WEIGHT dis_loss = src_dis_loss + target_dis_loss total_loss = seg_loss + dis_loss total_loss.backward() self.optim.step() if np.isnan(float(dis_loss.data[0])): raise ValueError('dis_loss is nan while training') if np.isnan(float(seg_loss.data[0])): raise ValueError('total_loss is nan while training') if self.iteration % self.loss_print_interval == 0: logger.info( "After weight Loss: seg_Loss={}, distill_LOSS={}, src_dis_loss={}, target_dis_loss={}".format(l_seg.data[0], distill_loss.data[0], src_dis_loss.data[0],target_dis_loss.data[0])) def train(self): """ Function to train our model. Calls train_epoch function every epoch. Also performs learning rate annhealing """ logger.info("train_loader length: {}".format(len(self.train_loader))) logger.info("target_loader length: {}".format(len(self.target_loader))) iters_per_epoch = min(len(self.target_loader), len(self.train_loader)) self.iters_per_epoch = iters_per_epoch - (iters_per_epoch % self.batch_size) - 1 logger.info("iters_per_epoch :{}".format(self.iters_per_epoch)) self.max_epoch = args.max_epoch for epoch in tqdm.trange(self.epoch, args.max_epoch, desc='Train'): self.epoch = epoch self.optim = step_scheduler(self.optim, self.epoch, base_lr_schedule, "base model") self.optimD = step_scheduler(self.optimD, self.epoch, dis_lr_schedule, "discriminater model") self.model.train() self.netD.train() self.train_epoch() self.model.eval() self.validate() self.model.train() # return to training mode if __name__ == '__main__': main()
[ "taohu620@gmail.com" ]
taohu620@gmail.com
f44bca1b4446469132b9c580b3d500987df2806b
0902ddd4a455c10c2c7dedac872069b8223e7250
/ppomppu_scraper/__init__.py
0701f16db84fd59186ef86e4a4e6ae60f5c5b01e
[]
no_license
kyuhwas/ppomppu_scraper
f77f8561b6eb4a4aab18f3e0da32da230ebdc7b9
a4e24b969898c164d7ef33f034495b50c097e94d
refs/heads/master
2021-10-19T00:33:14.382761
2019-02-16T00:04:49
2019-02-16T00:04:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
260
py
from .utils import now from .utils import get_soup from .utils import normalize_text from .utils import strf_to_datetime from .utils import news_dateformat from .utils import user_dateformat from .parser import parse_page from .scraper import yield_parsed_page
[ "soy.lovit@gmail.com" ]
soy.lovit@gmail.com
fe8c1da06cb5220b0e5ee515224cc1101de51d57
6be8aa517e679b33b47d35f100e6590902a8a1db
/DP/Problem54.py
72cbb8c1c999c705d1e1d21afdf23d8dfda03060
[]
no_license
LeeJuhae/Algorithm-Python
7ca4762712e5e84d1e277abecb3bf39c9cbd4e56
729947b4428205adfbac194a5527b0eeafe1c525
refs/heads/master
2023-04-24T01:02:36.430970
2021-05-23T07:17:25
2021-05-23T07:17:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
540
py
# https://www.acmicpc.net/problem/17182 import sys from itertools import permutations read = sys.stdin.readline n, st = map(int, read().strip().split()) dp = [list(map(int, read().strip().split())) for _ in range(n)] for k in range(n): for i in range(n): for j in range(n): dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]) ans = float('inf') for cites in permutations(range(n), n): prev = st tmp = 0 for city in cites: tmp += dp[prev][city] prev = city ans = min(ans, tmp) print(ans)
[ "gusdn0657@gmail.com" ]
gusdn0657@gmail.com
9d7fa1949f2329fb360cf30a14031fc756ee8814
83f0cdbc9e1f7261dcd1ff5fc0c8ef4280e84fbb
/ADaM/python/cdisc_library.py
8437f8e380df5cc47b45fd6272dc69f18a942760
[ "MIT" ]
permissive
mihir-shinde/CSS2020-Hackathon
0c39d59ddb1503f0c4170b230f789b8f29fee9ae
f9538ee425fe7eb0573757cdd2346d1f8c7998c1
refs/heads/master
2023-03-16T05:06:26.518324
2020-09-25T16:20:12
2020-09-25T16:20:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,958
py
import requests class CDISCConnector: BASE_URL = "https://library.cdisc.org/api/" def __init__(self, username, password): self._client = None self._username = username self._password = password self._cache = {} @property def client(self): if self._client is None: session = requests.Session() session.auth = (self._username, self._password) session.headers self._client = session return self._client def flush(self): self._cache = {} def _get(self, path): url = self.BASE_URL + path if url not in self._cache: response = self.client.get(url) if response.status_code == 200: self._cache[url] = response.json() return self._cache.get(url, {}) @property def products(self): return self.get_products() def get_products(self): contents = self._get("mdr/products") specs = {} if contents: for aspect, asp_def in contents.get("_links").items(): if aspect == "self": continue for spec, spec_def in asp_def.get("_links").items(): if spec == "self": continue # Assumption href = spec_def[0].get('href') specs[spec] = href return specs def adam(self, version="1-1"): """ Get the ADaM Specifications """ path = f"mdr/adam/adamig-{version}" response = self._get(path) if not response.status_code == 200: if response.status_code == 401: print("Authentication not recognised") return {} elif response.status_code == 404: print("Standard or Dataset not found") return {} return response.json() def adam_dataset(self, dataset, version="1-1"): """ Get the ADaM Dataset Specifications """ path = f"mdr/adam/adamig-{version}/{dataset}" response = self._get(path) if not response.status_code == 200: if response.status_code == 401: print("Authentication not recognised") return {} elif response.status_code == 404: print("Standard or Dataset not found") return {} return response.json() def adam_var(self, dataset, variable, version="1-1"): """ Get the ADaM Dataset variable Specifications """ path = f"mdr/adam/adamig-{version}/datastructures/{dataset}/variables/{variable}" response = self._get(path) if not response.status_code == 200: if response.status_code == 401: print("Authentication not recognised") return {} elif response.status_code == 404: print("Standard or Dataset not found") return {} return response.json() def sdtm(self, version="3-3"): """ Get the SDTM Specifications """ response = self._get(f"mdr/sdtmig/{version}") if not response.status_code == 200: if response.status_code == 401: print("Authentication not recognised") return {} elif response.status_code == 404: print("Standard or Dataset not found") return {} return response.json() def sdtm_dataset(self, dataset, version="3-3"): """ Get the SDTM Dataset Specifications """ response = self._get(f"mdr/sdtmig/{version}/datasets/{dataset}") if not response.status_code == 200: if response.status_code == 401: print("Authentication not recognised") return {} elif response.status_code == 404: print("Standard or Dataset not found") return {} return response.json() def sdtm_variable(self, dataset, variable, version="3-3"): """ Get the SDTM Specifications """ response = self._get(f"mdr/sdtmig/{version}/datasets/{dataset}/variables/{variable}") if not response.status_code == 200: if response.status_code == 401: print("Authentication not recognised") return {} elif response.status_code == 404: print("Standard or Dataset not found") return {} return response.json() def get_terminology_by_name(self, name, parent): """ Given the username for the Codelist find the """ pass def terminology_set(self, name, parent="sdtm"): """ Get the codelist """
[ "glow@mdsol.com" ]
glow@mdsol.com
cc2d67c10951e85ac38fb33a2a8857e71a6610fd
1c67732a24042a991cc9f7e764d4640522391972
/back/gamedata/admin.py
d0e2b17e7528b7c6c839144c30b720f95932f249
[]
no_license
sungguenja/bsgg
1061ccc6f5f08ed9ad14d3a332af020ec7a5df22
447283378ac3bb8f489e2a4662bfb6513bc37be2
refs/heads/master
2023-04-01T14:15:05.491775
2021-04-06T09:46:25
2021-04-06T09:46:25
318,800,558
0
0
null
null
null
null
UTF-8
Python
false
false
308
py
from django.contrib import admin from .models import Area, Animal, Item, AreaItem, AreaAnimal, AnimalItem # Register your models here. admin.site.register(Area) admin.site.register(Animal) admin.site.register(Item) admin.site.register(AreaItem) admin.site.register(AreaAnimal) admin.site.register(AnimalItem)
[ "59605197+sungguenja@users.noreply.github.com" ]
59605197+sungguenja@users.noreply.github.com
0315172cd8f2f418b8753f197edeb6c03507474d
ac0b9c85542e6d1ef59c5e9df4618ddf22223ae0
/kratos/applications/FluidDynamicsApplication/python_scripts/apply_custom_velocity_constraints.py
22b0262260595debdf02adca990f94e5f573eb8c
[]
no_license
UPC-EnricBonet/trunk
30cb6fbd717c1e78d95ec66bc0f6df1a041b2b72
1cecfe201c8c9a1b87b2d87faf8e505b7b1f772d
refs/heads/master
2021-06-04T05:10:06.060945
2016-07-15T15:29:00
2016-07-15T15:29:00
33,677,051
3
0
null
null
null
null
UTF-8
Python
false
false
3,124
py
from KratosMultiphysics import * from FluidDynamicsApplication import * def Factory(settings, Model): if(type(settings) != Parameters): raise Exception("expected input shall be a Parameters object, encapsulating a json string") return ApplyCustomVelocityConstraintProcess(Model, settings["Parameters"]) ##all the processes python processes should be derived from "python_process" class ApplyCustomVelocityConstraintProcess(Process): def __init__(self, Model, settings ): Process.__init__(self) model_part = Model[settings["model_part_name"].GetString()] if settings["is_fixed_x"].GetBool() == True: # Auxiliar x-component parameters creation x_params = Parameters("{}") x_params.AddValue("model_part_name",settings["model_part_name"]) x_params.AddValue("mesh_id",settings["mesh_id"]) x_params.AddValue("is_fixed",settings["is_fixed_x"]) x_params.AddValue("value",settings["value"][0]) x_params.AddEmptyValue("variable_name").SetString("VELOCITY_X") self.x_component_process = ApplyConstantScalarValueProcess(model_part, x_params) if settings["is_fixed_y"].GetBool() == True: # Auxiliar y-component parameters creation y_params = Parameters("{}") y_params.AddValue("model_part_name",settings["model_part_name"]) y_params.AddValue("mesh_id",settings["mesh_id"]) y_params.AddValue("is_fixed",settings["is_fixed_y"]) y_params.AddValue("value",settings["value"][1]) y_params.AddEmptyValue("variable_name").SetString("VELOCITY_Y") self.y_component_process = ApplyConstantScalarValueProcess(model_part, y_params) if settings["is_fixed_z"].GetBool() == True: # Auxiliar x-component parameters creation z_params = Parameters("{}") z_params.AddValue("model_part_name",settings["model_part_name"]) z_params.AddValue("mesh_id",settings["mesh_id"]) z_params.AddValue("is_fixed",settings["is_fixed_z"]) z_params.AddValue("value",settings["value"][2]) z_params.AddEmptyValue("variable_name").SetString("VELOCITY_Z") self.z_component_process = ApplyConstantScalarValueProcess(model_part, z_params) # Auxiliar vector with the fixicity settings self.fixicity_vec = [settings["is_fixed_x"].GetBool(), settings["is_fixed_y"].GetBool(), settings["is_fixed_z"].GetBool()] def ExecuteInitialize(self): if self.fixicity_vec[0] == True: self.x_component_process.ExecuteInitialize() if self.fixicity_vec[1] == True: self.y_component_process.ExecuteInitialize() if self.fixicity_vec[2] == True: self.z_component_process.ExecuteInitialize()
[ "enriquebonetgil@hotmail.com" ]
enriquebonetgil@hotmail.com
b1b73aec37759c72a704ea13002ec87a409dff1c
6fcfb638fa725b6d21083ec54e3609fc1b287d9e
/python/matrix-org_synapse/synapse-master/synapse/__init__.py
ff251ce5973b833547a661e133844a21b6b52695
[]
no_license
LiuFang816/SALSTM_py_data
6db258e51858aeff14af38898fef715b46980ac1
d494b3041069d377d6a7a9c296a14334f2fa5acc
refs/heads/master
2022-12-25T06:39:52.222097
2019-12-12T08:49:07
2019-12-12T08:49:07
227,546,525
10
7
null
2022-12-19T02:53:01
2019-12-12T07:29:39
Python
UTF-8
Python
false
false
700
py
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This is a reference implementation of a Matrix home server. """ __version__ = "0.19.2"
[ "659338505@qq.com" ]
659338505@qq.com
8251ffe046d39813fb96ab3eda7aaf564efa9dde
21155deb4419380b995c09946a680a261c524b5b
/meraki/models/subnet_model.py
f08d566a104c927c12dbea3f8f178de10ea8c155
[ "MIT" ]
permissive
dexterlabora/meraki-python-sdk
620efab5e6b6eb32ca52308be1cb740748fc0f30
f6e6d61bd8694548169cd872b0642def69115bcb
refs/heads/master
2023-05-25T06:50:21.845198
2019-06-13T12:22:34
2019-06-13T12:22:34
182,791,973
0
1
NOASSERTION
2023-05-22T21:37:22
2019-04-22T13:22:08
Python
UTF-8
Python
false
false
1,690
py
# -*- coding: utf-8 -*- """ meraki This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ). """ class SubnetModel(object): """Implementation of the 'Subnet' model. TODO: type model description here. Attributes: local_subnet (string): The CIDR notation subnet used within the VPN use_vpn (bool): Indicates the presence of the subnet in the VPN """ # Create a mapping from Model property names to API property names _names = { "local_subnet":'localSubnet', "use_vpn":'useVpn' } def __init__(self, local_subnet=None, use_vpn=None): """Constructor for the SubnetModel class""" # Initialize members of the class self.local_subnet = local_subnet self.use_vpn = use_vpn @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary local_subnet = dictionary.get('localSubnet') use_vpn = dictionary.get('useVpn') # Return an object of this model return cls(local_subnet, use_vpn)
[ "git@apimatic.io" ]
git@apimatic.io
7eede2990f6e638af015bc568bd54608b7a9581e
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
/events_write_1/event-bu_delete.py
1d62d387f9b2e00234829669c850e7bdd2a0f3aa
[]
no_license
lxtxl/aws_cli
c31fc994c9a4296d6bac851e680d5adbf7e93481
aaf35df1b7509abf5601d3f09ff1fece482facda
refs/heads/master
2023-02-06T09:00:33.088379
2020-12-27T13:38:45
2020-12-27T13:38:45
318,686,394
0
0
null
null
null
null
UTF-8
Python
false
false
1,042
py
#!/usr/bin/python # -*- codding: utf-8 -*- import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from common.execute_command import write_one_parameter # url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/delete-event-bus.html if __name__ == '__main__': """ create-event-bus : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/create-event-bus.html describe-event-bus : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/describe-event-bus.html """ parameter_display_string = """ # name : The name of the event bus to delete. """ add_option_dict = {} ####################################################################### # parameter display string add_option_dict["parameter_display_string"] = parameter_display_string # ex: add_option_dict["no_value_parameter_list"] = "--single-parameter" write_one_parameter("events", "delete-event-bus", "name", add_option_dict)
[ "hcseo77@gmail.com" ]
hcseo77@gmail.com
67a4431f2cf41a56085422a65fa040772f0312e1
5edbc16216806de0c32634fae1ae67c4773fbf65
/wiki/migrations/0002_auto_20160820_2351.py
8878c2f9679bb51843d6d084ebf7537e0c527bb0
[]
no_license
MilesWilliams/klaritywiki
431d9139309c2997aeaeeb02afce9b4da43cff8d
197c0f9c4094a64e437eb2a51b531747c262290b
refs/heads/master
2020-12-02T20:44:30.703329
2016-08-22T12:10:48
2016-08-22T12:10:48
66,269,030
0
0
null
null
null
null
UTF-8
Python
false
false
385
py
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-20 21:51 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wiki', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='Category', new_name='Categories', ), ]
[ "miles@klarity.co.za" ]
miles@klarity.co.za
ebec3629eb42d836bab2a456034eb71b975018dd
bad62c2b0dfad33197db55b44efeec0bab405634
/sdk/workloads/azure-mgmt-workloads/setup.py
98da49aa95a0f0e5fcc66f523e70cc2345923cf2
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
test-repo-billy/azure-sdk-for-python
20c5a2486456e02456de17515704cb064ff19833
cece86a8548cb5f575e5419864d631673be0a244
refs/heads/master
2022-10-25T02:28:39.022559
2022-10-18T06:05:46
2022-10-18T06:05:46
182,325,031
0
0
MIT
2019-07-25T22:28:52
2019-04-19T20:59:15
Python
UTF-8
Python
false
false
2,764
py
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import re import os.path from io import open from setuptools import find_packages, setup # Change the PACKAGE_NAME only to change folder and different name PACKAGE_NAME = "azure-mgmt-workloads" PACKAGE_PPRINT_NAME = "Workloads Management" # a-b-c => a/b/c package_folder_path = PACKAGE_NAME.replace('-', '/') # a-b-c => a.b.c namespace_name = PACKAGE_NAME.replace('-', '.') # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, 'version.py') if os.path.exists(os.path.join(package_folder_path, 'version.py')) else os.path.join(package_folder_path, '_version.py'), 'r') as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.md', encoding='utf-8') as f: readme = f.read() with open('CHANGELOG.md', encoding='utf-8') as f: changelog = f.read() setup( name=PACKAGE_NAME, version=version, description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), long_description=readme + '\n\n' + changelog, long_description_content_type='text/markdown', license='MIT License', author='Microsoft Corporation', author_email='azpysdkhelp@microsoft.com', url='https://github.com/Azure/azure-sdk-for-python', keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'License :: OSI Approved :: MIT License', ], zip_safe=False, packages=find_packages(exclude=[ 'tests', # Exclude packages that will be covered by PEP420 or nspkg 'azure', 'azure.mgmt', ]), include_package_data=True, package_data={ 'pytyped': ['py.typed'], }, install_requires=[ 'msrest>=0.6.21', 'azure-common~=1.1', 'azure-mgmt-core>=1.3.0,<2.0.0', ], python_requires=">=3.6" )
[ "noreply@github.com" ]
test-repo-billy.noreply@github.com
8aa95b8aee556ee8fa7fb2ff5c965d5021d95fbd
60561fd3efd5ecd8f984c4767c8e1017f66dbfd0
/apps/unsubscribes/migrations/0002_unsubscribeemail_user.py
a5468036448b33392ed58db1295c00f26159ef47
[]
no_license
kaushalaman97/react
fd3b691340ba877ace3b9feec0a93103b30f466f
4b34ace3357fbba0aa6616d761da2f501993bcc4
refs/heads/main
2023-03-08T16:33:48.675925
2021-02-26T14:23:38
2021-02-26T14:23:38
342,596,858
0
0
null
null
null
null
UTF-8
Python
false
false
622
py
# Generated by Django 3.1.4 on 2021-02-24 08:54 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('unsubscribes', '0001_initial'), ] operations = [ migrations.AddField( model_name='unsubscribeemail', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
[ "mohit.kaushal@techstriker.com" ]
mohit.kaushal@techstriker.com
a60bfa7980001c986bed8b71d56e75e0c5b2a66e
1730f8cea72838a677b52fe82e72d91aa8f68f75
/003_queues/003_solutionCourseProvided.py
37326ef9b6a6f674a399d5971a030bad629104f7
[ "MIT" ]
permissive
remichartier/026_UdacityTechnicalInterviewPrep
354097e25972a7214b8d1f84fcd3e80b69e79333
fa52b5f57bdd4e79751059971bb9f73fa0ca8004
refs/heads/main
2023-04-07T15:25:16.499791
2021-04-18T05:15:23
2021-04-18T05:15:23
354,467,066
0
0
null
null
null
null
UTF-8
Python
false
false
327
py
# I managed to write all of the methods in one line! class Queue(object): def __init__(self, head=None): self.storage = [head] def enqueue(self, new_element): self.storage.append(new_element) def peek(self): return self.storage[0] def dequeue(self): return self.storage.pop(0)
[ "remipr.chartier@gmail.com" ]
remipr.chartier@gmail.com
6c6fb1d95838c3f889b46a7dc6de313d15b867a4
01f8b69a1d13578bd013f5e60199ad151863799c
/examples/_relative/xxx.py
ef8d091dbbd19d048dc7c9164f14db13c6a7efe3
[ "MIT" ]
permissive
podhmo/pyinspect
e3dd9331627091de90a172d9d7eff34307bf2496
32ff53c7ceb6a382b635f6c8b98b15f2213d18ff
refs/heads/master
2020-03-22T20:19:06.961689
2019-12-19T15:14:26
2019-12-19T15:14:26
140,589,327
4
0
null
2019-12-19T15:14:28
2018-07-11T14:45:17
Python
UTF-8
Python
false
false
123
py
def f(x): return g(x, 1) def g(x, acc): if x == 0: return acc else: return g(x - 1, acc * x)
[ "ababjam61+github@gmail.com" ]
ababjam61+github@gmail.com
f165e00d444f850aee54fecab36cf98b9209d337
09e57dd1374713f06b70d7b37a580130d9bbab0d
/benchmark/startQiskit_noisy2453.py
5211053a79a7324e34dd64e88d63b85985dd3c0e
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
4,238
py
# qubit number=4 # total number=42 import cirq import qiskit from qiskit.providers.aer import QasmSimulator from qiskit.test.mock import FakeVigo from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2 import numpy as np import networkx as nx def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() return oracle def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=39 prog.cz(input_qubit[0],input_qubit[3]) # number=40 prog.h(input_qubit[3]) # number=41 prog.cx(input_qubit[0],input_qubit[3]) # number=23 prog.cx(input_qubit[0],input_qubit[3]) # number=33 prog.x(input_qubit[3]) # number=34 prog.cx(input_qubit[0],input_qubit[3]) # number=35 prog.cx(input_qubit[0],input_qubit[3]) # number=25 prog.cx(input_qubit[0],input_qubit[3]) # number=12 prog.h(input_qubit[2]) # number=30 prog.cz(input_qubit[0],input_qubit[2]) # number=31 prog.h(input_qubit[2]) # number=32 prog.x(input_qubit[2]) # number=21 prog.h(input_qubit[2]) # number=36 prog.cz(input_qubit[0],input_qubit[2]) # number=37 prog.h(input_qubit[2]) # number=38 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.h(input_qubit[0]) # number=5 prog.h(input_qubit[3]) # number=16 prog.cz(input_qubit[1],input_qubit[3]) # number=17 prog.h(input_qubit[3]) # number=18 oracle = build_oracle(n-1, f) prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]]) prog.h(input_qubit[1]) # number=6 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=9 prog.h(input_qubit[0]) # number=26 prog.cz(input_qubit[3],input_qubit[0]) # number=27 prog.h(input_qubit[0]) # number=28 prog.cx(input_qubit[3],input_qubit[0]) # number=14 prog.y(input_qubit[2]) # number=29 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog if __name__ == '__main__': a = "111" b = "0" f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b) prog = make_circuit(4,f) backend = FakeVigo() sample_shot =8000 info = execute(prog, backend=backend, shots=sample_shot).result().get_counts() backend = FakeVigo() circuit1 = transpile(prog,backend,optimization_level=2) writefile = open("../data/startQiskit_noisy2453.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.__len__(),file=writefile) print(circuit1,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
56369aec96a4cef7cf632a602fd07ffec540ec5f
ee3e8773f86da51e39fe1b1a57237ad558c0f991
/plotting/easy_plotting.py
ef5f64774999291358476bfc58818463ad0dfdd9
[]
no_license
qyx268/plato
72cd9ca2a6d5e28cd1618433ebc6af21fd2161e7
b7c84c021bc26d63c768e9d08e28bbaf77d79a87
refs/heads/master
2021-01-15T21:07:56.182831
2016-04-15T12:33:21
2016-04-15T12:33:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,316
py
from collections import OrderedDict from general.nested_structures import flatten_struct from plotting.data_conversion import vector_length_to_tile_dims import plotting.matplotlib_backend as eplt import numpy as np __author__ = 'peter' def ezplot(anything, plots = None, hang = True, **plot_preference_kwargs): """ Make a plot of anything. Anything at all. :param anything: Anything. """ data_dict = flatten_struct(anything) figure, plots = plot_data_dict(data_dict, plots, mode = 'static', hang = hang, **plot_preference_kwargs) return figure, plots def plot_data_dict(data_dict, plots = None, mode = 'static', hang = True, figure = None, size = None, **plot_preference_kwargs): """ Make a plot of data in the format defined in data_dict :param data_dict: dict<str: plottable_data> :param plots: Optionally, a dict of <key: IPlot> identifying the plot objects to use (keys should be the same as those in data_dict). :return: The plots (same ones you provided if you provided them) """ assert mode in ('live', 'static') if isinstance(data_dict, list): assert all(len(d) == 2 for d in data_dict), "You can provide data as a list of 2 tuples of (plot_name, plot_data)" data_dict = OrderedDict(data_dict) if plots is None: plots = {k: eplt.get_plot_from_data(v, mode = mode, **plot_preference_kwargs) for k, v in data_dict.iteritems()} if figure is None: if size is not None: from pylab import rcParams rcParams['figure.figsize'] = size figure = eplt.figure() n_rows, n_cols = vector_length_to_tile_dims(len(data_dict)) for i, (k, v) in enumerate(data_dict.iteritems()): eplt.subplot(n_rows, n_cols, i+1) plots[k].update(v) eplt.title(k, fontdict = {'fontsize': 8}) oldhang = eplt.isinteractive() eplt.interactive(not hang) eplt.show() eplt.interactive(oldhang) return figure, plots def funplot(func, xlims = None, n_points = 100): """ Plot a function :param func: :param xlims: :param n_points: :return: """ if xlims is None: xlims = eplt.gca().get_xbound() xs, xe = xlims x = np.linspace(xs, xe, n_points) eplt.plot(x, func(x)) eplt.gca().set_xbound(*xlims)
[ "peter.ed.oconnor@gmail.com" ]
peter.ed.oconnor@gmail.com
29cc73d94435bfd91f4071297e290173c3e70a6f
86cc876d2b7cbc29d5c13a73d4d985079c73ed68
/thingflow/adapters/mqtt.py
fe0b20c00a3689ab9dac8f62fb3d9c69fce6d0b5
[ "Apache-2.0" ]
permissive
masayoshi-louis/thingflow-python
74fe6f90a37803a27bd69eff9163f7fb668836b4
c191a8fedac6a962994945830c872e957f929e29
refs/heads/master
2020-03-26T08:13:58.334964
2017-08-08T03:59:09
2017-08-08T03:59:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,643
py
# Copyright 2016 by MPI-SWS and Data-Ken Research. # Licensed under the Apache 2.0 License. import time from collections import namedtuple try: import paho.mqtt.client as paho except ImportError: print("could not import paho.mqtt.client") import ssl from thingflow.base import InputThing, OutputThing, EventLoopOutputThingMixin MQTTEvent = namedtuple('MQTTEvent', ['timestamp', 'state', 'mid', 'topic', 'payload', 'qos', 'dup', 'retain' ]) import random random.seed() import datetime class MockMQTTClient(object): def __init__(self, client_id=""): self.userdata = None self.client_id = client_id self.on_message = None self.on_connect = None self.on_publish = None def connect(self, host, port=1883): if self.on_connect: self.on_connect(self, self.userdata, None, 0) return 0 def subscribe(self, topics): pass def publish(self, topic, payload, qos, retain=False): if self.on_publish: self.on_publish(self, self.userdata, 0) def username_pw_set(self, username, password=""): pass def loop(self, timeout=1.0, max_packets=1): s = random.randint(1, max_packets) for i in range(0, s): msg = MQTTEvent(datetime.datetime.now(), 0, i, 'bogus/bogus', 'xxx', 0, False, False) if self.on_message: self.on_message(self, self.userdata, msg) time.sleep(timeout) return 0 def disconnect(self): pass class MQTTWriter(InputThing): """Subscribes to internal events and pushes them out to MQTT. The topics parameter is a list of (topic, qos) pairs. Events should be serialized before passing them to the writer. """ def __init__(self, host, port=1883, client_id="", client_username="", client_password=None, server_tls=False, server_cert=None, topics=[], mock_class=None): self.host = host self.port = port self.client_id = client_id self.client_username = client_id self.client_password = client_password self.topics = topics self.server_tls = server_tls self.server_cert = server_cert if mock_class: self.client = MockMQTTClient(self.client_id) else: self.client = paho.Client(self.client_id) if self.client_username: self.client.username_pw_set(self.client_username, password=self.client_password) self._connect() def _connect(self): if self.server_tls: raise Exception("TBD") print(self.client.tls_set(self.server_tls.server_cert, cert_reqs=ssl.CERT_OPTIONAL)) print(self.client.connect(self.host, self.port)) else: self.client.connect(self.host, self.port) self.client.subscribe(self.topics) def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) self.client.on_connect = on_connect def on_publish(client, userdata, mid): print("Successfully published mid %d" % mid) self.client.on_publish = on_publish def on_next(self, msg): """Note that the message is passed directly to paho.mqtt.client. As such, it must be a string, a bytearray, an int, a float or None. Usually, you would use something like to_json (in thingflow.filters.json) to do the serialization of events. """ # publish the message to the topics retain = msg.retain if hasattr(msg, 'retain') else False for (topic, qos) in self.topics: self.client.publish(topic, msg, qos, retain) def on_error(self, e): self.client.disconnect() def on_completed(self): self.client.disconnect() def __str__(self): return 'MQTTWriter(%s)' % ', '.join([topic for (topic,qos) in self.topics]) class MQTTReader(OutputThing, EventLoopOutputThingMixin): """An reader that creates a stream from an MQTT broker. Initialize the reader with a list of topics to subscribe to. The topics parameter is a list of (topic, qos) pairs. Pre-requisites: An MQTT broker (on host:port) --- tested with mosquitto The paho.mqtt python client for mqtt (pip install paho-mqtt) """ def __init__(self, host, port=1883, client_id="", client_username="", client_password=None, server_tls=False, server_cert=None, topics=[], mock_class=None): super().__init__() self.stop_requested = False self.host = host self.port = port self.client_id = client_id self.client_username = client_id self.client_password = client_password self.topics = topics self.server_tls = server_tls self.server_cert = server_cert if mock_class: self.client = MockMQTTClient(self.client_id) else: self.client = paho.Client(self.client_id) if self.client_username: self.client.username_pw_set(self.client_username, password=self.client_password) self._connect() def on_message(client, userdata, msg): m = MQTTEvent(msg.timestamp, msg.state, msg.mid, msg.topic, msg.payload, msg.qos, msg.dup, msg.retain) self._dispatch_next(m) self.client.on_message = on_message def _connect(self): if self.server_tls: raise Exception("TBD") print(self.client.tls_set(self.server_tls.server_cert, cert_reqs=ssl.CERT_OPTIONAL)) print(self.client.connect(self.host, self.port)) else: self.client.connect(self.host, self.port) def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe(self.topics) self.client.on_connect = on_connect def _observe_event_loop(self): print("starting event loop") while True: if self.stop_requested: break result = self.client.loop(1) if result != 0: self._connect() self.stop_requested = False self.client.disconnect() print("Stopped private event loop") def _stop_loop(self): self.stop_requested = True print("requesting stop") def __str__(self): return 'MQTTReader(%s)' % ', '.join([topic for (topic,qos) in self.topics])
[ "jeff@data-ken.org" ]
jeff@data-ken.org
e06d2b176396a29ae9f62cab21aeb06a0c165897
e0980f704a573894350e285f66f4cf390837238e
/.history/news/models_20201124125405.py
ad4367cc96dbe5bc9bd177dc7020584d0a479ff6
[]
no_license
rucpata/WagtailWebsite
28008474ec779d12ef43bceb61827168274a8b61
5aa44f51592f49c9a708fc5515ad877c6a29dfd9
refs/heads/main
2023-02-09T15:30:02.133415
2021-01-05T14:55:45
2021-01-05T14:55:45
303,961,094
0
0
null
null
null
null
UTF-8
Python
false
false
221
py
from django.db import models from wagtail.contrib.forms.models import AbstractEmailForm # Create your models here. class NewsPage(AbstractEmailForm): tempalte ='news/news_page.html' leanding_page_template = ''
[ "rucinska.patrycja@gmail.com" ]
rucinska.patrycja@gmail.com
d913b9c0afd66a6ee6f04517d7ca25d9e5a27bf4
8dd06c1cb548f1a2457607e352646f3e20efc2c3
/front/__init__.py
5d1715e08b4f1cd4da658cd7d2bdd4437a3a51c7
[]
no_license
lordhamster66/Automation-Engineering
98f3df9ca14957acd481ddb7e2acd6ae94a681d4
10cf77f04a204784da1a03e17c46ce5147d2f56e
refs/heads/master
2022-11-08T12:08:39.331341
2017-06-16T05:59:27
2017-06-16T05:59:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
94
py
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Breakering" # Date: 2017/5/24
[ "1079614505@qq.com" ]
1079614505@qq.com
e7f9eb6f18a705e2446062b9a7609948f8193c95
46349356d4812a6bf04a1dff4ee3311864f8b7ff
/ma_py/mic_utils/estimate_gg_pdf_nm_fast/estimate_gg_pdf.py
494d1dd50b6c30a772ba4dcee8a2594e1c295ed2
[]
no_license
alexdoberman/ma
1ca9d20f64d0e8c87feff9f7bb04d09d3088aeb3
219e5e87b80c6a795c0d4161b3ad22b9973ed745
refs/heads/master
2022-07-17T13:15:21.672335
2020-05-12T15:10:40
2020-05-12T15:10:40
263,365,873
12
2
null
null
null
null
UTF-8
Python
false
false
3,807
py
# -*- coding: utf-8 -*- import numpy as np import soundfile as sf import matplotlib.pyplot as plt import glob import math from scipy import optimize import scipy.stats as stats def fun_ML_c(f, *args): """ Calc log likelihood for complex data :param f: - shape :param args: :return: """ (scale, y) = args K = y.shape[0] B = math.gamma(1.0/f) / math.gamma(2.0/f) p1 = K*(np.log(f) - np.log(np.pi * math.gamma(1.0/f) *B *scale)) p2 = np.sum(np.power( (np.abs(y)**2)/(B*scale), f)) R = p1 - p2 return - R def estimate_shape_factor_c_(y, scale): """ Estimate shape factor for complex data :param y: - complex array :param scale: :return: """ args = (scale, y) minimum = optimize.brent(fun_ML_c, args=args, brack=(0.02, .3)) return minimum def estimate_scale_c(y, shape_factor): """ Estimate scale for complex data :param y: :param shape_factor: :return: """ K = y.shape[0] B = math.gamma(1.0/shape_factor) / math.gamma(2.0/shape_factor) scale = np.power( np.sum(np.power(np.abs(y), 2*shape_factor))*shape_factor/K, 1.0/shape_factor) / B return scale def estimate_gg_pdf_param_c(y, tol = 0.0000001): """ Estim GG pdf params for complex data :param y: :param tol: :return: """ shape_factor_prev = 1 scale_prev = np.mean(np.power(np.abs(y), 2)) max_iter = 200 print ('scale_prev = {}'.format(scale_prev)) for _iter in range(max_iter): shape_factor = estimate_shape_factor_c(y, scale_prev) scale = estimate_scale_c(y, shape_factor) print (" iter = {} shape = {} scale = {}".format(_iter, shape_factor, scale)) if (np.abs(scale - scale_prev) < tol and np.abs(shape_factor - shape_factor_prev) < tol): return shape_factor, scale scale_prev = scale shape_factor_prev = shape_factor print("Warning: estimate_gg_pdf_param_c - not convergent!") return None, None def main(): n_fft = 512 gg_params = [] for freq_bin in range(1, int(n_fft / 2)): print('Process freq_ind = {}'.format(freq_bin)) path = "./out_bin/bin_{}.npy".format(freq_bin) y = np.load(path) f, scale = estimate_gg_pdf_param_c(y) gg_params.append([freq_bin, f, scale]) np.save("gg_params_freq_f_scale", np.array(gg_params)) np.save("gg_params_freq_f_scale", np.array(gg_params)) def estimate_shape_factor_c(y, scale): """ Estimate shape factor for complex data :param y: - complex array :param scale: :return: """ args = (scale, y) ff = np.linspace(0.02, 0.9, 200) L = [] for i in ff: args = (scale, y) L.append(fun_ML_c(i, *args)) L = np.array(L) min_index = np.argmin(L) l_min = np.min(min_index - 5, 0) r_min = min_index + 5 a = ff[l_min] b = ff[r_min] c = ff[min_index] minimum = optimize.brent(fun_ML_c, args=args, brack=(a, b)) return minimum #return L[min_index] def debug_run(): freq_bin = 1 print('Process freq_ind = {}'.format(freq_bin)) path = "./out_bin/bin_{}.npy".format(freq_bin) y = np.load(path) # f, scale = estimate_gg_pdf_param_c(y) # print (f, scale) ff = np.linspace(0.02, 0.9, 200) L = [] for i in ff: args = (0.04692564477433535, y) L.append(fun_ML_c(i, *args)) L = np.array(L) min_index = np.argmin(L) l_min = np.min(min_index - 5, 0) r_min = min_index + 5 a = ff[l_min] b = ff[r_min] c = ff[min_index ] print (l_min,min_index,r_min) print (a,c,b) plt.plot(ff, L, label="L") plt.legend(loc='best') plt.show() if __name__ == '__main__': #debug_run() main()
[ "lavrentyev@speechpro.com" ]
lavrentyev@speechpro.com
bb254c654547f81e9990ee4cf77ce5783ed9cdd3
96b53c177d3060a9149fead7c2481f631d954d2e
/virtual/bin/alembic
86b62ed49fb847db593874c05a7dda327114015a
[ "MIT" ]
permissive
JOFLIX/pitch
0a094c93025fa36e28938412e31fa210cd76613c
c821acf138b07f148be0cc5fbe6c82bd6396a428
refs/heads/master
2022-09-29T06:40:22.370088
2019-08-07T07:46:43
2019-08-07T07:46:43
200,628,592
0
0
null
2022-09-16T18:06:49
2019-08-05T09:51:31
Python
UTF-8
Python
false
false
257
#!/home/moringa/Desktop/pitch_your_work/virtual/bin/python3 # -*- coding: utf-8 -*- import re import sys from alembic.config import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "joflixooko@outlook.com" ]
joflixooko@outlook.com
c70d686b8a66449aa75277ec024a414043f77dab
8b00e2b136636841b38eb182196e56f4721a1e4c
/trio/_util.py
121513b20e80d517c58bc5e6fb5c7f2255ca441a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
xyicheng/trio
77c8c1e08e3aa4effe8cf04e879720ccfcdb7d33
fa091e2e91d196c2a57b122589a166949ea03103
refs/heads/master
2021-01-23T00:05:59.618483
2017-03-16T04:25:05
2017-03-16T04:25:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,494
py
import sys from functools import wraps import async_generator __all__ = ["aitercompat", "acontextmanager"] # Decorator to handle the change to __aiter__ in 3.5.2 def aiter_compat(aiter_impl): if sys.version_info < (3, 5, 2): @wraps(aiter_impl) async def __aiter__(*args, **kwargs): return aiter_impl(*args, **kwargs) return __aiter__ else: return aiter_impl # Very much derived from the one in contextlib, by copy/pasting and then # asyncifying everything. # So this is a derivative work licensed under the PSF License, which requires # the following notice: # # Copyright © 2001-2017 Python Software Foundation; All Rights Reserved class _AsyncGeneratorContextManager: def __init__(self, func, args, kwds): self._agen = func(*args, **kwds).__aiter__() async def __aenter__(self): if sys.version_info < (3, 5, 2): self._agen = await self._agen try: return await self._agen.asend(None) except StopAsyncIteration: raise RuntimeError("async generator didn't yield") from None async def __aexit__(self, type, value, traceback): if type is None: try: await self._agen.asend(None) except StopAsyncIteration: return else: raise RuntimeError("async generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = type() try: await self._agen.athrow(type, value, traceback) raise RuntimeError("async generator didn't stop after athrow()") except StopAsyncIteration as exc: # Suppress StopIteration *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed. return (exc is not value) except RuntimeError as exc: # Don't re-raise the passed in exception. (issue27112) if exc is value: return False # Likewise, avoid suppressing if a StopIteration exception # was passed to throw() and later wrapped into a RuntimeError # (see PEP 479). if exc.__cause__ is value: return False raise except: # only re-raise if it's *not* the exception that was # passed to throw(), because __exit__() must not raise # an exception unless __exit__() itself failed. But throw() # has to raise the exception to signal propagation, so this # fixes the impedance mismatch between the throw() protocol # and the __exit__() protocol. # if sys.exc_info()[1] is not value: raise def acontextmanager(func): """Like @contextmanager, but async.""" if not async_generator.isasyncgenfunction(func): raise TypeError( "must be an async generator (native or from async_generator; " "if using @async_generator then @acontextmanager must be on top.") @wraps(func) def helper(*args, **kwds): return _AsyncGeneratorContextManager(func, args, kwds) return helper
[ "njs@pobox.com" ]
njs@pobox.com
945b2e66bd120592ad55fe796ccf88aeb4bb2efe
e1e5ffef1eeadd886651c7eaa814f7da1d2ade0a
/Systest/lib/py/issu.py
3fd94a49e3fafb90378548fd7e78467b943c7ff7
[]
no_license
muttu2244/MyPython
1ddf1958e5a3514f9605d1f83c0930b24b856391
984ca763feae49a44c271342dbc15fde935174cf
refs/heads/master
2021-06-09T02:21:09.801103
2017-10-10T07:30:04
2017-10-10T07:30:04
13,803,605
0
0
null
null
null
null
UTF-8
Python
false
false
568,600
py
#!/usr/bin/env python2.5 ####################################################################### # # Copyright (c) Stoke, Inc. # All Rights Reserved. # # This code is confidential and proprietary to Stoke, Inc. and may only # be used under a license from Stoke. # ####################################################################### # AUTHOR: Jeremiah Alfrey jalfrey@stoke.com ####################################################################### import sys, os mydir = os.path.dirname(__file__) qa_lib_dir = mydir if qa_lib_dir not in sys.path: sys.path.insert(1,qa_lib_dir) ### python stuff import time import shutil import string ### local stuff from logging import getLogger from pexpect import TIMEOUT import pexpect import time import datetime import re # what is this for? from pprint import pprint # Used for nslookup import socket ### import SSX # this import may not be required. #from device import SSX # used for unix_to_dos_path conversion import ntpath # used to get_mac_address import CISCO enable_prompt_regex = "[\r\n]*\S+\[\S+\]#" yesno_prompt_regex =".*[\r\n.]*\(\[*yes\]*/\[*no\]*\)\s*$" debug = False month_list = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] # This is a complete list of all the valid ports on the SSX. When the 14 slot chassis is tested this will need to be changed # to include the new ports valid_port_list = ['0/0','1/0','2/0','2/1','2/2','2/3','3/0','3/1','3/2','3/3','4/0','4/1','4/2','4/3'] def cli_cmd(self, command, raw=False): """ This is a greatly imroved version of cmd from /SSX/device.py It will read and parse the command prompt to correctly and quickly detect it. This method can parse very long outputs and is much faster then the existing method To use it simply send the command and the output will be returned The output is returned as a list []. If you use the raw=True you will get it as a single long string not split yet. """ debug = False if debug: print 'now in cli_cmd' timeout = 5 self.ses.sendline('\r') # The first line we read is empty raw_prompt = self.ses.readline() # This is the actual prompt raw_prompt = self.ses.readline() if debug: print 'raw_prompt:', raw_prompt prompt_pieces = raw_prompt.strip() if len(prompt_pieces) < 2: self.ses.sendline('\r') # The first line we read is empty raw_prompt = self.ses.readline() # This is the actual prompt raw_prompt = self.ses.readline() if debug: print 'raw_prompt:', raw_prompt else: if prompt_pieces == '#': if debug: print 'detected QNX Shell prompt: #' prompt = '#' else: prompt_pieces = prompt_pieces.split('[') if debug: print 'hostname:', prompt_pieces[0] print 'remainder:', prompt_pieces prompt_hostname = prompt_pieces[0] prompt_pieces = prompt_pieces[1].split(']') if debug: print 'Context:', prompt_pieces[0] print 'remainder:', prompt_pieces prompt_context = prompt_pieces[0] prompt_admin_level = prompt_pieces[1] #prompt = 'australia' prompt = prompt_hostname + '.' + prompt_context + '.' + prompt_admin_level if debug: print 'prompt:', prompt retr = self.ses.expect(prompt, timeout = timeout) if retr == 0: if debug: print 'command successfull' elif retr == 1: print 'Something broke while executing command!' sys.exit(1) else: print retr if debug: print 'setting term length infinite' self.ses.sendline('term length infinite') retr = self.ses.expect(prompt, timeout = timeout) if retr == 0: if debug: print 'command successfull' elif retr == 1: print 'Something broke while executing command!' sys.exit(1) else: print retr if debug: print 'About to execute the command you requested' print 'command:', command self.ses.sendline(command) retr = self.ses.expect(prompt, timeout = timeout) if retr == 0: if debug: print 'command successfull' elif retr == 1: print 'Something broke while executing command!' sys.exit(1) else: print retr raw_rtrn = self.ses.before raw_after = self.ses.after if debug: print 'This is what the command returned:' print '----------------------------------' print raw_rtrn print '-------' print raw_after print '----------------------------------' if raw: # We need to remove the first line of text but it's all one long line # so we count the length of the original command and add some for the CR\LF characters command_length = len(command) + 2 return raw_rtrn[command_length:] # The 1: tells the system to return everything except the first line # The first line contains the command that was executed. else: rtrn = raw_rtrn.splitlines() return rtrn[1:] def issu_enable(self, timeout=200): """enables ISSU with a set timeout""" debug = False if debug: print 'now in issu.py method issu_enable' self.ses.sendline("system issu enable") index = self.ses.expect(yesno_prompt_regex,timeout=timeout) if index == 0 : self.ses.sendline("yes") if "-con" in self.host: self._handle_login(timeout = timeout) else: time.sleep(timeout) self.telnet() else : print "in enable mode" def install(self, tree, build, package_name, target_path='/hd/issu', username = 'builder', password = 'fuxor8', linux_ip='10.1.1.101'): """Retrieves a package via SFTP from the network and installs the package tree = 4.6-prod build = 2010011818 package_name = 4.6A1 username = builder password = password full_path (optional) = /auto/build/builder/4.6-prod/2010011818/qnx/cb/mc/StokeOS-4.6A1 linux_ip = 10.1.1.101 (this is qa-radxpm-1) """ # It's assumed that the host running this script is auto mounting the build directories # and that the packages for installation are out there # It's also assumed that the SSX (DUT) has network connectivity and can reach the testing host. debug = False ## Debug if debug: print 'now in issu.py install' ## Validate arguments # the only argument we can actually validate is the linux_ip # the SSX will only accept an ip address in the sftp command not a hostname # so we need to first check to see if it's a hostname and then if not then # we can try to convert it. If that failes we must bail if not validIP(linux_ip): if debug: print 'detected the value linux_ip is not a valid IP address.' print 'attempting to do an NS lookup on the hostname' linux_ip_tmp = nslookup_by_ip(linux_ip) if validIP(linux_ip_tmp): linux_ip = linux_ip_tmp else: print 'invalid IP address or Host Name provided for liux_ip:', linux_ip return ("invalid IP address or Host Name provided for liux_ip: %s" % linux_ip) build_dir = '/auto/build/builder/' back_half = '/qnx/cb/mc/StokeOS-' installed_packages = [] ## Need to see is the path /hd/issu exists # !!!!! command = 'dir ' + target_path #result_raw = self.cmd('dir /hd/issu') try: result_raw = self.cmd(command) except: print 'Unable to list the ISSU directory' print 'System responded' self.ses.before() self.ses.after() result = result_raw.splitlines() try: installed_packages = show_versions(self) print 'Completed reading installed packages' print 'Found the following versions installed:' for item in installed_packages: print item except: print 'Unable to read versions installed' return 'Unable to read versions installed' ##### # Look to see if the package is already installed if package_name in installed_packages: # If so then return with a success print 'The package:', package_name, 'is already installed on the SSX' print 'Installation will be skipped.' return(0) else: print 'The package', package_name, 'will be installed' # the image name looks like 'StokeOS-4.5B2-2009092913' image_name = 'StokeOS-' + package_name + '-' + build ## We need to see if the file is already on the system # to avoid overwriting the file images_on_the_system = [] marker_found = False if debug: print 'About to parse the dir /hd/issu command' print 'Searching the hard drive for the requested version' # The result is from the earlier Dir information for line in result: if len(line) > 0: """ if debug: print 'Line to be processed:', line """ # This test will be run for every line # but there are only like 8 lines so no big deal if 'Unable to access directory' in result: # If this fails then something is really messed up! command = 'mkdir ' + target_path #self.cmd('mkdir /hd/issu') self.cmd(command) else: ## Warning if other files are present then their filenames ## will be stored but it should have net zero effect. # This turns off the storage if 'File system:' in line: marker_found = False """ if debug: print 'Found end of versions' """ # This stores the values if marker_found: """ if debug: print 'Found a version:', word[3] """ word = line.split() images_on_the_system.append(word[3]) # This turns on the storage if '--------- -------- ---------- ----' in line: marker_found = True if debug: print 'Found beginning of versions' if debug: print 'Images installed on the system are:' for line in images_on_the_system: print line print 'We were looking for the following image' print image_name if image_name in images_on_the_system: print 'Image was found on the HD. Will not be coppied over' else: ## Now we need to actually do the work of copying the package over. ##### print 'Image not found on hard drive. It will be retrieved.' if debug: print 'Piecing the parts together' # We're already conntecte to the SSX # We need to SFTP the file from the linux_ip to the SSX # To do that we need to know the full path to the file # We have the pieces so we need to assemble them """ if debug: print 'The full_path variable will contain these parts:' print 'build_dir:', build_dir print 'tree:', tree print 'build:', build print 'back_half:', back_half print 'package_name:', package_name """ # we're re-defining this variable because it was not passed in full_path = build_dir + tree + '/' + build + back_half + package_name if debug: print 'Full path:', full_path print 'Image will be written to the following filename:', image_name print 'It will be written to /hd/issu/' + image_name # At this point we have all the pieces to assemble the SFTP command """ cmd = 'copy sftp://' + username + '@' + linux_ip + ':' + full_path + \ ' /hd/issu/' + image_name """ # added target path for specifiying location to install TO cmd = 'copy sftp://' + username + '@' + linux_ip + ':' + full_path + \ ' ' + target_path + '/' + image_name print 'about to run the command:' print cmd ########## # Copy the file over # Here we run the command using the ftppasswd method retr = self.ftppasswd(cmd, password, 210) if retr: print 'Failed to SFTP the file over. Aborting install!' return(1) if debug: print 'Completed sending the new build to the SSX' ########### # At this point the file is actually on the SSX and we can attempt to "install" it. #command = 'system install package /hd/issu/' + image_name # Added target path command = 'system install package ' + target_path + '/' + image_name if debug: print "install command will be: %s" % command #self.cmd(command) #result = self.cmd('yes') self.ses.sendline("%s" % command) index = self.ses.expect(['will be done', 'Install is not permitted'], timeout=30) print self.ses.before if index == 0: print 'recieved YES/NO prompt' self.ses.sendline('yes') print 'installing package .....' elif index == 1: print 'ISSU is already in progress. Can not install package!' return 'ERROR - Install is not permitted as ISSU Revert is in progress' else: return 'Failed to install package' index = self.ses.expect(['invalid package path or file', 'Installation complete', 'Installed packages maximum limit'], timeout=300) if index == 0: print 'System unable to install file. Bad filename or path' return(1) elif index == 1: print 'Installation complete!' return(0) elif index == 2: print 'There are too many packages installed. Please manually remove at lest 1.' return(1) else: print 'Timeout while installing package.' return(1) def change_version(self, version, method, config_filename='default', ignore_port_down = False): """Performs Upgrade, Revert and Select """ debug = False # Wait time could be externall exposed if needed wait_time = 10 if method not in ('upgrade','revert','select'): return "Unsuported method %s" % method ########### # UPGRADE # ########### elif method == 'upgrade': print 'now in issu.py change_version upgrade' versions_installed = show_versions(self) if version in versions_installed: # Send the upgrade command if ignore_port_down: if debug: print 'about to run the command:' print "system upgrade package %s ignore-port-down" % version self.ses.sendline("system upgrade package %s ignore-port-down" % version) else: if debug: print 'about to run the command:' print "system upgrade package %s" % version self.ses.sendline("system upgrade package %s" % version) index = self.ses.expect(['Save configuration to file', 'Package not installed', \ 'not supported', 'ISSU mode is disabled', 'in inconsistent state', \ 'Upgrade is in progress', 'No Previous Version'], timeout=wait_time) if index == 0: if config_filename == 'default': print 'Saving system configuration to default filename' # Press enter to accept the default system prompt self.ses.sendline() else: print 'Saving system configuration to:', config_filename # Otherwise put in the filename # Expected format is '/hd/issu-upgd-2010-04-20.cfg' self.ses.sendline(config_filename) index_2 = self.ses.expect(['Proceed?', 'ERROR: Slot 0 StokeBloader images',\ 'ERROR: Slot 1 StokeBloader images', 'ERROR: Slot 2 StokeBloader images', \ 'ERROR: Slot 3 StokeBloader images', 'ERROR: Slot 4 StokeBloader images'], timeout=wait_time) if index_2 == 0: # Use this method because we are expecting the prompt self.cmd('yes') print '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' print 'system now upgrading to version:', version print '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' return 0 elif index_2 == 1: print 'Flash banks do not match.' return 'Flash mismatch at slot 0' elif index_2 == 2: print 'Flash banks do not match.' return 'Flash mismatch at slot 1' elif index_2 == 3: print 'Flash banks do not match.' return 'Flash mismatch at slot 2' elif index_2 == 4: print 'Flash banks do not match.' return 'Flash mismatch at slot 3' elif index_2 == 5: print 'Flash banks do not match.' return 'Flash mismatch at slot 4' else: return "Timeout while waiting for proceed prompt" elif index == 1: # Should be converted to log Error message print 'Package not Installed' return 'Package not installed' elif index == 2: # Should be converted to log Error message print "Package selected: %s is not supported" %version return "Package selected: %s is not supported" %version elif index == 3: print 'ISSU dissabled on system. Aborting!' return 'ISSU dissabled on system. Aborting!' elif index == 4: print 'ISSU Already in process. Unable to Upgrade!' return 'ISSU Already in process. Unable to Upgrade!' elif index == 5: print 'Upgrade is already in progress' return 'upgrade already in progress' elif index == 6: print 'No Previous version present in ISSU history to revert to' return 'previous version not present' else: print "Timeout when attempting to %s package %s" % (method, version) else: print 'Unable to upgrade to version', version print 'Package not installed on sysetm' return 'Unable to upgrade to package, because it is not installed' ########## # REVERT # ########## elif method == 'revert': if debug: print 'in issus.py change_version reverting' self.ses.sendline('system revert package ignore-port-down') index = self.ses.expect(['Save configuration to file', 'not supported', 'Pre-Revert Checks Failed', \ 'ISSU Upgrade is in progress', 'not permitted during ISSU soak phase', \ 'in inconsistent state'], timeout=wait_time) if index == 0: if config_filename == 'default': # Press enter to accept the default system prompt self.ses.sendline() else: # Otherwise put in the filename # Expected format is '/hd/issu-upgd-2010-04-20.cfg' self.ses.sendline(config_filename) index_2 = self.ses.expect('Proceed?', timeout=wait_time) if index_2 == 0: # Use this method because we are expecting the prompt self.cmd('yes') return 0 if index_2 == 1: return "Timeout while waiting for proceed prompt" elif index == 1: print 'Revert not supported!' return 'Revert not supported!' elif index == 2: print 'Pre-Revert Checks Failed' return 0 elif index == 3: print 'ISSU Upgrade is in progress. Revert aborted!' return 'ISSU Upgrade is in progress. Revert aborted!' elif index == 4: print 'not permitted during ISSU soak phase' return 'not permitted during ISSU soak phase' elif index == 5: print 'Action will leave card(s) in inconsistent state' print 'This error comes up when the system is still booting right after the cards come to' print 'Running State. Please try putting a time.sleep(60) in the code to fix this!' self.cmd('no') return 'ISSU Action still in process. Action will leave card(s) in inconsistent state;' else: print "Timeout when attempting to %s" % method ########## # SELECT # ########## elif method == 'select': # Due to the fact that they changed the prompts from ISSUv1 to ISSUv2 # we get the prompts in a different combination and order. # There are several paths through this code. if debug: print 'in issu.py change_version selecting' print 'about to run the following command:' print "system select package %s" % version self.ses.sendline("system select package %s" % version) if debug: print 'Command sent. Waiting for response' index = self.ses.expect(['Select will clear revert history', 'will erase all revert history', 'Proceed?', \ 'Package not installed', 'Select is not permitted during ISSU soak phase', 'same as Current Version', \ 'Save configuration to file'], timeout=wait_time) if debug: print 'Parsing system response' if (index in [0,1,2]): # 'Select will clear revert history' # Proceed? (yes/[no]) self.ses.sendline('yes') if index == 2: # We got the early proceed prompt from ISSUv1 return 0 elif index == 3: print 'Package not installed!' return 'Package not installed!' elif index == 4: print 'Select is not permitted during ISSU soak phase' return 'Select is not permitted during ISSU soak phase' elif index == 5: print 'Requested version is already current version' return 0 elif index == 6: if config_filename == 'default': # Press enter to accept the default system prompt self.ses.sendline() else: # Otherwise put in the filename # Expected format is '/hd/issu-upgd-2010-04-20.cfg' self.ses.sendline(config_filename) else: print self.ses.before() print "Timeout when attempting to %s package %s" % (method, version) return 'Timeout during Select' index = self.ses.expect(['Save configuration to file', 'System will be automatically reloaded'], timeout=wait_time) if index == 0: if config_filename == 'default': # Press enter to accept the default system prompt self.ses.sendline() else: # Otherwise put in the filename # Expected format is '/hd/issu-upgd-2010-04-20.cfg' self.ses.sendline(config_filename) elif index == 1: print 'Save Filename prompt not detected.' else: print "Timeout when attempting to %s package %s" % (method, version) return 'Timeout during Select' index = self.ses.expect('Proceed?', timeout=wait_time) if index == 0: # Use this method because we are expecting the prompt self.ses.sendline('yes') #self.ssx.cmd('yes') if (self.host.find("-con") != -1): print('Using console. Need to wait for Shutdown') index = self.ses.expect('Shutdown', timeout=60) if index != 0: print 'System did not shutdown to reboot' return 1 # At this point the system is doing a reboot if everything # worked as planned. #time.sleep(1) #self.ssx.wait4cards() print 'Select command accepted by system' print 'System will now reboot the GLC then the IMC' print 'After command completes telnet sessions to the system will be lost' return 0 else: return "Timeout while waiting for proceed prompt" # Catch all for change version else: return "Version requested was not %s" % method def upgrade(self, version, auto_corect = True): """Wrapper function for change_version """ print 'now in issu.py upgrade' retr = change_version(self, version, 'upgrade') # Sometimes the flash does not match on the cards # It's easy to correct and not a situation for alarm bad_flash = False if auto_corect: print 'Checking to see if there was any flash corruption.' try: return_code = str(retr) except: print 'unable to cast the return value as a string!' return 1 if 'slot 0' in return_code: # If it's bad correct the flash corruption bad_flash = True print 'Correcting flash mismatch' command = 'flash commit 0' self.ses.sendline(command) retr = self.ses.expect(['PRIMARY bank copied to BACKUP bank.'], timeout = 30) if retr == 0: print 'Commit passed' else: print 'unable to correct flash problem on slot 0' return 'Corrupt flash image on slot 0' elif 'slot 1' in return_code: bad_flash = True print 'Correcting flash mismatch' command = 'flash commit 1' self.ses.sendline(command) retr = self.ses.expect(['PRIMARY bank copied to BACKUP bank.'], timeout = 30) if retr == 0: print 'Commit passed' else: print 'unable to correct flash problem on slot 1' return 'Corrupt flash image on slot 1' elif 'slot 2' in return_code: bad_flash = True print 'Correcting flash mismatch' command = 'flash commit 2' self.ses.sendline(command) retr = self.ses.expect(['PRIMARY bank copied to BACKUP bank.'], timeout = 30) if retr == 0: print 'Commit passed' else: print 'unable to correct flash problem on slot 2' return 'Corrupt flash image on slot 2' elif 'slot 3' in return_code: bad_flash = True print 'Correcting flash mismatch' command = 'flash commit 3' self.ses.sendline(command) retr = self.ses.expect(['PRIMARY bank copied to BACKUP bank.'], timeout = 30) if retr == 0: print 'Commit passed' else: print 'unable to correct flash problem on slot 3' return 'Corrupt flash image on slot 3' elif 'slot 4' in return_code: bad_flash = True print 'Correcting flash mismatch' command = 'flash commit 4' self.ses.sendline(command) retr = self.ses.expect(['PRIMARY bank copied to BACKUP bank.'], timeout = 30) if retr == 0: print 'Commit passed' else: print 'unable to correct flash problem on slot 4' return 'Corrupt flash image on slot 4' else: print 'No flash corruption detected.' # Then try to upgrade the system if bad_flash: print 'Attempting to upgrade the package again.' retr = change_version(self, version, 'upgrade') print 'now returning from issu.py upgrade' return retr def revert(self): """Wrapper function for change_version """ if debug: print 'Now in issu.py revert' version = 'NA' retr = change_version(self, version, 'revert') return retr def select(self, version): """Wrapper function for change_version """ retr = change_version(self, version, 'select') return retr def status(self, slot_filter='all'): """Runs "show upgrade status" and parses the output returns a dictionary of card status """ debug = False if debug: print 'now in issu.py status' # instantiate a dictionary to store the return data status_dict = {} # get the status raw_output = self.cmd('show upgrade status') # Check for ISSUv1 issu_v1 = False ## Sample output """ australia[local]#show upgrade status 01 ISSU Operation:Upgrade 02 03 Slot StokeOS Ver Upgrade Status 04 ---- ----------- --------------------------------------------- 05 0 4.6B1 In-Progress(Flashing Started) 06 1 4.6B1S1 Complete 07 2 4.6B1 Not Started 08 3 4.6B1 Not Started 09 4 4.6B1 Not Started """ # Sometimes it looks like this """ australia[local]#show upgrade status 01 ISSU Operation:Upgrade 02 System is currently in ISSU soak phase 03 04 Slot StokeOS Ver Upgrade Status 05 ---- ----------- --------------------------------------------- 06 0 4.6B1 In-Progress(Flashing Started) 07 1 4.6B1S1 Complete 08 2 4.6B1 Not Started 09 3 4.6B1 Not Started 10 4 4.6B1 Not Started """ # If your running an ISSUv1 build it looks like this """ 01 Slot Upgrade Status 02 ---- -------------- 03 0 Not Started 04 1 Not Started 05 2 Not Started 06 3 Not Started 07 4 Not Started """ # chop the output into lines output = raw_output.splitlines() """ if debug: print 'Number or lines in output:', len(output) for line in output: print 'line:', line """ if (len(output) > 2): # the data we care about is on lines 1, 5-9 ## Line 1 line_1 = output[1].rstrip() if (len(line_1) > 2): #words = output[1].split() words = line_1.split() """ if debug: print 'The first line contains:', words """ if words[0] == 'ISSU': ## ('ISSU', 'Operation:Upgrade') issu_status = words[1].split(':') ## ('Operation','Upgrade') status_dict['ISSU Status'] = issu_status[1] """ if debug: print 'The status detected was', status_dict['ISSU Status'] """ elif 'Upgrade' in line_1: #status_dict['ISSU Status'] = 'upgrade' status_dict['status'] = 'upgrade' elif 'Revert' in line_1: #status_dict['ISSU Status'] = 'revert' status_dict['status'] = 'revert' elif 'Slot' in line_1: print '@@@@@@@@ Detected system running ISSUv1 @@@@@@@@@' print 'ISSU automation not capable of parsing the output at this time' issu_v1 = True return 'Unknown Status' else: print 'Failure in issu.py status. Unknown status:', line_1 print line_1 return 'Unknown Status' ## Line 2 line_2 = output[2].rstrip() if (len(line_2) > 2): words = line_2.split() if 'soak' in words: status_dict['ISSU Status'] = 'soak phase' # The lenght of the output changes because they remove a line of text # this leads to missing card 0 sometimes. # we must go look for that seperator line then start_line = 0 for raw_line in output: start_line = start_line + 1 if '-----------' in raw_line: break """ if debug: print 'The first line we care about should be:' print output[start_line] """ if issu_v1: for raw_line in output[start_line:]: if debug: print 'Line to be processed is:' print raw_line local_dict = {} line = raw_line.lstrip() words = line.split(' ',2) slot = "slot %s" % words[0] if debug: print 'slot #', words[0] local_dict['status'] = words[2].lstrip() if debug: print 'status:', words[2].lstrip() status_dict[slot] = local_dict if debug: print 'The status_dict contains:', status_dict else: ## Remaining lines # Ths odd notation means take all the lines from 4 onward for raw_line in output[start_line:]: if debug: print 'Line to be processed is:' print raw_line local_dict = {} #status = [] line = raw_line.lstrip() words = line.split(' ',2) local_dict['version'] = words[1] if debug: print 'version:', words[1] local_dict['status'] = words[2].lstrip() if debug: print 'status:', words[2].lstrip() slot = "slot %s" % words[0] if debug: print 'slot #', words[0] status_dict[slot] = local_dict if debug: print status_dict if debug: print 'The status_dict contains:', status_dict # we have now parsed all the data. Now to return what the user wants if slot_filter == 'all': """ if debug: print 'returning the whole dictionary' """ return status_dict elif slot_filter in status_dict.keys(): if debug: print '==================================' print 'Detected filter on:', slot_filter print 'The filtered dictionary contains:' print status_dict[slot_filter] print '==================================' return status_dict[slot_filter] else: return "Invalid slot. Expected: %s" % status_dict.keys() else: # The ISSU is not in process. Return a Pass value of 0 return status_dict def install_status(self, slot_filter='all'): """Pulls the ISSU status of the install returns a dictionary of card status """ debug = False if debug: print 'now in issu.py status' # instantiate a dictionary to store the return data status_dict = {} # get the status raw_output = self.cmd('show upgrade status') ## Sample output """ australia[local]#show upgrade status 01 ISSU Operation:Upgrade 02 03 Slot StokeOS Ver Upgrade Status 04 ---- ----------- --------------------------------------------- 05 0 4.6B1 In-Progress(Flashing Started) 06 1 4.6B1S1 Complete 07 2 4.6B1 Not Started 08 3 4.6B1 Not Started 09 4 4.6B1 Not Started """ # Sometimes it looks like this """ australia[local]#show upgrade status 01 ISSU Operation:Upgrade 02 System is currently in ISSU soak phase 03 04 Slot StokeOS Ver Upgrade Status 05 ---- ----------- --------------------------------------------- 06 0 4.6B1 In-Progress(Flashing Started) 07 1 4.6B1S1 Complete 08 2 4.6B1 Not Started 09 3 4.6B1 Not Started 10 4 4.6B1 Not Started """ # chop the output into lines output = raw_output.splitlines() """ if debug: print 'Number or lines in output:', len(output) for line in output: print 'line:', line """ if (len(output) > 2): # the data we care about is on lines 1, 5-9 ## Line 1 line_1 = output[1].rstrip() if (len(line_1) > 2): #words = output[1].split() words = line_1.split() """ if debug: print 'The first line contains:', words """ if words[0] == 'ISSU': ## ('ISSU', 'Operation:Upgrade') issu_status = words[1].split(':') ## ('Operation','Upgrade') status_dict['ISSU Status'] = issu_status[1] """ if debug: print 'The status detected was', status_dict['ISSU Status'] """ if 'Upgrade' in line_1: status_dict['ISSU Status'] = 'upgrade' elif 'Revert' in line_1: status_dict['ISSU Status'] = 'revert' else: print 'Failure in issu.py status. Unknown status:', line_1 print line_1 return 'Unknown Status' ## Line 2 line_2 = output[2].rstrip() if (len(line_2) > 2): words = line_2.split() if 'soak' in words: status_dict['ISSU Status'] = 'soak phase' # The lenght of the output changes because they remove a line of text # this leads to missing card 0 sometimes. # we must go look for that seperator line then start_line = 0 for raw_line in output: start_line = start_line + 1 if '-----------' in raw_line: break """ if debug: print 'The first line we care about should be:' print output[start_line] """ ## Remaining lines # Ths odd notation means take all the lines from 4 onward for raw_line in output[start_line:]: """ if debug: print 'Line to be processed is:' print raw_line """ local_dict = {} #status = [] line = raw_line.lstrip() words = line.split(' ',2) local_dict['version'] = words[1] """ if debug: print 'version:', words[1] """ local_dict['status'] = words[2].lstrip() """ if debug: print 'status:', words[2].lstrip() """ slot = "slot %s" % words[0] """ if debug: print 'slot #', words[0] """ status_dict[slot] = local_dict """ if debug: print status_dict """ if debug: print 'The status_dict contains:', status_dict # we have now parsed all the data. Now to return what the user wants if slot_filter == 'all': """ if debug: print 'returning the whole dictionary' """ return status_dict elif slot_filter in status_dict.keys(): if debug: print '==================================' print 'Detected filter on:', slot_filter print 'The filtered dictionary contains:' print status_dict[slot_filter] print '==================================' return status_dict[slot_filter] else: return "Invalid slot. Expected: %s" % status_dict.keys() else: # The ISSU is not in process. Return a Pass value of 0 return status_dict def wait_issu(self, max_time = 2400, poll_interval=5): """Polls the system during upgrade/revert waiting for ISSU to complete """ complete = False issu_status = status(self) debug = False """ if debug: print 'This is what we got back from the status function' print issu_status """ try: card_list = issu_status.keys() except: print 'unable to parse the status of the system.' return 'Failed to get status' """ if debug: print 'this is our list of keys from that dictionary' print card_list """ number_of_cards = len(card_list) if issu_status.has_key('ISSU Status'): print 'Detected system in ISSU.' number_of_cards = number_of_cards - 1 ## Debug #print 'Now in wait_issu function!' #print 'The value of debug is:', debug """ if debug: print 'Card list contains:', card_list print 'Detected', number_of_cards, 'cards' """ print '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' print 'Waiting for the ISSU process to complete.' print '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' # This line is used for the aut-revert functions. It was interfering with # the normal upgrade and revert functions and needs to be re-written. done = ['Complete', 'Not Started', 'Auto-Revert Complete'] auto_reverting = False while not complete: time.sleep(poll_interval) issu_status = status(self) card_pass_count = 0 for card in card_list: if card == 'ISSU Status': if issu_status['ISSU Status'] == 'Complete': print 'Detected ISSU status complete' # Need to figure out if the system is in auto revert # This might be the right string elif issu_status['ISSU Status'] == 'Auto Revert': print 'Detected systm is Auto Reverting' auto_reverting = True debug = True else: print 'ISSU Status is:', issu_status['ISSU Status'] if debug: print 'Please look for auto revert status and update,' print 'issu.py function wait_issu to include exact auto revert string' elif (not issu_status.has_key('ISSU Status')): # when that field disapears then it's done print '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' print '^^^^^^^ ISSU Process Complete ^^^^^^^^^^^' print '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' return 0 #complete = True #break else: if debug: print 'checking' , card, 'for status' #if issu_status[card]['status'] == 'Complete': if debug: print 'About to see if the card:', card, 'is in one of these states:', done print 'ISSU status for this card is reported as:', issu_status[card]['status'] print card, ':', issu_status[card]['status'] # This branch is for normal upgrade and revert if issu_status[card]['status'] in 'Complete': if debug: print '!!!! Detected card complete !!!!' #print 'card', card, 'Complete' card_pass_count = card_pass_count + 1 #If the system is in auto-rever then a "not-started" is also done # Code needs to be updated to fix this. elif 'Auto-Revert' in issu_status[card]['status']: print 'Detected system in Auto-Revert via card status' auto_reverting = True # This branch is for auto-reverting elif auto_reverting: if debug: print 'Now in auto-revert detection loop' if issu_status[card]['status'] in done: if debug: print '!!!! Detected card complete !!!!' card_pass_count = card_pass_count + 1 else: print 'Card was not Done. It was:', issu_status[card]['status'] else: if debug: print 'Card was not done ---' print card, 'Status:', issu_status[card]['status'] #break print 'Card pass rate:', card_pass_count if card_pass_count == number_of_cards: print 'Detected all cards complete' complete = True if issu_status.has_key('ISSU Status'): if issu_status['ISSU Status'] == 'soak phase': print 'Detected Soak Phase. Waiting for soak to complete.' complete = False # timer to make sure th polling will eventually finish max_time = max_time - poll_interval print 'Time left:', max_time if max_time < 1: print 'Maximum polling time was exceeded!' print 'System never completed ISSU' return 'Timeout whill polling. Excessive time' return 0 def install_base(self, base_version, username = 'regress', password = 'gleep7', linux_ip = '10.1.1.101'): """This method is used to return the running system to a known base version prior to begining normal ISSU testing. It uses the methods of install and select to do this. self = self.ssx (SSX object) base_version = ['package_name':'4.7', 'build':'2010022188','tree':'4.7'] """ # Two branches # 1. If the version it's running now is not the same version then we can # simply install the base version and select over to it # 2. The other possibility is the version it's running is not the same build ID # meaning you are testing a newer or older build of the same version. # to install and select to this we must: # A. Install a known good older version # B. Select down to that version # C. Uninstall the old package # D. Install the new package # E. Select to the new package if debug: print '----------------------------' print 'now in issu.py install_base' if not(username == 'regress'): print 'Non default username detected:', username if not(password == 'gleep7'): print 'Non default password detected:', password if not (linux_ip == '10.1.1.101'): print 'Non default linux_ip detected:', linux_ip running_ver = self.get_version() print 'System will be selected back to the base version' print 'Base version is:', base_version print 'running version is:', running_ver if debug: print 'testing for:', running_ver['branch'], '=', base_version['package_name'] if (running_ver['branch'] == base_version['package_name']): if debug: print 'Detected that the running version name is the same as the base' # If the version we want to install is the same as the running version but the # build ID is different then we need to do case 2 above. if not (running_ver['build'] == base_version['build']): if debug: print 'Build ID is different then running version.' print 'System will:' print '1. Select to older version' print '2. Remove old build' print '3. Install base version' print '4. Select to base version' ## Write code here! pass else: # If the package name and the build ID are the same then We're already # running the correct version. Just return print 'The build ID is also the same. System now at base version.' return(0) else: # This is the simpler path case 1 above if debug: print 'The system is not running the base version.' print 'Sysetm will be installed with base version' ########## # Install print("About to install version %s" % base_version) retr = install(self, tree = base_version['tree'], \ build = base_version['build'], \ package_name = base_version['package_name'], \ username = username, \ password = password, \ linux_ip = linux_ip) print("install returned %s" % retr) if retr: print 'Something went wrong. Returning' return retr ######## # Select print 'Base version now installed.' print 'Selecting to base version (reboot)' retr = select(self, base_version['package_name']) if retr: print 'Something went wrong. Returning' return retr else: return 0 """ print 'System performing select now.' print 'Please reconnect after reload' return 0 """ """ reboot_time = 120 print("waiting for the system to finish rebooting: %s seconds" % reboot_time) time.sleep(reboot_time) rebooting = True retries = 20 while rebooting: print('Sleeping for 30 seconds') time.sleep(30) try: print 'Connecting to SSX' self.ssx.telnet() print 'Made it past the telnet command' # if that command does not fail then the rebooting state should change rebooting = False except: print('System not up yet') retries = retries - 1 print("%s retries left" % retries) if retries == 0: print("System never came back up after select!") sys.exit(1) print 'Completed Select to base version' """ return 0 def check_session_traffic(self, username_list = 'all', poll_time = 10): """This function will use the session_counters method to pull all the active sessions. Then it will check session by session to see if the counters are increasing. We expect some sessions will not be sending traffic. To handle that the function accepts a list of sessions to check. The calling program is responsible to remove items from that list once they have been detected to no longet be sending traffic. """ # Accumulate the result here. # At the end filter based on requested usernames. result = {} if username_list == 'all': print 'All Sessions will be examined' print 'Polling the session counters' baseline = session_counters(self) print 'Waiting:', poll_time, 'seconds' time.sleep(poll_time) delta = session_counters(self) print 'Computing the delta' else: print 'Select sessions will be examined' print 'Polling the session counters' # This is all the data raw_baseline = session_counters(self) print 'Waiting:', poll_time, 'seconds' time.sleep(poll_time) # this is all the data raw_delta = session_counters(self) print 'Computing the delta' baseline = {} delta = {} # Now we filter it before doing accounting for username in raw_baseline: if username in username_list: baseline[username] = raw_baseline[username] # And we filter the detla as well. for username in raw_delta: if username in username_list: delta[username] = raw_delta[username] if len(baseline): print 'Found sessions' else: print 'No Sessions are active!' return 'No Sessions are active!' # At this point we have all the data required we just need to parse it. session_list = baseline.keys() print 'The following sessions will be parsed:', session_list active_sessions = 0 inactive_sessions = 0 total_sessions = len(session_list) print 'Detected', total_sessions, 'Sessions' for username in session_list: if delta.has_key(username): # Reset the local variables xmit_active = False rcv_active = False # Check the TX if baseline[username]['Xmit Bytes'] < delta[username]['Xmit Bytes']: xmit_active = True # Check the RX if baseline[username]['Rcv Bytes'] < delta[username]['Rcv Bytes']: rcv_active = True # Store the results. if xmit_active and rcv_active: result[username] = 'Active' active_sessions = active_sessions + 1 elif xmit_active: result[username] = 'Xmit only' active_sessions = active_sessions + 1 elif rcv_active: result[username] = 'Rcv only' active_sessions = active_sessions + 1 else: result[username] = 'Inactive' inactive_sessions = inactive_sessions + 1 else: print 'The following session dropped out while polling' print baseline[username] # We'll count that dropped one as an inactive session inactive_sessions = inactive_sessions + 1 result['Active Sessions'] = active_sessions result['Inactive Sessions'] = inactive_sessions # note the variable must be cast as a float to actually get a decimal result. result['Percent Active'] = 100 * (float(active_sessions) / total_sessions) result['Percent Inactive'] = 100 * (float(inactive_sessions) / total_sessions) return result def show_card_state(self): """Simple command runs "show card" and parses the output then returns it: Here is a sample Dictionary output: {'Status': 'Complete', 'slot 2': {'serial_number': '0130901190900001', 'state': 'Running', 'hw_rev': '09.01', 'type': 'GLC2', 'model_name': '4x1000Base-X'}, 'slot 3': {'serial_number': '0110323060000110', 'state': 'Running', 'hw_rev': '02.07', 'type': 'GLC1', 'model_name': '4x1000Base-X'}, 'slot 0': {'serial_number': '0020905420820003', 'state': 'Running(Active)', 'hw_rev': '09.05', 'type': 'IMC1', 'model_name': 'Stoke IMC1'}, 'slot 1': {'serial_number': '0020140050000026', 'state': 'Running(Standby)', 'hw_rev': '05.02', 'type': 'IMC1', 'model_name': 'Stoke IMC1'}, 'slot 4': {'serial_number': '0130114060000035', 'state': 'Running', 'hw_rev': '02.05', 'type': 'GLC2', 'model_name': '4x1000Base-X'}} NOTE: Dictionary is not Sorted """ debug = False status_dict = {} command = "show card" raw_card_response = self.cmd(command) if len(raw_card_response) > 0: card_response = raw_card_response.splitlines() # There could be a test right here to make sure the lines are present # or we got an error message if 'ERROR:' in card_response[1]: print 'Detected an error when running: show card' print 'Returned text was:' print raw_card_response status_dict['Status'] = 'Error' return status_dict if debug: print 'The following lines will be processed:' print card_response[3:] print '======================================' # We don't really want the two header lines so we omit them for line in card_response[3:]: if debug: print 'This is the line to process:', line words = line.split() local_dict = {} if len(words) == 7: slot = words[0] local_dict['type'] = words[1] local_dict['state'] = words[2] local_dict['serial_number'] = words[3] local_dict['model_name'] = words[4] + ' ' + words[5] local_dict['hw_rev'] = words[6] elif len(words) == 6: slot = words[0] local_dict['type'] = words[1] local_dict['state'] = words[2] local_dict['serial_number'] = words[3] local_dict['model_name'] = words[4] local_dict['hw_rev'] = words[5] else: print 'This line has too many/few elements', len(words) print words status_dict['Status'] = 'Error' return status_dict current_slot = 'slot ' + slot status_dict[current_slot] = local_dict status_dict['Status'] = 'Complete' return status_dict def wait_for_cards(self, timeout = 360, poll_time = 10): """Waits for ALL cards to come to a running state by polling the system. This is a rewrite of device.py wait4cards and should be used as a replacement. """ debug = False if debug: print 'now in issu.py wait_for_cards' print 'System is now waiting for all cards to come to a running state' print 'Status will be updated every', poll_time, 'seconds' running = ['Running(Active)','Running(Standby)', 'Running'] total_wait = 0 # This will run until either the timout is reached or an error occurs or all cards # come to a running state while True: print '------------------------' running_card_count = 0 running_card_list = [] current_card_state = show_card_state(self) if current_card_state['Status'] == 'Complete': if debug: print 'was able to retrieve current card state' print 'now processing' card_list = current_card_state.keys() if debug: print 'Detected the following cards:', card_list for card in card_list: if not (card == 'Status'): card_state = current_card_state[card]['state'] if card_state in running: #print card, 'Has come to running state' running_card_count = running_card_count + 1 running_card_list.append(card) if running_card_count == (len(card_list) - 1): print 'All cards have come to running state.' print 'Total wait time was', total_wait return 0 else: return 'Failed to retrieve card state' try: print 'ISSU Status:', current_card_state['Status'] except: print 'No ISSU Status to report' print 'The following cards are running', running_card_list print 'Elapsed time:', total_wait, 'seconds' time.sleep(poll_time) total_wait = total_wait + poll_time timeout = timeout - poll_time if timeout < 1: return 'Timeout while polling system' def all_cards_running(self, debug=False): """Uses the method show_card_state to verify all cards are running. Returns True/False Designed as simple test to be run at the begining/end of tests. Does not wait for cards. If you want to see some output use the debug option! """ if debug: print 'now in issu.py method all_cards_running' # This checks to see if any of the cards are in an "error" state card_state = show_card_state(self) # We don't need this record del card_state['Status'] if debug: print 'here is the raw dictionary' print card_state print 'here is the card information' for card in card_state: if debug: print card_state[card] if 'Running' in card_state[card]['state']: if debug: print 'Card:', card, 'is in running state' else: if debug: print 'Card', card, 'is NOT in running state. FAIL' #self.fail("Card %s is NOT in running state" % card) return False return True def kill_pid(self, raw_pid='none', raw_slot=0): """Method kills processes by PID only """ slot_range = [0,1,2,3,4] # Validate the input if raw_pid == 'none': return 'No PID Provided!' try: pid = int(raw_pid) except: print 'PID value not an Integer:', raw_pid return 'Non integer value for PID' try: slot = int(raw_slot) except: print 'Invalid value for slot:', raw_slot print 'Was expecting an integer.' if not (slot in slot_range): print 'Invalid value for slot:', slot print 'Must be in range:', slot_range # Build the command command = 'process coredump ' + str(slot) + ' ' + str(pid) if debug: print 'The command will be:', command self.ses.sendline("%s" % command) index = self.ses.expect(['Continue'], timeout=30) print self.ses.before if index == 0: self.cmd('yes') else: print 'Failed to send core dump command!' return 'Failed' return 0 def list_ike_sessions(self, slot = 'all'): """Uses "show ike-session list" or "show ike-session SLOT_NUMBER list" to get ike-session details. Then returns the output """ debug = False slot_range = [0,1,2,3,4,'all'] # We will accumulate all the sesion information into this list return_session_list = [] expected_values = ['SLOT','Session Handle','IKE Version','Remote IP',\ 'IKE-SA ID','Session Addr','Session State'] # Example input """ australia[local]#show ike-session list 01 Mon Jun 21 16:11:20 PDT 2010. 02 03 ------------------------------------------------------------------------------- 04 SLOT : 2 05 Session Handle : fc440200 06 IKE Version : 2 07 Remote IP : 10.11.2.1 08 IKE-SA ID : 16502102800650210@r2 09 Session Addr : 172.1.0.1 10 Session State : IPSEC-ESTABLISHED, IKE-SA DONE, CHILD-SA MATURE 11 ------------------------------------------------------------------------------- 12 13 ------------------------------------------------------------------------------- 14 SLOT : 3 15 Session Handle : f4480200 16 IKE Version : 2 <LAN<->LAN> 17 Remote IP : 10.11.3.1 18 IKE-SA ID : sswan 19 Session State : IPSEC-ESTABLISHED, IKE-SA DONE, CHILD-SA MATURE 20 ------------------------------------------------------------------------------- 21 """ # Example return value: """ [{'SLOT': ' 2', 'Session Addr': ' 172.1.0.1', 'IKE-SA ID': ' 16502102800650210@r2', 'IKE Version': ' 2', 'Session Handle': ' fc440201', 'Remote IP': ' 10.11.2.1', 'Session State': ' IPSEC-ESTABLISHED, IKE-SA DONE, CHILD-SA MATURE'}] """ if not (slot in slot_range): print 'Invalid Slot ID provided for filtering:', slot return 'Invalid Slot ID provided for filtering:', slot if slot == 'all': command = 'show ike-session list' else: command = 'show ike-session ' + str(slot) + ' list' if debug: print 'The command will be:', command raw_session_list = self.cmd(command) session_list = raw_session_list.splitlines() if debug: print 'The raw data returned from the command was:' print raw_session_list if session_list[1] == 'ERROR: No sessions found on any Card': print 'No Sessions present' return 'No Sessions present' # So we know that the first line which is line 0 is thrown away by our cmd API # The first available line is line 1 which contains the date. We don't want that. # Line 2 contains a space which is also useless to us. # So we'll start parsing at line 3 in_block = False local_session_dict = {} for line in session_list[2:]: # Look for the start. if '---' in line: if in_block == True: # If we find a second one it's the end in_block = False # Now we need to stuff this info into the list we return if debug: print 'Appending the local_sesions_dict containing:' print local_session_dict print 'To the return_session_list which contains:' print return_session_list return_session_list.append(local_session_dict) if debug: print 'Found the end of the block' # Flush the local_session_dict for the next block local_session_dict = {} else: if debug: print 'Found the beging of the block' in_block = True elif in_block: words = line.split(':') if debug: print 'Split words are:', words paramater = words[0].rstrip() if debug: print 'Stripped paramater is:', paramater if paramater in expected_values: # We simply store it in a local dictionary indexed on it's name if debug: print 'Found a paramater we expected:', paramater print 'Storing it in the local_session_dict' local_session_dict[paramater] = words[1].lstrip() if debug: print 'The local_session_dict contains:', local_session_dict else: print 'Got back a value we did not expect:', words[0] print 'Please modify issu.py list_ike_sessions expected_values list to include this!' """ else: print 'line contains:', line """ print 'Succesfully parsed session list' return return_session_list def list_tunnels(self): """Simply parses the 'show tunnel' output """ debug = False return_list = [] lines_to_parse = [] # Example Input """ 01 Name CctHdl Type Admin State 02 ------------------------------------------- -------- ---------- ------- ------- 03 tun1 ce000002 lan2lan:ip44 enable up 04 1 objects displayed. """ # Example output """ [{'CctHdl': 'ce000002', 'admin': 'enable', 'state': 'up', 'type': 'lan2lan:ip44', 'name': 'tun1'}] """ # It looks like the last line contains the number of tunnels configured. if debug: print 'Now in issu.py list_tunnels' command = 'show tunnel' raw_input = self.cmd(command) show_tunnel_list = raw_input.splitlines() # There needs to be some error checking here but I don't know what the bad input looks like yet if len(show_tunnel_list) < 4: print 'Detected no tunnels configured!' print 'Please review this raw ouptut.' print raw_input return 'No tunnels configured' number_of_tunnels = len(show_tunnel_list) - 4 if debug: print 'Detected', number_of_tunnels, 'Tunnels' # This builds up a list of lines we care about lines_to_parse = range(3, (number_of_tunnels + 3)) if debug: print 'The following lines will be parsed:', lines_to_parse for line_number in lines_to_parse: line = show_tunnel_list[line_number] local_dict = {} if debug: print 'The raw line is:' print line words = line.split() local_dict['name'] = words[0] local_dict['CctHdl'] = words[1] local_dict['type'] = words[2] local_dict['admin'] = words[3] local_dict['state'] = words[4] if debug: print 'local_dict contains:' print local_dict return_list.append(local_dict) if debug: print 'return_list contains:' print return_list print 'Completed parsing "show tunnel" command' return return_list def valid_month(month): """ verifies the input is a valid 3 character month like "jan", "feb" ... """ debug = False if debug: print 'verifying month is valid', month if month in month_list: if debug: print 'Valid month detected:', month return True else: if debug: print 'Invalid Month supplied:', month print 'Month must be one of the following:' print month_list return False def valid_day_of_month(day_of_month): """ verifies the input is a valid day of the month as an integer like "23" """ debug = False ############### ## Day of month try: num_day = int(day_of_month) except: print 'Day of month is not an integer. OOPS!' return False if not(num_day in range(1, 32)): print 'invalid number for day_of_month:', day_of_month return False elif len(day_of_month) == 0: print 'No day of month value provided' return False else: if debug: print 'Valid day of month detected:', day_of_month return True def valid_hour(hour): """ verifies the input is a valid hour of the day like "12" """ debug = False try: num_hour = int(hour) except: print 'Hour is not an integer:', hour return False if not(num_hour in range(0,24)): print 'There are only 24 hours in the day. Value too large!' return False elif len(hour) == 0: print 'No hour value provided!' return False else: if debug: print 'Valid hour detected:', hour return True def valid_minute(minute): """ verifies the input is a valid minute like "01" or "24" """ debug = False try: num_minute = int(minute) except: print 'Non numeric value for minute caught:', minute return False if not (num_minute in range(0, 60)): print 'Only 60 mintues in an hour. Invalid minute value caught:', minute return False if not (len(minute) == 2): print 'minute must contain two digits:', minute return False else: if debug: print 'Valid minute detected:', minute return True def valid_second(seconds): """ verifies the input is a valid second like "01" or "24" """ debug = False try: num_seconds = int(seconds) except: print 'Non numeric value for seconds caught:', seconds return False if not (num_seconds in range(0, 60)): print 'Only 60 mintues in an hour. Invalid seconds value caught:', seconds return False if not (len(seconds) == 2): print 'seconds must contain two digits:', seconds return False else: if debug: print 'Valid second detected:', seconds return True def validIP(address): debug = False if debug: print 'now in validIP in issu.py' print 'length of address:', len(address) try: parts = address.split(".") except: if debug: print 'unable to split the address:', address return False if len(parts) != 4: if debug: print 'there are not four octests', address return False first_octet = parts[0] try: int(first_octet) except: if debug: print 'first octet is not an integer', first_octet return False if int(first_octet) == 1: first_octet_1 = True if debug: print 'First octet is 1' else: first_octet_1 = False if not 1 <= int(first_octet) <= 254: return False for item in parts[1:]: try: int(item) except: if debug: print 'value:', item, 'is not an integer' return False if first_octet_1: if debug: print 'testing from 0 - 254' print 'value is:', item if not 0 <= int(item) <= 254: if debug: print 'value not in range 0-254, value:', item return False else: if debug: print 'testing from 0 - 254' print 'value is:', item if not 0 <= int(item) <= 254: if debug: print 'value not in range 1-254, value:', item return False return True def pull_syslog(self, clock): """ Pulls the information available from "show log" and filters based on date/time """ debug = False ################### ## Input Validation # We need to first make sure that the incoming filter list contains all the fields we need! ######## ## Month if clock.has_key('month'): if valid_month(clock['month']): if debug: print 'Filtering on Month', clock['month'] else: print 'Invalid month detected:', clock['month'] return 'Invalid Month: ' + clock['month'] else: print 'Month option not detected. Must be present' return 'value "month" not set' ############### ## Day of month if clock.has_key('day_of_month'): if valid_day_of_month(clock['day_of_month']): if debug: print 'Filtering on day of month', clock['day_of_month'] else: print 'Invalid day of month provided:', clock['day_of_month'] return 'Invalid day of month provided: ' + clock['day_of_month'] else: print 'no day_of_month value provided!' return 'no day_of_month value provided!' ####### ## Hour if clock.has_key('hour'): if valid_hour(clock['hour']): if debug: print 'Filtering on hour', clock['hour'] else: print 'Invalid hour detected', clock['hour'] return 'Invalid hour detected ' + clock['hour'] ######### ## Minute if clock.has_key('minute'): if valid_minute(clock['minute']): if debug: print 'Filtering on minute', clock['minute'] else: print 'Invalid minute value provided:', clock['minute'] return 'Invalid minute value provided:' + clock['minute'] else: print 'No minute value found!' return 'no minute value found' ################################# ## Retrieving the Log information # The raw log lines look like this: """ Jul 19 10:43:40 [0] DEBUG Aaad-HA_SESSION_BUFF_LOAD_SUCCESS-1-0x4400d: Successfully loaded session buff type 1. """ # To be able to parse the log based on date/time we need: # month, day_of_month, raw_long_time # There is a problem with the time! # We need thing that happened after the start time #command = "show log | begin " + '"' + clock['month'] + ' ' + clock['day_of_month'] + '"' command = "show log | begin " + '"' + clock['month'] + ' ' \ + clock['day_of_month'] + ' ' + clock['hour'] + ':' + clock['minute'] + '"' if debug: print ("The command will be: %s" % command) self.ses.sendline(command) raw_log = '' raw_log_lines = [] collecting_input = True while collecting_input: retr = self.ses.expect([':$', enable_prompt_regex], timeout = 10) if retr == 0: raw_log = self.ses.before raw_lines = raw_log.splitlines() raw_log_lines += raw_lines if debug: print '-------------------------------' print 'We got some input. Here it is!' print 'it\'s', len(raw_log), 'raw characters' print 'it\'s', len(raw_lines), 'lines of text' print 'total is now', len(raw_log_lines) #print raw_log_lines print 'more input to capture' elif retr == 1: if debug: print 'back the prompt' raw_log = self.ses.before raw_lines = raw_log.splitlines() raw_log_lines += raw_lines collecting_input = False if debug: print '-------------------------------' print 'This is the last bit of input' print 'We got some input. Here it is!' print 'it\'s', len(raw_log), 'raw characters' print 'it\'s', len(raw_lines), 'lines of text' print 'total is now', len(raw_log_lines) else: print 'Timeout while retrieving logs. OOPS!' return 'timeout while retrieving logs' if len(raw_log_lines) < 2: print 'Not enough lines caught! Here is what we did get back' print raw_log_lines return 'No log retrieved' if debug: print 'Got the log back!' print 'there are', len(raw_log_lines), 'lines to parse' print 'Here are the first three of them' print raw_log_lines[1] print raw_log_lines[2] print raw_log_lines[3] print("Searching for log events after the start time") print("---------------------------------------------") ############################### ## Parse the lines from the log # 1. Try to parse the line and detect the date/time header # a. If that succeeds we hold the line in escrow in case there is more on the next line # aa. If there is already a line in escrow we save it to the return list # b. If that fails we join the current line to the line in escrow and store it # bb. If the old line was only 3 words long we add the ":" back in # This is the container we return the data in ret_list = [] discarded_lines = 0 broken_line = False escrow_line = '' for line in raw_log_lines[1:]: # Check for empty line if len(line) > 0: if debug: print("------------------------------------") print("The raw line is:") print(line) # Cut the line into words words = line.split() ############################################ ## Peace back together word missing ":" case if broken_line: if debug: print 'This should be the other half of the line' print escrow_line print 'The complete line should be:' print escrow_line, line # Here we have the first fragmenet and we join it to the other half escrow_words = escrow_line.split() if len(escrow_words) == 3: if debug: print 'We caught the special case where the ":" is missing.' word_three = escrow_words[2] + ':' + words[0] if debug: print 'our assembled third word is now', word_three head = escrow_words[0], escrow_words[1], word_three if debug: print 'the first three words should now be:', head tail = words[1:] words = head, tail if debug: print 'The full line should now be:' print words # We fixed the broken line broken_line = False # and we took the three words out of escrow escrow_line = '' ############################## ## Parse the month date header try: month_log = words[0] if not (valid_month(month_log)): if debug: print 'Invalid month detected' raise day_of_month_log = words[1] if not (valid_day_of_month(day_of_month_log)): if debug: print 'Invalid day of month detected' raise raw_time_log = words[2] if debug: print 'parsing raw_time:', raw_time_log long_time_log = raw_time_log.split(":") if debug: print 'the long_time_log contains:', long_time_log if not (len(long_time_log) == 3): if debug: print 'detected invalid time format:' print long_time_log raise hour_log = long_time_log[0] if not (valid_hour(hour_log)): if debug: print 'Invalid hour detected' raise minute_log = long_time_log[1] if not (valid_minute(minute_log)): if debug: print 'Invalid minute detected' raise second_log = long_time_log[2] if not (valid_second(second_log)): if debug: print 'invalid second detected' raise # We don't care about this stuff at this time but it could be # parsed in the future. logs_per_second_log = words[3] log_type = words[4] log_deamon = words[5] log_msg_type = words[6] log_message = words[7:] except: if debug: print 'Unable to parse this line:' print line print 'It is probably part of the previous line' # Yep it's broken somehow! Either # 1. It's missing it's ":" "special case" # 2. It is so long it linewrapped. broken_line = True # We store the fragment in escrow escrow_line = line #ret_list.append(line) if debug: print 'Succesfully parsed the date/time header' ##################################### ## Filter the line based on date time if not broken_line: # Ok now the log is parsed we need to compare the dat time if debug: print("The month is: %s" % month_log) print("looking for a month greater then: %s" % clock['month']) if clock['month'] == month_log: # Bug here it won't pass the end of the month to the next month if debug: print("The day is: %s" % day_of_month_log) print("Looking for a day greater then: %s" % clock['day_of_month']) if clock['day_of_month'] <= day_of_month_log: if debug: print("The hour is: %s" % hour_log) print("Looking for an hour greater then: %s" % clock['hour']) if clock['hour'] <= hour_log: if debug: print("The minute is: %s" % minute_log) print("Looking for a minute greater then: %s" % clock['minute']) if clock['minute'] <= minute_log: # At this point we got a good line. # If we had something in escrow we need to flush it to return_list if len(escrow_line) > 0: ret_list.append(escrow_line) if debug: print 'We now have a complete line that we are flusing to the return list:' print escrow_line print 'clearing the escrow' escrow_line = '' # It's possible for the line to have been split onto two lines # We will hold the line in escrow in case we catch the other half. else: if debug: print 'We have a good line. Saving it in escrow in case we find more parts of it' escrow_line = line elif clock['hour'] < hour_log: # At this point we got a good line. # If we had something in escrow we need to flush it to return_list if len(escrow_line) > 0: ret_list.append(escrow_line) if debug: print 'We now have a complete line that we are flusing to the return list:' print escrow_line print 'clearing the escrow' escrow_line = '' # It's possible for the line to have been split onto two lines # We will hold the line in escrow in case we catch the other half. else: if debug: print 'We have a good line. Saving it in escrow in case we find more parts of it' escrow_line = line else: if debug: print 'The following line was not saved becuase it is before the minute we want' print line discarded_lines += 1 elif clock['day_of_month'] < day_of_month_log: # At this point we got a good line. # If we had something in escrow we need to flush it to return_list if len(escrow_line) > 0: ret_list.append(escrow_line) if debug: print 'We now have a complete line that we are flusing to the return list:' print escrow_line print 'clearing the escrow' escrow_line = '' # It's possible for the line to have been split onto two lines # We will hold the line in escrow in case we catch the other half. else: if debug: print 'We have a good line. Saving it in escrow in case we find more parts of it' escrow_line = line else: if debug: print 'The following line was not saved becuase it is before the hour we want' print line discarded_lines += 1 else: if debug: print 'The following line was not saved becuase it is before the day of month we want' print line discarded_lines += 1 else: if debug: print 'The following line was not saved becuase it is before the month we want' print line discarded_lines += 1 ##################################################################################### ## concatenate the linewrapped line to the escrow line and add it to the return value if broken_line: # The words in the input line were broken up earlier # Make sure it's not the "special case" if len(words) > 3: # Make sure it's not the first input # we want to append this output if len(escrow_line) > 0: if debug: print 'Found the tail of a linewrapped line' print 'the head looks like:' print escrow_line print 'The tail looks like:' print line # We store it back into the escrow line because there could # be more linewrapped text. (Multi line) escrow_line = escrow_line + line if debug: print 'Put together it looks like' print escrow_line if debug: print 'clearing broken line status' broken_line = False else: # ok something is really messed up here. # 1. It's not words long # 2. We don't have any lines in escrow yet # It must just be crap print 'Detected something very wrong with this line:' print line return 'unknown exception with line' + line if debug: print 'Flusing the last line from escrow' print escrow_line ret_list.append(escrow_line) if debug: print '----------------------------------------' print 'Completed parsing the log file' print 'counted', len(ret_list), 'lines of log' print 'discarded', discarded_lines, 'lines' return ret_list def num_month_to_string(month): """ converts numeric months to three letter string months """ debug = False try: num_month = int(month) except: if debug: print 'non numeric month set' return 'non numeric month set' return month_list[num_month - 1] def name_month_to_num(month): """ converts the name like "Jul" back to a number """ month_list = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] if month in month_list: if month == 'Jan': return 1 elif month == 'Feb': return 2 elif month == 'Mar': return 3 elif month == 'Apr': return 4 elif month == 'May': return 5 elif month == 'Jun': return 6 elif month == 'Jul': return 7 elif month == 'Aug': return 8 elif month == 'Sep': return 9 elif month == 'Oct': return 10 elif month == 'Nov': return 11 elif month == 'Dec': return 12 else: print 'oh crap! Bug in issu.py name_month_num' else: print 'Invalid month supplied:', month print 'Must be one of these:', month_list return 'Invalid month name' def get_hidden_password(level = '2'): """ This command uses the cli-pwd to retrieve the hidden enable password for today only It takes in as it's input the level you need. Defaulting to 2 """ debug = False if debug: print 'Now in issu.py method get_hidden_password' if (level in range(1,7)): print 'Invalid level selected:', level print 'Level must be:', range(1,7) return 'Invalid level: ' + level search_string = 'level ' + level if debug: print 'search string will be:', search_string password = '' shell = os.popen("cli-pwd") for line in shell.readlines(): if search_string in line: if debug: print("Found the line we were looking for:") print(line) words = line.split() if debug: print("This should be the word we are looking for: %s" % words[3]) password = words[3].strip(',') if debug: print("This should be the password: %s" % password) print 'exiting this loop' break if debug: print 'about to return:', password return password def pull_internal_logs(self, clock): """ This method uses the hidden shell to look at the raw log files in /hd/logs and /hdp/logs It then filters the logs based on a date time and returns them in a list concatenated together There will be a list header for each log. The input is a date time which is the same format as the split show clock value That can be retrieved using the issu.py show_time function """ debug = False # Program Flow # 1. Validate Input # 2. Log in and pull the file list # 3. Parse the Special file # 4. Dump the other files # 5. Pull /hdp/logs file list # 6. Parse the special file # 7. Dump the other files ###################### ## 1. Input Validation ###################### # We need to first make sure that the incoming filter list contains all the fields we need! ######## ## Month if clock.has_key('month'): if valid_month(clock['month']): if debug: print 'Filtering on Month', clock['month'] else: print 'Invalid month detected:', clock['month'] return 'Invalid Month: ' + clock['month'] else: print 'Month option not detected. Must be present' return 'value "month" not set' ############### ## Day of month if clock.has_key('day_of_month'): if valid_day_of_month(clock['day_of_month']): if debug: print 'Filtering on day of month', clock['day_of_month'] else: print 'Invalid day of month provided:', clock['day_of_month'] return 'Invalid day of month provided: ' + clock['day_of_month'] else: print 'no day_of_month value provided!' return 'no day_of_month value provided!' ####### ## Hour if clock.has_key('hour'): if valid_hour(clock['hour']): if debug: print 'Filtering on hour', clock['hour'] else: print 'Invalid hour detected', clock['hour'] return 'Invalid hour detected ' + clock['hour'] ######### ## Minute if clock.has_key('minute'): if valid_minute(clock['minute']): if debug: print 'Filtering on minute', clock['minute'] else: print 'Invalid minute value provided:', clock['minute'] return 'Invalid minute value provided:' + clock['minute'] else: print 'No minute value found!' return 'no minute value found' ################################### ## 2. Log in and pull the file list ################################### ###################### ## Get enable password if debug: print 'retrieving the hidden enable password' password = get_hidden_password() if debug: print 'retrieved the password:', password ################# ## open the shell if debug: print 'opening the hidden enable shell' try: self.open_hidden_shell(password) except: print 'Unable to open the hidden enable shell!' return 'failed to open the hidden shell' if debug: print 'about to run a simple command in the hidden shell' #################### ## Get the file list if debug: print 'going to /hd/logs to read the log files' raw_output = self.hidden_cmd("cd \/hd\/logs") if debug: print 'the return value was' print raw_output if debug: print 'checking the current working directory' raw_output = self.hidden_cmd("pwd") if debug: print 'the return value was' print raw_output if debug: print 'counting the files in the directory' raw_output = self.hidden_cmd('ls | wc') if debug: print 'the raw output was:', raw_output try: raw_file_count = raw_output.split() file_count = int(raw_file_count[0]) if debug: print 'Found', file_count, 'files' if file_count > 1000: print 'There are more then 1000 log files.' print 'The API can not process the files.' print 'Please erase some files and re-try' return 1 except: print 'The value returned from the file count was not a number' print 'Please take a look:', raw_output return 1 #command = 'ls -1 event-log* | tail -n 300' command = 'ls -1 event-log*' if debug: print 'getting the list of log files in /hd/logs' print 'the command will be:', command #raw_output = self.hidden_cmd("ls | grep event-log", 10) raw_output = self.hidden_cmd(command, 10) #raw_output = self.cli_cmd(command) if debug: print 'the return value was' print raw_output ###################################### ## Look for files with the right date file_list = [] if debug: print 'Now parsing file list' print '---------------------' for line in raw_output.splitlines(): if debug: print '-------------------------' print 'raw line:' print line # The raw line looks like this: """ event-log-20100722-114132 """ # We split it on the "-" #if len(line) > 0: # We need to reject most of the filenames # our filename is always 25 characters if len(line) == 25: if debug: print 'found a line we care about' words = line.split('-') # Here is the decoded data we need to extract """ year: 2010 month: 07 day: 22 hour: 11 minute: 41 second: 32 """ date = words[2] year_file = date[:4] raw_month_file = date[4:6] month_file = num_month_to_string(raw_month_file) day_file = date[6:] time = words[3] hour_file = time[:2] minute_file = time[2:4] second_file = time[4:] if debug: print 'detected the following date time:' print 'year:', year_file, 'month:', month_file print 'day:', day_file print 'hour:', hour_file, 'minute:', minute_file, 'second:', second_file # now we must compare the parsed date/time and # compare it with our filter value if clock['month'] == month_file: if debug: print 'Found a file with the right month:', month_file if clock['day_of_month'] <= day_file: if debug: print 'Found a day that is equal to or greater our filter day:', day_file if clock['hour'] <= hour_file: if debug: print 'Found an hour that is equal or greater then filter hour:', hour_file if clock['minute'] <= minute_file: if debug: print 'found our file!' print line print 'Our input value for minute was:', minute_file print 'The minute value we are filtering on is:', clock['minute'] file_list.append(line) # If it's outright larger. Example I'm filtering on things that happened # After 1:10 and I find something that happened at 4:04 # Technically the minute is smaller 10 > 04 but the hour is larger # Therefore I need to keep it. elif clock['hour'] < hour_file: if debug: print 'Found a keeper:', line file_list.append(line) else: file_to_search_inside = line elif clock['day_of_month'] < day_file: if debug: print 'Found a keeper', line file_list.append(line) else: file_to_search_inside = line else: file_to_search_inside = line else: file_to_search_inside = line else: file_to_search_inside = '' if debug: print 'line is:', len(line), 'characters long' if len(line) > 25: print 'Rejecting this file name because it is too long' if len(line) < 25: print 'Rejecting this file name because it is too too short' if debug: print 'Done filtering' , len(raw_output.splitlines()), 'files' print 'Found', len(file_list), 'files to keep' for file in file_list: print file print 'We filtered on: 2010' + str(name_month_to_num(clock['month'])) + clock['day_of_month'] + \ '-' + clock['hour'] + clock['minute'] + '00' print 'The file that may contain some more logs is:', file_to_search_inside if debug: print 'Now we will dump the special file and search for the first entry after our date' # This is the list we return ret_list = [] found_line = False discarded_lines = 0 ############################# ## 3. Search our special file ############################# if len(file_to_search_inside) > 0: # Need to add the line reading to this function as well to speed it up. try: command = 'wc ' + file_to_search_inside except: print 'no files found to read. There is a bug in pull_internal_logs in issu.py!' sys.exit(1) try: raw_output = self.hidden_cmd(command, 20) except: print 'Failure while getting the line count of file', file return 'Failing to get the line count of file: ' + file # Example raw_output """ 387 4756 31900 event-log-20100723-140131 """ words = raw_output.split() if debug: print 'The raw output was:' print raw_output print 'The file:', file_to_search_inside, 'Has', words[0], 'lines of text' str_line_count = words[0] try: line_count = int(str_line_count) except: print 'We got a non integer for the line count!', str_line_count return 'invalid line count ' + str_line_count command = 'cat ' + file_to_search_inside if debug: print 'Command will be:', command print 'Sending command.' self.ses.sendline(command) # Begin reading the line of the file reading_input = True local_lines = [] # The first line returned is the command executed so we need to increment by 1 while reading_input: if debug: print 'Lines left:', line_count try: line = self.ses.readline() except: print 'unable to read the line!' if '/bin/sh: cannot fork - try again' in line: print 'Shell died. SSX probably restarting' return 'Lost Shell. SSX probably rebooting' if command in line: if debug: print 'we got the command line back!' else: if found_line: ret_list.append(line) else: if len(line) > 0: if debug: print("------------------------------------") print("The raw line is:") print(line) # Cut the line into words words = line.split() # raw line looks like """ Jul 23 01:50:20 [1] INFO Clock-TZSET: System timezone set to: PDT (Day Light Saving Not set) """ ############################## ## Parse the month date header try: month_log = words[0] if not (valid_month(month_log)): if debug: print 'Invalid month detected' raise day_of_month_log = words[1] if not (valid_day_of_month(day_of_month_log)): if debug: print 'Invalid day of month detected' raise raw_time_log = words[2] if debug: print 'parsing raw_time:', raw_time_log long_time_log = raw_time_log.split(":") if debug: print 'the long_time_log contains:', long_time_log if not (len(long_time_log) == 3): if debug: print 'detected invalid time format:' print long_time_log raise hour_log = long_time_log[0] if not (valid_hour(hour_log)): if debug: print 'Invalid hour detected' raise minute_log = long_time_log[1] if not (valid_minute(minute_log)): if debug: print 'Invalid minute detected' raise second_log = long_time_log[2] if not (valid_second(second_log)): if debug: print 'invalid second detected' raise # We don't care about this stuff at this time but it could be # parsed in the future. logs_per_second_log = words[3] log_type = words[4] log_deamon = words[5] log_msg_type = words[6] log_message = words[7:] except: if debug: print 'Unable to parse this line:' print line print 'It is probably part of the previous line' # Yep it's broken somehow! Either # 1. It's missing it's ":" "special case" # 2. It is so long it linewrapped. broken_line = True # We store the fragment in escrow escrow_line = line #ret_list.append(line) if debug: print 'Succesfully parsed the date/time header' ##################################### ## Filter the line based on date time if debug: print("The month is: %s" % month_log) print("looking for a month greater then: %s" % clock['month']) if clock['month'] == month_log: # Bug here it won't pass the end of the month to the next month if debug: print("The day is: %s" % day_of_month_log) print("Looking for a day greater then: %s" % clock['day_of_month']) if clock['day_of_month'] <= day_of_month_log: if debug: print("The hour is: %s" % hour_log) print("Looking for an hour greater then: %s" % clock['hour']) if clock['hour'] <= hour_log: if debug: print("The minute is: %s" % minute_log) print("Looking for a minute greater then: %s" % clock['minute']) if clock['minute'] <= minute_log: # We save the line ret_list.append(line) found_line = True if debug: print 'Found the beginning line. Skipping filtering other lines' elif clock['hour'] < hour_log: found_line = True if debug: print 'Found the beginning line. Skipping filtering other lines' ret_list.append(line) else: if debug: print 'The following line was not saved becuase it is before the minute we want' print line discarded_lines += 1 elif clock['day_of_month'] < day_of_month_log: found_line = True if debug: print 'Found the beginning line. Skipping filtering other lines' ret_list.append(line) else: if debug: print 'The following line was not saved becuase it is before the hour we want' print line discarded_lines += 1 elif clock['month'] < month_log: found_line = True if debug: print 'Found the beginning line. Skipping filtering other lines' ret_list.append(line) else: if debug: print 'The following line was not saved becuase it is before the day of month we want' print line discarded_lines += 1 else: if debug: print 'The following line was not saved becuase it is before the month we want' print line discarded_lines += 1 # Decement the line count line_count = line_count - 1 # Break when run out of lines to read if line_count == 0: if debug: 'At the end of the counted lines' reading_input = False ################### ## 4. Dump the rest ################### for file in file_list: if debug: print '----------------------------' print 'Now reading file:', file print '----------------------------' # At this point simply cat-ing the file and reading the output we try to filter every # character for the '#' prompt. This causes a huge delay and won't work for us. # Instead we will use 'wc' to count the number of lines we need to read until the next prompt command = 'wc ' + file try: raw_output = self.hidden_cmd(command, 20) except: print 'Failure while getting the line count of file', file break # Example raw_output """ 387 4756 31900 event-log-20100723-140131 """ words = raw_output.split() if debug: print 'The raw output was:' print raw_output print 'The file:', file, 'Has', words[0], 'lines of text' str_line_count = words[0] try: line_count = int(str_line_count) except: print 'We got a non integer for the line count!', str_line_count return 'invalid line count ' + str_line_count command = 'cat ' + file if debug: print 'Command will be:', command print 'Sending command.' self.ses.sendline(command) reading_input = True local_lines = [] while reading_input: if debug: print 'Lines left:', line_count try: line = self.ses.readline() except: print 'unable to read the line!' if debug: print 'line:' print line if command in line: if debug: print 'we got the command line back!' reading_input = False else: if debug: print 'Saving this line' local_lines.append(line) # Decrement the line counter line_count = line_count - 1 # Break when run out of lines to read if line_count == 0: if debug: 'At the end of the counted lines' reading_input = False if line_count == 0: if debug: print 'done dumping lines' reading_input == False if debug: print 'We caught:', len(local_lines), 'lines of output from file:', file for line in local_lines: ret_list.append(line) if debug: print 'The complete log is now:', len(ret_list) print '000000000000000000000000000000' print 'Completed parsing the /hd/logs' print 'now parsing /hdp/logs' print '000000000000000000000000000000' ret_list.append("end of /hd/logs") ret_list.append("INTERNAL LOGS BEGIN") ####################### ## 5. Get the file list ####################### raw_output = self.hidden_cmd("cd \/hdp\/logs") if debug: print 'the return value was' print raw_output raw_output = self.hidden_cmd("pwd") if debug: print 'the return value was' print raw_output raw_output = self.hidden_cmd("ls | grep event-log") if debug: print 'the return value was' print raw_output ###################################### ## Look for files with the right date file_list = [] if debug: print 'Now parsing file list' print '---------------------' for line in raw_output.splitlines(): if debug: print '-------------------------' print 'raw line:' print line # The raw line looks like this: """ event-log-20100722-114132 """ # We split it on the "-" if len(line) > 0: if debug: print 'found a line we care about' words = line.split('-') # Here is the decoded data we need to extract """ year: 2010 month: 07 day: 22 hour: 11 minute: 41 second: 32 """ date = words[2] year_file = date[:4] raw_month_file = date[4:6] month_file = num_month_to_string(raw_month_file) day_file = date[6:] time = words[3] hour_file = time[:2] minute_file = time[2:4] second_file = time[4:] if debug: print 'detected the following date time:' print 'year:', year_file, 'month:', month_file print 'day:', day_file print 'hour:', hour_file, 'minute:', minute_file, 'second:', second_file # now we must compare the parsed date/time and # compare it with our filter value if clock['month'] == month_file: if debug: print 'Found a file with the right month:', month_file if clock['day_of_month'] <= day_file: if debug: print 'Found a day that is equal to or greater our filter day:', day_file if clock['hour'] <= hour_file: if debug: print 'Found an hour that is equal or greater then filter hour:', hour_file if clock['minute'] <= minute_file: if debug: print 'found our file!' print line print 'Our input value for minute was:', minute_file print 'The minute value we are filtering on is:', clock['minute'] file_list.append(line) # If it's outright larger. Example I'm filtering on things that happened # After 1:10 and I find something that happened at 4:04 # Technically the minute is smaller 10 > 04 but the hour is larger # Therefore I need to keep it. elif clock['hour'] < hour_file: if debug: print 'Found a keeper:', line file_list.append(line) else: file_to_search_inside = line elif clock['day_of_month'] < day_file: if debug: print 'Found a keeper', line file_list.append(line) else: file_to_search_inside = line else: file_to_search_inside = line else: file_to_search_inside = line print 'Done filtering' , len(raw_output.splitlines()), 'files' print 'Found', len(file_list), 'files to keep' for file in file_list: print file print 'We filtered on: 2010' + clock['month'] + clock['day_of_month'] + \ '-' + clock['hour'] + clock['minute'] + '00' print 'The file that may contain some more logs is:', file_to_search_inside if debug: print 'Now we will dump the special file and search for the first entry after our date' # This is the list we return ret_list = [] found_line = False discarded_lines = 0 ############################# ## 6. Search our special file ############################# # Need to add the line reading to this function as well to speed it up. command = 'wc ' + file_to_search_inside try: raw_output = self.hidden_cmd(command, 20) except: print 'Failure while getting the line count of file', file return 'Failing to get the line count of file: ' + file # Example raw_output """ 387 4756 31900 event-log-20100723-140131 """ words = raw_output.split() if debug: print 'The raw output was:' print raw_output print 'The file:', file_to_search_inside, 'Has', words[0], 'lines of text' str_line_count = words[0] try: line_count = int(str_line_count) except: print 'We got a non integer for the line count!', str_line_count return 'invalid line count ' + str_line_count command = 'cat ' + file_to_search_inside if debug: print 'Command will be:', command print 'Sending command.' self.ses.sendline(command) # Begin reading the line of the file reading_input = True local_lines = [] # The first line returned is the command executed so we need to increment by 1 while reading_input: if debug: print 'Lines left:', line_count try: line = self.ses.readline() except: print 'unable to read the line!' if command in line: if debug: print 'we got the command line back!' else: if found_line: ret_list.append(line) else: if len(line) > 0: if debug: print("------------------------------------") print("The raw line is:") print(line) # Cut the line into words words = line.split() # raw line looks like """ Jul 27 20:17:08 [2] INT HaMgr-ACT_CONNECTION_AVAILABLE: active ha-mgr connection available """ ############################## ## Parse the month date header try: month_log = words[0] if not (valid_month(month_log)): if debug: print 'Invalid month detected' raise day_of_month_log = words[1] if not (valid_day_of_month(day_of_month_log)): if debug: print 'Invalid day of month detected' raise raw_time_log = words[2] if debug: print 'parsing raw_time:', raw_time_log long_time_log = raw_time_log.split(":") if debug: print 'the long_time_log contains:', long_time_log if not (len(long_time_log) == 3): if debug: print 'detected invalid time format:' print long_time_log raise hour_log = long_time_log[0] if not (valid_hour(hour_log)): if debug: print 'Invalid hour detected' raise minute_log = long_time_log[1] if not (valid_minute(minute_log)): if debug: print 'Invalid minute detected' raise second_log = long_time_log[2] if not (valid_second(second_log)): if debug: print 'invalid second detected' raise # We don't care about this stuff at this time but it could be # parsed in the future. logs_per_second_log = words[3] log_type = words[4] log_deamon = words[5] log_msg_type = words[6] log_message = words[7:] except: if debug: print 'Unable to parse this line:' print line print 'It is probably part of the previous line' # Yep it's broken somehow! Either # 1. It's missing it's ":" "special case" # 2. It is so long it linewrapped. broken_line = True # We store the fragment in escrow escrow_line = line #ret_list.append(line) if debug: print 'Succesfully parsed the date/time header' ##################################### ## Filter the line based on date time if debug: print("The month is: %s" % month_log) print("looking for a month greater then: %s" % clock['month']) if clock['month'] == month_log: # Bug here it won't pass the end of the month to the next month if debug: print("The day is: %s" % day_of_month_log) print("Looking for a day greater then: %s" % clock['day_of_month']) if clock['day_of_month'] <= day_of_month_log: if debug: print("The hour is: %s" % hour_log) print("Looking for an hour greater then: %s" % clock['hour']) if clock['hour'] <= hour_log: if debug: print("The minute is: %s" % minute_log) print("Looking for a minute greater then: %s" % clock['minute']) if clock['minute'] <= minute_log: # We save the line ret_list.append(line) found_line = True if debug: print 'Found the beginning line. Skipping filtering other lines' elif clock['hour'] < hour_log: found_line = True if debug: print 'Found the beginning line. Skipping filtering other lines' ret_list.append(line) else: if debug: print 'The following line was not saved becuase it is before the minute we want' print line discarded_lines += 1 elif clock['day_of_month'] < day_of_month_log: found_line = True if debug: print 'Found the beginning line. Skipping filtering other lines' ret_list.append(line) else: if debug: print 'The following line was not saved becuase it is before the hour we want' print line discarded_lines += 1 elif clock['month'] < month_log: found_line = True if debug: print 'Found the beginning line. Skipping filtering other lines' ret_list.append(line) else: if debug: print 'The following line was not saved becuase it is before the day of month we want' print line discarded_lines += 1 else: if debug: print 'The following line was not saved becuase it is before the month we want' print line discarded_lines += 1 # Decement the line count line_count = line_count - 1 # Break when run out of lines to read if line_count == 0: if debug: 'At the end of the counted lines' reading_input = False ################### ## 7. Dump the rest ################### for file in file_list: if debug: print '----------------------------' print 'Now reading file:', file print '----------------------------' # At this point simply cat-ing the file and reading the output we try to filter every # character for the '#' prompt. This causes a huge delay and won't work for us. # Instead we will use 'wc' to count the number of lines we need to read until the next prompt command = 'wc ' + file try: raw_output = self.hidden_cmd(command, 20) except: print 'Failure while getting the line count of file', file break # Example raw_output """ 387 4756 31900 event-log-20100723-140131 """ words = raw_output.split() if debug: print 'The raw output was:' print raw_output print 'The file:', file, 'Has', words[0], 'lines of text' str_line_count = words[0] try: line_count = int(str_line_count) except: print 'We got a non integer for the line count!', str_line_count return 'invalid line count ' + str_line_count command = 'cat ' + file if debug: print 'Command will be:', command print 'Sending command.' self.ses.sendline(command) reading_input = True local_lines = [] while reading_input: if debug: print 'Lines left:', line_count try: line = self.ses.readline() except: print 'unable to read the line!' if debug: print 'line:' print line if command in line: if debug: print 'we got the command line back!' else: if debug: print 'Saving this line' local_lines.append(line) # Decrement the line counter line_count = line_count - 1 # Break when run out of lines to read if line_count == 0: if debug: 'At the end of the counted lines' reading_input = False if debug: print 'We caught:', len(local_lines), 'lines of output from file:', file for line in local_lines: ret_list.append(line) if debug: print 'The complete log is now:', len(ret_list) ret_list.append("INTERNAL LOGS END") ########### ## Complete ########### if debug: print 'closing the shell' self.close_hidden_shell() if debug: print 'done with issu.py pull_internal_logs' return ret_list def pull_corefiles(self, clock, username='regress', user_password='gleep7', host='10.1.1.101'): """ retrieves the core files from the SSX and drops them in your CWD Files are renamed with the YYYY-MM-DD clock = list of split time username = username to log into the linux system with. Defaults to "regress" user_password = password for above username. Defaults to "gleep7" host = linux host to sftp the files to. Defaults to "10.1.1.101" which is qa-radxpm-1 """ # Program Flow # 1. Validate Input # 2. Get file list based on Date # 3. SFTP the files off # 4. Copy the files from /home/regress to /home/USERNAME ###################### ## 1. Input Validation ###################### # We need to first make sure that the incoming filter list contains all the fields we need! ######## ## Month if clock.has_key('month'): if valid_month(clock['month']): if debug: print 'Filtering on Month', clock['month'] else: print 'Invalid month detected:', clock['month'] return 'Invalid Month: ' + clock['month'] else: print 'Month option not detected. Must be present' return 'value "month" not set' ############### ## Day of month if clock.has_key('day_of_month'): if valid_day_of_month(clock['day_of_month']): if debug: print 'Filtering on day of month', clock['day_of_month'] else: print 'Invalid day of month provided:', clock['day_of_month'] return 'Invalid day of month provided: ' + clock['day_of_month'] else: print 'no day_of_month value provided!' return 'no day_of_month value provided!' ####### ## Hour if clock.has_key('hour'): if valid_hour(clock['hour']): if debug: print 'Filtering on hour', clock['hour'] else: print 'Invalid hour detected', clock['hour'] return 'Invalid hour detected ' + clock['hour'] ######### ## Minute if clock.has_key('minute'): if valid_minute(clock['minute']): if debug: print 'Filtering on minute', clock['minute'] else: print 'Invalid minute value provided:', clock['minute'] return 'Invalid minute value provided:' + clock['minute'] else: print 'No minute value found!' return 'no minute value found' ################################### ## 2. Log in and pull the file list ################################### ###################### ## Get enable password if debug: print 'retrieving the hidden enable password' password = get_hidden_password() if debug: print 'retrieved the password:', password ################# ## open the shell if debug: print 'opening the hidden enable shell' try: self.open_hidden_shell(password) except: print 'Unable to open the hidden enable shell!' return 'failed to open the hidden shell' if debug: print 'about to run a simple command in the hidden shell' #################### ## Get the file list dump_dirs = ['slot0','slot1','slot2','slot3','slot4'] file_list = [] for dir in dump_dirs: command = 'cd \/hd\/dump\/' + dir if debug: print 'the command will be:', command raw_output = self.hidden_cmd(command) if debug: print 'the return value was' print raw_output command = 'ls -l | grep core.gz' if debug: print 'the command will be:', command raw_output = self.hidden_cmd(command) if debug: print 'the return value was' print raw_output # the raw line looks like this: """ -rw-r--r-- 1 root root 2807430 Jul 26 16:53 dfn.1.core.gz """ discarded_lines = 0 raw_lines = raw_output.splitlines() for line in raw_lines[2:]: if debug: print 'parsing:' print line words = line.split() month_log = words[5] day_of_month_log = words[6] raw_time_log = words[7] split_time_log = raw_time_log.split(":") hour_log = split_time_log[0] minute_log = split_time_log[1] filename_log = words[8] if debug: print filename_log, 'Month:', month_log, 'day', day_of_month_log, 'hour:', hour_log, 'Minute:', minute_log full_path = dir + '/' + filename_log if debug: print 'That file lives:', full_path ##################################### ## Filter the line based on date time if debug: print("The month is: %s" % month_log) print("looking for a month greater then: %s" % clock['month']) if clock['month'] == month_log: # Bug here it won't pass the end of the month to the next month if debug: print("The day is: %s" % day_of_month_log) print("Looking for a day greater then: %s" % clock['day_of_month']) if clock['day_of_month'] <= day_of_month_log: if debug: print("The hour is: %s" % hour_log) print("Looking for an hour greater then: %s" % clock['hour']) if clock['hour'] <= hour_log: if debug: print("The minute is: %s" % minute_log) print("Looking for a minute greater then: %s" % clock['minute']) if clock['minute'] <= minute_log: # We save the line file_list.append(full_path) if debug: print 'Found a file:', filename_log elif clock['hour'] < hour_log: if debug: print 'Found a file:', filename_log file_list.append(full_path) else: if debug: print 'The following file was not saved becuase it is before the minute we want' print line discarded_lines += 1 elif clock['day_of_month'] < day_of_month_log: if debug: print 'Found a file:', filename_log file_list.append(full_path) else: if debug: print 'The following file was not saved becuase it is before the hour we want' print full_path elif clock['month'] < month_log: if debug: print 'Found a file:', filename_log file_list.append(full_path) else: if debug: print 'The following file was not saved becuase it is before the day of month we want' print filename_log else: if debug: print 'The following file was not saved becuase it is before the month we want' print filename_log print 'The following', len(file_list), 'core files will be coppied to the testing directory:' for file in file_list: print file self.close_hidden_shell() ################# ## SFTP files off unsaved_files = [] linux_file_list = [] for file in file_list: file_parts = file.split('/') slot = file_parts[-2] filename = file_parts[-1] filename_parts = filename.split(".") if len(filename_parts) == 3: filename_head = filename_parts[0] elif len(filename_parts) == 4: filename_head = filename_parts[0] + '-' + filename_parts[1] else: print 'This filename has too many "." in it!' print filename_parts filename_head = filename_parts[0] + '-' + filename_parts[1] extension = filename_parts[-2] + '.' + filename_parts[-1] month = name_month_to_num(clock['month']) if debug: print 'file:', file, 'filename:', filename print 'in slot:', slot if not clock.has_key('year'): print 'No year detected. Defaulting to 2010' clock['year'] = '2010' file_name_with_timestamp = filename_head + '-' + str(clock['year']) + str(month) + \ str(clock['day_of_month']) + str(clock['hour']) + str(clock['minute']) + '.' + str(extension) if debug: print 'the full filename will be:', file_name_with_timestamp command = 'copy /hd/dump/' + file + ' sftp://' + username + '@' + host + ':/home/' + username \ + '/' + file_name_with_timestamp if debug: print 'The command will be:' print command print 'Copying the core file:', filename, 'off the system.' #self.ftppasswd(command, user_password) self.ftppasswd(command, user_password, 60) print 'File copied succesfully' linux_file_list.append(file_name_with_timestamp) """ if len(unsaved_files) > 0: print 'There were:', len(file_list), 'files to copy.', len(unsaved_files), 'files were not coppied' #print 'These files were not coppied off the system:' #for file in unsaved_files: # print file """ print 'Completed copying Core Files off' current_dir = os.getcwd() if debug: print 'script is being run from:', current_dir for file in linux_file_list: source_path = '/home/' + username + '/' full_filename = source_path + file dest_filename = current_dir + '/' + file print '------------------------' print 'about to move:', full_filename, 'to:', dest_filename shutil.copyfile(full_filename, dest_filename) print 'file moved succesfully.' print 'All done moving the files.' return 0 def filter_logs(self, clock): """ Pulls information available from "show log". Then logs in and pulls the internal log files in /hd/logs and /hdp/logs It also pulls any core files to the scripts CWD """ debug = False ################### ## Input Validation # We need to first make sure that the incoming filter list contains all the fields we need! if debug: print 'Validating the Date/Time' ######## ## Month if clock.has_key('month'): if valid_month(clock['month']): if debug: print 'Filtering on Month', clock['month'] else: print 'Invalid month detected:', clock['month'] return 'Invalid Month: ' + clock['month'] else: print 'Month option not detected. Must be present' return 'value "month" not set' ############### ## Day of month if clock.has_key('day_of_month'): if valid_day_of_month(clock['day_of_month']): if debug: print 'Filtering on day of month', clock['day_of_month'] if clock['day_of_month'][0] == '0': # This line may require a space! clock['day_of_month'] = clock['day_of_month'].lstrip('0') if debug: print 'the stripped hour now looks like', clock['day_of_month'] else: print 'Invalid day of month provided:', clock['day_of_month'] return 'Invalid day of month provided: ' + clock['day_of_month'] else: print 'no day_of_month value provided!' return 'no day_of_month value provided!' ####### ## Hour if clock.has_key('hour'): if valid_hour(clock['hour']): if debug: print 'Filtering on hour', clock['hour'] print 'stripping any trailing zeros in the time' else: print 'Invalid hour detected', clock['hour'] return 'Invalid hour detected ' + clock['hour'] ######### ## Minute if clock.has_key('minute'): if valid_minute(clock['minute']): if debug: print 'Filtering on minute', clock['minute'] else: print 'Invalid minute value provided:', clock['minute'] return 'Invalid minute value provided:' + clock['minute'] else: print 'No minute value found!' return 'no minute value found' ret_logs = [] print 'Pulling information using "show log"' syslog = pull_syslog(self, clock) print 'Completed pulling information.' ret_logs.append(syslog) print 'Pulling the internal logging information.' internal_logs = pull_internal_logs(self, clock) print 'Complete pulling the internal log informaiton' ret_logs.append(internal_logs) print 'Retrieving any core files.' retr = pull_corefiles(self, clock) print 'Completed pulling core files' print 'Completed pulling log information' return ret_logs def generate_ixia_dict(source_file, number_of_streams, stream_dict): """ This method takes the variables from the topo.py configuration file and generates nested dictionaries that are required for the rewrite_ixia_config method. This method is written to shorten the manual labor of making configurations with large number of streams (10 or more) and is not required if you want to write the ixia_dictionary by hand. Variables: 'Chassis IP Address' - Topo 'Username' - Topo 'Source File' 'Card Number' - Topo 'Port Number' - Topo 'Number of Streams' # Per stream 'Stream Name' 'Source IP Address' 'Destination IP Address' 'Destination MAC Address' """ # Example values (working good) # with only 1 stream """ ixia_dict = { \ 'Chassis IP Address':'10.4.2.30', \ 'Username':'jalfrey', \ 'Source File':'JF-FUN-009-1.tcl', \ 'Card Number 3':{ \ 'Card Number':3, \ 'Port Number 3':{ \ 'Port Number':3, \ 'Source MAC Address':'00 de bb 00 00 01', \ 'Destination MAC Address':'00 DE BB 00 00 02', \ 'Stream ID 1':{ \ 'Stream ID':1, \ 'Stream Name':'Session_payload', \ 'Source IP Address':'10.11.12.1', \ 'Destination IP Address':'10.11.20.1', \ 'Destination MAC Address':'00 DE BB 00 00 02' } } } } """ # Topo to ixia_dict variable mapping """ 'Chassis IP Address' = topo.ixia['ip_addr'] 'Username' = topo.ixia['username'] 'Source File' = script_var['test_name'] - appears in jf_config.py 'Card Number' = topo.ixia['CardID'] 'Port Number' = topo.ixia['TxportID'] 'Number of Streams' = script_var['test_name'] - # Per stream 'Stream Name' = script_var['test_name'] - 'Stream ID' = fed into script 'Source IP Address' = fed into script 'Destination IP Address' = fed into script 'Destination MAC Address' = fed into script """ def rewrite_ixia_config(ixia_dict): """ This function opens an IXIA.tcl script and rewrites the IP Address and other values to make the script send traffic to any DUT All values MUST be set in this dictionary or the file can not be rewritten correctly! After this method completes it will write an ouptut file or if set to "none" it will return the whole configuration as a very long string which can then be split and fed into the IXIA via CLI ixia_dict{ Chassis IP Address:10.4.2.30 # The IP of the IXIA itself Username:jalfrey # Username that "owns" the ports that will send traffic Source File # This is the source file it is read from # This needs to either be a full path or relative to current directory path Output File # This can be set to "none" and the method will return the whole configuration # Or if it is set it will write the file out to disk Card Number_X: # If there are multiple cards then there will be multiple dictionaries. # For my configuration I use card 3 to the dictionary will be called # "Card Number 3" Dictionary { Card Number # Card which port lives on. Same information contained in the dictionary # name but just as the number "3" Port Number X: # Port to be configured. There will be one key per port Dictionary { Port Number # This is the port number on the IXIA itself (physical port) Source MAC Address # Can be set or left "default" which will leave the config unchanged or null '' Destination MAC Address # This is the MAC of what the IXIA is directly connected to # In my case it's a Cisco Router Stream ID X: # This is the Stream ID. There is one ID per stream configured Dictionary: { Stream ID:1 # Stream numeric ID. Matches "Stream ID X" value X Stream Name # Optional. If value is Null nothing will be set # whatever was there will be left there Source IP Address # Source on IXIA side Destination IP Address # Where the traffic should go. In my case that's the SSX (DUT) Destination MAC Address # This should be the same as the "Destination MAC Address" found above # But clearly it can be set differently but I'm not sure why # Maybe for testing through a Hub? } } } """ debug = False # Configuration will overwrite this value generate_output_file = False ############################### # Variable Validation Section # ############################### if len(ixia_dict) > 0: top_keys = ixia_dict.keys() if debug: print '------------------------------------' print 'The top keys extracted were:' for key in top_keys: print key, ':', ixia_dict[key] print '------------------------------------' # IP Address if ixia_dict.has_key('Chassis IP Address'): if validIP(ixia_dict['Chassis IP Address']): top_keys.remove('Chassis IP Address') if debug: print 'Chassis IP is valid' else: error_message = 'Invalid IP address for the chassis: ' + ixia_dict.has_key('Chassis IP Address') return error_message # Username if ixia_dict.has_key('Username'): if (len(ixia_dict['Username']) > 0): top_keys.remove('Username') if debug: print 'Username is valid' else: error_message = 'No Username value provided' return error_message # Source File if ixia_dict.has_key('Source File'): if (ixia_dict['Source File'] == ''): return 'No source file value set' if os.path.exists(ixia_dict['Source File']): top_keys.remove('Source File') if debug: print 'Source filename is valid' else: return 'unable to locate the source file!' # Output File # IF the length is zero then no file is generated # if it is set to "none" then no file is generated # Otherwise whatever the filename is it's generated with that # Since the filename could be mostly anything we don't validate it if ixia_dict.has_key('Output File'): # Here we change the case to lowercase so that we can compare the string once # Instead of testing to see if it's formatted like 'None', 'NONE', etc. output_filename = ixia_dict['Output File'].lower() if output_filename == 'none': generate_output_file = False if debug: print 'No output file will be generate' else: generate_output_file = True if debug: print 'Output file will be generated' top_keys.remove('Output File') if debug: print 'Output filename is valid' if debug: print 'At this point the top_keys should only contain card numbers' print top_keys # At this point the top_keys dictionary should only contain entries # of card numbers. like "Card Number 3" for card_number in top_keys: # Now we use this "key" to retrieve all the ports listed for that card # Then we verify the port list is valid port_list = ixia_dict[card_number].keys() if debug: print 'Now parsing the following items in the port_list' print port_list for port_number in port_list: if 'Card Number' in port_number: if not (int(ixia_dict[card_number][port_number]) in range(1,15)): error_message = 'Card Number: ' + ixia_dict[card_number][port_number] + ' Outside expected range of: 1-14' return error_message if 'Port Number' in port_number: if debug: print '000000000' print 'port_number = ', port_number print 'The port number being tested is:', ixia_dict[card_number][port_number]['Port Number'] # The range function is odd. If you say 1,13 you get 13 numbers # starting at 1 not zero and it ends at 12 instead of 13. if not (int(ixia_dict[card_number][port_number]['Port Number']) in range(1,14)): error_message = 'Port number: ' + port_number + ' on Card: ' \ + card_number + ' is invalide. Expected to be in the range 1 - 13' return error_message else: if debug: print 'the following item wil not be parsed:' print port_number else: return 'No variables set. Can not proceed!' ############## # Open Files # ############## try: input_file = open(ixia_dict['Source File'], 'r') except: return 'Unable to open the Soucre File' if generate_output_file: try: output_file = open(ixia_dict['Output File'], 'w') except: return 'Unable to open the ouptut file!' ######################## # Parse the input_file # ######################## # Method: # # 1. Read the file line by line # 2. Look for section headers # a. If the line matches one of the section headers we note that down # b. The section header itself may need re-writing # c. Increment the section header counter # 3. Inside the sections search for specific lines # 4. Read each line and write it to the output file # 5. When special lines are found re-write them and write to output file next_header = '# This Script has been generated by Ixia ScriptGen' next_line = 'default_nothing' modified_line = 'default_nothing' section_index = 0 line_index = 0 line_count = 0 break_after = 345 run_to_completion = True raw_keys = ixia_dict.keys() card_number_list = [] port_number_list = [] for key in raw_keys: if 'Card Number' in key: card_number_list.append(ixia_dict[key]['Card Number']) if debug: print 'We are expecting to configure the following cards:', card_number_list if debug: print 'Now reading the input file line by line looking for the section headers' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' for input_line in input_file: line_count = line_count + 1 if debug and (line_count > break_after) and not run_to_completion: print 'Breaking here for debuging' return 0 if debug: print '******* Line Number:', line_count, ' ********************' print 'have: "', input_line.strip(), '"' print 'want Header:', next_header print ' want Line: "', next_line, '"' print '******* Line Number:', line_count, ' ********************' if next_header in input_line: if debug: print 'valid header:"', next_header, '"' # This will give us a numeric index telling us what section we're in section_index = section_index + 1 if section_index == 1: next_line = 'if {[ixConnectToTclServer' if debug: print 'Found first section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(input_line) elif section_index == 2: modified_line = '######### Chassis list - {' + ixia_dict['Chassis IP Address'] + '} #########\n' next_line = 'ixConnectToChassis {' + local_chassis_ip_address + '}' if debug: print 'Found second section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(modified_line) elif section_index == 3: modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] + ' #########\n' next_line = 'chassis get "' + local_chassis_ip_address + '"' if debug: print 'Found second section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(modified_line) elif section_index == 4: next_line = 'set card ' if debug: print 'Found second section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(input_line) elif section_index == 5: long_card_number = 'Card Number ' + str(card_number_list[0]) raw_port_list = ixia_dict[long_card_number].keys() port_name_list = [] for key in raw_port_list: if 'Port' in key: port_name_list.append(key) if debug: print 'building the port_number_list from the port_name_list:' print port_name_list print 'ixia_dict[long_card_number]:', ixia_dict[long_card_number] for port in port_name_list: if debug: print 'port:', port print 'long_card_number:', long_card_number port_number_list.append(ixia_dict[long_card_number][port]['Port Number']) if debug: print 'port_number_list:', port_number_list if debug: print 'The ports that will be configured for card:', long_card_number, 'are:', port_number_list # Example line """ ######### Chassis-10.4.2.30 Card-3 Port-3 ######### """ words = input_line.split() raw_port_number = words[3].split('-') local_port_number = raw_port_number[1] modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] \ + ' Card-' + str(card_number_list[0]) + ' Port-' + str(port_number_list[0]) + ' #########\n' if generate_output_file: output_file.write(input_line) next_line = 'set port ' + str(local_port_number) elif section_index == 6: if generate_output_file: output_file.write(input_line) # This is a strange one. This header is identical to a header we have already seen in section 5 # but if we executed the same code it would mess stuff up so we just look for it to step # over it. next_header = '######### Chassis-' + local_chassis_ip_address + ' Card-' + str(local_card_number) elif section_index == 7: modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] + \ ' Card-' + str(card_number_list[0]) + ' Port-' + str(port_number_list[0]) + ' #########\n' next_line = 'chassis get "' + local_chassis_ip_address + '"' if generate_output_file: output_file.write(input_line) else: return 'Failure while parsing the section index' # line we're looking for elif (next_line in input_line) and (len(input_line) > 2): if debug: print 'valid line: "', input_line.strip(), '"' words = input_line.split() if debug: print 'The line was broken into these words:' print words if section_index == 1: if line_index == 0: raw_target_word = words[2].split(']') local_chassis_ip_address = raw_target_word[0] if debug: print 'The Chassis IP Address found in the original configuraiton file was:', local_chassis_ip_address next_line = 'ixPuts "Error connecting to Tcl Server ' + local_chassis_ip_address + ' "' # now we need to rewrite the line and write it to the log file modified_line = ' if {[ixConnectToTclServer ' + ixia_dict['Chassis IP Address'] + ']} {\n' line_index = line_index + 1 elif line_index == 1: modified_line = ' ixPuts "Error connecting to Tcl Server ' + ixia_dict['Chassis IP Address'] + ' "\n' # we may need to empy the next line variable because we are looking for a section header #next_line = '' next_header = '######### Chassis list - {' + local_chassis_ip_address + '} #########' line_index = line_index + 1 # reset the line index because we are going to the next section line_index = 0 else: print 'line_index out of range at value:', line_index return 'Error in automation! bad line index in section 1' elif section_index == 2: if line_index == 0: modified_line = 'ixConnectToChassis {' + ixia_dict['Chassis IP Address'] + '}\n' next_line = 'set owner "' line_index = line_index + 1 elif line_index == 1: modified_line = 'set owner "' + ixia_dict['Username'] + '"\n' # going to the next section next_header = '######### Chassis-' + local_chassis_ip_address + ' #########' line_index = 0 elif section_index == 3: if line_index == 0: modified_line = 'chassis get "' + ixia_dict['Chassis IP Address'] + '"\n' # going to next section next_header = '######### Card Type : 10/100/1000 LSM XMVR16 ############' line_index = 0 elif section_index == 4: if line_index == 0: # There could be multiple cards. It's hard to say if there should be more then one # variable for the card number. I don't think it's neccarry because the system configures # the cards sequentially so it should not be overwritten. local_card_number = words[2] # We take the first element from the card number list. # After we're done using that information we will delete it from the list # and then we can use element zero again. (like a stack) modified_line = 'set card ' + str(card_number_list[0]) + '\n' #next_header = '######### Chassis-' + local_chassis_ip_address + ' ' + local_card_number next_header = '######### Chassis-' + local_chassis_ip_address + ' Card-' + local_card_number line_index = 0 elif section_index == 5: if line_index == 0: modified_line = 'set port ' + str(port_number_list[0]) + '\n' line_index = line_index + 1 next_line = 'port config -MacAddress "' elif line_index == 1: long_port_number = 'Port Number ' + str(port_number_list[0]) # The source MAC address "can" be configured if you like # But this does lead to more complexity about "what" to configure it to try: modified_line = next_line + ixia_dict[long_card_number][long_port_number]['Source MAC Address'] + '"\n' except: modified_line = input_line line_index = 0 next_header = '######### Generating streams for all the ports from above #########' else: error_message = 'line_index out of range 0-1 for section_index 5!' return error_message elif section_index == 6: error_message = 'Failure. Found a line in section six not expected.' return error_message elif section_index == 7: if line_index == 0: modified_line = 'chassis get "' + ixia_dict['Chassis IP Address'] + '"\n' line_index = line_index + 1 #next_line = 'set card ' + local_card_number[0] next_line = 'set card' elif line_index == 1: modified_line = 'set card ' + str(card_number_list[0]) + '\n' line_index = line_index + 1 next_line = 'set port ' + local_port_number elif line_index == 2: modified_line = 'set port ' + str(port_number_list[0]) + '\n' line_index = line_index + 1 """ if debug: print 'Looking for the stream ID itself in this dictionary:' print ixia_dict print 'Using these two keys to find it:' print long_card_number, long_port_number """ raw_stream_id = ixia_dict[long_card_number][long_port_number].keys() """ if debug: print 'Sorting through this list of keys:' print raw_stream_id """ stream_id_list = [] for key in raw_stream_id: if 'Stream ID' in key: """ if debug: print 'Found a Stream ID:', key """ stream_id_list.append(key) """ elif debug: print 'This value was not the Stream ID:', key """ stream_number_list = [] for stream_id in stream_id_list: stream_number_list.append(ixia_dict[long_card_number][long_port_number][stream_id]) long_stream_id = stream_id_list[0] next_line = 'set streamId ' + str(stream_number_list[0]['Stream ID']) # At this point we're configuring the individual streams # This will need to recurse itself until done with all the streams # # At the end of this mess we will check to see if there are more then one streams listed # in the stream_numbe_list. If so that means that there are more then on stream that # needs to be rewritten. To achieve this feat we will do a little cute trick. # 1. We will remove the first element in the stream_number_list[0] # 2. Then we will change the line_index = 2 so that this whole routine # is repeated until there are no more streams to rewrite. # # The hopes are that all the streams are actully in this section. elif line_index == 3: modified_line = 'set streamId ' + str(stream_number_list[0]['Stream ID']) + '\n' next_line = '# Stream ' + str(stream_number_list[0]['Stream ID']) line_index = line_index + 1 elif line_index == 4: modified_line = '# Stream ' + str(stream_number_list[0]['Stream ID']) + '\n' next_line = 'stream config -name "' line_index = line_index + 1 elif line_index == 5: modified_line = 'stream config -name "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Stream Name'] + '"\n' next_line = 'stream config -framesize ' line_index = line_index + 1 elif line_index == 6: if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Frame Size'): modified_line = 'stream config -framesize ' + \ str(ixia_dict[long_card_number][long_port_number][long_stream_id]['Frame Size']) + '\n' else: modified_line = input_line next_line = 'ip config -sourceIpAddr "' line_index = line_index + 1 elif line_index == 7: modified_line = 'ip config -sourceIpAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Source IP Address'] + '"\n' next_line = 'ip config -destIpAddr "' line_index = line_index + 1 elif line_index == 8: modified_line = 'ip config -destIpAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination IP Address'] + '"\n' next_line = 'ip config -destMacAddr "' line_index = line_index + 1 elif line_index == 9: modified_line = 'ip config -destMacAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination MAC Address'] + '"\n' if len(stream_number_list) > 1: stream_number = stream_number_list[0] stream_number_list.remove(stream_number) line_index = 2 else: error_message = 'Something went wrong while processing the line_index value. Out of range 1-8' return error_message else: print 'Something should happen here!' if len(modified_line) > 1: # Write out the modified line if generate_output_file: if debug: print 'The modified line to be written will be:' print modified_line output_file.write(modified_line) else: print 'modified line:', modified_line else: # Write out the original line if generate_output_file: output_file.write(input_line) else: """ if debug: print 'This is the line that would have been written out' print input_line print '-----------------------------------------------------------------------' """ if debug: print 'The ending section index is:', section_index print 'The ending line index is:', line_index # Clean up input_file.close() if generate_output_file: print 'Closing the output file:', output_file output_file.close() else: if debug: print 'This is where we would have closed the output file' return 0 def rewrite_ixia_config_2(ixia_dict): # updated for setting auto increment values. used for generating 8k traffic # Due to a change in the whitepsace of the config the method for finding the next line # must be changed. Instead of looking for the complete string the line must be sliced # so the whitespace is removed. Then the list must have the varibles removed from it # after that the list object can be compared with another list object. # This requires rewrite of all the expected lines to be lists. # most lines can be split on whitespace. The lines containing MAC addresses have # whitepace where the collons shoudl be. So the comparing logig should only # compare elements expected to elements read. That way it will stop reading before # it gets to the MAC. """ This function opens an IXIA.tcl script and rewrites the IP Address and other values to make the script send traffic to any DUT All values MUST be set in this dictionary or the file can not be rewritten correctly! After this method completes it will write an ouptut file or if set to "none" it will return the whole configuration as a very long string which can then be split and fed into the IXIA via CLI ixia_dict{ Chassis IP Address:10.4.2.30 # The IP of the IXIA itself Username:jalfrey # Username that "owns" the ports that will send traffic Source File # This is the source file it is read from # This needs to either be a full path or relative to current directory path Output File # This can be set to "none" and the method will return the whole configuration # Or if it is set it will write the file out to disk Card Number_X: # If there are multiple cards then there will be multiple dictionaries. # For my configuration I use card 3 to the dictionary will be called # "Card Number 3" Dictionary { Card Number # Card which port lives on. Same information contained in the dictionary # name but just as the number "3" Port Number X: # Port to be configured. There will be one key per port Dictionary { Port Number # This is the port number on the IXIA itself (physical port) Source MAC Address # Can be set or left "default" which will leave the config unchanged or null '' Destination MAC Address # This is the MAC of what the IXIA is directly connected to # In my case it's a Cisco Router Stream ID X: # This is the Stream ID. There is one ID per stream configured Dictionary: { Stream ID:1 # Stream numeric ID. Matches "Stream ID X" value X 0 - Stream Name # Optional. If value is Null nothing will be set # whatever was there will be left there 1 - Source IP Address # used for incrementing the source IP 2 - Source IP Mask 3 - Source IP Address Mode # Source on IXIA side 4 - Source IP Address Repeat Count # could be ipIncrHost or ... 5 - Source Class # when ipIncrHost enabled this option is ignored 6 - Destination IP Address 7 - Destination IP Mask 8 - Destination IP Address Mode 9 - Destination IP Address Repeat Count 10 - Destination Class # Where the traffic should go. In my case that's the SSX (DUT) 11 - Destination MAC Address # This should be the same as the "Destination MAC Address" found above # But clearly it can be set differently but I'm not sure why # Maybe for testing through a Hub? } } } """ debug = True # Configuration will overwrite this value generate_output_file = False ############################### # Variable Validation Section # ############################### if len(ixia_dict) > 0: top_keys = ixia_dict.keys() if debug: print '------------------------------------' print 'The top keys extracted were:' for key in top_keys: print key, ':', ixia_dict[key] print '------------------------------------' # IP Address if ixia_dict.has_key('Chassis IP Address'): if validIP(ixia_dict['Chassis IP Address']): top_keys.remove('Chassis IP Address') if debug: print 'Chassis IP is valid' else: error_message = 'Invalid IP address for the chassis: ' + ixia_dict.has_key('Chassis IP Address') return error_message # Username if ixia_dict.has_key('Username'): if (len(ixia_dict['Username']) > 0): top_keys.remove('Username') if debug: print 'Username is valid' else: error_message = 'No Username value provided' return error_message # Source File if ixia_dict.has_key('Source File'): if (ixia_dict['Source File'] == ''): return 'No source file value set' if os.path.exists(ixia_dict['Source File']): top_keys.remove('Source File') if debug: print 'Source filename is valid' else: return 'unable to locate the source file!' # Output File # IF the length is zero then no file is generated # if it is set to "none" then no file is generated # Otherwise whatever the filename is it's generated with that # Since the filename could be mostly anything we don't validate it if ixia_dict.has_key('Output File'): # Here we change the case to lowercase so that we can compare the string once # Instead of testing to see if it's formatted like 'None', 'NONE', etc. output_filename = ixia_dict['Output File'].lower() if output_filename == 'none': generate_output_file = False if debug: print 'No output file will be generate' else: generate_output_file = True if debug: print 'Output file will be generated' top_keys.remove('Output File') if debug: print 'Output filename is valid' if debug: print 'At this point the top_keys should only contain card numbers' print top_keys # At this point the top_keys dictionary should only contain entries # of card numbers. like "Card Number 3" for card_number in top_keys: # Now we use this "key" to retrieve all the ports listed for that card # Then we verify the port list is valid port_list = ixia_dict[card_number].keys() if debug: print 'Now parsing the following items in the port_list' print port_list for port_number in port_list: if 'Card Number' in port_number: if not (int(ixia_dict[card_number][port_number]) in range(1,15)): error_message = 'Card Number: ' + ixia_dict[card_number][port_number] + ' Outside expected range of: 1-14' return error_message if 'Port Number' in port_number: if debug: print '000000000' print 'port_number = ', port_number print 'The port number being tested is:', ixia_dict[card_number][port_number]['Port Number'] # The range function is odd. If you say 1,13 you get 13 numbers # starting at 1 not zero and it ends at 12 instead of 13. if not (int(ixia_dict[card_number][port_number]['Port Number']) in range(1,14)): error_message = 'Port number: ' + port_number + ' on Card: ' \ + card_number + ' is invalide. Expected to be in the range 1 - 13' return error_message else: if debug: print 'the following item wil not be parsed:' print port_number else: return 'No variables set. Can not proceed!' ############## # Open Files # ############## try: input_file = open(ixia_dict['Source File'], 'r') except: return 'Unable to open the Soucre File' if generate_output_file: try: output_file = open(ixia_dict['Output File'], 'w') except: return 'Unable to open the ouptut file!' ######################## # Parse the input_file # ######################## # Method: # # 1. Read the file line by line # 2. Look for section headers # a. If the line matches one of the section headers we note that down # b. The section header itself may need re-writing # c. Increment the section header counter # 3. Inside the sections search for specific lines # 4. Read each line and write it to the output file # 5. When special lines are found re-write them and write to output file next_header = '# This Script has been generated by Ixia ScriptGen' next_line = 'default_nothing' modified_line = 'default_nothing' section_index = 0 line_index = 0 line_count = 1 ######################## ## Used for Debugging ## run_to_completion = True break_after = 57 ######################## raw_keys = ixia_dict.keys() card_number_list = [] port_number_list = [] next_line_cache = '' for key in raw_keys: if 'Card Number' in key: card_number_list.append(ixia_dict[key]['Card Number']) if debug: print 'We are expecting to configure the following cards:', card_number_list if debug: print 'Now reading the input file line by line looking for the section headers' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' for input_line in input_file: """ if debug and (line_count >= break_after) and not run_to_completion: print 'Breaking on line:', line_count ,'for debuging' return 0 line_count = line_count + 1 """ ################### ## regex rewrite ## ################### local_debug = False if not (next_line_cache == next_line): if debug: print 'the next line we are looking for has changed. Regex will be regenerated' next_line_cache = next_line #Due to the searching bug we now need to change the next_line variable into a regex here # Logic # chop it into words # append the \s* betwen the words. That means any number of spaces in regex # then compile it into a regex pattern so we can search using it. if local_debug: print 'reworking the next line to become regex' print next_line next_line_words = next_line.split() if local_debug: print 'the split words are:', next_line_words raw_regex_next_line = '' #word = '' if local_debug: print '*' * 40 for raw_word in next_line_words: word = '' # regex does not like some characters and will fail! # we need to "escape" them with an extra slash if local_debug: print 'looking for invalid characters in word' for char in raw_word: if local_debug: print 'working on char:', char if char in ['[',']','\\','/','{','}']: if local_debug: print 'found a bad char:', char word = word + '[\\' + char + ']' else: if local_debug: print 'found a regular char:', char word = word + char if local_debug: print 'word is now:', word print '*' * 40 if local_debug: print 'working on word:', raw_word raw_regex_next_line = raw_regex_next_line + word + '\s*' if local_debug: print 'the raw regex is now:', raw_regex_next_line # now finally at the end of the statement we need a don't care # we will only look for the first part of the statement # the end can be anything raw_regex_next_line = raw_regex_next_line + '.*' if local_debug: print 'the completed raw regex is:', raw_regex_next_line next_line_regex = re.compile(raw_regex_next_line) ####################### ## end regex rewrite ## ####################### if debug: print '******* Line Number:', line_count, ' ********************' print 'have: "', input_line.strip(), '"' print 'want Header:', next_header print ' want Line: "', next_line, '"' try: print ' regex: "', raw_regex_next_line, '"' except: pass print '******* Line Number:', line_count, ' ********************' ############################### ## Do the regex matchin here ## ############################### #There seems to be no if regex.match logic available #so we need to do the logic here so we can use it for a branch later match = re.search(next_line_regex, input_line) if next_header in input_line: if debug: print 'valid section header:', input_line.strip() # This will give us a numeric index telling us what section we're in section_index = section_index + 1 if section_index == 1: next_line = 'if {[ixConnectToTclServer' if debug: print 'Found first section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(input_line) elif section_index == 2: modified_line = '######### Chassis list - {' + ixia_dict['Chassis IP Address'] + '} #########\n' next_line = 'ixConnectToChassis {' + local_chassis_ip_address + '}' if debug: print 'Found second section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(modified_line) elif section_index == 3: modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] + ' #########\n' next_line = 'chassis get "' + local_chassis_ip_address + '"' if debug: print 'Found third section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(modified_line) elif section_index == 4: next_line = 'set card ' if debug: print 'Found fourth section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(input_line) elif section_index == 5: if debug: print 'found fith section header' long_card_number = 'Card Number ' + str(card_number_list[0]) raw_port_list = ixia_dict[long_card_number].keys() port_name_list = [] for key in raw_port_list: if 'Port' in key: port_name_list.append(key) if debug: print 'building the port_number_list from the port_name_list:' print port_name_list print 'ixia_dict[long_card_number]:', ixia_dict[long_card_number] for port in port_name_list: if debug: print 'port:', port print 'long_card_number:', long_card_number port_number_list.append(ixia_dict[long_card_number][port]['Port Number']) if debug: print 'port_number_list:', port_number_list if debug: print 'The ports that will be configured for card:', long_card_number, 'are:', port_number_list # Example line """ ######### Chassis-10.4.2.30 Card-3 Port-3 ######### """ words = input_line.split() raw_port_number = words[3].split('-') local_port_number = raw_port_number[1] modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] \ + ' Card-' + str(card_number_list[0]) + ' Port-' + str(port_number_list[0]) + ' #########\n' if generate_output_file: output_file.write(modified_line) next_line = 'set port ' + str(local_port_number) elif section_index == 6: if debug: print 'found sixth section header' if generate_output_file: output_file.write(input_line) # This is a strange one. This header is identical to a header we have already seen in section 5 # but if we executed the same code it would mess stuff up so we just look for it to step # over it. next_header = '######### Chassis-' + local_chassis_ip_address + ' Card-' + str(local_card_number) elif section_index == 7: if debug: print 'found seventh section header. (final)' modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] + \ ' Card-' + str(card_number_list[0]) + ' Port-' + str(port_number_list[0]) + ' #########\n' next_line = 'chassis get "' + local_chassis_ip_address + '"' if generate_output_file: output_file.write(input_line) else: return 'Failure while parsing the section index' elif match: """ The IXIA does not care about the size of the whitespace. Some .tcl files will have different amount of space between the variable names. The old method for searching for the lines to replace was: if the line we were looking for was: "filter config -captureTriggerPattern anyPattern" the value in that line we would want to change would be: "anyPattern" So the line minus the variable we want to change would be: "filter config -captureTriggerPattern " We were checking to see if that partial line was part of the line we wanted to change. The problem with this is the spacing of the original line in the tcl script could change. Say like "filter config -captureTriggerPattern " That would cause the line to not be found. To work around this problem the following will be done: 1. The string we are loooking for which is called next_line will be changed into a regular expression 2. the file will be searched using regular expressions """ # line we're looking for #elif (next_line in input_line) and (len(input_line) > 2): # Changed order in statement so lenght is evaluated first. Faster if debug: print 'Found a next_line: "', input_line.strip(), '"' words = input_line.split() if debug: print 'The line was broken into these words:' print words if section_index == 1: if debug: print 'now in section 1' if line_index == 0: raw_target_word = words[2].split(']') local_chassis_ip_address = raw_target_word[0] if debug: print 'The Chassis IP Address found in the original configuraiton file was:', local_chassis_ip_address #next_line = 'errorMsg "Error connecting to Tcl Server ' + local_chassis_ip_address + ' "' next_line = 'errorMsg "Error connecting to Tcl Server 127.0.0.1 "' # now we need to rewrite the line and write it to the log file modified_line = ' if {[ixConnectToTclServer ' + ixia_dict['Chassis IP Address'] + ']} {\n' line_index = line_index + 1 elif line_index == 1: modified_line = ' errorMsg "Error connecting to Tcl Server ' + ixia_dict['Chassis IP Address'] + ' "\n' # we may need to empy the next line variable because we are looking for a section header #next_line = '' next_header = '######### Chassis list - {' + local_chassis_ip_address + '} #########' line_index = line_index + 1 # reset the line index because we are going to the next section line_index = 0 else: print 'line_index out of range at value:', line_index return 'Error in automation! bad line index in section 1' elif section_index == 2: if line_index == 0: modified_line = 'ixConnectToChassis {' + ixia_dict['Chassis IP Address'] + '}\n' next_line = 'set owner "' line_index = line_index + 1 elif line_index == 1: modified_line = 'set owner "' + ixia_dict['Username'] + '"\n' # going to the next section next_header = '######### Chassis-' + local_chassis_ip_address + ' #########' line_index = 0 elif section_index == 3: if line_index == 0: modified_line = 'chassis get "' + ixia_dict['Chassis IP Address'] + '"\n' # going to next section #next_header = '######### Card Type : 10/100/1000 LSM XMVR16 ############' next_header = '######### Card Type : 10/100/1000 LSM XMVDC16 ############' line_index = 0 elif section_index == 4: if line_index == 0: # There could be multiple cards. It's hard to say if there should be more then one # variable for the card number. I don't think it's neccarry because the system configures # the cards sequentially so it should not be overwritten. local_card_number = words[2] # We take the first element from the card number list. # After we're done using that information we will delete it from the list # and then we can use element zero again. (like a stack) modified_line = 'set card ' + str(card_number_list[0]) + '\n' #next_header = '######### Chassis-' + local_chassis_ip_address + ' ' + local_card_number #next_header = '######### Chassis-' + local_chassis_ip_address + ' Card-' + local_card_number next_header = '######### Chassis-127.0.0.1' + ' Card-' + local_card_number line_index = 0 elif section_index == 5: if line_index == 0: modified_line = 'set port ' + str(port_number_list[0]) + '\n' line_index = line_index + 1 next_line = 'port config -MacAddress "' elif line_index == 1: long_port_number = 'Port Number ' + str(port_number_list[0]) # The source MAC address "can" be configured if you like # But this does lead to more complexity about "what" to configure it to try: modified_line = next_line + ixia_dict[long_card_number][long_port_number]['Source MAC Address'] + '"\n' except: modified_line = input_line line_index = 0 next_header = '######### Generating streams for all the ports from above #########' else: error_message = 'line_index out of range 0-1 for section_index 5!' return error_message elif section_index == 6: error_message = 'Failure. Found a line in section six not expected.' return error_message elif section_index == 7: if line_index == 0: modified_line = 'chassis get "' + ixia_dict['Chassis IP Address'] + '"\n' line_index = line_index + 1 #next_line = 'set card ' + local_card_number[0] next_line = 'set card' elif line_index == 1: modified_line = 'set card ' + str(card_number_list[0]) + '\n' line_index = line_index + 1 next_line = 'set port ' + local_port_number elif line_index == 2: modified_line = 'set port ' + str(port_number_list[0]) + '\n' line_index = line_index + 1 """ if debug: print 'Looking for the stream ID itself in this dictionary:' print ixia_dict print 'Using these two keys to find it:' print long_card_number, long_port_number """ raw_stream_id = ixia_dict[long_card_number][long_port_number].keys() """ if debug: print 'Sorting through this list of keys:' print raw_stream_id """ stream_id_list = [] for key in raw_stream_id: if 'Stream ID' in key: """ if debug: print 'Found a Stream ID:', key """ stream_id_list.append(key) """ elif debug: print 'This value was not the Stream ID:', key """ stream_number_list = [] for stream_id in stream_id_list: stream_number_list.append(ixia_dict[long_card_number][long_port_number][stream_id]) long_stream_id = stream_id_list[0] next_line = 'set streamId ' + str(stream_number_list[0]['Stream ID']) # At this point we're configuring the individual streams # This will need to recurse itself until done with all the streams # # At the end of this mess we will check to see if there are more then one streams listed # in the stream_numbe_list. If so that means that there are more then on stream that # needs to be rewritten. To achieve this feat we will do a little cute trick. # 1. We will remove the first element in the stream_number_list[0] # 2. Then we will change the line_index = 2 so that this whole routine # is repeated until there are no more streams to rewrite. # # The hopes are that all the streams are actully in this section. elif line_index == 3: modified_line = 'set streamId ' + str(stream_number_list[0]['Stream ID']) + '\n' next_line = '# Stream ' + str(stream_number_list[0]['Stream ID']) line_index = line_index + 1 elif line_index == 4: modified_line = '# Stream ' + str(stream_number_list[0]['Stream ID']) + '\n' next_line = 'stream config -name "' line_index = line_index + 1 elif line_index == 5: modified_line = 'stream config -name "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Stream Name'] + '"\n' next_line = 'stream config -framesize ' line_index = line_index + 1 elif line_index == 6: if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Frame Size'): modified_line = 'stream config -framesize ' + \ str(ixia_dict[long_card_number][long_port_number][long_stream_id]['Frame Size']) + '\n' else: modified_line = input_line next_line = 'ip config -sourceIpAddr "' line_index = line_index + 1 elif line_index == 7: modified_line = 'ip config -sourceIpAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Source IP Address'] + '"\n' next_line = 'ip config -destIpAddr "' line_index = line_index + 1 elif line_index == 8: modified_line = 'ip config -destIpAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination IP Address'] + '"\n' next_line = 'ip config -destMacAddr "' line_index = line_index + 1 elif line_index == 9: modified_line = 'ip config -destMacAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination MAC Address'] + '"\n' if len(stream_number_list) > 1: stream_number = stream_number_list[0] stream_number_list.remove(stream_number) line_index = 2 else: error_message = 'Something went wrong while processing the line_index value. Out of range 1-8' return error_message else: print 'Something should happen here!' if len(modified_line) > 1: # Write out the modified line if generate_output_file: if debug: print 'The modified line to be written will be:' print modified_line output_file.write(modified_line) else: print 'modified line:', modified_line else: # Write out the original line if generate_output_file: output_file.write(input_line) else: if debug: print 'This is the line that would have been written out' print input_line.strip() print '-----------------------------------------------------------------------' ############################# ## Global debug breakpoint ## ############################# if debug and (line_count >= break_after) and not run_to_completion: print 'Breaking on line:', line_count ,'for debuging' return 0 line_count = line_count + 1 #################### ## end breakpoint ## #################### if debug: print 'The ending section index is:', section_index print 'The ending line index is:', line_index # Clean up input_file.close() if generate_output_file: print 'Closing the output file:', output_file output_file.close() else: if debug: print 'This is where we would have closed the output file' return 0 def rewrite_ixia_config_3(ixia_dict): # updated for setting auto increment values. used for generating 8k traffic # Due to a change in the whitepsace of the config the method for finding the next line # must be changed. Instead of looking for the complete string the line must be sliced # so the whitespace is removed. Then the list must have the varibles removed from it # after that the list object can be compared with another list object. # This requires rewrite of all the expected lines to be lists. # most lines can be split on whitespace. The lines containing MAC addresses have # whitepace where the collons shoudl be. So the comparing logig should only # compare elements expected to elements read. That way it will stop reading before # it gets to the MAC. """ This function opens an IXIA.tcl script and rewrites the IP Address and other values to make the script send traffic to any DUT All values MUST be set in this dictionary or the file can not be rewritten correctly! After this method completes it will write an ouptut file or if set to "none" it will return the whole configuration as a very long string which can then be split and fed into the IXIA via CLI ixia_dict{ Chassis IP Address:10.4.2.30 # The IP of the IXIA itself Username:jalfrey # Username that "owns" the ports that will send traffic Source File # This is the source file it is read from # This needs to either be a full path or relative to current directory path Output File # This can be set to "none" and the method will return the whole configuration # Or if it is set it will write the file out to disk Card Number_X: # If there are multiple cards then there will be multiple dictionaries. # For my configuration I use card 3 to the dictionary will be called # "Card Number 3" Dictionary { Card Number # Card which port lives on. Same information contained in the dictionary # name but just as the number "3" Port Number X: # Port to be configured. There will be one key per port Dictionary { Port Number # This is the port number on the IXIA itself (physical port) Source MAC Address # Can be set or left "default" which will leave the config unchanged or null '' Destination MAC Address # This is the MAC of what the IXIA is directly connected to # In my case it's a Cisco Router Stream ID X: # This is the Stream ID. There is one ID per stream configured Dictionary: { Stream ID:1 # Stream numeric ID. Matches "Stream ID X" value X 0 - Stream Name # Optional. If value is Null nothing will be set # whatever was there will be left there Frame Size 1 - Source IP Address # used for incrementing the source IP 2 - Source IP Mask 3 - Source IP Address Mode # Source on IXIA side 4 - Source IP Address Repeat Count # could be ipIncrHost or ... 5 - Source Class # when ipIncrHost enabled this option is ignored 6 - Destination IP Address 7 - Destination IP Mask 8 - Destination IP Address Mode 9 - Destination IP Address Repeat Count 10 - Destination Class # Where the traffic should go. In my case that's the SSX (DUT) 11 - Destination MAC Address # This should be the same as the "Destination MAC Address" found above # But clearly it can be set differently but I'm not sure why # Maybe for testing through a Hub? } } } """ debug = True # Configuration will overwrite this value generate_output_file = False ############################### # Variable Validation Section # ############################### if len(ixia_dict) > 0: top_keys = ixia_dict.keys() if debug: print '------------------------------------' print 'The top keys extracted were:' for key in top_keys: print key, ':', ixia_dict[key] print '------------------------------------' # IP Address if ixia_dict.has_key('Chassis IP Address'): if validIP(ixia_dict['Chassis IP Address']): top_keys.remove('Chassis IP Address') if debug: print 'Chassis IP is valid' else: error_message = 'Invalid IP address for the chassis: ' + ixia_dict.has_key('Chassis IP Address') return error_message # Username if ixia_dict.has_key('Username'): if (len(ixia_dict['Username']) > 0): top_keys.remove('Username') if debug: print 'Username is valid' else: error_message = 'No Username value provided' return error_message # Source File if ixia_dict.has_key('Source File'): if (ixia_dict['Source File'] == ''): return 'No source file value set' if os.path.exists(ixia_dict['Source File']): top_keys.remove('Source File') if debug: print 'Source filename is valid' else: return 'unable to locate the source file!' # Output File # IF the length is zero then no file is generated # if it is set to "none" then no file is generated # Otherwise whatever the filename is it's generated with that # Since the filename could be mostly anything we don't validate it if ixia_dict.has_key('Output File'): # Here we change the case to lowercase so that we can compare the string once # Instead of testing to see if it's formatted like 'None', 'NONE', etc. output_filename = ixia_dict['Output File'].lower() if output_filename == 'none': generate_output_file = False if debug: print 'No output file will be generate' else: generate_output_file = True if debug: print 'Output file will be generated' top_keys.remove('Output File') if debug: print 'Output filename is valid' if debug: print 'At this point the top_keys should only contain card numbers' print top_keys # At this point the top_keys dictionary should only contain entries # of card numbers. like "Card Number 3" for card_number in top_keys: # Now we use this "key" to retrieve all the ports listed for that card # Then we verify the port list is valid port_list = ixia_dict[card_number].keys() if debug: print 'Now parsing the following items in the port_list' print port_list for port_number in port_list: if 'Card Number' in port_number: if not (int(ixia_dict[card_number][port_number]) in range(1,15)): error_message = 'Card Number: ' + ixia_dict[card_number][port_number] + ' Outside expected range of: 1-14' return error_message if 'Port Number' in port_number: if debug: print '000000000' print 'port_number = ', port_number print 'The port number being tested is:', ixia_dict[card_number][port_number]['Port Number'] # The range function is odd. If you say 1,13 you get 13 numbers # starting at 1 not zero and it ends at 12 instead of 13. if not (int(ixia_dict[card_number][port_number]['Port Number']) in range(1,14)): error_message = 'Port number: ' + port_number + ' on Card: ' \ + card_number + ' is invalide. Expected to be in the range 1 - 13' return error_message else: if debug: print 'the following item wil not be parsed:' print port_number else: return 'No variables set. Can not proceed!' ############## # Open Files # ############## try: input_file = open(ixia_dict['Source File'], 'r') except: return 'Unable to open the Soucre File' if generate_output_file: try: output_file = open(ixia_dict['Output File'], 'w') except: return 'Unable to open the ouptut file!' ######################## # Parse the input_file # ######################## # Method: # # 1. Read the file line by line # 2. Look for section headers # a. If the line matches one of the section headers we note that down # b. The section header itself may need re-writing # c. Increment the section header counter # 3. Inside the sections search for specific lines # 4. Read each line and write it to the output file # 5. When special lines are found re-write them and write to output file next_header = '# This Script has been generated by Ixia ScriptGen' next_line = 'default_nothing' modified_line = 'default_nothing' section_index = 0 line_index = 0 line_count = 1 ######################## ## Used for Debugging ## run_to_completion = True break_after = 57 ######################## raw_keys = ixia_dict.keys() card_number_list = [] port_number_list = [] next_line_cache = '' for key in raw_keys: if 'Card Number' in key: card_number_list.append(ixia_dict[key]['Card Number']) if debug: print 'We are expecting to configure the following cards:', card_number_list if debug: print 'Now reading the input file line by line looking for the section headers' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' print '-----------------------------------------------------------------------' for input_line in input_file: """ if debug and (line_count >= break_after) and not run_to_completion: print 'Breaking on line:', line_count ,'for debuging' return 0 line_count = line_count + 1 """ ################### ## regex rewrite ## ################### local_debug = False if not (next_line_cache == next_line): if debug: print 'the next line we are looking for has changed. Regex will be regenerated' next_line_cache = next_line #Due to the searching bug we now need to change the next_line variable into a regex here # Logic # chop it into words # append the \s* betwen the words. That means any number of spaces in regex # then compile it into a regex pattern so we can search using it. if local_debug: print 'reworking the next line to become regex' print next_line next_line_words = next_line.split() if local_debug: print 'the split words are:', next_line_words raw_regex_next_line = '' #word = '' if local_debug: print '*' * 40 for raw_word in next_line_words: word = '' # regex does not like some characters and will fail! # we need to "escape" them with an extra slash if local_debug: print 'looking for invalid characters in word' for char in raw_word: if local_debug: print 'working on char:', char if char in ['[',']','\\','/','{','}']: if local_debug: print 'found a bad char:', char word = word + '[\\' + char + ']' else: if local_debug: print 'found a regular char:', char word = word + char if local_debug: print 'word is now:', word print '*' * 40 if local_debug: print 'working on word:', raw_word raw_regex_next_line = raw_regex_next_line + word + '\s*' if local_debug: print 'the raw regex is now:', raw_regex_next_line # now finally at the end of the statement we need a don't care # we will only look for the first part of the statement # the end can be anything raw_regex_next_line = raw_regex_next_line + '.*' if local_debug: print 'the completed raw regex is:', raw_regex_next_line next_line_regex = re.compile(raw_regex_next_line) ####################### ## end regex rewrite ## ####################### if debug: print '******* Line Number:', line_count, ' ********************' print 'have: "', input_line.strip(), '"' print 'want Header:', next_header print ' want Line: "', next_line, '"' try: print ' regex: "', raw_regex_next_line, '"' except: pass print '******* Line Number:', line_count, ' ********************' ############################### ## Do the regex matchin here ## ############################### #There seems to be no if regex.match logic available #so we need to do the logic here so we can use it for a branch later match = re.search(next_line_regex, input_line) if next_header in input_line: if debug: print 'valid section header:', input_line.strip() # This will give us a numeric index telling us what section we're in section_index = section_index + 1 if section_index == 1: next_line = 'if {[ixConnectToTclServer' if debug: print 'Found first section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(input_line) elif section_index == 2: modified_line = '######### Chassis list - {' + ixia_dict['Chassis IP Address'] + '} #########\n' next_line = 'ixConnectToChassis {' + local_chassis_ip_address + '}' if debug: print 'Found second section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(modified_line) elif section_index == 3: modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] + ' #########\n' next_line = 'chassis get "' + local_chassis_ip_address + '"' if debug: print 'Found third section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(modified_line) elif section_index == 4: next_line = 'set card ' if debug: print 'Found fourth section header' print 'next_line updated to:', next_line if generate_output_file: output_file.write(input_line) elif section_index == 5: if debug: print 'found fith section header' long_card_number = 'Card Number ' + str(card_number_list[0]) raw_port_list = ixia_dict[long_card_number].keys() port_name_list = [] for key in raw_port_list: if 'Port' in key: port_name_list.append(key) if debug: print 'building the port_number_list from the port_name_list:' print port_name_list print 'ixia_dict[long_card_number]:', ixia_dict[long_card_number] for port in port_name_list: if debug: print 'port:', port print 'long_card_number:', long_card_number port_number_list.append(ixia_dict[long_card_number][port]['Port Number']) if debug: print 'port_number_list:', port_number_list if debug: print 'The ports that will be configured for card:', long_card_number, 'are:', port_number_list # Example line """ ######### Chassis-10.4.2.30 Card-3 Port-3 ######### """ words = input_line.split() raw_port_number = words[3].split('-') local_port_number = raw_port_number[1] modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] \ + ' Card-' + str(card_number_list[0]) + ' Port-' + str(port_number_list[0]) + ' #########\n' if generate_output_file: output_file.write(modified_line) next_line = 'set port ' + str(local_port_number) elif section_index == 6: if debug: print 'found sixth section header' if generate_output_file: output_file.write(input_line) # This is a strange one. This header is identical to a header we have already seen in section 5 # but if we executed the same code it would mess stuff up so we just look for it to step # over it. next_header = '######### Chassis-' + local_chassis_ip_address + ' Card-' + str(local_card_number) elif section_index == 7: if debug: print 'found seventh section header. (final)' modified_line = '######### Chassis-' + ixia_dict['Chassis IP Address'] + \ ' Card-' + str(card_number_list[0]) + ' Port-' + str(port_number_list[0]) + ' #########\n' next_line = 'chassis get "' + local_chassis_ip_address + '"' if generate_output_file: output_file.write(input_line) else: return 'Failure while parsing the section index' elif match: """ The IXIA does not care about the size of the whitespace. Some .tcl files will have different amount of space between the variable names. The old method for searching for the lines to replace was: if the line we were looking for was: "filter config -captureTriggerPattern anyPattern" the value in that line we would want to change would be: "anyPattern" So the line minus the variable we want to change would be: "filter config -captureTriggerPattern " We were checking to see if that partial line was part of the line we wanted to change. The problem with this is the spacing of the original line in the tcl script could change. Say like "filter config -captureTriggerPattern " That would cause the line to not be found. To work around this problem the following will be done: 1. The string we are loooking for which is called next_line will be changed into a regular expression 2. the file will be searched using regular expressions """ # line we're looking for #elif (next_line in input_line) and (len(input_line) > 2): # Changed order in statement so lenght is evaluated first. Faster if debug: print 'Found a next_line: "', input_line.strip(), '"' words = input_line.split() if debug: print 'The line was broken into these words:' print words if section_index == 1: if debug: print 'now in section 1' if line_index == 0: raw_target_word = words[2].split(']') local_chassis_ip_address = raw_target_word[0] if debug: print 'The Chassis IP Address found in the original configuraiton file was:', local_chassis_ip_address #next_line = 'errorMsg "Error connecting to Tcl Server ' + local_chassis_ip_address + ' "' next_line = 'errorMsg "Error connecting to Tcl Server 127.0.0.1 "' # now we need to rewrite the line and write it to the log file modified_line = ' if {[ixConnectToTclServer ' + ixia_dict['Chassis IP Address'] + ']} {\n' line_index = line_index + 1 elif line_index == 1: modified_line = ' errorMsg "Error connecting to Tcl Server ' + ixia_dict['Chassis IP Address'] + ' "\n' # we may need to empy the next line variable because we are looking for a section header #next_line = '' next_header = '######### Chassis list - {' + local_chassis_ip_address + '} #########' line_index = line_index + 1 # reset the line index because we are going to the next section line_index = 0 else: print 'line_index out of range at value:', line_index return 'Error in automation! bad line index in section 1' elif section_index == 2: if line_index == 0: modified_line = 'ixConnectToChassis {' + ixia_dict['Chassis IP Address'] + '}\n' next_line = 'set owner "' line_index = line_index + 1 elif line_index == 1: modified_line = 'set owner "' + ixia_dict['Username'] + '"\n' # going to the next section next_header = '######### Chassis-' + local_chassis_ip_address + ' #########' line_index = 0 elif section_index == 3: if line_index == 0: modified_line = 'chassis get "' + ixia_dict['Chassis IP Address'] + '"\n' # going to next section #next_header = '######### Card Type : 10/100/1000 LSM XMVR16 ############' next_header = '######### Card Type : 10/100/1000 LSM XMVDC16 ############' line_index = 0 elif section_index == 4: if line_index == 0: # There could be multiple cards. It's hard to say if there should be more then one # variable for the card number. I don't think it's neccarry because the system configures # the cards sequentially so it should not be overwritten. local_card_number = words[2] # We take the first element from the card number list. # After we're done using that information we will delete it from the list # and then we can use element zero again. (like a stack) modified_line = 'set card ' + str(card_number_list[0]) + '\n' #next_header = '######### Chassis-' + local_chassis_ip_address + ' ' + local_card_number #next_header = '######### Chassis-' + local_chassis_ip_address + ' Card-' + local_card_number next_header = '######### Chassis-127.0.0.1' + ' Card-' + local_card_number line_index = 0 elif section_index == 5: if line_index == 0: modified_line = 'set port ' + str(port_number_list[0]) + '\n' line_index = line_index + 1 next_line = 'port config -MacAddress "' elif line_index == 1: long_port_number = 'Port Number ' + str(port_number_list[0]) # The source MAC address "can" be configured if you like # But this does lead to more complexity about "what" to configure it to try: modified_line = next_line + ixia_dict[long_card_number][long_port_number]['Source MAC Address'] + '"\n' except: modified_line = input_line line_index = 0 next_header = '######### Generating streams for all the ports from above #########' else: error_message = 'line_index out of range 0-1 for section_index 5!' return error_message elif section_index == 6: error_message = 'Failure. Found a line in section six not expected.' return error_message elif section_index == 7: if line_index == 0: modified_line = 'chassis get "' + ixia_dict['Chassis IP Address'] + '"\n' line_index = line_index + 1 #next_line = 'set card ' + local_card_number[0] next_line = 'set card' elif line_index == 1: modified_line = 'set card ' + str(card_number_list[0]) + '\n' line_index = line_index + 1 next_line = 'set port ' + local_port_number elif line_index == 2: modified_line = 'set port ' + str(port_number_list[0]) + '\n' line_index = line_index + 1 """ if debug: print 'Looking for the stream ID itself in this dictionary:' print ixia_dict print 'Using these two keys to find it:' print long_card_number, long_port_number """ raw_stream_id = ixia_dict[long_card_number][long_port_number].keys() """ if debug: print 'Sorting through this list of keys:' print raw_stream_id """ stream_id_list = [] for key in raw_stream_id: if 'Stream ID' in key: """ if debug: print 'Found a Stream ID:', key """ stream_id_list.append(key) """ elif debug: print 'This value was not the Stream ID:', key """ stream_number_list = [] for stream_id in stream_id_list: stream_number_list.append(ixia_dict[long_card_number][long_port_number][stream_id]) long_stream_id = stream_id_list[0] next_line = 'set streamId ' + str(stream_number_list[0]['Stream ID']) # At this point we're configuring the individual streams # This will need to recurse itself until done with all the streams # # At the end of this mess we will check to see if there are more then one streams listed # in the stream_numbe_list. If so that means that there are more then on stream that # needs to be rewritten. To achieve this feat we will do a little cute trick. # 1. We will remove the first element in the stream_number_list[0] # 2. Then we will change the line_index = 2 so that this whole routine # is repeated until there are no more streams to rewrite. # # The hopes are that all the streams are actully in this section. elif line_index == 3: ## Stream ID ## modified_line = 'set streamId ' + str(stream_number_list[0]['Stream ID']) + '\n' next_line = '# Stream ' + str(stream_number_list[0]['Stream ID']) line_index = line_index + 1 elif line_index == 4: ## Stream number ## modified_line = '# Stream ' + str(stream_number_list[0]['Stream ID']) + '\n' next_line = 'stream config -name "' line_index = line_index + 1 elif line_index == 5: ## Stream name ## modified_line = 'stream config -name "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Stream Name'] + '"\n' next_line = 'stream config -framesize ' line_index = line_index + 1 elif line_index == 6: ## Framesize ## # There may be a bug here. It looks like the new framesize is not single quoted if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Frame Size'): modified_line = 'stream config -framesize ' + \ str(ixia_dict[long_card_number][long_port_number][long_stream_id]['Frame Size']) + '\n' else: modified_line = input_line next_line = 'ip config -sourceIpAddr "' line_index = line_index + 1 elif line_index == 7: ## source IP Address ## modified_line = 'ip config -sourceIpAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Source IP Address'] + '"\n' #next_line = 'ip config -destIpAddr "' next_line = 'ip config -sourceIpMask "' line_index = line_index + 1 ## New variables ## # This is where the new variables come in elif line_index == 8: ## source IP Address Mask ## # generally set to "255.255.0.0" if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Source IP Mask'): modified_line = 'ip config -sourceIpMask "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Source IP Mask'] + '"\n' else: modified_line = input_line next_line = 'ip config -sourceIpAddrMode' line_index = line_index + 1 elif line_index == 9: ## source IP Address Mode ## # normally set to "ipIncrHost" if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Source IP Address Mode'): modified_line = 'ip config -sourceIpAddrMode ' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Source IP Address Mode'] + '\n' else: modified_line = input_line next_line = 'ip config -sourceIpAddrRepeatCount' line_index = line_index + 1 elif line_index == 10: ## source IP Address Repeat Count## if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Source IP Address Repeat Count'): modified_line = 'ip config -sourceIpAddrRepeatCount ' + \ str(ixia_dict[long_card_number][long_port_number][long_stream_id]['Source IP Address Repeat Count']) + '\n' else: modified_line = input_line next_line = 'ip config -sourceClass' line_index = line_index + 1 elif line_index == 11: ## source IP Class ## # used for incerementing the source IP. # typicall set to "classC" if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Source IP Class'): modified_line = 'ip config -sourceClass ' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Source IP Class'] + '\n' else: modified_line = input_line next_line = 'ip config -destIpAddr' line_index = line_index + 1 ## End new variables ## #elif line_index == 8: # generally set to ""30.222.0.1"" # string is quoted elif line_index == 12: ## destination IP address modified_line = 'ip config -destIpAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination IP Address'] + '"\n' #next_line = 'ip config -destMacAddr "' next_line = 'ip config -destIpAddrMode' line_index = line_index + 1 ## New variables ## elif line_index == 13: ## destination IP Address Mode ## # genearlly set to "ipIncrHost" if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Destination IP Address Mode'): modified_line = 'ip config -destIpAddrMode ' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination IP Address Mode'] + '\n' else: modified_line = input_line next_line = 'ip config -destIpAddrRepeatCount' line_index = line_index + 1 elif line_index == 14: ## destination IP Address Repeat Count ## # genearlly set to "4096" if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Destination IP Address Repeat Count'): modified_line = 'ip config -destIpAddrRepeatCount ' + \ str(ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination IP Address Repeat Count']) + '\n' else: modified_line = input_line next_line = 'ip config -destClass' line_index = line_index + 1 elif line_index == 15: ## destination Class ## # genearlly set to "classC" if ixia_dict[long_card_number][long_port_number][long_stream_id].has_key('Destination IP Class'): modified_line = 'ip config -destClass ' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination IP Class'] + '\n' else: modified_line = input_line next_line = 'ip config -destMacAddr' line_index = line_index + 1 ## end new variables ## #elif line_index == 9: elif line_index == 16: ## Destionation MAC address ## Debug print ixia_dict[long_card_number][long_port_number][long_stream_id].keys() modified_line = 'ip config -destMacAddr "' + \ ixia_dict[long_card_number][long_port_number][long_stream_id]['Destination MAC Address'] + '"\n' if len(stream_number_list) > 1: stream_number = stream_number_list[0] stream_number_list.remove(stream_number) line_index = 2 else: error_message = 'Something went wrong while processing the line_index value. Out of range 1-8' return error_message else: print 'Something should happen here!' if len(modified_line) > 1: # Write out the modified line if generate_output_file: if debug: print 'The modified line to be written will be:' print modified_line output_file.write(modified_line) else: print 'modified line:', modified_line else: # Write out the original line if generate_output_file: output_file.write(input_line) else: if debug: print 'This is the line that would have been written out' print input_line.strip() print '-----------------------------------------------------------------------' ############################# ## Global debug breakpoint ## ############################# if debug and (line_count >= break_after) and not run_to_completion: print 'Breaking on line:', line_count ,'for debuging' return 0 line_count = line_count + 1 #################### ## end breakpoint ## #################### if debug: print 'The ending section index is:', section_index print 'The ending line index is:', line_index # Clean up input_file.close() if generate_output_file: print 'Closing the output file:', output_file output_file.close() else: if debug: print 'This is where we would have closed the output file' return 0 def scp_to_ixia(source_file, destination_file, ixia = '10.1.10.12', username = 'ixia', password = '1102607'): """ This simple method will copy a file from your local filesystem to the IXIA of choice to the specified file location """ # local debug debug = True max_copy_time = 120 if debug: print 'now in issu.py scp_to_ixia' if debug: print 'incoming variables:' print ' source_file:', source_file print ' destination_file:', destination_file print ' ixia:', ixia print ' username:', username print ' password:', password # The Logging functions change the current working directory (CWD) to /Logs # That means all the files end up in /Logs instead of the script directory # This leads to confusion and a mess. current_dir = os.getcwd() if debug: print 'current working dir is:', current_dir dir_name = os.path.split(current_dir) if 'Logs' in dir_name: if debug: print 'we are in the log dir!' in_log_dir = True else: if debug: print 'we are not in the log dir!' in_log_dir = False if in_log_dir: os.chdir('../') # we will use the os.system method. It has many failures. The best way would be to use # a library called paramiko. But you would need to install it everywhere if debug: print 'trying to SCP the file' """ the format of the scp command is: scp <local file> <username>@<hostname/IP>:<destination file> """ no_hostname = 'nodename nor servname provided, or not known' accept_key = 'Are you sure you want to continue connecting (yes/no)?' password_prompt = 'password:' bad_username_password = 'Permission denied, please try again.' no_such_local_file = 'No such file or directory' permission_denied = 'Permission denied' if debug: print 'the command will be:' print "scp -q %s %s@%s:%s" % (source_file, username, ixia, destination_file) ses = pexpect.spawn("scp -q %s %s@%s:%s" % (source_file, username, ixia, destination_file)) # This is where you set the timeout for the SCP to start retr = ses.expect([accept_key, password_prompt, no_hostname, permission_denied], timeout = 10) if retr == 0: # This is the accept_key optionn: ses.sendline('yes') retr == ses.expect([password_prompt], timeout = 10) if retr == 0: # This is the password option: ses.sendline(password) else: print 'timeout waiting for password prompt' raise("timeout during SCP") elif retr == 1: # This is the password option: if debug: print ses.before ses.sendline(password) elif retr == 2: # no_hostname option print ses.before() raise("unable to SCP file. Error in command") elif retr == 3: # Permission denied raise("Permission denied") else: print 'timeoute while trying to SCP file' raise("timout during SCP") # this is where the max copy time is set. That means how long it takes to transfer the file # It's set at 120 seconds (2 minutes). That should be pleanty for any IXIA config #retr = ses.expect([bad_username_password, '$', no_such_local_file], timeout = max_copy_time) retr = ses.expect([bad_username_password, pexpect.EOF, no_such_local_file], timeout = max_copy_time) if retr == 0: print 'bad username or password provided' raise('bad username or password provided') elif retr == 1: if debug: print 'SCP successful' elif retr == 2: error_root = ses.before error_message = 'No such file or directory: %s' % error_root print error_message raise('No such file or directory') else: error_message = 'maximum time: %s for SCP to complete exceeded' % max_copy_time print error_message raise('Max copy time exceeded') return 0 def get_mac_cisco(cisco_ip, interface): """ Connects to cisco and retrieves the MAC address for the interface specified. Input: cisco_ip = hostname or IP of console interface = interface on cisco. 1/0, 3/1 etc. Returns: MAC address """ """ All API dealing with the cisco are passed only the cisco IP. The idea is to not remain connected. Cisco configuration is infrequent and generally we remain disconnected during the test. """ debug = True if debug: print 'connecting to cisco:', cisco_ip cisco = CISCO.CISCO(cisco_ip) cisco.console(cisco_ip) if debug: print 'figuring out the full interface name' # This code taken from CISCO.py clear_interface_config out = cisco.cmd("sh ip interface brief | inc %s"%interface) intType=re.search("(\w+Ethernet)",out).group(0) # conf = self.cmd("show running interface %s %s"%(intType,intf)) interface_name = intType + ' ' + interface if debug: print 'the interface name is:', interface_name raw_line = cisco.cmd("show interfaces %s | include address" % interface_name) raw_words = raw_line.split() if debug: print 'raw words:', raw_words print 'this should be the MAC:', raw_words[6] return raw_words[6] cisco.close() def get_mac_ssx(self, interface): """ takes the SSX object. retrieves the MAC address of the port specified Input: SSX Object interface = 2/1, 3/2 Returns: MAC address """ """ We are going to run into some problems here. the SSX can have two or four ports per line card. There is no way of knowing in advance if the port exists prior to retrieving the information. There needs to be some way of signaling the developer that the port does not exist. """ debug = True if debug: print 'retrieving the port information for port:', interface port_detail = show_port_detail(self, interface) if debug: print 'here is the dictionary we got back:' print port_detail[interface] return port_detail[interface]['MAC Address'] def cisco_mac_to_ixia_mac(mac_address): """ The MAC address from a cisco is formatted: "0013.196e.0a81" The IXIA MAC format is "01 80 C2 00 00 01" This API converts from cisco to ixia format """ debug = True if debug: print 'incomding MAC:', mac_address parts = str.upper(mac_address).split('.') part_1 = parts[0][:2] part_2 = parts[0][2:] part_3 = parts[1][2:] part_4 = parts[1][:2] part_5 = parts[2][2:] part_6 = parts[2][:2] ixia_mac = part_1 + ' ' + part_2 + ' ' + part_3 + ' ' + part_4 + ' ' + part_5 + ' ' + part_6 return ixia_mac def ssx_mac_to_ixia_mac(mac_address): """ The MAC address from a ssx is formatted: "00:12:73:00:64:a0" The IXIA MAC format is "01 80 C2 00 00 01" This API converts from ssx to ixia format """ debug = True if debug: print 'incoming MAC:', mac_address parts = str.upper(mac_address).split(':') ixia_mac = parts[0] + ' ' + parts[1] + ' ' + parts[2] + ' ' + parts[3] + ' ' + parts[4] + ' ' + parts[5] return ixia_mac def ftp(source_file, destination_file, hostname='localhost', destination_directory='current', username='regress', password='gleep7',getOrPut='put'): """ This is a simple function that will take a local file specified as "source_file" and FTP put it to a remote system into the destination_directory if specified. There are two optional variables to set the "username" and "password" of the remote FTP server. source_file = full path and filename of the source file or relative path destination_file = the filename itself hostname = ip address or hostname destination_directory = just the directory not the filename username = ftp username password = password for that user getOrPut = ftp put/get. Default: put When this function finishes it will return. If anything is returned the put/get failed. Return value will be the error message. """ debug = False timeout = 10 if (not os.path.exists(source_file)) and (getOrPut == 'put'): # check source file only if it is a put return 'Invalid source file:' + source_file if debug: if hostname == 'localhost': print 'Openning connection to localhost' else: print 'Openning connection to', hostname cmd = 'ftp ' + hostname if debug: print 'command will be:', cmd try: ses = pexpect.spawn(cmd) except: error_message = 'unable to connect to host ' + hostname return error_message prompt = 'Name' retr = ses.expect([prompt, 'Connection refused'], timeout=timeout) if debug: print 'retr ', retr # This is what we want if retr == 0: if debug: print 'username ', username ses.sendline(username) retr = ses.expect(['Password required'], timeout=timeout) if retr == 0: if debug: print 'password ', password ses.sendline(password) prompt = 'ftp>' retr = ses.expect([prompt, 'cannot log in'], timeout=timeout) if retr == 0: print 'succusffully logged into host:', hostname elif retr == 1: return 'invalid username or password' else: return 'timeout while waiting for login (network error)' if retr == 1: error_message = 'Connection refused' return error_message if retr == 2: error_message = 'Timeout while connecting' return error_message if not (destination_directory == 'current'): cmd = 'cd ' + destination_directory if debug: print 'comand will be:', cmd ses.sendline(cmd) retr = ses.expect(['command successful', 'find the file specified','CWD successful'], timeout=timeout) if debug: print 'retr', retr if retr > 2: return 'Unable to change directory to: ' + destination_directory else: print 'changed directory to:', destination_directory # expect the prompt retr = ses.expect([prompt], timeout=timeout) if retr > 0: return 'Unable to get the prompt' else: if debug: print 'Get the prompt' if getOrPut == 'put': cmd = 'put ' + destination_file else: cmd = 'get ' + source_file + " " + destination_file if debug: print 'cmd ', cmd time.sleep(5) ses.sendline(cmd) retr = ses.expect(["Transfer OK",prompt], timeout) if debug: print 'retr ', retr if retr > 1: return 'unable to put the file' else: print 'file:', destination_file, 'was %s to the server successfully' %getOrPut cmd = 'bye' ses.sendline(cmd) # Done! return 0 def clear_context(self, context=""): """Clear the configuration of a specific context on a SSX Leaves no context behind. Rewrite of clear_context from device.py """ debug = False # Checking to make sure the context exists! context_list = list_contexts(self) context_names = context_list.keys() if context in context_names: print "Clearing the configuration of context:", context command = 'config' if debug: print 'command will be:', command retrn_val = self.cmd(command) command = 'no context ' + context if debug: print 'command will be:', command retrn_val = self.cmd(command) # Code needs to be written to handle any failed return value if debug: print 'Command returned:', retrn_val command = 'end' if debug: print 'command will be:', command retrn_val = self.cmd(command) ################################ ## Verify Context was Removed ## ################################ print 'Verifying Context was removed' command = 'show configuration context ' + context if debug: print 'The command will be:', command raw_retrn_val = self.cmd(command) retrn_val = string.lstrip(raw_retrn_val) expected_string = 'ERROR: Context ' + context + ' not found' if debug: print 'Checking to see if:' print '"', expected_string, '" = "', retrn_val, '"' if retrn_val == expected_string: print 'Context was succesfully removed' return else: print 'Context was NOT removed!' print 'System returned:', retrn_val sys.exit(1) else: print 'Context name provided:', context, 'Is NOT a context on the SSX. FAIL' sys.exit(1) def minimal_configuration(self): """ This method will remove all the contexts except local. This will allow loading of configuration without conflicting configuration from the last config used. It will also work over a telnet session """ debug = False context_dict = list_contexts(self) if debug: print "the SSX has the following contexts:" context_list = context_dict.keys() if debug: print "==========================================" print "About to remove all contexts except local" for context in context_list: if context != 'local': if debug: print "About to clear the context:", context retrn_val = clear_context(self, context) if debug: print "returned:", retrn_val print "Context was cleared sucessfully" print 'All configuration was removed successfully except "local" context' # Now we need to unblind all the physical interfaces. print 'unbinding all the Ethernet ports except admin (0/0, 1/0)' unbind_interfaces(self) return def unbind_interfaces(self, protect_admin=True): """ This will remove all the physical port configuration By default it will not remove the admin ports of 0/0 and 1/0 """ # Example Port Config """ australia(cfg-port)#show conf port port ethernet 0/0 bind interface mgmt local exit enable exit port ethernet 1/0 bind interface mgmt local exit enable exit port ethernet 2/0 bind interface 2-0 r2 ipsec policy ikev2 phase1 name p11 ipsec policy ikev2 phase2 name p12 exit service ipsec enable exit port ethernet 2/1 bind interface 2-1 tunnels ipsec policy ikev2 phase1 name ph1_c1 ipsec policy ikev2 phase2 name ph2_c1 exit service ipsec enable exit port ethernet 2/2 bind interface 2-2 r2 exit enable exit port ethernet 2/3 bind interface 2-3 tunnels exit enable exit port ethernet 3/0 service ipsec enable exit port ethernet 3/1 enable exit port ethernet 3/2 enable exit port ethernet 3/3 enable exit port ethernet 4/0 bind interface ashu local exit service ipsec enable exit port ethernet 4/1 enable exit port ethernet 4/2 enable exit port ethernet 4/3 enable exit """ debug = False admin_ports = ['0/0','1/0'] command = 'show conf port ' raw_ports = self.cmd(command) port_conf = raw_ports.splitlines() # This is a list where we accumulate the commands # we will execute to clear the ports clear_commands = [] # used to ignore the configuration in an admin port admin_port = False if debug: print '------------------------------------' for raw_line in port_conf: if len(raw_line) > 1: if debug: print 'The raw line is:' print raw_line words = raw_line.split() if debug: print 'after split:' print words print 'checking to see if this is an interface name' if words[0] == 'port': if debug: print 'testing:', words[2] if words[2] in valid_port_list: if debug: print 'found and interface:', words[2] if words[2] not in admin_ports: admin_port = False if debug: print 'Found a port:', words[2] print 'Saving it to the clear_commands' if len(clear_commands) > 0: clear_commands.append('exit') clear_commands.append(raw_line) else: if protect_admin: if debug: print 'found an admin port' print 'port will be left configured' admin_port = True if protect_admin == False: if debug: print 'found an admin interface' print 'Will be unconfiguring it as well' admin_port = False else: if debug: print 'This line not an interface' print raw_line elif admin_port == False: if debug: 'line not protected as admin' if not 'exit' == words[0]: no_line = 'no' + raw_line if debug: print 'no line:' print no_line clear_commands.append(no_line) else: if debug: print 'discarding:', raw_line else: if debug: print 'discarding this line' print raw_line if debug: print '------------------------------------' if debug: print 'Completed processing the port config' print 'now removing the interfaces' print 'The commands that will be run are:' print '----------------------------------' for line in clear_commands: print line command = 'conf' self.cmd(command) for line in clear_commands: self.cmd(line) if debug: print 'completed sending commands' command = 'end' self.cmd(command) return def odd_or_even(value): """ Very simple check to see if an integer is odd or even """ try: int(value) except: return 'Value provided was not an integer' return value%2 and 'Odd' or 'Even' def ssx_date_to_log(date, offset=0): """ This function will take the date/time from the SSX command "show clock" and then reformat the date/time to be identical to the event log format of "event-log-yyyymmdd-hhmmss". This method is for generating the fake log files required to verify the log errasal This method takes as it's input the date and an offset in days. The method will subtract the offset in days from the original days """ debug = False try: int(offset) except: print 'The offset value passed:', offset, 'Was not an integer!' raise("invalid offset value %s" % offset) begin_time_stamp_parts = date.split() test_year = int(begin_time_stamp_parts[3]) if debug: print 'test_year:', test_year test_letter_month = begin_time_stamp_parts[1] if debug: print 'test_letter_month:', test_letter_month test_month = name_month_to_num(test_letter_month) if debug: print 'test_month:', test_month test_day = int(begin_time_stamp_parts[2]) if debug: print 'test_day:', test_day time_parts = begin_time_stamp_parts[4].split(':') if debug: print 'time_parts:', time_parts test_hour = int(time_parts[0]) if debug: print 'test_hour', time_parts test_minute = int(time_parts[1]) if debug: print 'test_minute:', test_minute test_second = int(time_parts[2]) if debug: print 'test_second:', test_second # Convert the date/time into python native format if debug: print test_year, test_month, test_day, test_hour, test_minute, test_second now = datetime.datetime(test_year, test_month, test_day, test_hour, test_minute, test_second) if not(offset == 0): actual_offset = datetime.timedelta(days=offset) calculated_date = now - actual_offset else: calculated_date = now log_filename = calculated_date.strftime("%Y%m%d-%H%M%S") return log_filename def nslookup_by_host(hostname): """ This runs just like a command line nslookup command. You provide the hostname. Method returns the IP Address """ debug = False if debug: print 'about to retrieve the ip for:', hostname try: output = socket.gethostbyname(hostname) if debug: print 'the raw output was:', output except: output = 'not found' return output def nslookup_by_ip(ip_address): """ This runs just like a command line nslookup command. You provide the IP I provide the hostname This method is broken on our systems! I don't know why. It works fine on my mac. """ debug = False if debug: print 'received the following IP Adress:', ip_address if validIP(ip_address): try: output = socket.gethostbyaddr(ip_address) if debug: print 'the raw output was:', output return output[0] except: output = 'not available' return output else: output = 'invalid IP adderss provided' return output def unix_to_dos_path(path): """ On UNIX the path is formated using the forward slash / On Windows the path uses the backslash \ So when you are using UNIX with windows you will need to convert any path statements. This takes the UNIX style path and generates a python friendly DOS style of path. (adding extra slashes to escape the slashes) the companion function is called dos_to_unix """ debug = False if debug: print 'now in issu.py unix_to_dos' if debug: print 'the path passed was:' print path return_path = ntpath.abspath(path) return return_path def dos_to_unix_path(path): """ On UNIX the path is formated using the forward slash / On Windows the path uses the backslash \ So when you are using UNIX with windows you will need to convert any path statements. This takes the DOS style path and generates a python friendly UNIX style of path. (adding extra slashes to escape the slashes) the companion function is called unix_to_dos """ debug = False if debug: print 'now in issu.py dos_to_unix' if debug: print 'the path passed was:' print path return_path = '' if debug: print '*' * 40 for char in path: if debug: print 'processing char:', char if char == '\\': if debug: print 'changing slash' return_path = return_path + '/' else: return_path = return_path + char if debug: print 'accumulated path:' print return_path print '*' * 40 if debug: print 'the return_path looks like:' print return_path print path return return_path def select_to_base(self, base_version): """ This method will take the version and select the system back to that base version. This would be used at the beginning of any ISSU related test to set the system to a known version. The version iformation consists of two values. The version itself like: 4.6B2 = package name The build ID like: 2010051019 = build base_version = {'package_name':'4.6B2', 'build':'2010051019'} """ debug = False # Get the current version from the SSX running_ver = self.ssx.get_version() if debug: self.myLog.info("The system is currently running %s " % running_ver) #if (running_ver['build'] == topo.base_version['build']): if (running_ver['build'] == base_version['build']): if debug: self.myLog.debug("Build version on system same as base version: %s" % running_ver['build']) build_the_same = True else: build_the_same = False #if (running_ver['branch'] == topo.base_version['package_name']): if (running_ver['branch'] == base_version['package_name']): self.myLog.debug("Branch name on the system same as base version: %s" % running_ver['branch']) branch_the_same = True else: branch_the_same = False if build_the_same and branch_the_same: if debug: self.myLog.info('System is running base version already. No install/select required') else: if debug: self.myLog.info('About to boot the system with the base version') #self.myLog.info("Base version is: %s " % topo.base_version) self.myLog.info("Base version is: %s " % base_version) self.myLog.debug("8888888888888888888") #retr = install_base(self.ssx, topo.base_version) retr = install_base(self.ssx, base_version) if debug: self.myLog.debug("8888888888888888888") if retr: self.myLog.error('Somethine went wrong when selecting to base version!') self.myLog.error(" it was: %s", retr) sys.exit(1) # we need to close that file handle to create a fresh one. time.sleep(2) self.ssx.close() reboot_time = 200 if debug: self.myLog.info("waiting for the system to finish rebooting: %s seconds" % reboot_time) time.sleep(reboot_time) rebooting = True retries = 20 while rebooting: if debug: self.myLog.info('Sleeping for 30 seconds') time.sleep(30) try: if debug: self.myLog.info('Connecting to SSX') self.ssx.telnet() if debug: self.myLog.info('Made it past the telnet command') # if that command does not fail then the rebooting state should change rebooting = False except: if debug: self.myLog.info('System not up yet') retries = retries - 1 if debug: self.myLog.info("%s retries left" % retries) if retries == 0: if debug: self.myLog.info("System never came back up after select!") # Need to return the failure here #sys.exit(1) return 'System never came back up after select!' if debug: self.myLog.info('Completed Select to base version') self.ssx.wait4cards() return 'complete' def session_counters_handle(self, session_handle): """This method pulls the session counters via the session handle. it executes "show session counters handle <handle>" It returns a dictionary containing all the fields present in the output """ if debug: print 'Now in issu.py session_counters_handle method' # Example Data """ 01 Tue May 11 10:32:22 PDT 2010. 02 03 Username Session Rcv Pkts Xmit Pkts Rcv Bytes Xmit Bytes 04 Handle 05 -------------------- ---------- ----------- ----------- ----------- ----------- 06 16502102800650210@r2 fc44020b 58869 58897 2708020 2709492 """ # If you provide an invalid session handle there is no response from the SSX # This will result in an empty dictionary being returned. results = {} command = "show session counters handle %s" % session_handle session_counters_raw = self.cmd(command) if debug: print 'This is the raw result:', session_counters_raw if len(session_counters_raw) > 0: # Chop the ouput into lines session_counters = session_counters_raw.splitlines() # We have a good idea of what the ouptut is going to look like. # The very last line "should" always contain our data. # The column headers will not change so we don't need to look at them. words = session_counters[-1:].split() results['Username'] = words[0] results['Session Handle'] = words[1] results['Rcv Pkts'] = words[2] results['Xmit Pkts'] = words[3] results['Rcv Bytes'] = words[4] results['Xmit Bytes'] = words[5] if debug: print 'Completed parsing the output. This is what we got:' print results return results else: print 'Invalid Session Handle provided:', session_handle return 0 def session_counters_username(self, username): """This method pulls the session counters via the session username. It returns a dictionary containing all the fields present in the output """ if debug: print 'Now in issu.py session_counters_username method' # Example Data """ 01 Tue May 11 10:32:22 PDT 2010. 02 03 Username Session Rcv Pkts Xmit Pkts Rcv Bytes Xmit Bytes 04 Handle 05 -------------------- ---------- ----------- ----------- ----------- ----------- 06 16502102800650210@r2 fc44020b 58869 58897 2708020 2709492 """ # If you provide an invalid session handle there is no response from the SSX # This will result in an empty dictionary being returned. results = {} command = "show session counters username %s" % username session_counters_raw = self.cmd(command) if debug: print 'This is the raw result:', session_counters_raw if len(session_counters_raw) > 0: # Chop the ouput into lines session_counters = session_counters_raw.splitlines() # We have a good idea of what the ouptut is going to look like. # The very last line "should" always contain our data. # The column headers will not change so we don't need to look at them. words = session_counters[-1:].split() results['Username'] = words[0] results['Session Handle'] = words[1] results['Rcv Pkts'] = words[2] results['Xmit Pkts'] = words[3] results['Rcv Bytes'] = words[4] results['Xmit Bytes'] = words[5] if debug: print 'Completed parsing the output. This is what we got:' print results return results else: print 'Invalid Session Handle provided:', session_handle return 0 def session_counters(self): """This returns a list indexed on username of every session listed along with a dictionary of the values """ debug = False if debug: print 'Now in issu.py session_counters_method' # Example Data """ 01 Tue May 11 10:32:22 PDT 2010. 02 03 Username Session Rcv Pkts Xmit Pkts Rcv Bytes Xmit Bytes 04 Handle 05 -------------------- ---------- ----------- ----------- ----------- ----------- 06 16502102800650210@r2 fc44020b 58869 58897 2708020 2709492 07 16502102800650211@r2 fc44021b 0 0 0 0 """ # If you provide an invalid session handle there is no response from the SSX # This will result in an empty dictionary being returned. results = {} command = "show session counters" session_counters_raw = self.cmd(command) if debug: print 'This is the raw result:', session_counters_raw if len(session_counters_raw) > 0: # Chop the ouput into lines session_counters = session_counters_raw.splitlines() # we need to figure out which lines to read. The output is variable. # The header information is always 5 lines long. # We can take the lenght of the output and subtract the header to get # the length of the output we want. # The calculation should net a negative number. We hope. line_count = 6 - len(session_counters) if debug: print 'We calculated there should be', line_count, 'lines to parse' print 'If the above output is positive then something went wrong.' print 'Found', abs(line_count), 'sessions active' """ if debug: print 'The lines we will process are:' print session_counters[line_count:] """ # This odd syntax should get us only the last N lines. for line in session_counters[line_count:]: if '-------' in line: print 'We went too far and got the seperator!' print 'Please increase the number of lines to count in.' else: # Create a fresh local dictionary to accumulate the results into line_dict = {} # cut the line into words words = line.split() # The list is indexed on the username # so we will store it here for clean code username = words[0] # Everything else is dumpted into the local dictionary line_dict['Username'] = words[0] line_dict['Session Handle'] = words[1] line_dict['Rcv Pkts'] = words[2] line_dict['Xmit Pkts'] = words[3] line_dict['Rcv Bytes'] = words[4] line_dict['Xmit Bytes'] = words[5] # This packs the line dictionary into the results dictionary results[username] = line_dict return results def show_process(self, slot='all'): """Runs the command 'show process' and parses the output. """ slot_list = ['slot 0','slot 1','slot 2','slot 3','slot 4'] process_dict = {} debug = False # Sample raw input """ australia[local]#show process 01 Name PID StartTime CPU NumThreads Priority 02 -------------- ------- ------------------------ --- ---------- -------- 03 NSM:0 651272 Tue Jun 01 15:31:53 0 21 7 04 Smid:0 696345 Tue Jun 01 15:32:03 0 10 7 05 Ip:0 696349 Tue Jun 01 15:32:07 0 32 7 06 CtxMgr:0 696348 Tue Jun 01 15:32:07 0 9 7 07 Fpd:0 696347 Tue Jun 01 15:32:06 0 16 7 08 Aaad:0 696353 Tue Jun 01 15:32:09 1 31 7 09 Cli:0 696368 Tue Jun 01 15:36:39 0 8 7 10 Snmpd:0 696355 Tue Jun 01 15:32:09 0 9 7 11 Inets:0 696354 Tue Jun 01 15:32:09 0 13 7 12 Logind:0 696346 Tue Jun 01 15:32:06 0 9 7 13 Ospf:0 696350 Tue Jun 01 15:32:07 0 10 7 14 Bgp4:0 696351 Tue Jun 01 15:32:07 0 11 7 15 Evl:0 696342 Tue Jun 01 15:32:03 0 13 7 16 EvlColl:0 696343 Tue Jun 01 15:32:03 0 8 7 17 Qosd:0 696352 Tue Jun 01 15:32:07 0 10 7 18 IkedMc:0 696356 Tue Jun 01 15:32:09 0 11 7 19 Ntp:0 696357 Tue Jun 01 15:32:09 0 10 7 20 Rip:0 696358 Tue Jun 01 15:32:09 0 12 7 21 Evt:0 696341 Tue Jun 01 15:32:03 0 9 7 22 Fabric:0 696364 Tue Jun 01 15:32:09 0 8 7 """ if slot == 'all': command = 'show process' elif slot in slot_list: command = 'show process ' + slot else: print 'Invalide specification for slot:', slot print 'Expected slot to be one of the following:', slot_list return 'Invalid option' raw_process_list = self.cmd(command) process_list = raw_process_list.splitlines() if debug: print 'The raw value returned was:' print process_list for raw_line in process_list[3:]: line = raw_line.split() local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line raw_name = line[0].split(':') name = raw_name[0] if debug: print 'The name is:', name local_dict['pid'] = line[1] if debug: print 'The PID is:', local_dict['pid'] day = line[2] month = line[3] year = line[4] time = line[5] start_time = day, month, year, time local_dict['start_time'] = start_time if debug: print 'The start time is:', local_dict['start_time'] local_dict['cpu'] = line[6] if debug: print 'The CPU it\'s on is:', local_dict['cpu'] local_dict['number_of_threads'] = line[7] if debug: print 'The number of threads is:', local_dict['number_of_threads'] local_dict['priority'] = line[8] if debug: print 'The priority is:', local_dict['priority'] # We store each entry in the main dictionary we return process_dict[name] = local_dict return process_dict def show_process_cpu(self, slot='all'): """Runs the command 'show process' and parses the output. """ slot_list = ['slot 0','slot 1','slot 2','slot 3','slot 4'] process_dict = {} debug = False # Sample raw input # If you have normal page breaks turned on (normal CLI) you will see the # banner information containing the column headers like "name" "PID" etc. # at every page break. You will also see the CPU Utilization again # This information is redundant and will be identical """ australia[local]#show process cpu 01 CPU0 Utilization for 5 seconds: 3.45% 1 Minute: 5.20% 5 Minutes: 11.56% 02 CPU1 Utilization for 5 seconds: 0.21% 1 Minute: 0.22% 5 Minutes: 2.68% 03 04 Name PID StartTime CPU uTime sTime % Now 05 -------------- ------- ------------------------ --- ------ ------ ------ 06 System:0 0 Mon Jun 20 13:22:23 0/1 16.337 5.995 0.00% 07 NSM:0 602115 Mon Jun 20 13:22:22 0 6.909 0.904 1.09% 08 Smid:0 671769 Mon Jun 20 13:22:31 0 1.004 0.065 0.00% 09 Ip:0 671773 Mon Jun 20 13:22:33 0 0.524 0.095 0.09% 10 CtxMgr:0 671772 Mon Jun 20 13:22:33 0 0.100 0.009 0.00% 11 Fpd:0 671771 Mon Jun 20 13:22:33 0 0.253 0.037 0.19% 12 Aaad:0 671777 Mon Jun 20 13:22:34 1 0.217 0.140 0.00% 13 Cli:0 831542 Mon Jun 20 13:23:21 0 0.976 0.043 0.79% 14 Cli:1 999472 Mon Jun 20 13:27:01 0 0.839 0.009 0.00% 15 Snmpd:0 671779 Mon Jun 20 13:22:34 0 0.128 0.020 0.00% 16 Inets:0 671778 Mon Jun 20 13:22:34 0 0.128 0.034 0.00% 17 Logind:0 671770 Mon Jun 20 13:22:33 0 0.088 0.006 0.00% 18 Logind:1 831541 Mon Jun 20 13:23:20 0 0.079 0.007 0.00% 19 Ospf:0 671774 Mon Jun 20 13:22:33 0 0.126 0.013 0.00% 20 Bgp4:0 671775 Mon Jun 20 13:22:33 0 0.132 0.016 0.00% 21 Evl:0 671766 Mon Jun 20 13:22:31 0 0.113 0.012 0.00% 22 EvlColl:0 671767 Mon Jun 20 13:22:31 0 0.101 0.027 0.00% 23 Qosd:0 671776 Mon Jun 20 13:22:33 0 0.118 0.010 0.00% 24 IkedMc:0 671780 Mon Jun 20 13:22:34 0 0.145 0.023 0.00% 25 Ntp:0 671781 Mon Jun 20 13:22:34 0 0.106 0.021 0.00% 26 Rip:0 671782 Mon Jun 20 13:22:34 0 0.127 0.013 0.00% 27 Evt:0 671765 Mon Jun 20 13:22:31 0 0.129 0.029 0.00% 28 Fabric:0 671788 Mon Jun 20 13:22:35 0 0.091 0.012 0.00% 29 Fsync:0 671768 Mon Jun 20 13:22:31 0 0.171 0.170 0.00% 30 TunMgr:0 671783 Mon Jun 20 13:22:34 0 0.095 0.022 0.00% 31 PPPoEMC:0 671784 Mon Jun 20 13:22:34 0 0.091 0.016 0.00% 32 PPPdMc:0 671785 Mon Jun 20 13:22:34 0 0.102 0.021 0.00% 33 CDR:0 671786 Mon Jun 20 13:22:34 0 0.182 0.012 0.00% 34 DHCPdMC:0 671787 Mon Jun 20 13:22:35 0 0.123 0.018 0.00% 35 MIPd:0 671789 Mon Jun 20 13:22:35 0 0.133 0.021 0.00% 36 SLA:0 671790 Mon Jun 20 13:22:35 0 0.101 0.014 0.00% 37 Dfn:0 671791 Mon Jun 20 13:22:35 1 0.194 0.108 0.00% """ if debug: print 'now in show_process_cpu in issu.py' if slot == 'all': command = 'show process cpu' elif slot in slot_list: command = 'show process cpu slot' + slot else: print 'Invalid specification for slot:', slot print 'Expected slot to be one of the following:', slot_list return 'Invalid option' raw_process_list = self.cmd(command) #raw_process_list = cmd(command) process_list = raw_process_list.splitlines() if debug: print 'The raw value returned was:' print process_list # processing this output will be split into two sections # Section 1: # This includes the cpu utilization stats. (2 lines) # Section 2: # This includes the states for each process (all other lines) ############# # Section 1 # ############# """ {'CPU0': {'1 minute': '7.28', '5 minute': '4.44', '5 second': '20.63'}, 'CPU1': {'1 minute': '0.48', '5 minute': '0.25', '5 second': '0.17'}} """ if debug: print 'now processing the CPU usage header' print '-----------------------------------' cpu_usage = {} local_dict = {} for line_number in range(1,3): if debug: print 'now processing line:', line_number print 'Raw line:', process_list[line_number] raw_input = process_list[line_number].split() if debug: print 'the splite elements are:' print raw_input cpu_number = raw_input[0] if debug: print 'now processing:', cpu_number local_dict[cpu_number] = {} ## 5 Second raw_five_second = raw_input[5] if debug: print 'processing the 5 second value:', raw_five_second # This is index notation for everything except the last char # on the line five_second = raw_five_second[:-1] if debug: print '5 second average:', five_second local_dict[cpu_number]['5 second'] = five_second ## 1 minute raw_one_minute = raw_input[8] if debug: print 'processing the 1 minute value:', raw_one_minute # This is index notation for everything except the last char # on the line one_minute = raw_one_minute[:-1] if debug: print '1 minute average:', one_minute local_dict[cpu_number]['1 minute'] = one_minute ## 5 minute raw_five_minute = raw_input[11] if debug: print 'processing the 5 minute value:', raw_five_minute # This is index notation for everything except the last char # on the line five_minute = raw_five_minute[:-1] if debug: print '5 minute average:', five_minute local_dict[cpu_number]['5 minute'] = five_minute if debug: print 'The CPU utilizaiton dictionary contains:' print local_dict process_dict['CPU Utilization'] = local_dict if debug: print 'The return dictionary (process_dict) now contains:' print process_dict ############# # Section 2 # ############# if debug: print 'now processing per process stats' print '--------------------------------' for raw_line in process_list[6:]: if debug: print 'now processing raw line:' print raw_line line = raw_line.split() local_dict = {} raw_name = line[0].split(':') ## Process Name name = raw_name[0] if debug: print 'The name is:', name ## PID (program ID) local_dict['pid'] = line[1] if debug: print 'The PID is:', local_dict['pid'] ## Start Time day = line[2] month = line[3] year = line[4] time = line[5] start_time = day, month, year, time local_dict['start_time'] = start_time if debug: print 'The start time is:', local_dict['start_time'] ## CPU local_dict['CPU'] = line[6] if debug: print 'running on CPU:', local_dict['CPU'] ## uTime local_dict['uTime'] = line[7] if debug: print 'running uTime:', local_dict['uTime'] ## sTime local_dict['sTime'] = line[8] if debug: print 'runnit sTime:', local_dict['sTime'] ## % Now raw_percent_now = line[9] # This strips the '%' off the value to make it easier # to process with automation local_dict['percent now'] = raw_percent_now[:-1] if debug: print '% now:', local_dict['percent now'] # We store each entry in the main dictionary we return process_dict[name] = local_dict # uncomment of to process only 1 line """ if debug: print '--------------------------' print 'stopping here for debuging' print '--------------------------' sys.exit(1) """ if debug: print 'returning from show_process_cpu' print '-------------------------------' return process_dict def show_tunnel_details(self, slot = 'all', handle = 'none'): """Retrieves the 'show ike-session list' information then filters out only tunnels. Once tunnel handle is known can filter by handle Can also be filted by slot. """ debug = False slot_range = [0,1,2,3,4,'all'] tunnel_list = [] if not (slot in slot_range): print 'Invalid slot passed:', slot print 'Expected to be one of the following:', slot_range return 'Invalid Slot number supplied' if slot == 'all': raw_session_list = list_ike_sessions(self) else: raw_session_list = list_ike_sessions(self, slot) if raw_session_list == 'No Sessions present': return 'No Tunnels present' if debug: print 'The raw_session list contains:' print raw_session_list # The format of the Tunnel response is similar to the tha of a Session # The differences are as follows: # 1. Contains 6 lines of output # 2. IKE Version = 2 <LAN<->LAN> # we will filter on the second option for item in raw_session_list: if debug: print 'the complete item is:' print item print 'Searching for ike version info' print item['IKE Version'] if item['IKE Version'] == '2 <LAN<->LAN>': if debug: print '!!!!Found a tunnel!!!!' tunnel_list.append(item) if debug: print 'Here are the Tunnels' print tunnel_list return tunnel_list def show_session_details(self, slot = 'all', handle = 'none'): """Retrieves the 'show ike-session list' information then filters out only tunnels. Once tunnel handle is known can filter by handle Can also be filted by slot. """ # Method not yet written. def show_time(self): """ runs the "show clock" command returns the output """ debug = False ret_dict = {} if debug: print 'now in issu.py show_time' time_stamp = self.cmd('show clock') if debug: print("The timestamp that was retrieved is: %s" % time_stamp) # The raw input looks like this """ Mon Jul 19 2010 10:43:43 PDT """ if debug: print("Parsing the current time") # We parse it into it's elements raw_time = time_stamp.split() ret_dict['day_of_week'] = raw_time[0] ret_dict['month'] = raw_time[1] ret_dict['day_of_month'] = raw_time[2] ret_dict['year'] = raw_time[3] raw_long_time = raw_time[4] ret_dict['timezone'] = raw_time[5] long_time = raw_long_time.split(":") ret_dict['hour'] = long_time[0] ret_dict['minute'] = long_time[1] ret_dict['second'] = long_time[2] if debug: print 'The fully parsed values are:' print ret_dict return ret_dict def show_port_counters_detail(self, filter_port = 'None'): """ This function runs the command "show port counters detail" on the SSX. It then takes the output from that command and parses all the values. For your convenience you can filter out the data from a single port by passing in a "filter_port" value """ debug = False # Example raw input """ Tue Sep 28 09:45:04 PDT 2010. Port Input Output ----- ----------------------------------- ----------------------------------- 0/0 Good Packets: 267565 Packets: 149557 Octets: 194788889 Octets: 24106413 UcastPkts: 240846 UcastPkts: 149543 McastPkts: 26635 McastPkts: 0 BcastPkts: 84 BcastPkts: 14 ErrorPkts: 0 ErrorPkts: 0 OctetsGood: 194788889 OctetsGood: 24106413 OctetsBad: 0 OctetsBad: 0 PktRate(pps, 0-sec avg): 0 PktRate(pps, 0-sec avg): 0 DataRate(bps, 0-sec avg): 0 DataRate(bps, 0-sec avg): 0 BandWidthUtil(%, 0-sec avg): 0 BandWidthUtil(%, 0-sec avg): 0 CRCErrors: 0 PktsCRCErrs: 0 DataErrors: 0 TotalColls: 0 AlignErrs: 0 SingleColls: 0 LongPktErrs: 0 MultipleColls: 0 JabberErrs: 0 LateCollisions: 0 SymbolErrs: 0 ExcessiveColls: 0 PauseFrames: 0 PauseFrames: 0 UnknownMACCtrl: 0 FlowCtrlColls: 0 VeryLongPkts: 0 ExcessLenPkts: 0 RuntErrPkts: 0 UnderrunPkts: 0 ShortPkts: 0 ExcessDefers: 0 CarrierExtend: 0 SequenceErrs: 0 SymbolErrPkts: 0 NoResourceDrop: 0 1/0 Good Packets: 53279 Packets: 6028 Octets: 37718652 Octets: 955547 UcastPkts: 26555 UcastPkts: 6020 McastPkts: 26634 McastPkts: 0 BcastPkts: 90 BcastPkts: 8 ErrorPkts: 0 ErrorPkts: 0 OctetsGood: 37718652 OctetsGood: 955547 OctetsBad: 0 OctetsBad: 0 PktRate(pps, 0-sec avg): 0 PktRate(pps, 0-sec avg): 0 DataRate(bps, 0-sec avg): 0 DataRate(bps, 0-sec avg): 0 BandWidthUtil(%, 0-sec avg): 0 BandWidthUtil(%, 0-sec avg): 0 CRCErrors: 0 PktsCRCErrs: 0 DataErrors: 0 TotalColls: 0 AlignErrs: 0 SingleColls: 0 LongPktErrs: 0 MultipleColls: 0 JabberErrs: 0 LateCollisions: 0 SymbolErrs: 0 ExcessiveColls: 0 PauseFrames: 0 PauseFrames: 0 UnknownMACCtrl: 0 FlowCtrlColls: 0 VeryLongPkts: 0 ExcessLenPkts: 0 RuntErrPkts: 0 UnderrunPkts: 0 ShortPkts: 0 ExcessDefers: 0 CarrierExtend: 0 SequenceErrs: 0 SymbolErrPkts: 0 NoResourceDrop: 0 """ command = "show port counters detail" if debug: print 'The command to the SSX will be:', command print 'Calling function cli_cmd() to execute command' raw_card_response = cli_cmd(self, command) """ if debug: print 'returned from cli_cmd()' print 'here is the raw returned value' print raw_card_response print '******************* *************** ************** ****************' """ input_dict = {} output_dict = {} return_dict = {} port_name = '' # We start by reading only line 4 and beyond. We don't want the following lines: """ Tue Sep 28 09:45:04 PDT 2010. Port Input Output ----- ----------------------------------- ----------------------------------- """ if debug: print 'the raw_card_response contains:', len(raw_card_response), 'lines' for line in raw_card_response[3:]: if debug: print 'processing line:' print '"', line, '"' print 'contains:', len(line), 'characters' if len(line) > 0: words = line.split() if debug: print 'words:' print words # At this point it splits the names and leaves the ':' on the end # This makes for messy processing! # We need to # 1. identify all the words till the ':' # 2. Join them back into a single "word" new_line = [] if words[0] in valid_port_list: port_name = words[0] # We then remove it from the list words.remove(port_name) if debug: print 'Found the port name:', port_name input_dict_key = '' input_value = '' found_input_key = False found_input_value = False output_dict_key = '' output_value = '' found_output_key = False found_output_value = False if debug: print 'the line now countains:', len(words), 'words to parse' print words for element in words: if debug: print 'working on word:', element if found_input_key == False: if debug: print 'looking for the input_key value' if element[-1] == ':': input_dict_key = input_dict_key + ' ' + element.strip(':') found_input_key = True if debug: print 'found input key:', input_dict_key else: input_dict_key = input_dict_key + ' ' + element if debug: print 'this was just part of a longer key:', input_dict_key elif (found_input_key == True) and (found_input_value == False): if debug: print 'looking for the input value' input_value = element found_input_value = True if debug: print 'found the input value:', input_value elif (found_input_value == True) and (found_output_key == False): if debug: print 'looking fo the output_key' if element[-1] == ':': output_dict_key = output_dict_key + ' ' + element.strip(':') found_output_key = True if debug: print 'found the output key:', output_dict_key else: output_dict_key = output_dict_key + ' ' + element if debug: print 'this was just part of a longer key:', output_dict_key else: # The last thing left must be the output value output_value = element found_output_value = True if debug: print 'found the output value:', output_value if (found_output_value == False) and (len(words) > 2): print 'Unable to determine the output value for', output_dict_key print 'please examine the following line:' print line print 'It was broken into the following words:' print words print 'Those were recognized as:' print 'Input', input_dict_key, ':', input_value print 'Output', output_dict_key, ': Unable to recoginze value!' sys.exit(1) input_dict[input_dict_key.lstrip()] = input_value if len(output_value) > 0: output_dict[output_dict_key.lstrip()] = output_value if debug: print '========= Parsed Data ===========' print 'input_dict:' print input_dict print 'output_dict' print output_dict print '========= Parsed Data ===========' else: if debug: print 'this should be a section end' # When we reach the end of a section we stick our local dictionary with all the values # for a port into the return dictionary indexed on port name/number. dict_key = port_name + ' Input' return_dict[dict_key] = input_dict # We now need to clear the dictionary so we can get the next values input_dict = {} dict_key = port_name + ' Output' return_dict[dict_key] = output_dict output_dict = {} if debug: print 'section end found' if debug: print 'Done processing the command!' print 'This is what we got back' print return_dict return return_dict def show_system_mtu(self): """ This function runs the command "show system" on the SSX and searches for the MTU values It will then return a dictionar that looks like this: {'Next Boot': '1500', 'Current Boot': '1500'} """ debug = False ret_dict = {} if debug: print 'about to run the command "show system | grep MTU"' show_system_raw = self.cmd('show system | grep MTU') if debug: print 'the output of the command was:' print show_system_raw show_system_lines = show_system_raw.splitlines() if debug: print 'counted', len(show_system_lines), 'lines to parse.' current_boot = show_system_lines[1].split() ret_dict['Current Boot'] = current_boot[1] next_boot = show_system_lines[2].split() ret_dict['Next Boot'] = next_boot[1] if debug: print 'about to return:' print ret_dict return ret_dict def show_port_detail(self, port_filter='none'): """ This function runs the command "show port detail" on the SSX and returns a netsted dictionary containing all the information available. """ # Currenlty the port_filter is not implemented debug = False # Example raw data """ australia[r2]#show port detail Tue Oct 26 13:35:08 PDT 2010. 0/0 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:0a:d0 Connector Autonegotiation: Enabled Type: RJ45 Speed: 100 Vendor: Marvell Duplex: Full Model No: 88E1111 MTU 1500 Serial No: N/A Transcvr: Unknown 1/0 Admin State: Configured Media Type: Eth Link State: Down MAC Address: 00:12:73:00:0a:d1 Connector Autonegotiation: Enabled Type: RJ45 Speed: 100 Vendor: Marvell Duplex: Full Model No: 88E1111 MTU 1500 Serial No: N/A Transcvr: Unknown 2/0 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:15:80 Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: AVAGO Duplex: Full Model No: ABCU-5710RZ MTU 1500 Serial No: AN08474W5T Transcvr: 1000BASE-T 2/1 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:15:81 Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: AVAGO Duplex: Full Model No: ABCU-5710RZ MTU 1500 Serial No: AN07381VZ2 Transcvr: 1000BASE-T 2/2 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:15:82 Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: FIBERXON INC. Duplex: Full Model No: FTM-C012R-LM MTU 1500 Serial No: au220052201136 Transcvr: 1000BASE-T 2/3 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:15:83 Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: AVAGO Duplex: Full Model No: ABCU-5710RZ MTU 1500 Serial No: AN07250ZPR Transcvr: 1000BASE-T 3/0 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:07:40 Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: FIBERXON INC. Duplex: Full Model No: FTM-C012R-LM MTU 1500 Serial No: AU220062414400 Transcvr: 1000BASE-T 3/1 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:07:41 Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: AVAGO Duplex: Full Model No: ABCU-5710RZ MTU 1500 Serial No: AN07331GAR Transcvr: 1000BASE-T 3/2 Admin State: Unconfigured Media Type: Eth Link State: Down MAC Address: 00:12:73:00:07:42 Connector Autonegotiation: Disabled Type: SFP Speed: 1000 Vendor: AVAGO Duplex: Full Model No: ABCU-5710RZ MTU 1500 Serial No: AN0852519F Transcvr: 1000BASE-T 3/3 Admin State: Unconfigured Media Type: Eth Link State: Down MAC Address: 00:12:73:00:07:43 Connector Autonegotiation: Disabled Type: SFP Speed: 1000 Vendor: AVAGO Duplex: Full Model No: ABCU-5710RZ MTU 1500 Serial No: AN07250ZKZ Transcvr: 1000BASE-T 4/0 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:09:48 Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: FIBERXON INC. Duplex: Full Model No: FTM-C012R-LM MTU 1500 Serial No: AU210052303996 Transcvr: 1000BASE-T 4/1 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:09:49 Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: FIBERXON INC. Duplex: Full Model No: FTM-C012R-LM MTU 1500 Serial No: AU220053201722 Transcvr: 1000BASE-T 4/2 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:09:4a Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: FIBERXON INC. Duplex: Full Model No: FTM-C012R-LM MTU 1500 Serial No: AU210052304186 Transcvr: 1000BASE-T 4/3 Admin State: Up Media Type: Eth Link State: Up MAC Address: 00:12:73:00:09:4b Connector Autonegotiation: Enabled Type: SFP Speed: 1000 Vendor: FIBERXON INC. Duplex: Full Model No: FTM-C012R-LM MTU 1500 Serial No: AU220053201743 Transcvr: 1000BASE-T """ ## Note: # # This data is very similar to other data but the "Connector" data is wrapped so # that messes things up a bit. We need to be sure to do the following: # 1. Look for the keyword "Connector" and then skip it # 2. For all the connector data we should append the word "Connector" on # to the values. Such as "Type" becomes "Connector Type" # # The MAC has a bunch of Collons in it ":" and that could get "split" out # We should fix that somehow. if debug: print '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&' print 'now in issu.py show_port_details' print 'about to run the command "show port detail"' show_port_detail_raw = self.cmd('show port detail') if debug: print 'the output of the command was:' print show_port_detail_raw ret_dict = {} # These dictionaries should not be needed. #left_dict = {} #right_dict = {} local_dict = {} port_name = '' valid_connector_values = ['Type','Vendor','Model No','Serial No','Transcvr'] show_port_detail_lines = show_port_detail_raw.splitlines() for line in show_port_detail_lines[2:]: if debug: print 'processing line:' print '"', line, '"' print 'contains:', len(line), 'characters' if len(line) > 0: #================================================= # The values are key:value key:value on the line # This means there are two columns of data # We look for the left one first # then we look for the right one. left_dict_key = '' left_value = '' found_left_key = False found_left_value = False right_dict_key = '' right_value = '' found_right_key = False found_right_value = False found_connector = False words = line.split() if debug: print 'words:' print words # At this point it splits the names and leaves the ':' on the end # This makes for messy processing! # We need to # 1. identify all the words till the ':' # 2. Join them back into a single "word" new_line = [] if words[0] in valid_port_list: port_name = words[0] # We then remove it from the list words.remove(port_name) if debug: print 'Found the port name:', port_name elif words[0] == 'Connector': if debug: print 'Found the Connector' found_connector = True if debug: print 'Removing it from the line' words.remove('Connector') if debug: print 'the line now countains:', len(words), 'words to parse' print words for element in words: if debug: print 'working on word:', element if found_left_key == False: if debug: print 'looking for the left_key value' if element[-1] == ':': left_dict_key = left_dict_key + ' ' + element.strip(':') found_left_key = True if debug: print 'found left key:', left_dict_key else: left_dict_key = left_dict_key + ' ' + element if debug: print 'this was just part of a longer key:', left_dict_key elif (found_left_key == True) and (found_left_value == False): if debug: print 'looking for the left value' left_value = element found_left_value = True if debug: print 'found the left value:', left_value elif (found_left_value == True) and (found_right_key == False): if debug: print 'looking fo the right_key' if element[-1] == ':': if element == 'Duplex:': left_value = left_value + right_dict_key if debug: print 'Found a piece of the last value:', right_dict_key right_dict_key = element.strip(':') found_right_key = True if debug: print 'found the right key:', right_dict_key else: right_dict_key = right_dict_key + ' ' + element.strip(':') found_right_key = True if debug: print 'found the right key:', right_dict_key elif element == 'MTU': right_dict_key = element found_right_key = True if debug: print 'found the right key:', right_dict_key else: right_dict_key = right_dict_key + ' ' + element if debug: print 'this was just part of a longer key:', right_dict_key else: # The last thing left must be the right value right_value = element found_right_value = True if debug: print 'found the right value:', right_value """ if (found_right_value == False) and (len(words) > 2): print 'Unable to determine the right value for', right_dict_key print 'please examine the following line:' print line print 'It was broken into the following words:' print words print 'Those were recognized as:' print 'left', left_dict_key, ':', left_value print 'right', right_dict_key, ': Unable to recoginze value!' sys.exit(1) """ #left_dict[left_dict_key.lstrip()] = left_value local_dict[left_dict_key.lstrip()] = left_value if len(right_value) > 0: #right_dict[right_dict_key.lstrip()] = right_value local_dict[right_dict_key.lstrip()] = right_value if debug: print '========= Parsed Data ===========' print 'output for port:', port_name print 'local_dict:' print local_dict print '========= Parsed Data ===========' else: if debug: print 'this should be a section end for port:', port_name # When we reach the end of a section we stick our local dictionary with all the values # for a port into the return dictionary indexed on port name/number. dict_key = port_name ret_dict[port_name] = local_dict # We now need to clear the dictionary so we can get the next values local_dict = {} if debug: print 'section end found' # There is still the last port information in the buffer. Need to save it too dict_key = port_name ret_dict[port_name] = local_dict if debug: print 'Last port found:', port_name print 'end of processing data' if debug: print 'completed show_port_details method' print '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&' return ret_dict def show_ip_interface_detail(self, context='local'): """ This function runs the command "show ip interface detail" on the SSX and returns a netsted dictionary containing all the information available. """ # Sample raw_data """ Name: tunnel_loopbk IP address: 10.19.0.1/32 State: Up mtu: Arp: Off Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Loopback Index: 0x25 Bind/session count: 0 Session default: No Bound to: None Name: tun_ssx1 IP address: 172.1.1.2/32 State: Up mtu: 1500 Arp: Off Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Tunnel Index: 0x26 Bind/session count: 1 Session default: No Bound to: lan2lan/ip4/2 Name: 4-0 IP address: 10.11.40.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x27 Bind/session count: 1 Session default: No Bound to: cct 4/0/1 Name: 4-1 IP address: 10.11.41.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x28 Bind/session count: 1 Session default: No Bound to: cct 4/1/1 Name: 4-2 IP address: 10.11.42.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x29 Bind/session count: 1 Session default: No Bound to: cct 4/2/1 Name: 4-3 IP address: 10.11.43.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x2a Bind/session count: 1 Session default: No Bound to: cct 4/3/1 Name: 2-0 IP address: 10.11.20.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x2c Bind/session count: 1 Session default: No Bound to: cct 2/0/1 Name: 2-1 IP address: 10.11.21.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x2d Bind/session count: 1 Session default: No Bound to: cct 2/1/1 Name: 2-2 IP address: 10.11.22.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x2e Bind/session count: 1 Session default: No Bound to: cct 2/2/1 Name: 2-3 IP address: 10.11.23.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x2f Bind/session count: 1 Session default: No Bound to: cct 2/3/1 Name: 3-0 IP address: 10.11.30.1/24 State: Up mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x30 Bind/session count: 1 Session default: No Bound to: cct 3/0/1 Name: 3-1 IP address: 10.11.31.1/24 State: Up mtu: 1400 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x31 Bind/session count: 1 Session default: No Bound to: cct 3/1/1 Name: 3-2 IP address: 10.11.32.1/24 State: Down mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x32 Bind/session count: 0 Session default: No Bound to: None Name: 3-3 IP address: 10.11.33.1/24 State: Down mtu: 1500 Arp: On Arp timeout: 3600 Arp refresh: Off Ignore DF: Off Icmp unreachables: Off Mask reply: Off Default source: No Description: None Type: Classic Index: 0x33 Bind/session count: 0 Session default: No Bound to: None """ debug = False # The ip interfaces are based on the context you are in self.cmd("context %s" % context) if debug: print '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&' print 'now in issu.py show_ip_interface_detail' print 'about to run the command "show ip interface detail"' show_ip_interface_detail_raw = self.cmd('show ip interface detail') ret_dict = {} local_dict = {} end_of_section = False port_name = '' show_ip_interface_detail_lines = show_ip_interface_detail_raw.splitlines() for line in show_ip_interface_detail_lines[1:]: if debug: print 'processing line:' print '"', line, '"' print 'contains:', len(line), 'characters' if len(line) > 0: #================================================= # The values are key:value key:value on the line # This means there are two columns of data # We look for the left one first # then we look for the right one. left_dict_key = '' left_value = '' found_left_key = False found_left_value = False right_dict_key = '' right_value = '' found_right_key = False found_right_value = False found_connector = False words = line.split() if debug: print 'words:' print words # At this point it splits the names and leaves the ':' on the end # This makes for messy processing! # We need to # 1. identify all the words till the ':' # 2. Join them back into a single "word" new_line = [] if debug: print 'the line now countains:', len(words), 'words to parse' print words for element in words: if debug: print 'working on word:', element if found_left_key == False: if debug: print 'looking for the left_key value' if element[-1] == ':': left_dict_key = left_dict_key + ' ' + element.strip(':') found_left_key = True if debug: print 'found left key:', left_dict_key else: left_dict_key = left_dict_key + ' ' + element if debug: print 'this was just part of a longer key:', left_dict_key elif (found_left_key == True) and (found_left_value == False): if debug: print 'looking for the left value' left_value = element found_left_value = True if debug: print 'found the left value:', left_value elif found_left_key and found_left_value and (len(port_name) < 1): if (left_dict_key == ' Name'): port_name = left_value if debug: print '!!!! found ip interface name:', port_name elif (found_left_value == True) and (found_right_key == False): if debug: print 'looking fo the right_key' if element[-1] == ':': if element == 'Duplex:': left_value = left_value + right_dict_key if debug: print 'Found a piece of the last value:', right_dict_key right_dict_key = element.strip(':') found_right_key = True if debug: print 'found the right key:', right_dict_key else: right_dict_key = right_dict_key + ' ' + element.strip(':') found_right_key = True if debug: print 'found the right key:', right_dict_key else: right_dict_key = right_dict_key + ' ' + element if debug: print 'this was just part of a longer key:', right_dict_key else: # The last thing left must be the right value right_value = element found_right_value = True if debug: print 'found the right value:', right_value """ if (found_right_value == False) and (len(words) > 2): print 'Unable to determine the right value for', right_dict_key print 'please examine the following line:' print line print 'It was broken into the following words:' print words print 'Those were recognized as:' print 'left', left_dict_key, ':', left_value print 'right', right_dict_key, ': Unable to recoginze value!' sys.exit(1) """ #left_dict[left_dict_key.lstrip()] = left_value local_dict[left_dict_key.lstrip()] = left_value if len(right_value) > 0: #right_dict[right_dict_key.lstrip()] = right_value local_dict[right_dict_key.lstrip()] = right_value if debug: print '========= Parsed Data ===========' print 'output for port:', port_name print 'local_dict:' print local_dict print '========= Parsed Data ===========' else: if debug: print 'this should be a section end for port:', port_name # When we reach the end of a section we stick our local dictionary with all the values # for a port into the return dictionary indexed on port name/number. dict_key = port_name ret_dict[port_name] = local_dict # We now need to clear the dictionary so we can get the next values local_dict = {} port_name = '' if debug: print 'section end found' # There is still the last port information in the buffer. Need to save it too dict_key = port_name ret_dict[port_name] = local_dict if debug: print 'Last port found:', port_name print 'end of processing data' # Return the system back to the default context self.cmd("context local") if debug: print 'completed show_port_details method' print '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&' return ret_dict def list_contexts(self): """This method runs the command "show context all" and parses the output. It returns a nested dictionary indexed on the context names dict = {'context name':{'index':'1','domains':'null'}} to get only the context names use dict.keys() """ debug = False retrn_dict = {} if debug: print 'Now in issu.py method list_contexts' command = "show context all" raw_output = self.cmd(command) raw_lines = raw_output.splitlines() if debug: print 'The raw_lines is:', raw_lines print '===============================' for line in raw_lines[3:]: local_dict = {} if debug: print 'processing line:', line words = line.split() context_name = words[0] local_dict['index'] = words[1] local_dict['domains'] = words[2:] retrn_dict[context_name] = local_dict if debug: print 'Done with list_contexts returning' print 'The retrn_dict contains:' print retrn_dict return retrn_dict def show_logging(self): """ This method executes the command "show logging". That command is hidden from tab completion normally The data included in the response is the internal buffers that control when the files are flushed to the disk. This method simply retrieves that data and parses it. """ debug = False # Example Data """ 00 Save Next 01 Log Size First-Ix Last-Ix Next-Ix Start-Ix Save-Ix W Not Read 02 ------ ----- ---------- ---------- ---------- ---------- ---------- - ---------- 03 Local 8192 0 5653 5654 N 0 04 0 5653 5654 05 Glob-R 8192 0 1858 1859 1806 7950 N 0 06 0 1858 1859 1806 7950 07 Glob-D 32768 304130 336897 336898 336790 361366 Y 24611 08 9218 9217 9218 9110 918 09 Glob-I 2048 1859 3906 3907 3606 5142 Y 0 10 1859 1858 1859 1558 1046 11 File Readers 1 12 Syslog Readers 0 """ if debug: print 'Now in issu.py method show_logging' ret_dict = {} command = 'show logging' raw_output = self.cmd(command) if debug: print 'The raw values are:' print raw_output print '-------------------------------------' lines = raw_output.splitlines() if len(lines) > 0: local_dict = {} line_number = 3 if debug: print 'The following lines will be processed:' print lines[4:11] for line in lines[4:12]: if debug: print 'processing line:' print line words = line.split() if debug: print 'Broke the line into these words:' print words print 'testing to see if we are on an odd or even line' print odd_or_even(line_number) if (odd_or_even(line_number) == 'Odd'): local_dict = {} log_name = words[0] if debug: print 'Found the log name:', log_name local_dict['Size'] = words[1] if debug: print 'Found the Size:', words[1] local_dict['First-Ix 1'] = words[2] if debug: print 'Found the First-Ix 1:', words[2] local_dict['Last-Ix 1'] = words[3] if debug: print 'Found Last-IX 1:', words[3] local_dict['Next-Ix 1'] = words[4] if debug: print 'Found Next-Ix 1:', words[4] if log_name == 'Local': if debug: print 'Processing local info' local_dict['W'] = words[5] if debug: print 'found W:', words[5] local_dict['Not Read'] = words[6] if debug: print 'found Not Read:', words[6] else: if debug: print 'Not processing local info' local_dict['Save Start-Ix 1'] = words[5] if debug: print 'found Save Start-Ix 1:', words[5] local_dict['Next Save-Ix 1'] = words[6] if debug: print 'found Next Save-Ix 1:', words[6] local_dict['W'] = words[7] if debug: print 'found W:', words[7] local_dict['Not Read'] = words[8] if debug: print 'found Not Read:', words[8] if (odd_or_even(line_number) == 'Even'): local_dict['First-Ix 2'] = words[0] if debug: print 'found First-Ix 2:', words[0] local_dict['Last-Ix 2'] = words[1] if debug: print 'found Last-Ix 2:', words[1] local_dict['Next-Ix 2'] = words[2] if debug: print 'found Next-Ix 2:', words[2] if not(log_name == 'Local'): local_dict['Save Start-Ix 2'] = words[3] if debug: print 'Found Save Start-Ix 2:', words[3] local_dict['Next Save-Ix 2'] = words[4] if debug: print 'found Next Save-Ix 2:', words[4] if debug: print 'storing loca_dict in ret_dict for log name:', log_name ret_dict[log_name] = local_dict if debug: print 'The processed line looks like:' print local_dict if debug: print 'Done with line number:', line_number line_number = line_number + 1 if debug: print '-------------------------------------' file_readers_raw = lines[12].split() ret_dict['File Readers'] = file_readers_raw[2] syslog_readers_raw = lines[13].split() ret_dict['Syslog Readers'] = syslog_readers_raw[2] else: print 'We got no lines back from the command "show logging"!' print 'Something is broken!' sys.exit(1) return ret_dict def show_mem(self): """ runs the command "show memory" and parses the output """ # Example input """ australia[local]#show memory 00 01 Mon Jun 20 16:15:28 PDT 2011. 02 Slot Type Bytes Total Bytes Used % Available 03 ----- ----- --------------- --------------- ------------ 04 0 IMC1 2,147,483,648 689,876,992 67 05 1 IMC1 2,147,483,648 652,500,992 69 """ debug = False ret_dict = {} if debug: print 'now in show_mem part of issu.py' command = 'show mem' raw_mem_list = self.cmd(command) mem_list = raw_mem_list.splitlines() if debug: print 'The raw value returned was:' for line in mem_list: print line ## Date/Time local_dict = {} raw_line = mem_list[1] if debug: print 'the raw line is:' print raw_line words = raw_line.split() local_dict['day of week'] = words[0] local_dict['month'] = words[1] local_dict['day'] = words[2] raw_time = words[3] if debug: print 'the raw time is:' print raw_time time = raw_time.split(':') local_dict['hour'] = time[0] local_dict['minute'] = time[1] local_dict['second'] = time[2] local_dict['time zone'] = words[4] local_dict['year'] = words[5] ret_dict['time stamp'] = local_dict for raw_line in mem_list[4:]: local_dict = {} if debug: print 'the raw line is:' print raw_line words = raw_line.split() if debug: print 'the split values are:' print words slot = 'slot ' + words[0] local_dict['type'] = words[1] local_dict['bytes total'] = words[2] local_dict['bytes used'] = words[3] local_dict['percent available'] = words[4] if debug: print 'the local dictionary contains:' for key in local_dict.keys(): print key, ':' , local_dict[key] # pack the values into the return dictionary ret_dict[slot] = local_dict return ret_dict def show_syscount(self): """ Executes the command "show syscount" and then returns a parsed dictionary """ # Example Input """ 0 1 Wed Jun 22 07:54:55 PDT 2011. 2 System Counters: 3 IMC Switchover: 0 4 Card Reset: 2 5 Card Restart: 0 6 Process Core: 1 7 Process Exit: 1 8 Process Restart: 0 9 CRIT Event: 4 10 ERR Event: 1 11 WARN Event: 25 """ debug = False if debug: print 'now in show_syscount in issu.py' ret_dict = {} command = 'show syscount' raw_syscount = self.cmd(command) syscount_lines = raw_syscount.splitlines() if debug: print 'the raw values are:' line_index = 0 for line in syscount_lines: print repr(line_index).ljust(2), line line_index = line_index + 1 # we throw away lines 0-2 for line in syscount_lines[3:]: if debug: print 'processing the following line:' print line # Break the line into words words = line.split(':') counter_name = words[0].lstrip() if counter_name == 'IMC Switchover': ret_dict['IMC Switchover'] = int(words[1]) elif counter_name == 'Card Reset': ret_dict['Card Reset'] = int(words[1]) elif counter_name == 'Card Restart': ret_dict['Card Restart'] = int(words[1]) elif counter_name == 'Process Core': ret_dict['Process Core'] = int(words[1]) elif counter_name == 'Process Exit': ret_dict['Process Exit'] = int(words[1]) elif counter_name == 'Process Restart': ret_dict['Process Restart'] = int(words[1]) elif counter_name == 'CRIT Event': ret_dict['CRIT Event'] = int(words[1]) elif counter_name == 'ERR Event': ret_dict['ERR Event'] = int(words[1]) elif counter_name == 'WARN Event': ret_dict['WARN Event'] = int(words[1]) else: print 'While processing the "show syscount" command encountered' print 'the following value: "' + words[0] + '"' print 'the method show_syscount can not process it!' sys.exit(1) return ret_dict def show_version(self, slot='active'): """ runs the command "show version" optionally will run the command "show version slot 1" it then parses the output and returns a dictionary of values """ debug = True # the default behavior is to show the "active" cards version # optionally you can specify a slot # Sample input """ 0 1 Slot 1 Information (IMC1): 2 ---------------------------------------------------------------------------- 3 StokeOS Release 4.146X1B1S4 (2011061319). 4 Built Mon Jun 13 20:41:21 PDT 2011 by builder. 5 6 Stoke uptime is 2 minutes 7 Card uptime is 2 minutes 8 9 System restart at Wed Jun 22 09:27:18 PDT 2011 10 Card restart at Wed Jun 22 09:27:18 PDT 2011 11 Restart by remote reset 12 13 Firmware Version: v91 14 15 Stoke-Boot Version 16 *Booted Primary: StokeBoot Release 4.2 (2009120817). 17 Booted Backup: StokeBoot Release 4.2 (2009120817). 18 Stoke-Bloader Version 19 *Booted Primary: Stoke Bootloader Release 4.146X1B1S4 (2011061319). 20 Booted Backup: Stoke Bootloader Release 4.6B1S4 (2011061319). """ if debug: print 'now in show_version is issu.py' ret_dict = {} valid_slot_list = range(0,5) if slot == 'active': command = 'show version' elif int(slot) in valid_slot_list: command = 'show version slot ' + str(slot) else: print 'invalid option for slot:', slot print 'must be one of the following:', valid_slot_list sys.exit(1) raw_version_list = self.cmd(command) version_list = raw_version_list.splitlines() if debug: print 'the raw input was:' line_index = 0 for line in version_list: print repr(line_index).ljust(2), line line_index = line_index + 1 # Parsing: # Slot 1 Information (IMC1): line = version_list[1] if debug: print 'parsing:', line words = line.split() ret_dict['slot'] = words[1] raw_card_type = words[3] card_type = raw_card_type.strip('():') ret_dict['card type'] = card_type # Parsing: # StokeOS Release 4.146X1B1S4 (2011061319). line = version_list[3] if debug: print 'parsing:', line words = line.split() ret_dict['version'] = words[2] raw_build_id = words[3] build_id = raw_build_id.strip('().') ret_dict['build id'] = build_id # Parsing # Built Mon Jun 13 20:41:21 PDT 2011 by builder. line = version_list[4] if debug: print 'parsing:', line words = line.split() if debug: print 'the split line:' print words local_dict = {} local_dict['day of week'] = words[1] local_dict['month'] = words[2] local_dict['day of month'] = words[3] raw_time = words[4] time = raw_time.split(':') local_dict['hour'] = time[0] local_dict['minute'] = time[1] local_dict['second'] = time[2] local_dict['time zone'] = words[5] local_dict['year'] = words[6] ret_dict['build date time'] = local_dict ret_dict['build by'] = words[8] if (slot == 'active') or (version_list[6][0:5] == 'Stoke'): if debug: print 'parsing output for Active card' # Parsing # Stoke uptime is 2 minutes line = version_list[6] words = line.split() local_dict = {} if len(words) == 5: local_dict['hour'] = 0 local_dict['minute'] = int(words[3]) else: local_dict['hour'] = int(words[3]) local_dict['minute'] = int(words[5]) ret_dict['system uptime'] = local_dict # Parsing # Card uptime is 2 minutes line = version_list[7] if debug: print 'parsing:', line words = line.split() if debug: print 'the split line contains:' print words local_dict = {} if len(words) == 5: local_dict['hour'] = 0 local_dict['minute'] = int(words[3]) else: local_dict['hour'] = int(words[3]) local_dict['minute'] = int(words[5]) ret_dict['card uptime'] = local_dict # Parsing # System restart at Wed Jun 22 09:27:18 PDT 2011 line = version_list[9] if debug: print 'parsing:', line words = line.split() local_dict = {} local_dict['day of week'] = words[3] local_dict['month'] = words[4] local_dict['day of month'] = words[5] raw_time = words[6] time = raw_time.split(':') local_dict['hour'] = time[0] local_dict['minute'] = time[1] local_dict['second'] = time[2] local_dict['time zone'] = words[7] local_dict['year'] = words[8] ret_dict['system restart date time'] = local_dict # Parsing # Card restart at Wed Jun 22 09:27:18 PDT 2011 line = version_list[10] if debug: print 'parsing:', line words = line.split() local_dict = {} local_dict['day of week'] = words[3] local_dict['month'] = words[4] local_dict['day of month'] = words[5] raw_time = words[6] time = raw_time.split(':') local_dict['hour'] = time[0] local_dict['minute'] = time[1] local_dict['second'] = time[2] local_dict['time zone'] = words[7] local_dict['year'] = words[8] ret_dict['card restart date time'] = local_dict # Parsing # Restart by remote reset ret_dict['restart by'] = version_list[11:] # Parsing # Firmware Version: v91 line = version_list[13] if debug: print 'parsing:', line words = line.split() ret_dict['firmware version'] = words[2] # Parsing # *Booted Primary: StokeBoot Release 4.2 (2009120817). line = version_list[16] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['primary'] = {'version': version, 'build id': build_id} # Parsing # Booted Backup: StokeBoot Release 4.2 (2009120817). line = version_list[17] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['backup'] = {'version': version, 'build id': build_id} ret_dict['stoke boot version'] = local_dict # Parsing # *Booted Primary: Stoke Bootloader Release 4.146X1B1S4 (2011061319). line = version_list[21] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['primary'] = {'version': version, 'build id': build_id} # Parsing # Booted Backup: Stoke Bootloader Release 4.6B1S4 (2011061319). line = version_list[22] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['backup'] = {'version': version, 'build id': build_id} ret_dict['stoke os version'] = local_dict elif slot in ['0','1']: if debug: print 'parsing output for selected card' print 'card is either in slot-0 or slot-1' # sample input """ 0 1 Slot 1 Information (IMC1): 2 ---------------------------------------------------------------------------- 3 StokeOS Release 4.6B1S2 (2010062215). 4 Built Tue Jun 22 16:44:08 PDT 2010 by builder. 5 6 Card uptime is 1 week, 5 days, 8 hours, 38 minutes 7 8 Card restart at Thu Jun 23 02:18:41 PDT 2011 9 Restart by remote reset 10 11 Firmware Version: v91 12 13 Stoke-Boot Version 14 *Booted Primary: StokeBoot Release 4.2 (2009120817). 15 Booted Backup: StokeBoot Release 4.2 (2009120817). 16 Stoke-Bloader Version 17 *Booted Primary: Stoke Bootloader Release 4.6B1S2 (2010062215). 18 Booted Backup: Stoke Bootloader Release 4.146X1B1S4 (2011061319). 19 Update Backup: Stoke Bootloader Release 4.6B1S2 (2010062215). """ # Parsing # Card uptime is 2 minutes line = version_list[6] if debug: print 'parsing:', line words = line.split() if debug: print 'the split line contains:' print words local_dict = {} if len(words) == 5: local_dict['hour'] = 0 local_dict['minute'] = int(words[3]) else: local_dict['hour'] = int(words[3]) local_dict['minute'] = int(words[5]) ret_dict['card uptime'] = local_dict # Parsing # Card restart at Thu Jun 23 02:33:34 PDT 2011 line = version_list[8] if debug: print 'parsing:', line words = line.split() local_dict = {} local_dict['day of week'] = words[3] local_dict['month'] = words[4] local_dict['day of month'] = words[5] raw_time = words[6] time = raw_time.split(':') local_dict['hour'] = time[0] local_dict['minute'] = time[1] local_dict['second'] = time[2] local_dict['time zone'] = words[7] local_dict['year'] = words[8] ret_dict['card restart date time'] = local_dict # Parsing # Restart by remote reset ret_dict['restart by'] = version_list[8:] # Parsing # Firmware Version: v91 line = version_list[11] if debug: print 'parsing:', line words = line.split() ret_dict['firmware version'] = words[2] # Parsing # *Booted Primary: StokeBoot Release 4.2 (2009120817). line = version_list[14] if debug: print '16 *Booted Primary: StokeBoot Release 4.2 (2009120817).' print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['primary'] = {'version': version, 'build id': build_id} # Parsing # Booted Backup: StokeBoot Release 4.2 (2009120817). line = version_list[15] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['backup'] = {'version': version, 'build id': build_id} ret_dict['stoke boot version'] = local_dict # Parsing # *Booted Primary: Stoke Bootloader Release 4.146X1B1S4 (2011061319). line = version_list[17] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['primary'] = {'version': version, 'build id': build_id} # Parsing # Booted Backup: Stoke Bootloader Release 4.6B1S4 (2011061319). line = version_list[18] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['backup'] = {'version': version, 'build id': build_id} ret_dict['stoke os version'] = local_dict else: if debug: print 'parsing output for selected card' print 'card is either in slot-2, slot-3 or slot-4' # sample input """ 0 1 Slot 2 Information (GLC2): 2 ---------------------------------------------------------------------------- 3 StokeOS Release 4.6B1S2 (2010062215). 4 Built Tue Jun 22 16:44:08 PDT 2010 by builder. 5 6 Card uptime is 12 hours, 25 minutes 7 8 Card restart at Thu Jun 23 02:33:34 PDT 2011 9 Restart by remote reset 10 11 Firmware Version: v91 12 13 Stoke MicroEngine Image Release 4.0 (2010062216 builder). 14 15 Stoke-Boot Version 16 *Booted Primary: StokeBoot Release 4.2 (2009120817). 17 Booted Backup: StokeBoot Release 4.2 (2009120817). 18 Stoke-Bloader Version 19 *Booted Primary: Stoke Bootloader Release 4.6B1S2 (2010062215). 20 Booted Backup: Stoke Bootloader Release 4.6B1S2 (2010062215). """ # Parsing # Card uptime is 2 minutes line = version_list[6] if debug: print 'parsing:', line words = line.split() if debug: print 'the split line contains:' print words local_dict = {} if len(words) == 5: local_dict['hour'] = 0 local_dict['minute'] = int(words[3]) else: local_dict['hour'] = int(words[3]) local_dict['minute'] = int(words[5]) ret_dict['card uptime'] = local_dict # Parsing # Card restart at Thu Jun 23 02:33:34 PDT 2011 line = version_list[8] if debug: print 'parsing:', line words = line.split() local_dict = {} local_dict['day of week'] = words[3] local_dict['month'] = words[4] local_dict['day of month'] = words[5] raw_time = words[6] time = raw_time.split(':') local_dict['hour'] = time[0] local_dict['minute'] = time[1] local_dict['second'] = time[2] local_dict['time zone'] = words[7] local_dict['year'] = words[8] ret_dict['card restart date time'] = local_dict # Parsing # Restart by remote reset ret_dict['restart by'] = version_list[8:] # Parsing # Firmware Version: v91 line = version_list[11] if debug: print 'parsing:', line words = line.split() ret_dict['firmware version'] = words[2] # Parsing # *Booted Primary: StokeBoot Release 4.2 (2009120817). line = version_list[16] if debug: print '16 *Booted Primary: StokeBoot Release 4.2 (2009120817).' print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['primary'] = {'version': version, 'build id': build_id} # Parsing # Booted Backup: StokeBoot Release 4.2 (2009120817). line = version_list[17] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['backup'] = {'version': version, 'build id': build_id} ret_dict['stoke boot version'] = local_dict # Parsing # *Booted Primary: Stoke Bootloader Release 4.146X1B1S4 (2011061319). line = version_list[19] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['primary'] = {'version': version, 'build id': build_id} # Parsing # Booted Backup: Stoke Bootloader Release 4.6B1S4 (2011061319). line = version_list[20] if debug: print 'parsing:', line words = line.split() local_dict = {} version = words[4] build_id = words[5].strip('().') local_dict['backup'] = {'version': version, 'build id': build_id} ret_dict['stoke os version'] = local_dict return ret_dict def show_environmental(self): """ Runs the command "shown environmental" and parses the output it then returns a nested dictionary """ debug = False # sample input """ 0 1 Environmental status as of Wed Jun 22 13:41:53 2011 2 Data polling interval is 60 second(s) 3 4 Voltage readings: 5 ================= 6 Slot Source Level 7 ---- ------ ------- 8 0 No errors detected 9 1 No errors detected 10 2 No errors detected 11 3 No errors detected 12 4 No errors detected 13 14 Temperature readings: 15 ===================== 16 Slot Source Level 17 ---- ------ ------- 18 0 No errors detected 19 1 No errors detected 20 2 No errors detected 21 3 No errors detected 22 4 No errors detected 23 24 25 Power status: 26 ============= 27 Slot Source Level 28 ---- ------ ------- 29 PEMA No errors detected 30 PEMB No errors detected 31 32 Fan status: 33 =========== 34 Slot Source Level 35 ---- ------ ------- 36 FANTRAY1 No errors detected 37 FANTRAY2 No errors detected 38 39 Alarm status: 40 ============= 41 No System-Wide Alarm triggered 42 ALARMM1 No errors detected """ if debug: print 'now in show_environmental in issu.py' ret_dict = {} command = 'show environmental' raw_environmental = self.cmd(command) environmental_lines = raw_environmental.splitlines() if debug: print 'the raw values are:' line_index = 0 for line in environmental_lines: print repr(line_index).ljust(2), line line_index = line_index + 1 # Now we parse the sections section_header = ['Voltage readings:','Temperature readings:','Power status:','Fan status:','Alarm status:'] crap_lines = ['=================','Slot Source Level','---- ------ -------', \ '=====================','=============', '==========='] local_dict = {} line_counter = 0 section_name = '' for line in environmental_lines[3:-4]: if debug: print 'now processing:' print line if len(line.strip()) > 1: if line in section_header: raw_section_name = line.strip(':') section_name = raw_section_name.lower() if debug: print 'clearing the local dictionary' local_dict = {} if debug: print 'local dictionary:', local_dict print 'found section header:', section_name elif line in crap_lines: if debug: print 'discarding this stuff:' print line pass else: words = line.split('\t') if debug: print 'the split line looks like:' print words try: slot = int(words[0]) except: slot = words[0] if len(words[1]) == 0: words.remove('') slot_name = 'slot ' + str(slot) local_dict[slot_name] = {} source = words[1].lstrip() local_dict[slot_name]['source'] = source if len(words) > 2: level = words[2] local_dict[slot_name]['level'] = level if debug: print 'the local dictionary for section:', section_name print local_dict else: if len(local_dict) > 1: ret_dict[section_name] = local_dict if debug: print '-------------------------------------------------------------' print 'storing the following local_dict values into the main ret_dict' print 'under section:', section_name local_dict_keys = local_dict.keys() for key in local_dict_keys: print key print '\t', local_dict[key] print 'here is the ret_dict' ret_dict_keys = ret_dict.keys() for key in ret_dict_keys: print key sub_keys = ret_dict[key].keys() for sub_key in sub_keys: print '\t', sub_key print '\t\t', ret_dict[key][sub_key] print '-------------------------------------------------------------' local_dict = {} general_alarm = environmental_lines[-2].strip('\t') local_dict['general status'] = general_alarm raw_alarmm1 = environmental_lines[-1].split('\t') if debug: print 'the last line contains:' print raw_alarmm1 alarmm1 = raw_alarmm1[2].lstrip(' ') local_dict['alarmm1'] = alarmm1 ret_dict['alarm status'] = local_dict return ret_dict def show_file_system(self): """ Runs the command "show file-system" which is a hidden command to display the disk utilization. It then parses the output and returns a nested dictionary of values. """ debug = False if debug: print 'now in show_file_system in issu.py' # Sample Input """ 0 1 Thu Jun 23 11:53:16 PDT 2011. 2 Name Size % Used Used Free 3 ---------------- -------------- ------ -------------- -------------- 4 /hd 40,012,611,584 16 6,551,703,552 33,460,908,032 5 /hdp 40,013,643,776 2 935,257,088 39,078,386,688 6 /cfint 128,974,848 11 14,220,800 114,754,048 7 /cfintp 130,007,040 0 53,248 129,953,792 """ ret_dict = {} command = 'show file-system' raw_file_system = self.cmd(command) file_system_lines = raw_file_system.splitlines() if debug: print 'the raw values are:' line_index = 0 for line in file_system_lines: print repr(line_index).ljust(2), line line_index = line_index + 1 for line in file_system_lines[4:]: local_dict = {} if debug: print 'now processing the following line:' print line words = line.split() if debug: print 'the split line contains:' print words mount_point = words[0].strip('\t/') local_dict['size'] = words[1] local_dict['percent used'] = words[2] local_dict['used'] = words[3] local_dict['free'] = words[4] if debug: print 'for the mount point:', mount_point print local_dict ret_dict[mount_point] = local_dict return ret_dict def show_versions(self): """Retrieves the versions installed on the system and returns a dictionary of them """ debug = False installed_packages = [] ## We need to see if the package is already installed on the system!! show_system_raw = self.cmd('show system') show_system_lines = show_system_raw.splitlines() # We will parse the linse last to first searching for two things # 1. Other Packages: # 2. In-Use Packages: # When we find the second item we will stop searching searching = True ndex = len(show_system_lines) - 1 if debug: print 'Found', ndex, 'lines' while searching: current_line = show_system_lines[ndex] if debug: print 'Parsing this line:', current_line word = current_line.split() # If the word is in the search list we don't want that line if not (word[0] in ('Other','In-Use','reverts')): print 'Found the following version installed:', word[0] installed_packages.append(word[0]) if word[0] == 'In-Use': print 'Found the last line. All versions read.' searching = False ndex = ndex - 1 if debug: print 'Found the following versions installed:' for item in installed_packages: print item print 'returning from issu.py show_versions' return installed_packages def show_versions_and_build(self): """Retrieves the versions installed on the system and returns a dictionary of them """ debug = False installed_packages = {} ## We need to see if the package is already installed on the system!! show_system_raw = self.cmd('show system') show_system_lines = show_system_raw.splitlines() # We will parse the linse last to first searching for two things # 1. Other Packages: # 2. In-Use Packages: # When we find the second item we will stop searching searching = True ndex = len(show_system_lines) - 1 if debug: print 'Found', ndex, 'lines' print '------------------------' while searching: current_line = show_system_lines[ndex] if debug: print 'Parsing this line:', current_line word = current_line.split() # If the word is in the search list we don't want that line if not (word[0] in ('Other','In-Use','reverts', 'ISSU')): print 'Found the following version installed:', word[0] if debug: print 'The version should be:', word[-1] version = word[0] raw_build_id = word[-1] build_id = raw_build_id[1:-3] if debug: print 'Build ID determined to be:', build_id installed_packages[version] = build_id if debug: print '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' if word[0] == 'In-Use': print 'Found the last line. All versions read.' searching = False ndex = ndex - 1 if debug: print 'Found the following versions installed:' for item in installed_packages: print item print 'returning from issu.py show_versions' return installed_packages def show_port(self): """ Runs the command "show port" and parses the ouptut """ debug = False # Sample raw imput """ Wed Dec 14 11:15:04 PDT 2011. Port Type Admin Link Speed Duplex Connector Medium MAC Address ----- ---- ------ ------ ----- ------ --------- ------ ----------------- 0/0 Eth Config Down 100M Full RJ45 Copper 00:12:73:00:0a:d0 1/0 Eth Up Up 100M Full RJ45 Copper 00:12:73:00:0a:d1 """ if debug: print 'now in issu.py show_port' port_dict = {} raw_port = self.cmd("show port") if debug: print 'the raw returned value was:' print raw_port port_list = raw_port.splitlines() if debug: line_index = 0 print 'the lines are:' for line in port_list: print line_index, line line_index = line_index + 1 labels_line = port_list[2].split() divider_line = port_list[3] columnDict = parse_divider_line(self,divider_line) if debug: print 'The columnDict is:' print columnDict for raw_line in port_list[4:]: line = raw_line local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() if debug: print 'The name is:', name local_dict["Type"] = line[0] for labels_idx in range(1,(len(labels_line) - 1)): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 local_dict[labels_line[labels_idx]] = line[start:end].strip() if debug: print("The %s is: %s " %(labels_line[labels_idx],local_dict[labels_line[labels_idx]])) # We store each entry in the main dictionary we return port_dict[name] = local_dict return port_dict ###### Anthony Ton code start here ######### def show_dos_counters(self, slot): """Runs the command 'show dos slot <0..4> counters' and parses the output. """ dos_dict = {} debug = False # Sample raw input """ kenya[local]#show dos slot 2 counters Total Drops -------------------------------------------------------------------------------- ARP : 0 0 Local TCP : 0 0 Local UDP : 0 0 Local ICMP : 0 0 IP4 MIP Exception : 0 0 IKE : 0 0 Local Adjacency : 0 0 ARP Transit : 0 0 IP4 Unreachable : 0 0 TTL Expired : 0 0 TTL Expired Encap : 0 0 IP4 Options : 0 0 Over MTU : 0 0 kenya[local]# # Sample dictionary output: { 'ARP': { 'Drops': '0', 'Total': '0'}, 'ARP Transit': { 'Drops': '0', 'Total': '0'}, 'IKE': { 'Drops': '0', 'Total': '0'}, 'IP4 MIP Exception': { 'Drops': '0', 'Total': '0'}, 'IP4 Options': { 'Drops': '0', 'Total': '0'}, 'IP4 Unreachable': { 'Drops': '0', 'Total': '0'}, 'Local Adjacency': { 'Drops': '0', 'Total': '0'}, 'Local ICMP': { 'Drops': '0', 'Total': '0'}, 'Local TCP': { 'Drops': '0', 'Total': '0'}, 'Local UDP': { 'Drops': '0', 'Total': '0'}, 'Over MTU': { 'Drops': '0', 'Total': '0'}, 'TTL Expired': { 'Drops': '0', 'Total': '0'}, 'TTL Expired Encap': { 'Drops': '0', 'Total': '0'}} """ command = "show dos slot " + slot + " counter" raw_dos_list = self.cmd(command) dos_list = raw_dos_list.splitlines() if debug: print 'The raw value returned was:' print dos_list if 'ERROR:' in raw_dos_list: print 'Detected an error when running: ' + command print 'Returned text was:' print raw_dos_list dos_dict['Status'] = 'Error' return dos_dict for raw_line in dos_list[3:]: line = raw_line.split(':') local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line name = line[0].strip() if debug: print 'The name is:', name raw_data = line[1].split(); local_dict['Total'] = raw_data[0] if debug: print 'The Total is:', local_dict['Total'] local_dict['Drops'] = raw_data[1] if debug: print 'The Drops is:', local_dict['Drops'] # We store each entry in the main dictionary we return dos_dict[name] = local_dict return dos_dict def show_fast_path_counters(self): """Runs the command 'show fast-path counters' and parses the output. """ fastpath_dict = {} debug = False # Sample raw input """ kenya[local]#show fast-path counters Slot Port Type Count ---- ---- ----------------------------- ----------------- 2 1 InvalidFib 748 3 1 InvalidFib 2,067 kenya[local]# # Sample dictionary output: { '2/0': { 'Count': '363', 'Type': 'Reserved4'}, '2/1': { 'Count': '82', 'Type': 'Reserved4'}} """ command = "show fast-path counters" raw_fastpath_counters_list = self.cmd(command) fastpath_counters_list = raw_fastpath_counters_list.splitlines() if debug: print 'The raw value returned was:' print fastpath_counters_list labels_line = fastpath_counters_list[1].split() for raw_line in fastpath_counters_list[3:]: line = raw_line.split() local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line name = line[0] + "/" + line[1] if debug: print 'The name is:', name for labels_idx in range(2,len(labels_line)): local_dict[labels_line[labels_idx]] = line[labels_idx] if debug: print("The %s is: %s " %(labels_line[labels_idx],local_dict[labels_line[labels_idx]])) # We store each entry in the main dictionary we return fastpath_dict[name] = local_dict return fastpath_dict def parse_divider_line(self,str,divChar='-'): """ Parse the divider line and return a dictionary of length of each column in format {column#:[length,start,end],...,column#n:[start,end]} Example: "----- ---- ---------- ---" return {0:[0,4],1:[6,9],2:[11,20],3:[22,24]} """ local_dict = {} column = 0 startFound = False endFound = False for idx in range(0,len(str)): if (str[idx] == divChar) and not startFound: start = idx startFound = True endFound = False elif (str[idx] == ' ') and startFound: end = idx - 1 startFound = False endFound = True local_dict[column] = [start,end] column += 1 if startFound and (not endFound): # the last column has not been accounted for local_dict[column] = [start,len(str)-1] return local_dict def show_ip_ospf_route(self): """Runs the command 'show ip ospf route [detail]' and parses the output. """ ipOspfRoute_dict = {} debug = False # Sample raw input """ kenya[stoke]#show ip ospf route Network/Mask Cost Cost2 Nexthop Interface Area-ID ------------------ ----- ----- --------------- -------------- --------------- O 10.254.1.0/24 1 direct isp 0.0.0.0 O 11.11.11.11/32 1 direct lo0 0.0.0.0 kenya[stoke]# """ command = "show ip ospf route " raw_ip_ospf_route_list = self.cmd(command) ip_ospf_route_list = raw_ip_ospf_route_list.splitlines() if debug: print 'The raw value returned was:' print ip_ospf_route_list if 'ERROR:' in ip_ospf_route_list[1]: print 'Detected an error when running: ' + command print 'Returned text was:' print raw_ip_ospf_route_list ipOspfRoute_dict['Status'] = 'Error' return ipOspfRoute_dict labels_line = ip_ospf_route_list[1].split() divider_line = ip_ospf_route_list[2] columnDict = parse_divider_line(self,divider_line) if debug: print 'The columnDict is:' print columnDict for raw_line in ip_ospf_route_list[3:]: line = raw_line local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() if debug: print 'The name is:', name local_dict["Type"] = line[0] for labels_idx in range(1,len(labels_line)): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 local_dict[labels_line[labels_idx]] = line[start:end].strip() if debug: print("The %s is: %s " %(labels_line[labels_idx],local_dict[labels_line[labels_idx]])) # We store each entry in the main dictionary we return ipOspfRoute_dict[name] = local_dict return ipOspfRoute_dict def show_module_iked_slot_ma_pp_detail(self,slot): """Runs the command 'show module iked slot <slot> ma pp detail' and parses the output. """ modIkedMaPpDetail_dict = {} debug = False # Sample raw input """ kenya[local]#show module iked slot 2 ma pp detail _global_: User Element Size................0 User Init Elements..............0 User Grow Elements...............0 Max Elements....................0 Element Size.....................0 Grow Size.......................0 Initial Elements.................0 Grow Elements...................0 Elements In Use..................0 Allocations....................41 Frees............................0 Max Elements In Use.............0 HALibHAPP::0: User Element Size..............384 User Init Elements.............64 User Grow Elements..............64 Max Elements...................64 Element Size...................396 Grow Size..................28,672 Initial Elements................64 Grow Elements..................64 Elements In Use.................13 Allocations....................13 Frees............................0 Max Elements In Use............13 HALibHAGlobCB::0: User Element Size..............192 User Init Elements.............16 User Grow Elements..............16 Max Elements...................16 Element Size...................204 Grow Size...................4,096 Initial Elements................16 Grow Elements..................16 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 HALibAsyncCB::0: User Element Size...............48 User Init Elements..........1,024 User Grow Elements...........1,024 Max Elements........4,294,967,295 Element Size....................60 Grow Size..................65,536 Initial Elements.............1,024 Grow Elements...............1,024 Elements In Use..................0 Allocations................31,674 Frees.......................31,674 Max Elements In Use.............2 IKE Session Pool:17::0: User Element Size............2,120 User Init Elements..........8,000 User Grow Elements...........8,000 Max Elements...............91,216 Element Size.................2,132 Grow Size.................520,192 Initial Elements.............8,000 Grow Elements...............8,000 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV2 SA Pool:17::0: User Element Size............1,120 User Init Elements..........8,000 User Grow Elements...........8,000 Max Elements..............273,648 Element Size.................1,132 Grow Size.................520,192 Initial Elements.............8,000 Grow Elements...............8,000 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 ph1 pool:17::0: User Element Size............1,816 User Init Elements..........8,000 User Grow Elements...........8,000 Max Elements...............45,608 Element Size.................1,828 Grow Size.................520,192 Initial Elements.............8,000 Grow Elements...............8,000 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 natt opt pool:17::0: User Element Size..............132 User Init Elements..........8,000 User Grow Elements...........8,000 Max Elements...............45,608 Element Size...................144 Grow Size.................520,192 Initial Elements.............8,000 Grow Elements...............8,000 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 ph2 pool:17::0: User Element Size..............656 User Init Elements..........8,000 User Grow Elements...........8,000 Max Elements...............45,608 Element Size...................668 Grow Size.................520,192 Initial Elements.............8,000 Grow Elements...............8,000 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 ph2 app pool:17::0: User Element Size..............240 User Init Elements..........4,096 User Grow Elements...........4,096 Max Elements...............22,804 Element Size...................252 Grow Size.................520,192 Initial Elements.............4,096 Grow Elements...............4,096 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 ph2 app pool:17::1: User Element Size..............368 User Init Elements..........2,048 User Grow Elements...........2,048 Max Elements...............22,804 Element Size...................380 Grow Size.................520,192 Initial Elements.............2,048 Grow Elements...............2,048 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKE SA Info Pool:17::0: User Element Size..............824 User Init Elements.........16,000 User Grow Elements..........16,000 Max Elements..............547,296 Element Size...................836 Grow Size.................520,192 Initial Elements............16,000 Grow Elements..............16,000 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 OUT SA Block HA Poo:17::0: User Element Size..............640 User Init Elements............356 User Grow Elements.............356 Max Elements................5,696 Element Size...................652 Grow Size.................233,472 Initial Elements...............356 Grow Elements.................356 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKE Counter HA Pool:17::0: User Element Size..............560 User Init Elements..............4 User Grow Elements...............4 Max Elements....................4 Element Size...................572 Grow Size...................3,072 Initial Elements.................4 Grow Elements...................4 Elements In Use..................1 Allocations.....................1 Frees............................0 Max Elements In Use.............1 ISAKMP Statistics H:17::0: User Element Size..............428 User Init Elements..............4 User Grow Elements...............4 Max Elements....................4 Element Size...................440 Grow Size...................2,048 Initial Elements.................4 Grow Elements...................4 Elements In Use..................1 Allocations.....................1 Frees............................0 Max Elements In Use.............1 Tunmgr ha pool:17::0: User Element Size..............192 User Init Elements..........8,000 User Grow Elements...........8,000 Max Elements..............364,864 Element Size...................204 Grow Size.................520,192 Initial Elements.............8,000 Grow Elements...............8,000 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV2 last response:17::0: User Element Size..............368 User Init Elements..............4 User Grow Elements...............4 Max Elements..............273,648 Element Size...................380 Grow Size...................2,048 Initial Elements.................4 Grow Elements...................4 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV2 last response:17::1: User Element Size..............624 User Init Elements..............4 User Grow Elements...............4 Max Elements..............273,648 Element Size...................636 Grow Size...................3,072 Initial Elements.................4 Grow Elements...................4 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV2 last response:17::2: User Element Size............1,136 User Init Elements..............4 User Grow Elements...............4 Max Elements..............273,648 Element Size.................1,148 Grow Size...................5,120 Initial Elements.................4 Grow Elements...................4 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV2 last response:17::3: User Element Size............2,160 User Init Elements..............4 User Grow Elements...............4 Max Elements..............273,648 Element Size.................2,172 Grow Size..................12,288 Initial Elements.................4 Grow Elements...................4 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV1 Last Resp HA :17::0: User Element Size..............368 User Init Elements..............4 User Grow Elements...............4 Max Elements..............273,648 Element Size...................380 Grow Size...................2,048 Initial Elements.................4 Grow Elements...................4 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV1 Last Resp HA :17::1: User Element Size..............624 User Init Elements..............4 User Grow Elements...............4 Max Elements..............273,648 Element Size...................636 Grow Size...................3,072 Initial Elements.................4 Grow Elements...................4 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV1 Last Resp HA :17::2: User Element Size............1,136 User Init Elements..............4 User Grow Elements...............4 Max Elements..............273,648 Element Size.................1,148 Grow Size...................5,120 Initial Elements.................4 Grow Elements...................4 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 IKEV1 Last Resp HA :17::3: User Element Size............2,160 User Init Elements..............4 User Grow Elements...............4 Max Elements..............273,648 Element Size.................2,172 Grow Size..................12,288 Initial Elements.................4 Grow Elements...................4 Elements In Use..................0 Allocations.....................0 Frees............................0 Max Elements In Use.............0 kenya[local]# # Sample dictionary output { 'HALibAsyncCB::0:': { 'Allocations': '1,446', 'Element Size': '60', 'Elements In Use': '0', 'Frees': '1,446', 'Grow Elements': '1,024', 'Grow Size': '65,536', 'Initial Elements': '1,024', 'Max Elements': '4,294,967,295', 'Max Elements In Use': '1', 'User Element Size': '48', 'User Grow Elements': '1,024', 'User Init Elements': '1,024'}, 'HALibHAGlobCB::0:': { 'Allocations': '0', 'Element Size': '204', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '16', 'Grow Size': '4,096', 'Initial Elements': '16', 'Max Elements': '16', 'Max Elements In Use': '0', 'User Element Size': '192', 'User Grow Elements': '16', 'User Init Elements': '16'}, 'HALibHAPP::0:': { 'Allocations': '13', 'Element Size': '396', 'Elements In Use': '13', 'Frees': '0', 'Grow Elements': '64', 'Grow Size': '28,672', 'Initial Elements': '64', 'Max Elements': '64', 'Max Elements In Use': '13', 'User Element Size': '384', 'User Grow Elements': '64', 'User Init Elements': '64'}, 'IKE Counter HA Pool:17::0:': { 'Allocations': '1', 'Element Size': '572', 'Elements In Use': '1', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '3,072', 'Initial Elements': '4', 'Max Elements': '4', 'Max Elements In Use': '1', 'User Element Size': '560', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'IKE SA Info Pool:17::0:': { 'Allocations': '0', 'Element Size': '836', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '16,000', 'Grow Size': '520,192', 'Initial Elements': '16,000', 'Max Elements': '1,447,296', 'Max Elements In Use': '0', 'User Element Size': '824', 'User Grow Elements': '16,000', 'User Init Elements': '16,000'}, 'IKE Session Pool:17::0:': { 'Allocations': '0', 'Element Size': '2,132', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '8,000', 'Grow Size': '520,192', 'Initial Elements': '8,000', 'Max Elements': '241,216', 'Max Elements In Use': '0', 'User Element Size': '2,120', 'User Grow Elements': '8,000', 'User Init Elements': '8,000'}, 'IKEV1 Last Resp HA :17::0:': { 'Allocations': '0', 'Element Size': '380', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '2,048', 'Initial Elements': '4', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '368', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'IKEV1 Last Resp HA :17::1:': { 'Allocations': '0', 'Element Size': '636', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '3,072', 'Initial Elements': '4', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '624', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'IKEV1 Last Resp HA :17::2:': { 'Allocations': '0', 'Element Size': '1,148', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '5,120', 'Initial Elements': '4', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '1,136', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'IKEV1 Last Resp HA :17::3:': { 'Allocations': '0', 'Element Size': '2,172', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '12,288', 'Initial Elements': '4', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '2,160', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'IKEV2 SA Pool:17::0:': { 'Allocations': '0', 'Element Size': '1,132', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '8,000', 'Grow Size': '520,192', 'Initial Elements': '8,000', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '1,120', 'User Grow Elements': '8,000', 'User Init Elements': '8,000'}, 'IKEV2 last response:17::0:': { 'Allocations': '0', 'Element Size': '380', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '2,048', 'Initial Elements': '4', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '368', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'IKEV2 last response:17::1:': { 'Allocations': '0', 'Element Size': '636', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '3,072', 'Initial Elements': '4', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '624', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'IKEV2 last response:17::2:': { 'Allocations': '0', 'Element Size': '1,148', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '5,120', 'Initial Elements': '4', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '1,136', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'IKEV2 last response:17::3:': { 'Allocations': '0', 'Element Size': '2,172', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '12,288', 'Initial Elements': '4', 'Max Elements': '723,648', 'Max Elements In Use': '0', 'User Element Size': '2,160', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'ISAKMP Statistics H:17::0:': { 'Allocations': '1', 'Element Size': '440', 'Elements In Use': '1', 'Frees': '0', 'Grow Elements': '4', 'Grow Size': '2,048', 'Initial Elements': '4', 'Max Elements': '4', 'Max Elements In Use': '1', 'User Element Size': '428', 'User Grow Elements': '4', 'User Init Elements': '4'}, 'OUT SA Block HA Poo:17::0:': { 'Allocations': '0', 'Element Size': '652', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '942', 'Grow Size': '520,192', 'Initial Elements': '942', 'Max Elements': '15,072', 'Max Elements In Use': '0', 'User Element Size': '640', 'User Grow Elements': '942', 'User Init Elements': '942'}, 'Tunmgr ha pool:17::0:': { 'Allocations': '0', 'Element Size': '204', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '8,000', 'Grow Size': '520,192', 'Initial Elements': '8,000', 'Max Elements': '964,864', 'Max Elements In Use': '0', 'User Element Size': '192', 'User Grow Elements': '8,000', 'User Init Elements': '8,000'}, '_global_:': { 'Allocations': '41', 'Element Size': '0', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '0', 'Grow Size': '0', 'Initial Elements': '0', 'Max Elements': '0', 'Max Elements In Use': '0', 'User Element Size': '0', 'User Grow Elements': '0', 'User Init Elements': '0'}, 'natt opt pool:17::0:': { 'Allocations': '0', 'Element Size': '144', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '8,000', 'Grow Size': '520,192', 'Initial Elements': '8,000', 'Max Elements': '120,608', 'Max Elements In Use': '0', 'User Element Size': '132', 'User Grow Elements': '8,000', 'User Init Elements': '8,000'}, 'ph1 pool:17::0:': { 'Allocations': '0', 'Element Size': '1,828', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '8,000', 'Grow Size': '520,192', 'Initial Elements': '8,000', 'Max Elements': '120,608', 'Max Elements In Use': '0', 'User Element Size': '1,816', 'User Grow Elements': '8,000', 'User Init Elements': '8,000'}, 'ph2 app pool:17::0:': { 'Allocations': '0', 'Element Size': '252', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '4,096', 'Grow Size': '520,192', 'Initial Elements': '4,096', 'Max Elements': '60,304', 'Max Elements In Use': '0', 'User Element Size': '240', 'User Grow Elements': '4,096', 'User Init Elements': '4,096'}, 'ph2 app pool:17::1:': { 'Allocations': '0', 'Element Size': '380', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '2,048', 'Grow Size': '520,192', 'Initial Elements': '2,048', 'Max Elements': '60,304', 'Max Elements In Use': '0', 'User Element Size': '368', 'User Grow Elements': '2,048', 'User Init Elements': '2,048'}, 'ph2 pool:17::0:': { 'Allocations': '0', 'Element Size': '668', 'Elements In Use': '0', 'Frees': '0', 'Grow Elements': '8,000', 'Grow Size': '520,192', 'Initial Elements': '8,000', 'Max Elements': '120,608', 'Max Elements In Use': '0', 'User Element Size': '656', 'User Grow Elements': '8,000', 'User Init Elements': '8,000'}} """ command = "show module iked slot " + slot + " ma pp detail" raw_modIkedMaPpDetail_list = self.cmd(command) modIkedMaPpDetail_list = raw_modIkedMaPpDetail_list.splitlines() if debug: print 'The raw value returned was:' print modIkedMaPpDetail_list if 'ERROR:' in raw_modIkedMaPpDetail_list: print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modIkedMaPpDetail_list modIkedMaPpDetail_dict['Status'] = 'Error' return modIkedMaPpDetail_dict name = None local_dict = {} for raw_line in modIkedMaPpDetail_list[1:]: line = raw_line.strip() if debug: print '----------------------------------------------' print 'The line to be processed is:' print line # if the last character is :, then it is the name if debug: print("Last char is %s" %line[len(line)-1]) if line[len(line)-1] == ":": if name != None: # Done with previous name, save it to main dictionary modIkedMaPpDetail_dict[name] = local_dict local_dict = {} name = line if debug: print 'The name is:', name else: p = re.compile('(?P<name1>[A-Za-z ]*)\.+(?P<value1>[\d,]+)\s+(?P<name2>[A-Za-z ]*)\.+(?P<value2>[\d,]+)') m = p.search(line) if m: dict = m.groupdict() if debug: print("The dict is: %s " %dict) local_dict[dict['name1']] = dict['value1'] local_dict[dict['name2']] = dict['value2'] if debug: print("The %s is: %s " %(dict['name1'],local_dict[dict['name1']])) print("The %s is: %s " %(dict['name2'],local_dict[dict['name2']])) # We store last entry in the main dictionary we return modIkedMaPpDetail_dict[name] = local_dict return modIkedMaPpDetail_dict def show_module_iked_slot_ma_pool(self,slot): """Runs the command 'show module iked slot <slot> ma pool' and parses the output. """ modIkedMaPool_dict = {} debug = False # Sample raw input """ Stoke[local]#show module iked slot 2 ma pools Name Size InUse Free Allocs Frees ---------------- ------------- --------- --------- ------------- ------------- DaSet 128 64 6 64 0 DaJudy 40 49 2,075 22,442 22,393 DaJudy 72 2 2,093 27 25 DaJudy 136 10 514 19 9 CrhHandleData 60 5 35 5 0 CrhRegData 32 1 42 1 0 CrhCmdBlk 8,224 5 3 5 0 NvTimer 56 5 7,643 8,233 8,228 IpcConnIds 28 12 36 12 0 IpcArepIds 28 6 42 7 1 IpcReg 156 9 26 9 0 IpcConn 400 10 29 12 2 IpcRegmsg 8 9 19 9 0 IpcAsyncReply 344 6 10 7 1 IpcSndrArep 36 3 15 3 0 IpcThrEnt 36 0 18 10 10 IpcThrData 28 0 22 86 86 IpcRmReg 24 9 44 9 0 IpcRmInfo 36 1 145 25 24 IpcAmInfo 72 2 142 6,814 6,812 MsgVerPool 176 5 16 5 0 IpcTrWantReg 28 8 40 8 0 IpcTrRegac 76 14 19 15 1 IpcTrRegpc 72 14 21 15 1 IpcTrReg 84 9 32 9 0 IpcTrConn 388 10 30 12 2 IpcTrConnG 188 10 25 12 2 IpcTrSlot 64 10 28 12 2 IpcTrNode 112 10 22 12 2 IpcTrRegacI 28 14 34 15 1 IpcTrRegpcI 28 14 34 15 1 IpcTrCgIds 28 12 36 12 0 IpcPeer 48 14 18 14 0 IpcPeerMsgData 80 0 20 81 81 IpcPeerMsg 56 0 28 72 72 IpcQnxReg 80 9 23 9 0 IpcQnxConn 12 4 56 6 2 IpcTcpReg 52 9 37 9 0 IpcTcpConn 16 6 54 7 1 IpcTcpRegpc 104 14 20 15 1 IpcMsgReg 52 9 37 9 0 IpcMsgConn 124 16 20 19 3 NvMsg 8,300 6 26 13,710 13,704 EvtStateNotify 32 1 19 1 0 EvtCrhCallBack 8 0 28 15 15 EvtRegWait 40 0 17 1 1 H:CMOHandler 20 3 153 3 0 H:CMOHandler 20 2 154 2 0 H:CMOHandler 20 28 128 28 0 H:CMOHandler 20 1 155 1 0 CMOHandlerPool 12 34 2,010 34 0 CMOObjectPool 8,080 0 64 2 2 IKEd-var-pool 24 1,555 12,891 3,740 2,185 IKEd-var-pool 40 1 10,000 10,056 10,055 IKEd-var-pool 72 1 6,190 6 5 IKEd-var-pool 136 4 3,509 6 2 IKEd-var-pool 264 0 1,884 8 8 IKEd-var-pool 520 1 976 2 1 IKE global struc 848 1 1 1 0 DH pool 44 10,050 8,522 10,050 0 RNG pool 36 2,000 2,008 2,000 0 cdpipc 1,460 1 352 1 0 JobResult 44 0 4,166 12,050 12,050 JobDesc 272 0 1,831 12,050 12,050 JobHandle 72 0 6,191 12,050 12,050 Func pool 20 55 325 55 0 sess mgmt pool 32 0 1,114 4,117 4,117 iked_sess_h 32 1 3,999 1 0 p1 policy pool 2,636 0 50 1 1 p2 policy pool 96 0 55 1 1 DArbn:IKED_P1_MA 20 1 27 2 1 p1 map pool 696 0 51 1 1 DArbn:IKED_P2_MA 20 1 27 2 1 p2 map pool 52 0 62 1 1 DArbn:IKED_IP_P1 20 1 27 1 0 DArbn:IKED_IP_P2 20 1 27 1 0 DArbn:IKED_XAUTH 20 1 27 1 0 DArbn:IKED_IP_XA 20 1 27 1 0 DAt:IKEDV2_RCF_R 20 0 8,060 5 5 DAt:IKEDV2_RCF_S 20 0 8,060 3 3 80 objects displayed. Stoke[local]# # Sample dictionary output { 'CMOHandlerPool': { 'Allocs': '34', 'Free': '2,010', 'Frees': '0', 'InUse': '34', 'Size': '12'}, 'CMOObjectPool': { 'Allocs': '1', 'Free': '64', 'Frees': '1', 'InUse': '0', 'Size': '8,080'}, 'CrhCmdBlk': { 'Allocs': '4', 'Free': '4', 'Frees': '0', 'InUse': '4', 'Size': '8,224'}, 'CrhHandleData': { 'Allocs': '5', 'Free': '35', 'Frees': '0', 'InUse': '5', 'Size': '60'}, 'CrhRegData': { 'Allocs': '1', 'Free': '42', 'Frees': '0', 'InUse': '1', 'Size': '32'}, 'DArbn:IKED_IP_P1': { 'Allocs': '1', 'Free': '27', 'Frees': '0', 'InUse': '1', 'Size': '20'}, 'DArbn:IKED_IP_P2': { 'Allocs': '1', 'Free': '27', 'Frees': '0', 'InUse': '1', 'Size': '20'}, 'DArbn:IKED_IP_XA': { 'Allocs': '1', 'Free': '27', 'Frees': '0', 'InUse': '1', 'Size': '20'}, 'DArbn:IKED_P1_MA': { 'Allocs': '1', 'Free': '27', 'Frees': '0', 'InUse': '1', 'Size': '20'}, 'DArbn:IKED_P2_MA': { 'Allocs': '1', 'Free': '27', 'Frees': '0', 'InUse': '1', 'Size': '20'}, 'DArbn:IKED_XAUTH': { 'Allocs': '1', 'Free': '27', 'Frees': '0', 'InUse': '1', 'Size': '20'}, 'DH pool': { 'Allocs': '10,050', 'Free': '8,522', 'Frees': '0', 'InUse': '10,050', 'Size': '44'}, 'DaJudy': { 'Allocs': '12,146', 'Free': '2,078', 'Frees': '12,100', 'InUse': '46', 'Size': '40'}, 'DaJudy_1': { 'Allocs': '24', 'Free': '2,093', 'Frees': '22', 'InUse': '2', 'Size': '72'}, 'DaJudy_2': { 'Allocs': '17', 'Free': '514', 'Frees': '7', 'InUse': '10', 'Size': '136'}, 'DaSet': { 'Allocs': '64', 'Free': '6', 'Frees': '0', 'InUse': '64', 'Size': '128'}, 'EvtCrhCallBack': { 'Allocs': '3', 'Free': '28', 'Frees': '3', 'InUse': '0', 'Size': '8'}, 'EvtRegWait': { 'Allocs': '1', 'Free': '17', 'Frees': '1', 'InUse': '0', 'Size': '40'}, 'EvtStateNotify': { 'Allocs': '1', 'Free': '19', 'Frees': '0', 'InUse': '1', 'Size': '32'}, 'Func pool': { 'Allocs': '55', 'Free': '325', 'Frees': '0', 'InUse': '55', 'Size': '20'}, 'H:CMOHandler': { 'Allocs': '3', 'Free': '153', 'Frees': '0', 'InUse': '3', 'Size': '20'}, 'H:CMOHandler_1': { 'Allocs': '2', 'Free': '154', 'Frees': '0', 'InUse': '2', 'Size': '20'}, 'H:CMOHandler_2': { 'Allocs': '28', 'Free': '128', 'Frees': '0', 'InUse': '28', 'Size': '20'}, 'H:CMOHandler_3': { 'Allocs': '1', 'Free': '155', 'Frees': '0', 'InUse': '1', 'Size': '20'}, 'IKE global struc': { 'Allocs': '1', 'Free': '1', 'Frees': '0', 'InUse': '1', 'Size': '848'}, 'IKEd-var-pool': { 'Allocs': '3,543', 'Free': '12,904', 'Frees': '2,001', 'InUse': '1,542', 'Size': '24'}, 'IKEd-var-pool_1': { 'Allocs': '10,052', 'Free': '10,000', 'Frees': '10,051', 'InUse': '1', 'Size': '40'}, 'IKEd-var-pool_2': { 'Allocs': '4', 'Free': '6,189', 'Frees': '2', 'InUse': '2', 'Size': '72'}, 'IKEd-var-pool_3': { 'Allocs': '5', 'Free': '3,510', 'Frees': '2', 'InUse': '3', 'Size': '136'}, 'IKEd-var-pool_4': { 'Allocs': '2', 'Free': '1,884', 'Frees': '2', 'InUse': '0', 'Size': '264'}, 'IKEd-var-pool_5': { 'Allocs': '2', 'Free': '976', 'Frees': '1', 'InUse': '1', 'Size': '520'}, 'IpcAmInfo': { 'Allocs': '2', 'Free': '144', 'Frees': '2', 'InUse': '0', 'Size': '72'}, 'IpcArepIds': { 'Allocs': '5', 'Free': '43', 'Frees': '0', 'InUse': '5', 'Size': '28'}, 'IpcAsyncReply': { 'Allocs': '5', 'Free': '11', 'Frees': '0', 'InUse': '5', 'Size': '344'}, 'IpcConn': { 'Allocs': '12', 'Free': '29', 'Frees': '2', 'InUse': '10', 'Size': '400'}, 'IpcConnIds': { 'Allocs': '12', 'Free': '36', 'Frees': '0', 'InUse': '12', 'Size': '28'}, 'IpcMsgConn': { 'Allocs': '17', 'Free': '21', 'Frees': '2', 'InUse': '15', 'Size': '124'}, 'IpcMsgReg': { 'Allocs': '9', 'Free': '37', 'Frees': '0', 'InUse': '9', 'Size': '52'}, 'IpcPeer': { 'Allocs': '12', 'Free': '20', 'Frees': '0', 'InUse': '12', 'Size': '48'}, 'IpcPeerMsg': { 'Allocs': '62', 'Free': '28', 'Frees': '62', 'InUse': '0', 'Size': '56'}, 'IpcPeerMsgData': { 'Allocs': '71', 'Free': '20', 'Frees': '71', 'InUse': '0', 'Size': '80'}, 'IpcQnxConn': { 'Allocs': '6', 'Free': '56', 'Frees': '2', 'InUse': '4', 'Size': '12'}, 'IpcQnxReg': { 'Allocs': '9', 'Free': '23', 'Frees': '0', 'InUse': '9', 'Size': '80'}, 'IpcReg': { 'Allocs': '9', 'Free': '26', 'Frees': '0', 'InUse': '9', 'Size': '156'}, 'IpcRegmsg': { 'Allocs': '9', 'Free': '19', 'Frees': '0', 'InUse': '9', 'Size': '8'}, 'IpcRmInfo': { 'Allocs': '4', 'Free': '145', 'Frees': '3', 'InUse': '1', 'Size': '36'}, 'IpcRmReg': { 'Allocs': '9', 'Free': '44', 'Frees': '0', 'InUse': '9', 'Size': '24'}, 'IpcSndrArep': { 'Allocs': '3', 'Free': '15', 'Frees': '0', 'InUse': '3', 'Size': '36'}, 'IpcTcpConn': { 'Allocs': '5', 'Free': '55', 'Frees': '0', 'InUse': '5', 'Size': '16'}, 'IpcTcpReg': { 'Allocs': '9', 'Free': '37', 'Frees': '0', 'InUse': '9', 'Size': '52'}, 'IpcTcpRegpc': { 'Allocs': '13', 'Free': '21', 'Frees': '0', 'InUse': '13', 'Size': '104'}, 'IpcThrData': { 'Allocs': '73', 'Free': '22', 'Frees': '73', 'InUse': '0', 'Size': '28'}, 'IpcThrEnt': { 'Allocs': '6', 'Free': '18', 'Frees': '6', 'InUse': '0', 'Size': '36'}, 'IpcTrCgIds': { 'Allocs': '12', 'Free': '36', 'Frees': '0', 'InUse': '12', 'Size': '28'}, 'IpcTrConn': { 'Allocs': '12', 'Free': '30', 'Frees': '2', 'InUse': '10', 'Size': '388'}, 'IpcTrConnG': { 'Allocs': '12', 'Free': '25', 'Frees': '2', 'InUse': '10', 'Size': '188'}, 'IpcTrNode': { 'Allocs': '12', 'Free': '22', 'Frees': '2', 'InUse': '10', 'Size': '112'}, 'IpcTrReg': { 'Allocs': '9', 'Free': '32', 'Frees': '0', 'InUse': '9', 'Size': '84'}, 'IpcTrRegac': { 'Allocs': '13', 'Free': '20', 'Frees': '0', 'InUse': '13', 'Size': '76'}, 'IpcTrRegacI': { 'Allocs': '13', 'Free': '35', 'Frees': '0', 'InUse': '13', 'Size': '28'}, 'IpcTrRegpc': { 'Allocs': '13', 'Free': '22', 'Frees': '0', 'InUse': '13', 'Size': '72'}, 'IpcTrRegpcI': { 'Allocs': '13', 'Free': '35', 'Frees': '0', 'InUse': '13', 'Size': '28'}, 'IpcTrSlot': { 'Allocs': '12', 'Free': '28', 'Frees': '2', 'InUse': '10', 'Size': '64'}, 'IpcTrWantReg': { 'Allocs': '8', 'Free': '40', 'Frees': '0', 'InUse': '8', 'Size': '28'}, 'JobDesc': { 'Allocs': '12,050', 'Free': '1,831', 'Frees': '12,050', 'InUse': '0', 'Size': '272'}, 'JobHandle': { 'Allocs': '12,050', 'Free': '6,191', 'Frees': '12,050', 'InUse': '0', 'Size': '72'}, 'JobResult': { 'Allocs': '12,050', 'Free': '4,166', 'Frees': '12,050', 'InUse': '0', 'Size': '44'}, 'MsgVerPool': { 'Allocs': '5', 'Free': '16', 'Frees': '0', 'InUse': '5', 'Size': '176'}, 'NvMsg': { 'Allocs': '26', 'Free': '27', 'Frees': '21', 'InUse': '5', 'Size': '8,300'}, 'NvTimer': { 'Allocs': '1,659', 'Free': '7,643', 'Frees': '1,654', 'InUse': '5', 'Size': '56'}, 'Object Count': { 'Count': '74 objects displayed.'}, 'RNG pool': { 'Allocs': '2,000', 'Free': '2,008', 'Frees': '0', 'InUse': '2,000', 'Size': '36'}, 'cdpipc': { 'Allocs': '1', 'Free': '352', 'Frees': '0', 'InUse': '1', 'Size': '1,460'}, 'iked_sess_h': { 'Allocs': '1', 'Free': '3,999', 'Frees': '0', 'InUse': '1', 'Size': '32'}, 'sess mgmt pool': { 'Allocs': '828', 'Free': '1,114', 'Frees': '828', 'InUse': '0', 'Size': '32'}} """ command = "show module iked slot " + slot + " ma pool" raw_modIkedMaPool_list = self.cmd(command) modIkedMaPool_list = raw_modIkedMaPool_list.splitlines() if debug: print 'The raw value returned was:' print modIkedMaPool_list if 'ERROR:' in raw_modIkedMaPool_list: print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modIkedMaPool_list modIkedMaPool_dict['Status'] = 'Error' return modIkedMaPool_dict labels_line = modIkedMaPool_list[1].split() dupKey_dict = {} divider_line = modIkedMaPool_list[2] columnDict = parse_divider_line(self,divider_line) for raw_line in modIkedMaPool_list[3:]: line = raw_line if debug: print '----------------------------------------------' print 'The line to be processed is:' print line if "objects displayed" in line: # Save the objec count modIkedMaPool_dict["Object Count"] = {"Count":line} else: local_dict = {} start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() if debug: print 'The name is:', name for labels_idx in range(1,len(labels_line)): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 local_dict[labels_line[labels_idx]] = line[start:end].strip() if debug: print("The %s is: %s " %(labels_line[labels_idx],local_dict[labels_line[labels_idx]])) # We store last entry in the main dictionary we return if name in dupKey_dict: # for duplicate keys, append the index to the key ti differentiate between them dupKey_dict[name] += 1 name = name + "_" + `dupKey_dict[name]` modIkedMaPool_dict[name] = local_dict else: dupKey_dict[name] = 0 modIkedMaPool_dict[name] = local_dict return modIkedMaPool_dict def show_module_iked_slot_ma_shared(self,slot): """Runs the command 'show module iked slot <slot> ma share' and parses the output. """ modIkedMaShared_dict = {} debug = False # Sample raw input """ Stoke[local]#show module iked slot 2 ma shared Name/ Elements HiWat/ In Use/ Allocs/ Alloc Fail/ Pool Size Elem Size User Size Free Frees Double Free ---------------- --------- --------- --------- ------------- ----------- MBuf 97,340 4,109 4,099 18,935 0 211,812,352 2,176 2,144 93,241 14,836 0 FpdPage 4,964 1 1 1 0 20,971,520 4,224 4,192 4,963 0 0 Stoke[local]# # Sample dictionary output: { 'FpdPage': { 'Alloc Fail/': '0', 'Allocs/': '1', 'Double Free': '0', 'Elem Size': '4,224', 'Elements': '4,964', 'Free': '4,963', 'Frees': '0', 'HiWat/': '1', 'In Use/': '1', 'Pool Size': '20,971,520', 'User Size': '4,192'}, 'MBuf': { 'Alloc Fail/': '0', 'Allocs/': '4,099', 'Double Free': '0', 'Elem Size': '2,176', 'Elements': '97,340', 'Free': '93,241', 'Frees': '0', 'HiWat/': '4,099', 'In Use/': '4,099', 'Pool Size': '211,812,352', 'User Size': '2,144'}} """ command = "show module iked slot " + slot + " ma shared" raw_modIkedMaShared_list = self.cmd(command) modIkedMaShared_list = raw_modIkedMaShared_list.splitlines() if debug: print 'The raw value returned was:' print modIkedMaShared_list if 'ERROR:' in raw_modIkedMaShared_list: print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modIkedMaShared_list modIkedMaShared_dict['Status'] = 'Error' return modIkedMaShared_dict labels_line1 = modIkedMaShared_list[1] labels_line2 = modIkedMaShared_list[2] divider_line = modIkedMaShared_list[3] columnDict = parse_divider_line(self,divider_line) oddLine = False local_dict = {} for raw_line in modIkedMaShared_list[4:]: line = raw_line if debug: print '----------------------------------------------' print 'The line to be processed is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 #name = line[start:end].strip() if oddLine: labels_line = labels_line2 else: local_dict = {} labels_line = labels_line1 for idx in columnDict.keys(): start = columnDict[idx][0] end = columnDict[idx][1]+1 label = labels_line[start:end].strip() if (idx == 0) and (not oddLine): name = line[start:end].strip() if debug: print 'The name is:', name else: local_dict[label] = line[start:end].strip() if debug: print("The %s is: %s " %(label,local_dict[label])) # We store last entry in the main dictionary we return modIkedMaShared_dict[name] = local_dict if oddLine: oddLine = False else: oddLine = True return modIkedMaShared_dict def show_port_counters_drop(self,slotport): """Runs the command 'show port <slot/port> counters drop' and parses the output. """ portCountersDrop_dict = {} debug = False # Sample raw input """ Stoke[local]#show port 2/1 counters drop Port Drop Counters ----- -------------------------------------------- 2/1 Disabled Port: 0 CCT expects IPv4: 17626 Stoke[local]# # Sample dictionary output { '2/1': { 'Disabled Port': '0', 'Invalid FIB': '64'}} """ command = "show port " + slotport + " counters drop" raw_portCountersDrop_list = self.cmd(command) portCountersDrop_list = raw_portCountersDrop_list.splitlines() if debug: print 'The raw value returned was:' print portCountersDrop_list if ('ERROR:' in raw_portCountersDrop_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_portCountersDrop_list portCountersDrop_dict['Status'] = 'Error' return portCountersDrop_dict divider_line = portCountersDrop_list[2] columnDict = parse_divider_line(self,divider_line) local_dict = {} for raw_line in portCountersDrop_list[3:]: line = raw_line if debug: print '----------------------------------------------' print 'The line to be processed is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 tmp_name = line[start:end].strip() if tmp_name != "": name = tmp_name local_dict = {} if debug: print 'The name is:', name for idx in range(1,len(columnDict.keys())): start = columnDict[idx][0] end = columnDict[idx][1]+1 labelValue = line[start:end].strip().split(":") local_dict[labelValue[0].strip()] = labelValue[1].strip() if debug: print("The %s is: %s " %(labelValue[0],local_dict[labelValue[0]])) # We store last entry in the main dictionary we return portCountersDrop_dict[name] = local_dict return portCountersDrop_dict def show_process_cpu_non_zero(self): """Runs the command 'show process cpu non-zero' and parses the output. """ processCpuNonZero_dict = {} debug = False # Sample raw input """ Stoke[local]#show process cpu non-zero CPU0 Utilization for 5 seconds: 1.94% 1 Minute: 4.29% 5 Minutes: 4.14% CPU1 Utilization for 5 seconds: 0.01% 1 Minute: 0.15% 5 Minutes: 0.09% Name PID StartTime CPU uTime sTime % Now -------------- ------- ------------------------ --- ------ ------ ------ System:0 0 Sat Oct 01 11:01:44 all 38m21s 27.748 0.99% NSM:0 704514 Sat Oct 01 11:01:44 0 37m15s 2.553 1.09% Stoke[local]# # Sample dictionary output { 'CPU0 Utilization ': { 'fivemins': '2.54%', 'fivesecs': '21.03%', 'onemin': '3.02%'}, 'CPU1 Utilization ': { 'fivemins': '0.03%', 'fivesecs': '0.89%', 'onemin': '0.05%'}, 'Cli:0 ': { '% Now': '0.69%', 'CPU': '0', 'PID': '974895', 'StartTime': 'Fri Oct 07 20:35:03', 'sTime': '0.021', 'uTime': '0.423'}, 'Ip:0 ': { '% Now': '0.29%', 'CPU': '0', 'PID': '745500', 'StartTime': 'Fri Oct 07 19:39:21', 'sTime': '0.060', 'uTime': '0.451'}, 'NSM:0 ': { '% Now': '1.09%', 'CPU': '0', 'PID': '704514', 'StartTime': 'Fri Oct 07 19:39:10', 'sTime': '0.322', 'uTime': '38.418'}, 'System:0 ': { '% Now': '0.99%', 'CPU': 'all', 'PID': '0', 'StartTime': 'Fri Oct 07 19:39:11', 'sTime': '3.415', 'uTime': '50.834'}} """ command = "show process cpu non-zero" raw_processCpuNonZero_list = self.cmd(command) processCpuNonZero_list = raw_processCpuNonZero_list.splitlines() if debug: print 'The raw value returned was:' print processCpuNonZero_list # process the first two lines of output for idx in range(1,3): local_dict = {} line = processCpuNonZero_list[idx] p = re.compile('(?P<cpu>CPU. Utilization )for 5 seconds:\s+(?P<fivesecs>[\d.%]+)\s+1 Minute:\s+(?P<onemin>[\d.%]+)\s+5 Minutes:\s+(?P<fivemins>[\d.%]+)') m = p.search(line) if m: dict = m.groupdict() if debug: print("The dict is: %s " %dict) local_dict['fivesecs'] = dict['fivesecs'] if debug: print("The five seconds is: %s " %(local_dict['fivesecs'])) local_dict['onemin'] = dict['onemin'] if debug: print("The one minute is: %s " %(local_dict['onemin'])) local_dict['fivemins'] = dict['fivemins'] if debug: print("The five minutes is: %s " %(local_dict['fivemins'])) processCpuNonZero_dict[dict['cpu']] = local_dict labels_line = processCpuNonZero_list[4] divider_line = processCpuNonZero_list[5] columnDict = parse_divider_line(self,divider_line) for raw_line in processCpuNonZero_list[6:]: line = raw_line if debug: print '----------------------------------------------' print 'The line to be processed is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end] if debug: print 'The name is:', name local_dict = {} for idx in range(1,len(columnDict.keys())): start = columnDict[idx][0] end = columnDict[idx][1]+1 label = labels_line[start:end].strip() local_dict[label] = line[start:end].strip() if debug: print("The %s is: %s " %(label,local_dict[label])) # We store last entry in the main dictionary we return processCpuNonZero_dict[name] = local_dict return processCpuNonZero_dict def show_qos_red_slot(self,slot): """Runs the command 'show qos red slot <slot>' and parses the output. """ qosRedSlot_dict = {} debug = False # Sample raw input """ Stoke[local]#show qos red slot 2 average current port queue weight queue depth queue depth red drops red tail drops ---- ----- -------- ----------- ----------- -------------- -------------- 0 nct 1/1 0 0 0 0 ct 1/1 0 0 0 0 ef 1/1 0 0 0 0 af4 1/1 0 0 0 0 af3 1/1 0 0 0 0 af2 1/1 0 0 0 0 af1 1/1 0 0 0 0 be 1/1 0 0 0 0 1 nct 1/1 0 0 0 0 ct 1/1 0 0 0 0 ef 1/1 0 0 0 0 af4 1/1 0 0 0 0 af3 1/1 0 0 0 0 af2 1/1 0 0 0 0 af1 1/1 0 0 0 0 be 1/1 0 0 0 0 2 nct 1/1 0 0 0 0 ct 1/1 0 0 0 0 ef 1/1 0 0 0 0 af4 1/1 0 0 0 0 af3 1/1 0 0 0 0 af2 1/1 0 0 0 0 af1 1/1 0 0 0 0 be 1/1 0 0 0 0 3 nct 1/1 0 0 0 0 ct 1/1 0 0 0 0 ef 1/1 0 0 0 0 af4 1/1 0 0 0 0 af3 1/1 0 0 0 0 af2 1/1 0 0 0 0 af1 1/1 0 0 0 0 be 1/1 0 0 0 0 Stoke[local]# # Sample dictionary output { '0 - af1': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '0 - af2': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '0 - af3': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '0 - af4': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '0 - be': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '0 - ct': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '0 - ef': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '0 - nct': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '1 - af1': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '1 - af2': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '1 - af3': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '1 - af4': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '1 - be': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '1 - ct': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '1 - ef': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '1 - nct': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '2 - af1': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '2 - af2': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '2 - af3': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '2 - af4': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '2 - be': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '2 - ct': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '2 - ef': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '2 - nct': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '3 - af1': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '3 - af2': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '3 - af3': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '3 - af4': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '3 - be': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '3 - ct': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '3 - ef': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}, '3 - nct': { 'average queue depth': '0', 'current queue depth': '0', 'red drops': '0', 'red tail drops': '0', 'weight': '1/1'}} """ command = "show qos red slot " + slot raw_qosRedSlot_list = self.cmd(command) qosRedSlot_list = raw_qosRedSlot_list.splitlines() if debug: print 'The raw value returned was:' print qosRedSlot_list if ('ERROR:' in raw_qosRedSlot_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_qosRedSlot_list qosRedSlot_dict['Status'] = 'Error' return qosRedSlot_dict labels_line1 = qosRedSlot_list[1] labels_line2 = qosRedSlot_list[2] divider_line = qosRedSlot_list[3] columnDict = parse_divider_line(self,divider_line) for raw_line in qosRedSlot_list[4:]: line = raw_line.expandtabs(columnDict[1][0]) if debug: print '----------------------------------------------' print 'The line to be processed is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 tmp_name = line[start:end].strip() if tmp_name != "": name = "%s/%s" %(slot,tmp_name) local_dict = {} if debug: print 'The name is:', name else: tmp_dict = {} start = columnDict[1][0] end = columnDict[1][1]+1 qname = line[start:end].strip() for idx in range(2,len(columnDict.keys())): start = columnDict[idx][0] end = columnDict[idx][1]+1 label = labels_line1[start:end].strip() + " " + labels_line2[start:end].strip() label = label.strip() tmp_dict[label] = line[start:end].strip() if debug: print("The %s is: %s " %(label,tmp_dict[label])) local_dict[qname] = tmp_dict qosRedSlot_dict[name] = local_dict return qosRedSlot_dict def show_port_counters(self): """Runs the command 'show port counters' and parses the output. """ portCounters_dict = {} debug = False # Sample raw input """ Stoke[local]#show port counter Wed Oct 5 04:15:01 UTC 2011. Port Input Packets Input Octets Output Packets Output Octets ----- ---------------- ------------------ ---------------- ------------------ 0/0 22907 1709566 3926 308871 1/0 0 0 0 0 2/0 89288 7579994 76301 6534824 2/1 86243 7314258 76124 6506526 3/0 1660 157990 1926 127614 3/1 1678 159519 114 11646 4/0 17355 1377341 16934 1391282 4/1 14305 1117637 17561 1407530 Stoke[local]# # Sample dictionary output { '0/0': { 'Input Octets': '328099', 'Input Packets': '3020', 'Output Octets': '91680', 'Output Packets': '684'}, '1/0': { 'Input Octets': '0', 'Input Packets': '0', 'Output Octets': '0', 'Output Packets': '0'}, '2/0': { 'Input Octets': '32402', 'Input Packets': '221', 'Output Octets': '0', 'Output Packets': '0'}, '2/1': { 'Input Octets': '21164', 'Input Packets': '51', 'Output Octets': '0', 'Output Packets': '0'}} """ command = "show port counters" raw_portCounters_list = self.cmd(command) portCounters_list = raw_portCounters_list.splitlines() if debug: print 'The raw value returned was:' print portCounters_list labels_line = portCounters_list[2] divider_line = portCounters_list[3] columnDict = parse_divider_line(self,divider_line) for raw_line in portCounters_list[4:]: line = raw_line if debug: print '----------------------------------------------' print 'The line to be processed is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() if debug: print 'The name is:', name local_dict = {} for idx in range(1,len(columnDict.keys())): start = columnDict[idx][0] end = columnDict[idx][1]+1 label = labels_line[start:end].strip() local_dict[label] = line[start:end].strip() if debug: print("The %s is: %s " %(label,local_dict[label])) # We store last entry in the main dictionary we return portCounters_dict[name] = local_dict return portCounters_dict def show_ike_session_counters(self): """Runs the command 'show ike-session counters' and parses the output. """ ikeSessionCounters_dict = {} debug = False """ # Sample raw input iceland[ctx1]#show ike-session counters Wed Oct 5 16:43:42 UTC 2011. ----------------------------------------------------------------------- Phase1 Phase1 Phase1 Phase1 Phase2 Phase2 Slot Successful Dropped Failed Active Successful Failed ---- ---------- ---------- ---------- ---------- ---------- ---------- 2 0 0 150 0 0 150 ---- ---------- ---------- ---------- ---------- ---------- ---------- Sum 0 0 150 0 0 150 Active Sessions: 0 Total Sessions: 0 iceland[ctx1]# # Sample dictionary output { '2': { 'Phase1 Active': '0', 'Phase1 Dropped': '0', 'Phase1 Failed': '0', 'Phase1 Successful': '0', 'Phase2 Failed': '0', 'Phase2 Successful': '0'}, 'Sessions': { 'Active Sessions': '0', 'Total Sessions': '0'}, 'Sum': { 'Phase1 Active': '0', 'Phase1 Dropped': '0', 'Phase1 Failed': '0', 'Phase1 Successful': '0', 'Phase2 Failed': '0', 'Phase2 Successful': '0'} } """ command = "show ike-session counters" raw_ikeSessionCounters_list = self.cmd(command) ikeSessionCounters_list = raw_ikeSessionCounters_list.splitlines() if debug: print 'The raw value returned was:' print ikeSessionCounters_list labels_line1 = ikeSessionCounters_list[3] labels_line2 = ikeSessionCounters_list[4] divider_line = ikeSessionCounters_list[5] columnDict = parse_divider_line(self,divider_line) processLine = 6 for raw_line in ikeSessionCounters_list[6:]: line = raw_line if debug: print '----------------------------------------------' print 'The line to be processed is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() if (name == "----") or (name == ""): # the divider/empty line between slot and sum. Ignore these lines continue if debug: print 'The name is:', name local_dict = {} for idx in range(1,len(columnDict.keys())): start = columnDict[idx][0] end = columnDict[idx][1]+1 label = labels_line1[start:end].strip() + " " + labels_line2[start:end].strip() label = label.strip() local_dict[label] = line[start:end].strip() if debug: print("The %s is: %s " %(label,local_dict[label])) # We store last entry in the main dictionary we return ikeSessionCounters_dict[name] = local_dict processLine += 1 if name == "Sum": # End of normal output display. Stop break for raw_line in ikeSessionCounters_list[processLine:]: line = raw_line if debug: print '----------------------------------------------' print 'The line to be processed is:' print line p = re.compile('(?P<active>Active Sessions):\s+(?P<actses>[\d]+)\s+(?P<total>Total Sessions):\s+(?P<totses>[\d]+)') m = p.search(line) if m: local_dict = {} dict = m.groupdict() if debug: print("The dict is: %s " %dict) local_dict[dict['active']] = dict['actses'] if debug: print("The %s is: %s " %(dict['active'],local_dict[dict['active']])) local_dict[dict['total']] = dict['totses'] if debug: print("The %s is: %s " %(dict['total'],local_dict[dict['total']])) # We store last entry in the main dictionary we return ikeSessionCounters_dict['Sessions'] = local_dict return ikeSessionCounters_dict def show_environmental_detail(self): """Runs the command 'show environmental detail' and parses the output. """ environmentalDetail_dict = {} debug = False # Sample raw input """ iceland[local]#show environmental detail Environmental status as of Fri Oct 7 14:52:21 2011 Data polling interval is 60 second(s) Voltage readings: ================= Slot Source Reading Level ---- ------ ----------- ------- 0 GPP 1111 None 0 VCC 1.8V 1784 None 0 TCAM 1194 None 0 VCC 2.5V 2520 None 0 DDR Term 1239 None 0 VCC 3.3V 3294 None 0 VCC 5.0V 4985 None 0 FIC 4902 None 0 SysContr 1478 None 0 VCC 12.0V 11989 None 1 GPP 1122 None 1 VCC 1.8V 1784 None 1 TCAM 1214 None 1 VCC 2.5V 2492 None 1 DDR Term 1252 None 1 VCC 3.3V 3312 None 1 VCC 5.0V 4985 None 1 FIC 4957 None 1 SysContr 1494 None 1 VCC 12.0V 11923 None 1 GPP 1122 None 1 VCC 1.8V 1784 None 1 TCAM 1214 None 1 VCC 2.5V 2492 None 1 DDR Term 1252 None 1 VCC 3.3V 3312 None 1 VCC 5.0V 4985 None 1 FIC 4957 None 1 SysContr 1494 None 1 VCC 12.0V 11923 None 2 CPU 1.0V CA 1012 None 2 CPU 1.0V CB 1004 None 2 CPU 1.0V PL 996 None 2 CPU DDR3 1492 None 2 CPU SDRAM VTT 748 None 2 KBP0 Analog 892 None 2 KBP1 Analog 892 None 2 KBP0 Core 900 None 2 KBP1 Core 900 None 2 NPU 1.0V 996 None 2 NPU VDD SRAM 1004 None 2 NPU0 Analog 988 None 2 NPU1 Analog 988 None 2 NPU0 AC SD VTT 740 None 2 NPU0 BD SD VTT 740 None 2 NPU1 AC SD VTT 740 None 2 NPU1 BD SD VTT 732 None 2 NPU0 DDR3 1492 None 2 NPU1 DDR3 1484 None 2 Switch Analog 988 None 2 Switch Core 996 None 2 VCC 1.2V 1204 None 2 VCC 1.8V 1800 None 2 VCC 2.5V 2473 None 2 VCC 3.3V 3323 None 2 VCC 12.0V 11868 None Temperature readings: ===================== Slot Source Reading Level ---- ------ ----------- ------- 0 Inlet 33 None 0 Outlet 44 None 0 GPP0 60 None 0 GPP1 38 None 1 Inlet 31 None 1 Outlet 45 None 1 GPP0 64 None 1 GPP1 41 None 2 GPP0 71 None 2 NPU0 67 None 2 NPU1 77 None Power status: ============= Slot Source Reading Level ---- ------ ----------- ------- PEMA Power Trip OK None PEMA Temperature OK None PEMA -48V Powergood OK None PEMA -48V Miswire OK None PEMA Backplane 3.3V OK None PEMB Power Trip Tripped Minor PEMB Temperature OK None PEMB -48V Powergood OK None PEMB -48V Miswire OK None PEMB Backplane 3.3V OK None Fan status: =========== Slot Source Reading Level ---- ------ ----------- ------- FANTRAY1 48V Fuse-A OK None FANTRAY1 48V Fuse-B OK None FANTRAY1 Fans-Stat OK None FANTRAY1 Fan1 status 0 FANTRAY1 Fan2 status 0 FANTRAY1 Fan1 speed 4028 FANTRAY1 Fan2 speed 4700 FANTRAY2 48V Fuse-A OK None FANTRAY2 48V Fuse-B OK None FANTRAY2 Fans-Stat OK None FANTRAY2 Fan1 status 0 FANTRAY2 Fan2 status 0 FANTRAY2 Fan1 speed 4512 FANTRAY2 Fan2 speed 3889 Alarm status: ============= Slot Source Reading Level ---- ------ ----------- ------- ALARM1 Backplane 3.3V OK None ALARM1 Alarm Cutfoff Off None iceland[local]# Sample dictionary output: ========================= { 'Alarm status - ALARM1 - Alarm Cutfoff': { 'level': 'None', 'reading': 'Off'}, 'Alarm status - ALARM1 - Backplane 3.3V': { 'level': 'None', 'reading': 'OK'}, 'Fan status - FANTRAY1 - 48V Fuse-A': { 'level': 'None', 'reading': 'OK'}, 'Fan status - FANTRAY1 - 48V Fuse-B': { 'level': 'None', 'reading': 'OK'}, 'Fan status - FANTRAY1 - Fan1 speed': { 'reading': '4028'}, 'Fan status - FANTRAY1 - Fan1 status': { 'reading': '0'}, 'Fan status - FANTRAY1 - Fan2 speed': { 'reading': '4700'}, 'Fan status - FANTRAY1 - Fan2 status': { 'reading': '0'}, 'Fan status - FANTRAY1 - Fans-Stat': { 'level': 'None', 'reading': 'OK'}, 'Fan status - FANTRAY2 - 48V Fuse-A': { 'level': 'None', 'reading': 'OK'}, 'Fan status - FANTRAY2 - 48V Fuse-B': { 'level': 'None', 'reading': 'OK'}, 'Fan status - FANTRAY2 - Fan1 speed': { 'reading': '4338'}, 'Fan status - FANTRAY2 - Fan1 status': { 'reading': '0'}, 'Fan status - FANTRAY2 - Fan2 speed': { 'reading': '3889'}, 'Fan status - FANTRAY2 - Fan2 status': { 'reading': '0'}, 'Fan status - FANTRAY2 - Fans-Stat': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMA - -48V Miswire': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMA - -48V Powergood': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMA - Backplane 3.3V': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMA - Power Trip': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMA - Temperature': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMB - -48V Miswire': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMB - -48V Powergood': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMB - Backplane 3.3V': { 'level': 'None', 'reading': 'OK'}, 'Power status - PEMB - Power Trip': { 'level': 'Minor', 'reading': 'Tripped'}, 'Power status - PEMB - Temperature': { 'level': 'None', 'reading': 'OK'}, 'Temperature readings - 0 - GPP0': { 'level': 'None', 'reading': '60'}, 'Temperature readings - 0 - GPP1': { 'level': 'None', 'reading': '39'}, 'Temperature readings - 0 - Inlet': { 'level': 'None', 'reading': '33'}, 'Temperature readings - 0 - Outlet': { 'level': 'None', 'reading': '45'}, 'Temperature readings - 1 - GPP0': { 'level': 'None', 'reading': '64'}, 'Temperature readings - 1 - GPP1': { 'level': 'None', 'reading': '41'}, 'Temperature readings - 1 - Inlet': { 'level': 'None', 'reading': '31'}, 'Temperature readings - 1 - Outlet': { 'level': 'None', 'reading': '45'}, 'Temperature readings - 2 - GPP0': { 'level': 'None', 'reading': '71'}, 'Temperature readings - 2 - NPU0': { 'level': 'None', 'reading': '67'}, 'Temperature readings - 2 - NPU1': { 'level': 'None', 'reading': '76'}, 'Voltage readings - 0 - DDR Term': { 'level': 'None', 'reading': '1239'}, 'Voltage readings - 0 - FIC': { 'level': 'None', 'reading': '4902'}, 'Voltage readings - 0 - GPP': { 'level': 'None', 'reading': '1111'}, 'Voltage readings - 0 - SysContr': { 'level': 'None', 'reading': '1478'}, 'Voltage readings - 0 - TCAM': { 'level': 'None', 'reading': '1194'}, 'Voltage readings - 0 - VCC 1.8V': { 'level': 'None', 'reading': '1784'}, 'Voltage readings - 0 - VCC 12.0V': { 'level': 'None', 'reading': '11989'}, 'Voltage readings - 0 - VCC 2.5V': { 'level': 'None', 'reading': '2492'}, 'Voltage readings - 0 - VCC 3.3V': { 'level': 'None', 'reading': '3294'}, 'Voltage readings - 0 - VCC 5.0V': { 'level': 'None', 'reading': '4985'}, 'Voltage readings - 1 - DDR Term': { 'level': 'None', 'reading': '1252'}, 'Voltage readings - 1 - FIC': { 'level': 'None', 'reading': '5013'}, 'Voltage readings - 1 - GPP': { 'level': 'None', 'reading': '1122'}, 'Voltage readings - 1 - SysContr': { 'level': 'None', 'reading': '1486'}, 'Voltage readings - 1 - TCAM': { 'level': 'None', 'reading': '1214'}, 'Voltage readings - 1 - VCC 1.8V': { 'level': 'None', 'reading': '1784'}, 'Voltage readings - 1 - VCC 12.0V': { 'level': 'None', 'reading': '11923'}, 'Voltage readings - 1 - VCC 2.5V': { 'level': 'None', 'reading': '2492'}, 'Voltage readings - 1 - VCC 3.3V': { 'level': 'None', 'reading': '3312'}, 'Voltage readings - 1 - VCC 5.0V': { 'level': 'None', 'reading': '4985'}, 'Voltage readings - 2 - CPU 1.0V CA': { 'level': 'None', 'reading': '1012'}, 'Voltage readings - 2 - CPU 1.0V CB': { 'level': 'None', 'reading': '1004'}, 'Voltage readings - 2 - CPU 1.0V PL': { 'level': 'None', 'reading': '996'}, 'Voltage readings - 2 - CPU DDR3': { 'level': 'None', 'reading': '1484'}, 'Voltage readings - 2 - CPU SDRAM VTT': { 'level': 'None', 'reading': '740'}, 'Voltage readings - 2 - KBP0 Analog': { 'level': 'None', 'reading': '892'}, 'Voltage readings - 2 - KBP0 Core': { 'level': 'None', 'reading': '892'}, 'Voltage readings - 2 - KBP1 Analog': { 'level': 'None', 'reading': '892'}, 'Voltage readings - 2 - KBP1 Core': { 'level': 'None', 'reading': '900'}, 'Voltage readings - 2 - NPU 1.0V': { 'level': 'None', 'reading': '996'}, 'Voltage readings - 2 - NPU VDD SRAM': { 'level': 'None', 'reading': '1004'}, 'Voltage readings - 2 - NPU0 AC SD VTT': { 'level': 'None', 'reading': '740'}, 'Voltage readings - 2 - NPU0 Analog': { 'level': 'None', 'reading': '988'}, 'Voltage readings - 2 - NPU0 BD SD VTT': { 'level': 'None', 'reading': '740'}, 'Voltage readings - 2 - NPU0 DDR3': { 'level': 'None', 'reading': '1492'}, 'Voltage readings - 2 - NPU1 AC SD VTT': { 'level': 'None', 'reading': '740'}, 'Voltage readings - 2 - NPU1 Analog': { 'level': 'None', 'reading': '980'}, 'Voltage readings - 2 - NPU1 BD SD VTT': { 'level': 'None', 'reading': '740'}, 'Voltage readings - 2 - NPU1 DDR3': { 'level': 'None', 'reading': '1484'}, 'Voltage readings - 2 - Switch Analog': { 'level': 'None', 'reading': '988'}, 'Voltage readings - 2 - Switch Core': { 'level': 'None', 'reading': '996'}, 'Voltage readings - 2 - VCC 1.2V': { 'level': 'None', 'reading': '1204'}, 'Voltage readings - 2 - VCC 1.8V': { 'level': 'None', 'reading': '1800'}, 'Voltage readings - 2 - VCC 12.0V': { 'level': 'None', 'reading': '11868'}, 'Voltage readings - 2 - VCC 2.5V': { 'level': 'None', 'reading': '2473'}, 'Voltage readings - 2 - VCC 3.3V': { 'level': 'None', 'reading': '3323'} } """ command = "show environmental detail" raw_environmentalDetail_list = self.cmd(command) environmentalDetail_list = raw_environmentalDetail_list.splitlines() if debug: print 'The raw value returned was:' print environmentalDetail_list curname = "" isName = False for raw_line in environmentalDetail_list[4:]: line = raw_line.strip() if line in ["===========","---- ------ ----------- -------", \ "Slot Source Reading Level",""]: continue if debug: print '----------------------------------------------' print 'The line to be processed is:' print line regList = ['(?P<label>.*):','^(?P<slot>[a-zA-Z-0-9]{1,8})\s+(?P<source>[a-zA-Z-0-9\. \-]{1,15})\s+(?P<reading>[a-zA-Z-0-9\. ]{1,11})$','(?P<slot>[a-zA-Z-0-9]{1,8})\s+(?P<source>[a-zA-Z-0-9\. \-]{1,15})\s+(?P<reading>[a-zA-Z-0-9\. ]{1,11})\s+(?P<level>[\w]{1,7})'] pList = [re.compile(regexp) for regexp in regList] mList = [p.search(line) for p in pList] if debug: print 'The mList is:', mList local_dict = {} if curname != "": name = curname for m in mList: if m == None: continue dict = m.groupdict() if debug: print 'The dict is:', dict for key in dict.keys(): if debug: print 'The key is:', key if key == "label": curname = dict['label'].strip() name = curname isName = True if debug: print 'The name is:', name elif (key == "slot") or (key == "source"): print 'The name is:', name print 'dict[%s] is %s' %(key,dict[key]) name = '%s - %s' %(name,dict[key].strip()) isName = True if debug: print 'The name is:', name else: local_dict[key] = dict[key] isName = False if debug: print("The %s is: %s " %(key,local_dict[key])) break # We store last entry in the main dictionary we return if not isName: environmentalDetail_dict[name] = local_dict return environmentalDetail_dict def show_process_memory(self,slot='0'): """Runs the command 'show process mem slot <slot>' and parses the output. Default slot is 0 """ processMem_dict = {} debug = False # Sample raw input """ iceland[local]#show process mem Process Name PID Text Data soText soData Stack Heap Shared ------------- ------- ------- ------- ------- ------- ------- ------- ------- NSM 704514 16KB 4096 8MB 1192KB 156KB 17MB 249MB Smid 745496 224KB 16KB 12MB 3256KB 128KB 2504KB 21MB Ip 745500 4096 4096 8MB 2028KB 188KB 4928KB 260MB CtxMgr 745499 36KB 4096 7492KB 868KB 76KB 1268KB 21MB Fpd 745498 32KB 8192 7616KB 900KB 92KB 1300KB 243MB Aaad 745504 424KB 84KB 13MB 1312KB 204KB 5432KB 132MB Cli 925743 44KB 16KB 12MB 3272KB 120KB 2600KB 21MB Cli 1011760 44KB 16KB 12MB 3272KB 120KB 2600KB 21MB Snmpd 745506 604KB 52KB 7680KB 912KB 80KB 2324KB 22MB Inets 745505 32KB 8192 8MB 1056KB 112KB 1304KB 21MB Logind 745497 16KB 4096 7628KB 924KB 80KB 1268KB 21MB Logind 1011758 16KB 4096 7628KB 924KB 80KB 1268KB 21MB Ospf 745501 332KB 8192 8000KB 952KB 88KB 1304KB 38MB Bgp4 745502 320KB 8192 8020KB 960KB 96KB 1468KB 38MB Evl 745493 108KB 4096 7828KB 920KB 92KB 1272KB 25MB EvlColl 745494 36KB 4096 7508KB 876KB 76KB 1300KB 25MB Qosd 745503 180KB 4096 9MB 1108KB 92KB 1304KB 127MB IkedMc 745507 152KB 68KB 8MB 1004KB 88KB 1300KB 21MB Ntp 745508 4096 4096 8076KB 1188KB 92KB 1300KB 21MB Rip 745509 96KB 8192 7736KB 928KB 88KB 1268KB 38MB Evt 745492 32KB 4096 7492KB 868KB 76KB 1268KB 21MB Fsync 745495 20KB 4096 7408KB 868KB 72KB 1332KB 20MB TunMgr 745510 112KB 4096 7540KB 876KB 84KB 1304KB 23MB CDR 745511 112KB 8192 9MB 1076KB 100KB 1304KB 122MB DHCPdMC 745512 48KB 1028KB 7600KB 900KB 80KB 1268KB 21MB MIPd 745513 160KB 4096 7768KB 1952KB 96KB 2360KB 21MB SLA 745514 32KB 4096 7664KB 900KB 76KB 1272KB 21MB Dfn 745515 1172KB 4096 10MB 1072KB 92KB 13MB 21MB Gtppd 745516 52KB 4096 9MB 1100KB 84KB 1380KB 122MB iceland[local]# Sample dictionary output: ========================= { 'Aaad': { 'Data': '84KB', 'Heap': '5432KB', 'PID': '745504', 'Shared': '132MB', 'Stack': '204KB', 'Text': '424KB', 'soData': '1312KB', 'soText': '13MB'}, 'Bgp4': { 'Data': '8192', 'Heap': '1468KB', 'PID': '745502', 'Shared': '38MB', 'Stack': '96KB', 'Text': '320KB', 'soData': '960KB', 'soText': '8020KB'}, 'CDR': { 'Data': '8192', 'Heap': '1304KB', 'PID': '745511', 'Shared': '122MB', 'Stack': '100KB', 'Text': '112KB', 'soData': '1076KB', 'soText': '9MB'}, 'Cli': { 'Data': '16KB', 'Heap': '2600KB', 'PID': '925743', 'Shared': '21MB', 'Stack': '120KB', 'Text': '44KB', 'soData': '3272KB', 'soText': '12MB'}, 'Cli_1': { 'Data': '16KB', 'Heap': '2600KB', 'PID': '1011760', 'Shared': '21MB', 'Stack': '120KB', 'Text': '44KB', 'soData': '3272KB', 'soText': '12MB'}, 'Cli_2': { 'Data': '16KB', 'Heap': '2600KB', 'PID': '1011763', 'Shared': '21MB', 'Stack': '140KB', 'Text': '44KB', 'soData': '3272KB', 'soText': '12MB'}, 'CtxMgr': { 'Data': '4096', 'Heap': '1268KB', 'PID': '745499', 'Shared': '21MB', 'Stack': '80KB', 'Text': '36KB', 'soData': '868KB', 'soText': '7492KB'}, 'DHCPdMC': { 'Data': '1028KB', 'Heap': '1268KB', 'PID': '745512', 'Shared': '21MB', 'Stack': '80KB', 'Text': '48KB', 'soData': '900KB', 'soText': '7600KB'}, 'Dfn': { 'Data': '4096', 'Heap': '13MB', 'PID': '745515', 'Shared': '21MB', 'Stack': '92KB', 'Text': '1172KB', 'soData': '1072KB', 'soText': '10MB'}, 'Evl': { 'Data': '4096', 'Heap': '1272KB', 'PID': '745493', 'Shared': '25MB', 'Stack': '92KB', 'Text': '108KB', 'soData': '920KB', 'soText': '7828KB'}, 'EvlColl': { 'Data': '4096', 'Heap': '1300KB', 'PID': '745494', 'Shared': '25MB', 'Stack': '76KB', 'Text': '36KB', 'soData': '876KB', 'soText': '7508KB'}, 'Evt': { 'Data': '4096', 'Heap': '1268KB', 'PID': '745492', 'Shared': '21MB', 'Stack': '80KB', 'Text': '32KB', 'soData': '868KB', 'soText': '7492KB'}, 'Fpd': { 'Data': '8192', 'Heap': '1300KB', 'PID': '745498', 'Shared': '243MB', 'Stack': '92KB', 'Text': '32KB', 'soData': '900KB', 'soText': '7616KB'}, 'Fsync': { 'Data': '4096', 'Heap': '1332KB', 'PID': '745495', 'Shared': '20MB', 'Stack': '72KB', 'Text': '20KB', 'soData': '868KB', 'soText': '7408KB'}, 'Gtppd': { 'Data': '4096', 'Heap': '1380KB', 'PID': '745516', 'Shared': '122MB', 'Stack': '84KB', 'Text': '52KB', 'soData': '1100KB', 'soText': '9MB'}, 'IkedMc': { 'Data': '68KB', 'Heap': '1300KB', 'PID': '745507', 'Shared': '21MB', 'Stack': '88KB', 'Text': '152KB', 'soData': '1004KB', 'soText': '8MB'}, 'Inets': { 'Data': '8192', 'Heap': '1304KB', 'PID': '745505', 'Shared': '21MB', 'Stack': '116KB', 'Text': '32KB', 'soData': '1056KB', 'soText': '8MB'}, 'Ip': { 'Data': '4096', 'Heap': '4932KB', 'PID': '745500', 'Shared': '260MB', 'Stack': '188KB', 'Text': '4096', 'soData': '2028KB', 'soText': '8MB'}, 'Logind': { 'Data': '4096', 'Heap': '1268KB', 'PID': '745497', 'Shared': '21MB', 'Stack': '80KB', 'Text': '16KB', 'soData': '924KB', 'soText': '7628KB'}, 'Logind_1': { 'Data': '4096', 'Heap': '1268KB', 'PID': '1011758', 'Shared': '21MB', 'Stack': '80KB', 'Text': '16KB', 'soData': '924KB', 'soText': '7628KB'}, 'Logind_2': { 'Data': '4096', 'Heap': '1268KB', 'PID': '1011762', 'Shared': '21MB', 'Stack': '100KB', 'Text': '16KB', 'soData': '924KB', 'soText': '7628KB'}, 'MIPd': { 'Data': '4096', 'Heap': '2360KB', 'PID': '745513', 'Shared': '21MB', 'Stack': '96KB', 'Text': '160KB', 'soData': '1952KB', 'soText': '7768KB'}, 'NSM': { 'Data': '4096', 'Heap': '17MB', 'PID': '704514', 'Shared': '249MB', 'Stack': '160KB', 'Text': '16KB', 'soData': '1192KB', 'soText': '8MB'}, 'Ntp': { 'Data': '4096', 'Heap': '1300KB', 'PID': '745508', 'Shared': '21MB', 'Stack': '92KB', 'Text': '4096', 'soData': '1188KB', 'soText': '8076KB'}, 'Ospf': { 'Data': '8192', 'Heap': '1304KB', 'PID': '745501', 'Shared': '38MB', 'Stack': '88KB', 'Text': '332KB', 'soData': '952KB', 'soText': '8000KB'}, 'Qosd': { 'Data': '4096', 'Heap': '1304KB', 'PID': '745503', 'Shared': '127MB', 'Stack': '92KB', 'Text': '180KB', 'soData': '1108KB', 'soText': '9MB'}, 'Rip': { 'Data': '8192', 'Heap': '1268KB', 'PID': '745509', 'Shared': '38MB', 'Stack': '88KB', 'Text': '96KB', 'soData': '928KB', 'soText': '7736KB'}, 'SLA': { 'Data': '4096', 'Heap': '1272KB', 'PID': '745514', 'Shared': '21MB', 'Stack': '76KB', 'Text': '32KB', 'soData': '900KB', 'soText': '7664KB'}, 'Smid': { 'Data': '16KB', 'Heap': '2504KB', 'PID': '745496', 'Shared': '21MB', 'Stack': '132KB', 'Text': '224KB', 'soData': '3256KB', 'soText': '12MB'}, 'Snmpd': { 'Data': '52KB', 'Heap': '2324KB', 'PID': '745506', 'Shared': '22MB', 'Stack': '80KB', 'Text': '604KB', 'soData': '912KB', 'soText': '7680KB'}, 'TunMgr': { 'Data': '4096', 'Heap': '1304KB', 'PID': '745510', 'Shared': '23MB', 'Stack': '84KB', 'Text': '112KB', 'soData': '876KB', 'soText': '7540KB'}} """ command = "show process mem slot %s" %slot raw_processMem_list = self.cmd(command) processMem_list = raw_processMem_list.splitlines() if debug: print 'The raw value returned was:' print processMem_list if ('ERROR:' in raw_processMem_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_processMem_list processMem_dict['Status'] = 'Error' return processMem_dict labels_line = processMem_list[1] divider_line = processMem_list[2] columnDict = parse_divider_line(self,divider_line) dupKey_dict = {} for raw_line in processMem_list[3:]: line = raw_line.strip() if debug: print '----------------------------------------------' print 'The line to be processed is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() if name in dupKey_dict: # for duplicate keys, append the index to the key to differentiate between them dupKey_dict[name] += 1 name = name + "_" + `dupKey_dict[name]` else: dupKey_dict[name] = 0 if debug: print 'The name is:', name local_dict = {} for idx in range(1,len(columnDict.keys())): start = columnDict[idx][0] end = columnDict[idx][1]+1 labels_name = labels_line[start:end].strip() local_dict[labels_name] = line[start:end].strip() if debug: print("The %s is: %s " %(labels_name,local_dict[labels_name])) # We store last entry in the main dictionary we return processMem_dict[name] = local_dict return processMem_dict def showmoduleprocessmashared(self,slot): showmodprocmashared_dict = {} debug = False # Sample raw input """ Stoke[local]#show module Rip slot 0 ma shared Name/ Elements HiWat/ In Use/ Allocs/ Alloc Fail/ Pool Size Elem Size User Size Free Frees Double Free ---------------- --------- --------- --------- ------------- ----------- MBuf 97,340 48,463 47,543 60,251 0 211,812,352 2,176 2,144 49,797 12,708 0 FpdPage 4,964 13 13 13 0 20,971,520 4,224 4,192 4,951 0 0 RouteMap 1,351 0 0 0 0 3,145,728 2,328 2,320 1,351 0 0 PfxList 6,553 0 0 0 0 524,288 80 72 6,553 0 0 CommList 9,361 0 0 0 0 524,288 56 48 9,361 0 0 UI32Array 5,957 0 0 0 0 524,288 88 80 5,957 0 0 AsPathAcl 13,106 0 0 0 0 524,288 40 32 13,106 0 0 RtPolRegex200 20,164 0 0 0 0 4,194,304 208 200 20,164 0 0 RtPolRegex400 10,280 0 0 0 0 4,194,304 408 400 10,280 0 0 RtPolRegex512 6,898 0 0 0 0 4,194,304 608 600 6,898 0 0 Stoke[local]# # Sample output 'Rip': { 'AsPathAcl': { 'Alloc Fail': '0', 'Allocs': '0', 'Double Free': '0', 'Elem Size': '40', 'Elements': '13,106', 'Free': '13,106', 'Frees': '0', 'HiWat': '0', 'In Use': '0', 'Pool Size': '524,288', 'User Size': '32'}, 'CommList': { 'Alloc Fail': '0', 'Allocs': '0', 'Double Free': '0', 'Elem Size': '56', 'Elements': '9,361', 'Free': '9,361', 'Frees': '0', 'HiWat': '0', 'In Use': '0', 'Pool Size': '524,288', 'User Size': '48'}, 'FpdPage': { 'Alloc Fail': '0', 'Allocs': '13', 'Double Free': '0', 'Elem Size': '4,224', 'Elements': '4,964', 'Free': '4,951', 'Frees': '0', 'HiWat': '13', 'In Use': '13', 'Pool Size': '20,971,520', 'User Size': '4,192'}, 'MBuf': { 'Alloc Fail': '0', 'Allocs': '60,251', 'Double Free': '0', 'Elem Size': '2,176', 'Elements': '97,340', 'Free': '49,797', 'Frees': '12,708', 'HiWat': '48,463', 'In Use': '47,543', 'Pool Size': '211,812,352', 'User Size': '2,144'}, 'PfxList': { 'Alloc Fail': '0', 'Allocs': '0', 'Double Free': '0', 'Elem Size': '80', 'Elements': '6,553', 'Free': '6,553', 'Frees': '0', 'HiWat': '0', 'In Use': '0', 'Pool Size': '524,288', 'User Size': '72'}, 'RouteMap': { 'Alloc Fail': '0', 'Allocs': '0', 'Double Free': '0', 'Elem Size': '2,328', 'Elements': '1,351', 'Free': '1,351', 'Frees': '0', 'HiWat': '0', 'In Use': '0', 'Pool Size': '3,145,728', 'User Size': '2,320'}, 'RtPolRegex200': { 'Alloc Fail': '0', 'Allocs': '0', 'Double Free': '0', 'Elem Size': '208', 'Elements': '20,164', 'Free': '20,164', 'Frees': '0', 'HiWat': '0', 'In Use': '0', 'Pool Size': '4,194,304', 'User Size': '200'}, 'RtPolRegex400': { 'Alloc Fail': '0', 'Allocs': '0', 'Double Free': '0', 'Elem Size': '408', 'Elements': '10,280', 'Free': '10,280', 'Frees': '0', 'HiWat': '0', 'In Use': '0', 'Pool Size': '4,194,304', 'User Size': '400'}, 'RtPolRegex512': { 'Alloc Fail': '0', 'Allocs': '0', 'Double Free': '0', 'Elem Size': '608', 'Elements': '6,898', 'Free': '6,898', 'Frees': '0', 'HiWat': '0', 'In Use': '0', 'Pool Size': '4,194,304', 'User Size': '600'}, 'UI32Array': { 'Alloc Fail': '0', 'Allocs': '0', 'Double Free': '0', 'Elem Size': '88', 'Elements': '5,957', 'Free': '5,957', 'Frees': '0', 'HiWat': '0', 'In Use': '0', 'Pool Size': '524,288', 'User Size': '80'}} """ # call to get a list of processes on this slot processMemory_dict = show_process_memory(self,slot) #pprint(processMemory_dict,indent=4,width=20,depth=20) process_dict = {} for process in processMemory_dict.keys(): if process == "Status": # show_process_memory returns error then skip if processMemory_dict['Status'] == "Error": continue elif re.search('.*_\d+',process) != None: # probably _<digit> added to differentiate same process name in show_process_memory, then skip it continue command = "show module %s slot %s ma shared" %(process,slot) raw_modslotmashared_list = self.cmd(command) if ('ERROR:' in raw_modslotmashared_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modslotmashared_list showmodprocmashared_dict[process] = {'Error':raw_modslotmashared_list.strip()} continue elif raw_modslotmashared_list == "": # no output. Give out warning and continue on print "Command %s shows no output" %command continue modslotmashared_list = raw_modslotmashared_list.splitlines() if debug: print 'The raw value returned was:' print modslotmashared_list labels_line1 = modslotmashared_list[1] labels_line2 = modslotmashared_list[2] divider_line = modslotmashared_list[3] numcol = len(divider_line.split()) columnDict = parse_divider_line(self,divider_line) if debug: print 'The columnDict is:' print columnDict temp_dict = {} linenum = 4 for raw_line in modslotmashared_list[4:]: line = raw_line if debug: print '----------------------------------------------' print 'The line to be processes is:' print line if linenum % 2 == 0: # even line number local_dict = {} start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() startrange = 1 labels_line = labels_line1 else: startrange = 0 labels_line = labels_line2 for labels_idx in range(startrange,numcol): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 label_name = labels_line[start:end].strip(' /') local_dict[label_name] = line[start:end].strip() if debug: print("The %s is: %s " %(labels_line[label_name],local_dict[labels_line[label_name]])) # We store each entry in the temp dictionary # odd line we save if linenum % 2 == 1: temp_dict[name] = local_dict linenum += 1 # We store each temp dictionary to process showmodprocmashared_dict[process] = temp_dict return showmodprocmashared_dict def showmoduleprocessmapool(self,slot): showmodprocmapool_dict = {} debug = False # Sample raw input """ Stoke[local]#show module NSM slot 2 ma pool Name Size InUse Free Allocs Frees ---------------- ------------- --------- --------- ------------- ------------- DaSet 128 27 8 27 0 DaJudy 40 57 15 261 204 DaJudy 72 2 33 21 19 DaJudy 136 2 31 16 14 DaJudy 264 6 38 8 2 CrhHandleData 60 5 35 5 0 CrhRegData 32 21 22 21 0 CrhCmdBlk 8,224 4 4 21 17 NvTimer 56 19 24 20 1 IpcConnIds 28 20 28 20 0 IpcArepIds 28 4 44 4 0 IpcReg 156 4 31 4 0 IpcConn 400 20 19 20 0 IpcRegmsg 8 11 17 11 0 IpcAsyncReply 344 4 12 4 0 IpcSndrArep 36 3 15 3 0 IpcThrEnt 36 0 18 12 12 IpcThrData 28 0 22 118 118 IpcRmReg 24 4 49 4 0 IpcRmInfo 36 1 145 110 109 IpcAmInfo 72 0 144 44 44 MsgVerPool 176 2 19 2 0 IpcTrWantReg 28 4 44 4 0 IpcTrRegac 76 30 3 30 0 IpcTrRegpc 72 23 12 23 0 IpcTrReg 84 4 37 4 0 IpcTrConn 388 20 20 20 0 IpcTrConnG 188 15 20 15 0 IpcTrSlot 64 19 19 19 0 IpcTrNode 112 39 25 39 0 IpcTrRegacI 28 30 18 30 0 IpcTrRegpcI 28 23 25 23 0 IpcTrCgIds 28 15 33 15 0 IpcPeer 48 17 15 17 0 IpcPeerMsgData 80 0 20 118 118 IpcPeerMsg 56 0 28 118 118 IpcQnxReg 80 4 28 4 0 IpcQnxConn 12 12 48 12 0 IpcTcpReg 52 4 42 4 0 IpcTcpConn 16 6 54 6 0 IpcTcpRegpc 104 23 11 23 0 IpcMsgReg 52 4 42 4 0 IpcMsgConn 124 24 12 24 0 NvMsg 8,300 2 30 743 741 EvtStateNotify 32 4 16 4 0 EvtCrhCallBack 8 0 28 9 9 EvtRegWait 40 0 17 4 4 H:CMOHandler 20 3 153 3 0 H:CMOHandler 20 7 149 7 0 H:CMOHandler 20 28 128 28 0 H:CMOHandler 20 1 155 1 0 CMOHandlerPool 12 39 2,005 39 0 CMOObjectPool 8,080 0 64 2 2 IpcMbType 36 0 18 1 1 IpcMbMsg 36 0 40 2 2 NvfuCdpipcInfo 48 1 133 16 15 cdpipc 72 0 534 48,471 48,471 cdpipc 264 0 518 32 32 cdpipc 1,460 1 352 48,502 48,501 CardAgt I2C Job 28 0 73 404 404 ProcMgrNPE 680 15 20 15 0 NPE/NSE 188 7 28 7 0 PWQ 112 0 32 7 7 ProcMgr Mon Eve 28 0 22 218,278 218,278 64 objects displayed. Stoke[local]# # Sample output 'NSM': { '68 objects displ': { 'Allocs': '', 'Free': '', 'Frees': '', 'InUse': '', 'Size': 'yed.'}, 'CMOHandlerPool': { 'Allocs': '104', 'Free': '1,940', 'Frees': '0', 'InUse': '104', 'Size': '12'}, 'CMOObjectPool': { 'Allocs': '204', 'Free': '64', 'Frees': '204', 'InUse': '0', 'Size': '8,080'}, 'CardMgr I2C Job': { 'Allocs': '427,449', 'Free': '72', 'Frees': '427,448', 'InUse': '1', 'Size': '28'}, 'CrhCmdBlk': { 'Allocs': '9', 'Free': '8', 'Frees': '1', 'InUse': '8', 'Size': '8,224'}, 'CrhHandleData': { 'Allocs': '8', 'Free': '32', 'Frees': '0', 'InUse': '8', 'Size': '60'}, 'CrhRegData': { 'Allocs': '20', 'Free': '23', 'Frees': '0', 'InUse': '20', 'Size': '32'}, 'DaJudy': { 'Allocs': '1,310', 'Free': '18', 'Frees': '1,112', 'InUse': '198', 'Size': '40'}, 'DaJudy_2': { 'Allocs': '105', 'Free': '3', 'Frees': '73', 'InUse': '32', 'Size': '72'}, 'DaJudy_4': { 'Allocs': '73', 'Free': '20', 'Frees': '60', 'InUse': '13', 'Size': '136'}, 'DaJudy_8': { 'Allocs': '31', 'Free': '42', 'Frees': '29', 'InUse': '2', 'Size': '264'}, 'DaSet': { 'Allocs': '49', 'Free': '21', 'Frees': '0', 'InUse': '49', 'Size': '128'}, 'EvtCrhCallBack': { 'Allocs': '171', 'Free': '28', 'Frees': '171', 'InUse': '0', 'Size': '8'}, 'EvtRegWait': { 'Allocs': '7', 'Free': '17', 'Frees': '7', 'InUse': '0', 'Size': '40'}, 'EvtStateNotify': { 'Allocs': '7', 'Free': '13', 'Frees': '0', 'InUse': '7', 'Size': '32'}, 'H:CMOHandler': { 'Allocs': '12', 'Free': '144', 'Frees': '0', 'InUse': '12', 'Size': '20'}, 'H:CMOHandler_128': { 'Allocs': '1', 'Free': '155', 'Frees': '0', 'InUse': '1', 'Size': '20'}, 'H:CMOHandler_16': { 'Allocs': '31', 'Free': '125', 'Frees': '0', 'InUse': '31', 'Size': '20'}, 'H:CMOHandler_2': { 'Allocs': '14', 'Free': '142', 'Frees': '0', 'InUse': '14', 'Size': '20'}, 'H:CMOHandler_32': { 'Allocs': '12', 'Free': '144', 'Frees': '0', 'InUse': '12', 'Size': '20'}, 'H:CMOHandler_4': { 'Allocs': '4', 'Free': '152', 'Frees': '0', 'InUse': '4', 'Size': '20'}, 'H:CMOHandler_64': { 'Allocs': '8', 'Free': '148', 'Frees': '0', 'InUse': '8', 'Size': '20'}, 'H:CMOHandler_8': { 'Allocs': '22', 'Free': '134', 'Frees': '0', 'InUse': '22', 'Size': '20'}, 'HAMgrVRISet': { 'Allocs': '2', 'Free': '20', 'Frees': '0', 'InUse': '2', 'Size': '28'}, 'IpcAmInfo': { 'Allocs': '139', 'Free': '144', 'Frees': '139', 'InUse': '0', 'Size': '72'}, 'IpcArepIds': { 'Allocs': '22', 'Free': '29', 'Frees': '3', 'InUse': '19', 'Size': '28'}, 'IpcAsyncReply': { 'Allocs': '22', 'Free': '13', 'Frees': '3', 'InUse': '19', 'Size': '344'}, 'IpcConn': { 'Allocs': '103', 'Free': '37', 'Frees': '23', 'InUse': '80', 'Size': '400'}, 'IpcConnIds': { 'Allocs': '103', 'Free': '14', 'Frees': '21', 'InUse': '82', 'Size': '28'}, 'IpcMbMsg': { 'Allocs': '3', 'Free': '40', 'Frees': '3', 'InUse': '0', 'Size': '36'}, 'IpcMbType': { 'Allocs': '2', 'Free': '18', 'Frees': '2', 'InUse': '0', 'Size': '36'}, 'IpcMsgConn': { 'Allocs': '125', 'Free': '9', 'Frees': '26', 'InUse': '99', 'Size': '124'}, 'IpcMsgReg': { 'Allocs': '7', 'Free': '39', 'Frees': '0', 'InUse': '7', 'Size': '52'}, 'IpcPeer': { 'Allocs': '56', 'Free': '8', 'Frees': '0', 'InUse': '56', 'Size': '48'}, 'IpcPeerMsg': { 'Allocs': '458', 'Free': '28', 'Frees': '458', 'InUse': '0', 'Size': '56'}, 'IpcPeerMsgData': { 'Allocs': '452', 'Free': '20', 'Frees': '452', 'InUse': '0', 'Size': '80'}, 'IpcQnxConn': { 'Allocs': '59', 'Free': '24', 'Frees': '23', 'InUse': '36', 'Size': '12'}, 'IpcQnxReg': { 'Allocs': '7', 'Free': '25', 'Frees': '0', 'InUse': '7', 'Size': '80'}, 'IpcReg': { 'Allocs': '7', 'Free': '28', 'Frees': '0', 'InUse': '7', 'Size': '156'}, 'IpcRegmsg': { 'Allocs': '14', 'Free': '14', 'Frees': '0', 'InUse': '14', 'Size': '8'}, 'IpcRmInfo': { 'Allocs': '687', 'Free': '145', 'Frees': '686', 'InUse': '1', 'Size': '36'}, 'IpcRmReg': { 'Allocs': '7', 'Free': '46', 'Frees': '0', 'InUse': '7', 'Size': '24'}, 'IpcSndrArep': { 'Allocs': '5', 'Free': '13', 'Frees': '0', 'InUse': '5', 'Size': '36'}, 'IpcTcpConn': { 'Allocs': '19', 'Free': '44', 'Frees': '3', 'InUse': '16', 'Size': '16'}, 'IpcTcpReg': { 'Allocs': '7', 'Free': '39', 'Frees': '0', 'InUse': '7', 'Size': '52'}, 'IpcTcpRegpc': { 'Allocs': '85', 'Free': '9', 'Frees': '26', 'InUse': '59', 'Size': '104'}, 'IpcThrData': { 'Allocs': '477', 'Free': '22', 'Frees': '477', 'InUse': '0', 'Size': '28'}, 'IpcThrEnt': { 'Allocs': '38', 'Free': '18', 'Frees': '38', 'InUse': '0', 'Size': '36'}, 'IpcTrCgIds': { 'Allocs': '75', 'Free': '42', 'Frees': '21', 'InUse': '54', 'Size': '28'}, 'IpcTrConn': { 'Allocs': '103', 'Free': '40', 'Frees': '23', 'InUse': '80', 'Size': '388'}, 'IpcTrConnG': { 'Allocs': '75', 'Free': '18', 'Frees': '23', 'InUse': '52', 'Size': '188'}, 'IpcTrNode': { 'Allocs': '99', 'Free': '20', 'Frees': '23', 'InUse': '76', 'Size': '112'}, 'IpcTrReg': { 'Allocs': '7', 'Free': '34', 'Frees': '0', 'InUse': '7', 'Size': '84'}, 'IpcTrRegac': { 'Allocs': '115', 'Free': '13', 'Frees': '29', 'InUse': '86', 'Size': '76'}, 'IpcTrRegacI': { 'Allocs': '115', 'Free': '10', 'Frees': '29', 'InUse': '86', 'Size': '28'}, 'IpcTrRegpc': { 'Allocs': '85', 'Free': '11', 'Frees': '26', 'InUse': '59', 'Size': '72'}, 'IpcTrRegpcI': { 'Allocs': '85', 'Free': '37', 'Frees': '26', 'InUse': '59', 'Size': '28'}, 'IpcTrSlot': { 'Allocs': '79', 'Free': '20', 'Frees': '23', 'InUse': '56', 'Size': '64'}, 'IpcTrWantReg': { 'Allocs': '3', 'Free': '45', 'Frees': '0', 'InUse': '3', 'Size': '28'}, 'MsgVerPool': { 'Allocs': '3', 'Free': '18', 'Frees': '0', 'InUse': '3', 'Size': '176'}, 'NPE/NSE': { 'Allocs': '31', 'Free': '25', 'Frees': '21', 'InUse': '10', 'Size': '188'}, 'NSMClientSrvr': { 'Allocs': '3', 'Free': '137', 'Frees': '0', 'InUse': '3', 'Size': '104'}, 'NvMsg': { 'Allocs': '6,927', 'Free': '30', 'Frees': '6,925', 'InUse': '2', 'Size': '8,300'}, 'NvTimer': { 'Allocs': '35', 'Free': '24', 'Frees': '16', 'InUse': '19', 'Size': '56'}, 'PWQ': { 'Allocs': '31', 'Free': '31', 'Frees': '30', 'InUse': '1', 'Size': '112'}, 'ProcMgr Mon Eve': { 'Allocs': '116,642', 'Free': '22', 'Frees': '116,642', 'InUse': '0', 'Size': '28'}, 'ProcMgrNPE': { 'Allocs': '56', 'Free': '0', 'Frees': '21', 'InUse': '35', 'Size': '680'}, 'evt notify_wait': { 'Allocs': '105', 'Free': '1,071', 'Frees': '105', 'InUse': '0', 'Size': '72'}, 'evt notify_wait_2': { 'Allocs': '4', 'Free': '133', 'Frees': '4', 'InUse': '0', 'Size': '264'}} """ # call to get a list of processes on this slot processMemory_dict = show_process_memory(self,slot) #pprint(processMemory_dict,indent=4,width=20,depth=20) process_dict = {} for process in processMemory_dict.keys(): if process == "Status": # show_process_memory returns error then skip if processMemory_dict['Status'] == "Error": continue elif re.search('.*_\d+',process) != None: # probably _<digit> added to differentiate same process name in show_process_memory, then skip it continue command = "show module %s slot %s ma pool" %(process,slot) raw_modslotmapool_list = self.cmd(command) modslotmapool_list = raw_modslotmapool_list.splitlines() if debug: print 'The raw value returned was:' print modslotmapool_list if ('ERROR:' in raw_modslotmapool_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modslotmapool_list showmodprocmapool_dict[process] = {'Error':raw_modslotmapool_list.strip()} continue elif raw_modslotmapool_list == "": # no output. Give out warning and continue on print "Command %s shows no output" %command continue labels_line = modslotmapool_list[1].split() divider_line = modslotmapool_list[2] columnDict = parse_divider_line(self,divider_line) if debug: print 'The columnDict is:' print columnDict name_dict = {} temp_dict = {} for raw_line in modslotmapool_list[3:-1]: line = raw_line local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() if name in name_dict.keys(): name_dict[name] += 1 name = name + "_" + str(name_dict[name]) else: name_dict[name] = 0 for labels_idx in range(1,len(labels_line)): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 local_dict[labels_line[labels_idx]] = line[start:end].strip() if debug: print("The %s is: %s " %(labels_line[labels_idx],local_dict[labels_line[labels_idx]])) # We store each entry in the temp dictionary temp_dict[name] = local_dict # We store each temp dictionary to process showmodprocmapool_dict[process] = temp_dict return showmodprocmapool_dict def showmoduleprocessmapp(self,slot): showmodprocmapp_dict = {} debug = False # Sample raw input """ Stoke[local]#show module NSM slot 2 ma pp Elem__________________________________ Name Size InUse Allocs Frees Blocks ------------------------------ -------- --------- --------- --------- --------- _global_ 0 0 8 0 0 HALibHAPP::0 396 0 0 0 1 HALibHAGlobCB::0 204 0 0 0 1 HALibAsyncCB::0 60 0 0 0 1 Stoke[local]# # Sample output 'NSM': { 'GlcLSstats:16::0': { 'Allocs': '2', 'Blocks': '1', 'Frees': '0', 'InUse': '2', 'Size': '168'}, 'HALibAsyncCB::0': { 'Allocs': '17', 'Blocks': '0', 'Frees': '17', 'InUse': '0', 'Size': '60'}, 'HALibHAGlobCB::0': { 'Allocs': '2', 'Blocks': '1', 'Frees': '0', 'InUse': '2', 'Size': '204'}, 'HALibHAPP::0': { 'Allocs': '1', 'Blocks': '1', 'Frees': '0', 'InUse': '1', 'Size': '396'}, '_global_': { 'Allocs': '12', 'Blocks': '0', 'Frees': '0', 'InUse': '0', 'Size': '0'}}, """ # call to get a list of processes on this slot processMemory_dict = show_process_memory(self,slot) #pprint(processMemory_dict,indent=4,width=20,depth=20) process_dict = {} for process in processMemory_dict.keys(): if process == "Status": # show_process_memory returns error then skip if processMemory_dict['Status'] == "Error": continue elif re.search('.*_\d+',process) != None: # probably _<digit> added to differentiate same process name in show_process_memory, then skip it continue command = "show module %s slot %s ma pp" %(process,slot) raw_modslotmapp_list = self.cmd(command) modslotmapp_list = raw_modslotmapp_list.splitlines() if debug: print 'The raw value returned was:' print modslotmapp_list if ('ERROR:' in raw_modslotmapp_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modslotmapp_list showmodprocmapp_dict[process] = {'Error':raw_modslotmapp_list.strip()} continue elif raw_modslotmapp_list == "": # no output. Give out warning and continue on print "Command %s shows no output" %command continue labels_line = modslotmapp_list[2].split() divider_line = modslotmapp_list[3] columnDict = parse_divider_line(self,divider_line) if debug: print 'The columnDict is:' print columnDict temp_dict = {} for raw_line in modslotmapp_list[4:]: line = raw_line local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() for labels_idx in range(1,len(labels_line)): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 local_dict[labels_line[labels_idx]] = line[start:end].strip() if debug: print("The %s is: %s " %(labels_line[labels_idx],local_dict[labels_line[labels_idx]])) # We store each entry in the temp dictionary temp_dict[name] = local_dict # We store each temp dictionary to process showmodprocmapp_dict[process] = temp_dict return showmodprocmapp_dict def showmoduleprocessma(self,slot): showmodprocma_dict = {} debug = False # Sample raw input """ brazil[local]#show module NSM slot 2 ma Type Usage Allocs Frees ------------------------ ------------- ------------- ------------- Slabs 2,097,152 2 0 Pools 628,020 137,486 136,914 Default VarPool 107,808 402 302 VarPool Fixed Pools 732,176 60,522 60,454 VarPool malloc 0 0 0 Shared Pools 0 0 0 Persistent Pools 12,288 8 0 malloc 7,757,824 Overhead 18,192 94 0 MMap 2,097,152 2 0 User MMap 724 1 0 brazil[local]# Sample output: ============== 'NSM': { 'Default VarPool': { 'Allocs': '569', 'Frees': '469', 'Usage': '107,808'}, 'MMap': { 'Allocs': '2', 'Frees': '0', 'Usage': '2,097,152'}, 'Overhead': { 'Allocs': '94', 'Frees': '0', 'Usage': '18,192'}, 'Persistent Pools': { 'Allocs': '8', 'Frees': '0', 'Usage': '12,288'}, 'Pools': { 'Allocs': '287,847', 'Frees': '287,275', 'Usage': '628,020'}, 'Shared Pools': { 'Allocs': '0', 'Frees': '0', 'Usage': '0'}, 'Slabs': { 'Allocs': '2', 'Frees': '0', 'Usage': '2,097,152'}, 'User MMap': { 'Allocs': '1', 'Frees': '0', 'Usage': '724'}, 'VarPool Fixed Pools': { 'Allocs': '127,048', 'Frees': '126,980', 'Usage': '732,176'}, 'VarPool malloc': { 'Allocs': '0', 'Frees': '0', 'Usage': '0'}, 'malloc': { 'Allocs': '', 'Frees': '', 'Usage': '7,757,824'}}} """ # call to get a list of processes on this slot processMemory_dict = show_process_memory(self,slot) #pprint(processMemory_dict,indent=4,width=20,depth=20) process_dict = {} for process in processMemory_dict.keys(): if process == "Status": # show_process_memory returns error then skip if processMemory_dict['Status'] == "Error": continue elif re.search('.*_\d+',process) != None: # probably _<digit> added to differentiate same process name in show_process_memory, then skip it continue command = "show module %s slot %s ma" %(process,slot) raw_modslotma_list = self.cmd(command) modslotma_list = raw_modslotma_list.splitlines() if debug: print 'The raw value returned was:' print modslotma_list if ('ERROR:' in raw_modslotma_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modslotma_list showmodprocma_dict[process] = {'Error':raw_modslotma_list.strip()} continue elif raw_modslotma_list == "": # no output. Give out warning and continue on print "Command %s shows no output" %command continue labels_line = modslotma_list[1].split() divider_line = modslotma_list[2] columnDict = parse_divider_line(self,divider_line) if debug: print 'The columnDict is:' print columnDict temp_dict = {} for raw_line in modslotma_list[3:]: line = raw_line local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() for labels_idx in range(1,len(labels_line)): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 local_dict[labels_line[labels_idx]] = line[start:end].strip() if debug: print("The %s is: %s " %(labels_line[labels_idx],local_dict[labels_line[labels_idx]])) # We store each entry in the temp dictionary temp_dict[name] = local_dict # We store each temp dictionary to process showmodprocma_dict[process] = temp_dict return showmodprocma_dict def getshowmemcounters(self): """ Call show_mem to get data, but remove the "slot" keyword and remove time stamp entry """ shMemory_dict = show_mem(self.ssx) tmpDict = {} for slot in shMemory_dict.keys(): if slot == "time stamp": continue newSlot = slot[-1:] tmpDict[newSlot] = shMemory_dict[slot] return tmpDict def showmoduleprocessmappslab(self,slot): # Per Greg comment, treat this data as a slob, meaning calculate a total of how many entries # and the sum of "Space In Use" and report as one data point. showmodprocmappslab_dict = {} debug = False # Sample raw input """ {'Count': { 'Space In Use': 8204288, 'Total Entry': 8}, 'DHCPdLC': { 'Space In Use': 99328, 'Total Entry': 1}, 'Evl': { 'Space In Use': 99328, 'Total Entry': 1}, 'Evt': { 'Space In Use': 111616, 'Total Entry': 1}, 'Fpd': { 'Space In Use': 99328, 'Total Entry': 1}, 'Iked': { 'Space In Use': 8910848, 'Total Entry': 9}, 'Inspectd': { 'Space In Use': 99328, 'Total Entry': 1}, 'IpLc': { 'Space In Use': 99328, 'Total Entry': 1}, 'NSM': { 'Space In Use': 99328, 'Total Entry': 1}} """ # call to get a list of processes on this slot processMemory_dict = show_process_memory(self,slot) #pprint(processMemory_dict,indent=4,width=20,depth=20) process_dict = {} for process in processMemory_dict.keys(): if process == "Status": # show_process_memory returns error then skip if processMemory_dict['Status'] == "Error": continue elif re.search('.*_\d+',process) != None: # probably _<digit> added to differentiate same process name in show_process_memory, then skip it continue command = "show module %s slot %s ma pp-slab" %(process,slot) raw_modslotmappslab_list = self.cmd(command) modslotmappslab_list = raw_modslotmappslab_list.splitlines() if debug: print 'The raw value returned was:' print modslotmappslab_list if ('ERROR:' in raw_modslotmappslab_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modslotmappslab_list showmodprocmappslab_dict[process] = {'Error':raw_modslotmappslab_list.strip()} continue elif raw_modslotmappslab_list == "": # no output. Give out warning and continue on print "Command %s shows no output" %command continue labels_line1 = modslotmappslab_list[1] labels_line2 = modslotmappslab_list[2] divider_line = modslotmappslab_list[3] columnDict = parse_divider_line(self,divider_line) if debug: print 'The columnDict is:' print columnDict temp_dict = {} sum = 0 for raw_line in modslotmappslab_list[4:-1]: line = raw_line local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() for labels_idx in range(1,len(columnDict.keys())): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 label = labels_line1[start:end].strip() + " " + labels_line2[start:end].strip() label = label.strip() local_dict[label] = line[start:end].strip() if debug: print("The %s is: %s " %(label,local_dict[label])) # calculate the sum of inuse by adding size and subtracting free space if labels_idx == 1: # add it sum += int(local_dict[label].replace(',','')) elif labels_idx == 2: # subtract it sum -= int(local_dict[label].replace(',','')) # We store each entry in the temp dictionary temp_dict[name] = local_dict # We store each temp dictionary to process showmodprocmappslab_dict[process] = {'Total Entry':str(len(modslotmappslab_list[4:-1])),'Space In Use':str(sum)} return showmodprocmappslab_dict def showmoduleprocessmaslab(self,slot): # Per Greg comment, treat this data as a slob, meaning calculate a total of how many entries # and the sum of "Space In Use" and report as one data point. showmodprocmaslab_dict = {} debug = False # Sample raw input """ {'Count': { 'Space In Use': 6480896, 'Total Entry': 7}, 'DHCPdLC': { 'Space In Use': 1531904, 'Total Entry': 2}, 'Evl': { 'Space In Use': 1525760, 'Total Entry': 2}, 'Evt': { 'Space In Use': 1561600, 'Total Entry': 2}, 'Fpd': { 'Space In Use': 1505280, 'Total Entry': 2}, 'Iked': { 'Space In Use': 36207616, 'Total Entry': 35}, 'Inspectd': { 'Space In Use': 2042880, 'Total Entry': 2}, 'IpLc': { 'Space In Use': 39867392, 'Total Entry': 39}, 'NSM': { 'Space In Use': 2301952, 'Total Entry': 3}} """ # call to get a list of processes on this slot processMemory_dict = show_process_memory(self,slot) #pprint(processMemory_dict,indent=4,width=20,depth=20) process_dict = {} for process in processMemory_dict.keys(): if process == "Status": # show_process_memory returns error then skip if processMemory_dict['Status'] == "Error": continue elif re.search('.*_\d+',process) != None: # probably _<digit> added to differentiate same process name in show_process_memory, then skip it continue command = "show module %s slot %s ma slab" %(process,slot) raw_modslotmaslab_list = self.cmd(command) modslotmaslab_list = raw_modslotmaslab_list.splitlines() if debug: print 'The raw value returned was:' print modslotmaslab_list if ('ERROR:' in raw_modslotmaslab_list): print 'Detected an error when running: ' + command print 'Returned text was:' print raw_modslotmaslab_list showmodprocmaslab_dict[process] = {'Error':raw_modslotmaslab_list.strip()} continue elif raw_modslotmaslab_list == "": # no output. Give out warning and continue on print "Command %s shows no output" %command continue labels_line1 = modslotmaslab_list[1] labels_line2 = modslotmaslab_list[2] divider_line = modslotmaslab_list[3] columnDict = parse_divider_line(self,divider_line) if debug: print 'The columnDict is:' print columnDict temp_dict = {} sum = 0 for raw_line in modslotmaslab_list[4:-1]: line = raw_line local_dict = {} if debug: print '----------------------------------------------' print 'The line to be processes is:' print line start = columnDict[0][0] end = columnDict[0][1]+1 name = line[start:end].strip() for labels_idx in range(1,len(columnDict.keys())): start = columnDict[labels_idx][0] end = columnDict[labels_idx][1]+1 label = labels_line1[start:end].strip() + " " + labels_line2[start:end].strip() label = label.strip() local_dict[label] = line[start:end].strip() if debug: print("The %s is: %s " %(label,local_dict[label])) # calculate the sum of "Space in Use" in column 1 if labels_idx == 1: sum += int(local_dict[label].replace(',','')) # We store each entry in the temp dictionary temp_dict[name] = local_dict # We store each temp dictionary to process #showmodprocmaslab_dict[process] = temp_dict showmodprocmaslab_dict[process] = {'Total Entry':str(len(modslotmaslab_list[4:-1])),'Space In Use':str(sum)} return showmodprocmaslab_dict #================================ """ def uninstall(self,version = ""): # Uninstall a package. If verion is specified, uninstall that version # Otherwise, choose an avaialble version to install debug = True if version == "": # call to get a list of installed version installed_version = show_versions_and_build(self) if debug: pprint(installed_version,indent=4,width=20,depth=20) # try to uninstall one version enable_prompt_regex = "[\r\n]*\S+\[\S+\]#" yesno_prompt_regex =".*[\r\n.]*\(\[*yes\]*/\[*no\]*\)\s*$" for ver in installed_version.keys(): self.sendline('system uninstall package %s' %ver) done = False while not done: retr == self.expect(yesno_prompt_regex,enable_prompt_regex, timeout = 10) if retr == 0: self.sendline('system uninstall package %s' %ver) # This is the password option: ses.sendline(password) output = self.cmd("system uninstall package %s" %ver) """ #================================ # End section added by Anthony Ton
[ "muttu2244@yahoo.com" ]
muttu2244@yahoo.com
5a813bd10a9a6555bcb7a31df0d331852598cdba
5088fffefcbb3458ee2c8fca6d822487e13c4169
/04-zanke/monte_carlo.py
92515bfcf694126c02f491519d94ea6ab3eda678
[]
no_license
matijapretnar/uvod-v-programiranje
95de86fb63d6d06558984c05a40690f78d15aa5f
464a9c566ed3564a6baba60e7c79f9e25399d45e
refs/heads/master
2023-04-06T00:28:57.011142
2023-04-04T10:49:56
2023-04-04T10:49:56
52,275,510
5
34
null
2022-03-16T10:12:55
2016-02-22T13:32:48
Python
UTF-8
Python
false
false
853
py
import random def oceni_pi(n): v_krogu = 0 for i in range(1, n + 1): x = random.uniform(-1, 1) y = random.uniform(-1, 1) if x ** 2 + y ** 2 <= 1: v_krogu += 1 print(4 * v_krogu / i) delez_v_krogu = v_krogu / n return 4 * delez_v_krogu def nakljucna_tocka_v_krogu(x0=0, y0=0, r=1): while True: x = random.uniform(x0 - r, x0 + r) y = random.uniform(y0 - r, y0 + r) if (x - x0) ** 2 + (y - y0) ** 2 <= r ** 2: return x, y def nesmiselna_naloga(st_poskusov): razdalja_manj_kot_pol = 0 for _ in range(st_poskusov): x1, y1 = nakljucna_tocka_v_krogu() x2, y2 = nakljucna_tocka_v_krogu() if (x2 - x1) ** 2 + (y2 - y1) ** 2 <= (1 / 2) ** 2: razdalja_manj_kot_pol += 1 return razdalja_manj_kot_pol / st_poskusov
[ "matija@pretnar.info" ]
matija@pretnar.info
9a0ceb1f8a9e8cca78d4939bcf31c244e4acd324
e1abd868bfad11bf93c50eee1dc9976674de2358
/scaffold/suite/mass_flux_spatial_scales_plot.py
e0c9cd702c8515ce963bc91851a1de04cd43b566
[]
no_license
markmuetz/scaffold_analysis
5c7e9d04b24abe3462c8946381f4cab264bf09e0
c02d32536c801b23ac8a71e36d25fa922e7cfd94
refs/heads/master
2022-06-03T16:13:54.775718
2022-05-31T13:22:24
2022-05-31T13:22:24
92,677,664
0
0
null
null
null
null
UTF-8
Python
false
false
7,255
py
from itertools import groupby import matplotlib import numpy as np matplotlib.use('Agg') import pylab as plt from omnium import Analyser from scaffold.utils import cm_to_inch class MassFluxSpatialScalesPlotter(Analyser): """Plots histograms of mass flux for each power of 2 (n), and expt.""" analysis_name = 'mass_flux_spatial_scales_plot' multi_expt = True input_dir = 'omnium_output/{version_dir}/{expt}' input_filename = '{input_dir}/atmos.mass_flux_spatial_scales_combined.nc' output_dir = 'omnium_output/{version_dir}/suite_{expts}' output_filenames = ['{output_dir}/atmos.mass_flux_spatial_scales_plot.dummy'] def load(self): self.load_cubes() def run(self): pass def save(self, state, suite): with open(self.task.output_filenames[0], 'w') as f: f.write('done') def display_results(self): self.nbins = None self.x_cutoff = 0 self.xlim = None self.ylim = None self._plot_mass_flux_spatial() plt.close('all') def _plot_mass_flux_spatial(self): self.append_log('plotting mass_flux_spatial') heights = [] ns = [] for expt in self.task.expts: cubes = self.expt_cubes[expt] sorted_cubes = [] for cube in cubes: (height_level_index, thresh_index, n) = cube.attributes['mass_flux_spatial_key'] mf_key = (height_level_index, thresh_index, n) sorted_cubes.append((mf_key, cube)) # Each element is a tuple like: ((1, 2, 32), cube) # Sorting will put in correct order, sorting on initial tuple. sorted_cubes.sort() # Group on first element of tuple, i.e. on 1 for ((1, 2, 32), cube) for height_index, key_cubes in groupby(sorted_cubes, lambda x: x[0][0]): if height_index not in heights: heights.append(height_index) hist_data = [] dmax = 0 for i, key_cube in enumerate(key_cubes): # middle cube is the one with the middle thresh_index. mf_key = key_cube[0] cube = key_cube[1] # Pick out middle element, i.e. thresh_index == 1. if mf_key[1] == 1: hist_data.append((mf_key, cube)) dmax = max(cube.data.max(), dmax) # assert len(hist_data) == 3 for mf_key, hist_datum in hist_data: (height_index, thresh_index, n) = mf_key if n not in ns: ns.append(n) name = '{}.z{}.n{}.hist'.format(expt, height_index, n) plt.figure(name) plt.clf() plt.title('{} z{} n{} mass_flux_spatial_hist'.format(expt, height_index, n)) hist_kwargs = {} if self.xlim: hist_kwargs['range'] = self.xlim else: #hist_kwargs['range'] = (0, 0.1) pass if self.nbins: hist_kwargs['bins'] = self.nbins filtered_data = hist_datum.data[hist_datum.data >= self.x_cutoff] y, bin_edges = np.histogram(filtered_data, **hist_kwargs) bin_centers = 0.5 * (bin_edges[1:] + bin_edges[:-1]) # N.B. full width bins. width = bin_edges[1:] - bin_edges[:-1] plt.bar(bin_centers, y / n**2, width=width) if self.xlim: plt.xlim(self.xlim) if self.ylim: plt.ylim(self.ylim) plt.savefig(self.file_path(name + '.png')) name = '{}.z{}.all_n.hist'.format(expt, height_index) plt.figure(name) plt.plot(bin_centers, y / n**2, label=n) plt.figure('combined_expt_z{}_n{}'.format(height_index, n)) plt.plot(bin_centers, y / n**2, label=expt) both_name = 'both_z{}'.format(height_index) if plt.fignum_exists(both_name): f = plt.figure(both_name) ax1, ax2 = f.axes # f_poster f_p = plt.figure('poster_' + both_name) ax1_p, ax2_p = f_p.axes else: f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, num=both_name) ax1.set_ylabel('Frequency (rescaled)') ax2.set_ylabel('Frequency (rescaled)') ax2.set_xlabel('Mass flux (kg s$^{-1}$ m$^{-2}$)') if self.xlim: ax1.set_xlim(self.xlim) f_p, (ax1_p, ax2_p) = plt.subplots(1, 2, sharex=True, num='poster_' + both_name) ax1_p.set_ylabel('Frequency (rescaled)') ax1_p.set_xlabel('Mass flux (kg s$^{-1}$ m$^{-2}$)') ax2_p.set_xlabel('Mass flux (kg s$^{-1}$ m$^{-2}$)') if self.xlim: ax1_p.set_xlim(self.xlim) ax2_p.set_xlim(self.xlim) styles = {1: 'b-', 2: 'b--', 4: 'b-.'} if expt == 'S0' and n <= 4: style = styles[n] ax1.plot(bin_centers, y / n**2, style, label=n) ax1_p.plot(bin_centers, y / n**2, style, label=n) if n == 1: ax2.plot(bin_centers, y / n**2, label=expt) ax2_p.plot(bin_centers, y / n**2, label=expt) for height_index in heights: f = plt.figure('both_z{}'.format(height_index)) ax1, ax2 = f.axes ax1.legend(loc='upper right') ax2.legend(loc='upper right') plt.savefig(self.file_path('both_z{}.png'.format(height_index))) f_p = plt.figure('poster_both_z{}'.format(height_index)) f_p.set_size_inches(*cm_to_inch(25, 9)) ax1_p, ax2_p = f_p.axes ax1_p.legend(loc='upper right') ax2_p.legend(loc='upper right') plt.tight_layout() plt.savefig(self.file_path('poster_both_z{}.png'.format(height_index))) for expt in self.task.expts: name = '{}.z{}.all_n.hist'.format(expt, height_index) plt.figure(name) plt.title(name) plt.legend() plt.savefig(self.file_path(name + '.png')) for n in ns: plt.figure('combined_expt_z{}_n{}'.format(height_index, n)) plt.title('combined_expt_z{}_n{}'.format(height_index, n)) plt.legend() if self.xlim: plt.xlim(self.xlim) plt.savefig(self.file_path('z{}_n{}_combined.png'.format(height_index, n)))
[ "markmuetz@gmail.com" ]
markmuetz@gmail.com
236a43ce48ae7a3dc607333f6288c4fc335cd1aa
99feebd7e64a1961bd3f3c3b152c013b35bc9bad
/testCase/accounts_login_password_test.py
9c57ce1499bc222b00590c7440c7932a340c9b86
[]
no_license
andy-29/AutomatedTest
a551fb8d2d608c5191a9f1d71a30188f9a19bba5
1c3d2b5295f4b6df4e9321f6a75740a3970df3e4
refs/heads/master
2020-06-16T15:24:24.418593
2019-06-05T06:26:19
2019-06-05T06:26:19
195,621,212
0
0
null
null
null
null
UTF-8
Python
false
false
1,518
py
import os, sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) func = os.path.basename(__file__).split('_test.py')[0] from common.gmpackage import * @ddt class Accounts_Login_Password(unittest.TestCase): ''' 登入接口 ''' def setUp(self): self.host = g.host self.api_name = g.api_name(func) self.url = self.host + self.api_name @data(*(get_values(func, "test_accounts_login_password"))) def test_accounts_login_password(self, value): self._testMethodDoc = '登入接口' r = gmhttp.login() self.assertEqual(0,r.get('error')) @data(*(get_values(func, "test_accounts_login_password_errorPwd"))) def test_accounts_login_password_errorPwd(self, value): self._testMethodDoc = '账号正确,密码错误' user = value.get('requestdata').get('phone') pwd = value.get('requestdata').get('password') r = gmhttp.login(user,pwd) self.assertEqual(r, value.get('assertdata')) @data(*(get_values(func, "test_accounts_login_password_errorTel"))) def test_accounts_login_password_errorTel(self, value): self._testMethodDoc = '账号错误' user = value.get('requestdata').get('phone') pwd = value.get('requestdata').get('password') r = gmhttp.login(user,pwd) self.assertEqual(r, value.get('assertdata')) def tearDown(self): pass if __name__ == "__main__": Accounts_Login_Password.run()
[ "dayuezaichunji@163.com" ]
dayuezaichunji@163.com
8f9ef0086d4ee19c301005731bf09b20b0fc8a5c
9c21e49150c99751231ad399bdba1850bb60c88c
/keepers/migrations/0012_auto_20180619_0056.py
359b76f9d01a20e6c2e0917a4540eb44a4c47177
[ "MIT" ]
permissive
netvigator/auctions
3ab4086cb0bfbc736b17ede4e928f3ead2b08a4c
fc3766226cc65ac8694dffc74e893ecff8e7d07c
refs/heads/main
2023-05-25T15:55:01.249670
2023-05-06T14:51:12
2023-05-06T14:51:12
92,816,101
0
0
MIT
2023-02-16T05:24:34
2017-05-30T09:14:39
Python
UTF-8
Python
false
false
669
py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-06-19 00:56 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('keepers', '0011_auto_20180615_1818'), ] operations = [ migrations.AlterField( model_name='item', name='cSite', field=models.CharField(max_length=14, verbose_name='Site'), ), migrations.AlterField( model_name='item', name='tCreate', field=models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='created on'), ), ]
[ "gravesricharde@yahoo.com" ]
gravesricharde@yahoo.com
3118055357e21e818369addcd8052d38382bdada
060ce17de7b5cdbd5f7064d1fceb4ded17a23649
/fn_soar_utils/fn_soar_utils/components/funct_soar_utils_artifact_hash.py
fa0c9212fa4a7c4ee6fd5991f38a41c0ca9545f1
[ "MIT" ]
permissive
ibmresilient/resilient-community-apps
74bbd770062a22801cef585d4415c29cbb4d34e2
6878c78b94eeca407998a41ce8db2cc00f2b6758
refs/heads/main
2023-06-26T20:47:15.059297
2023-06-23T16:33:58
2023-06-23T16:33:58
101,410,006
81
107
MIT
2023-03-29T20:40:31
2017-08-25T14:07:33
Python
UTF-8
Python
false
false
2,521
py
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2018, 2022. All Rights Reserved. # pragma pylint: disable=unused-argument, no-self-use """Function implementation""" from json import dumps from logging import getLogger from hashlib import algorithms_guaranteed, new from resilient_lib import get_file_attachment, get_file_attachment_metadata, validate_fields from resilient_circuits import ResilientComponent, function, StatusMessage, FunctionResult, FunctionError LOG = getLogger(__name__) class FunctionComponent(ResilientComponent): """Component that implements SOAR function 'artifact_hash""" @function("soar_utils_artifact_hash") def _artifact_hash_function(self, event, *args, **kwargs): """Function: Calculate hashes for a file artifact.""" try: # Validate required inputs validate_fields(["incident_id", "artifact_id"], kwargs) # Get the function parameters: incident_id = kwargs.get("incident_id") # number artifact_id = kwargs.get("artifact_id") # number LOG.info("incident_id: %s", incident_id) LOG.info("artifact_id: %s", artifact_id) yield StatusMessage("Reading artifact...") client = self.rest_client() metadata = get_file_attachment_metadata(client, incident_id, artifact_id=artifact_id) data = get_file_attachment(client, incident_id, artifact_id=artifact_id) results = { "filename": metadata["name"], "content_type": metadata["content_type"], "size": metadata["size"], "created": metadata["created"] } # Hashlib provides a list of all "algorithms_available", but there's duplication, so # use the standard list: ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512') for algo in algorithms_guaranteed: impl = new(algo) impl.update(data) # shake algorithms require a 'length' parameter if algo.startswith("shake_"): results[algo] = impl.hexdigest(int(algo.split('_')[-1])) else: results[algo] = impl.hexdigest() LOG.info("%s sha1=%s", metadata["name"], results["sha1"]) # Produce a FunctionResult with the return value LOG.debug(dumps(results)) yield FunctionResult(results) except Exception: yield FunctionError()
[ "travis@example.org" ]
travis@example.org
6bd7ea042d4999a8e460c696c13d9bf95d339f9e
6f958fa3e9505d9cd0e75f51008de8e2d1c8c12f
/area/utils.py
7bd1474cb10f69ff99f85048316243a66a11b5b0
[]
no_license
yoachim/satellite_collisions
3b59472ae6672dda7ff28916879ce6ed6370a42c
4b5f475518cef526d117d83873e885a1fbd7aee8
refs/heads/master
2022-02-22T21:27:32.106308
2022-02-02T16:18:30
2022-02-02T16:18:30
220,065,836
0
0
null
null
null
null
UTF-8
Python
false
false
12,845
py
import datetime import numpy as np from astropy import time from astropy import units as u from astropy import constants as const from astropy.coordinates import EarthLocation from pycraf import satellite from rubin_sim.utils import Site import skyfield.sgp4lib as sgp4lib from astropy.time import Time import ephem from rubin_sim.utils import _angularSeparation, _buildTree, _xyz_from_ra_dec, xyz_angular_radius from rubin_sim.scheduler.utils import read_fields import healpy as hp # adapting from: # https://github.com/cbassa/satellite_analysis # https://nbviewer.jupyter.org/github/yoachim/19_Scratch/blob/master/sat_collisions/bwinkel_constellation.ipynb def grow_hp(inmap, hpids, radius=1.75, replace_val=np.nan): """ grow a healpix mask Parameters ---------- inmap : np.array A HEALpix map hpids : array The healpixel values to grow around radius : float (1.75) The radius to grow around each point (degrees) replace_val : float (np.nan) The value to plug into the grown areas """ nside = hp.npix2nside(np.size(inmap)) theta, phi = hp.pix2ang(nside=nside, ipix=hpids) vec = hp.ang2vec(theta, phi) ipix_disc = [hp.query_disc(nside=nside, vec=vector, radius=np.radians(radius)) for vector in vec] ipix_disc = np.unique(np.concatenate(ipix_disc)) outmap = inmap + 0 outmap[ipix_disc] = replace_val return outmap def satellite_mean_motion(altitude, mu=const.GM_earth, r_earth=const.R_earth): ''' Compute mean motion of satellite at altitude in Earth's gravitational field. See https://en.wikipedia.org/wiki/Mean_motion#Formulae ''' no = np.sqrt(4.0 * np.pi ** 2 * (altitude + r_earth) ** 3 / mu).to(u.day) return 1 / no def tle_from_orbital_parameters(sat_name, sat_nr, epoch, inclination, raan, mean_anomaly, mean_motion): ''' Generate TLE strings from orbital parameters. Note: epoch has a very strange format: first two digits are the year, next three digits are the day from beginning of year, then fraction of a day is given, e.g. 20180.25 would be 2020, day 180, 6 hours (UT?) ''' # Note: RAAN = right ascention (or longitude) of ascending node def checksum(line): s = 0 for c in line[:-1]: if c.isdigit(): s += int(c) if c == "-": s += 1 return '{:s}{:1d}'.format(line[:-1], s % 10) tle0 = sat_name tle1 = checksum( '1 {:05d}U 20001A {:14.8f} .00000000 00000-0 50000-4 ' '0 0X'.format(sat_nr, epoch)) tle2 = checksum( '2 {:05d} {:8.4f} {:8.4f} 0001000 0.0000 {:8.4f} ' '{:11.8f} 0X'.format( sat_nr, inclination.to_value(u.deg), raan.to_value(u.deg), mean_anomaly.to_value(u.deg), mean_motion.to_value(1 / u.day) )) return '\n'.join([tle0, tle1, tle2]) def create_constellation(altitudes, inclinations, nplanes, sats_per_plane, epoch=22050.1, name='Test'): my_sat_tles = [] sat_nr = 8000 for alt, inc, n, s in zip( altitudes, inclinations, nplanes, sats_per_plane): if s == 1: # random placement for lower orbits mas = np.random.uniform(0, 360, n) * u.deg raans = np.random.uniform(0, 360, n) * u.deg else: mas = np.linspace(0.0, 360.0, s, endpoint=False) * u.deg mas += np.random.uniform(0, 360, 1) * u.deg raans = np.linspace(0.0, 360.0, n, endpoint=False) * u.deg mas, raans = np.meshgrid(mas, raans) mas, raans = mas.flatten(), raans.flatten() mm = satellite_mean_motion(alt) for ma, raan in zip(mas, raans): my_sat_tles.append( tle_from_orbital_parameters( name+' {:d}'.format(sat_nr), sat_nr, epoch, inc, raan, ma, mm)) sat_nr += 1 return my_sat_tles def starlink_constellation(supersize=False, fivek=False, fourk=False): """ Create a list of satellite TLE's """ #altitudes = np.array([550, 1110, 1130, 1275, 1325, 345.6, 340.8, 335.9]) #inclinations = np.array([53.0, 53.8, 74.0, 81.0, 70.0, 53.0, 48.0, 42.0]) #nplanes = np.array([72, 32, 8, 5, 6, 2547, 2478, 2493]) #sats_per_plane = np.array([22, 50, 50, 75, 75, 1, 1, 1]) # new values from Bruce Macintosh from FCC application altitudes = np.array([328, 334, 345, 360, 373, 499, 604, 614], dtype=float) inclinations = np.array([30., 40., 53., 96.9, 75., 53, 148., 115.7]) nplanes = np.array([1, 1, 1, 40, 1, 1, 12, 18]) sats_per_plane = np.array([7178, 7178, 7178, 50, 1998, 4000, 12, 18]) if fourk: altitudes = np.array([550, 540, 570, 560, 560], dtype=float) inclinations = np.array([53, 53.2, 70, 97.6, 97.6]) nplanes = np.array([72, 72, 36, 6, 4]) sats_per_plane = np.array([22, 22, 20, 58, 43]) if supersize: # Let's make 4 more altitude and inclinations new_altitudes = [] new_inclinations = [] new_nplanes = [] new_sat_pp = [] for i in np.arange(0, 4): new_altitudes.append(altitudes+i*20) new_inclinations.append(inclinations+3*i) new_nplanes.append(nplanes) new_sat_pp.append(sats_per_plane) altitudes = np.concatenate(new_altitudes) inclinations = np.concatenate(new_inclinations) nplanes = np.concatenate(new_nplanes) sats_per_plane = np.concatenate(new_sat_pp) altitudes = altitudes * u.km inclinations = inclinations * u.deg my_sat_tles = create_constellation(altitudes, inclinations, nplanes, sats_per_plane, name='Starl') if fivek: stride = round(len(my_sat_tles)/5000) my_sat_tles = my_sat_tles[::stride] return my_sat_tles time_J2000 = datetime.datetime(2000, 1, 1, 12, 0) def _propagate(sat, dt): ''' True equator mean equinox (TEME) position from `sgp4` at given time. Then converted to ITRS Parameters ---------- sat : `sgp4.io.Satellite` instance Satellite object filled from TLE dt : `~datetime.datetime` Time Returns ------- xs, ys, zs : float TEME (=True equator mean equinox) position of satellite [km] ''' # pos [km], vel [km/s] position, velocity = sat.propagate( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second + dt.microsecond / 1e6) if position is None: raise ValueError('Satellite propagation error') # I _think_ this is supposed to take time since J2000 in days? # looking at https://space.stackexchange.com/questions/25988/sgp4-teme-frame-to-j2000-conversion jd_ut1 = dt - time_J2000 jd_ut1 = jd_ut1.days + jd_ut1.seconds/(3600.*24) new_position, new_velocity = sgp4lib.TEME_to_ITRF(jd_ut1, np.array(position), np.array(velocity)*86400) return tuple(new_position.tolist()) vec_propagate = np.vectorize(_propagate, excluded=['sat'], otypes=[np.float64] * 3) def lsst_location(): site = Site('LSST') obs_loc_lsst = EarthLocation(lat=site.latitude, lon=site.longitude, height=site.height) sat_obs_lsst = satellite.SatelliteObserver(obs_loc_lsst) return sat_obs_lsst class Constellation(object): """ Have a class to hold ephem satellite objects Parameters ---------- sat_tle_list : list of str A list of satellite TLEs to be used tstep : float (5) The time step to use when computing satellite positions in an exposure """ def __init__(self, sat_tle_list, alt_limit=30., fov=3.5, tstep=5., exptime=30.): self.sat_list = [ephem.readtle(tle.split('\n')[0], tle.split('\n')[1], tle.split('\n')[2]) for tle in sat_tle_list] self.alt_limit_rad = np.radians(alt_limit) self.fov_rad = np.radians(fov) self._make_observer() self._make_fields() self.tsteps = np.arange(0, exptime+tstep, tstep)/3600./24. # to days self.radius = xyz_angular_radius(fov) def _make_fields(self): """ Make tesselation of the sky """ # RA and dec in radians fields = read_fields() # crop off so we only worry about things that are up good = np.where(fields['dec'] > (self.alt_limit_rad - self.fov_rad))[0] self.fields = fields[good] self.fields_empty = np.zeros(self.fields.size) # we'll use a single tessellation of alt az leafsize = 100 self.tree = _buildTree(self.fields['RA'], self.fields['dec'], leafsize, scale=None) def _make_observer(self): telescope = Site(name='LSST') self.observer = ephem.Observer() self.observer.lat = telescope.latitude_rad self.observer.lon = telescope.longitude_rad self.observer.elevation = telescope.height def advance_epoch(self, advance=100): """ Advance the epoch of all the satellites """ # Because someone went and put a valueError where there should have been a warning # I prodly present the hackiest kludge of all time for sat in self.sat_list: sat._epoch += advance def update_mjd(self, mjd): """ observer : ephem.Observer object """ self.observer.date = ephem.date(time.Time(mjd, format='mjd').datetime) self.altitudes_rad = [] self.azimuth_rad = [] self.eclip = [] for sat in self.sat_list: try: sat.compute(self.observer) except ValueError: self.advance_epoch() sat.compute(self.observer) self.altitudes_rad.append(sat.alt) self.azimuth_rad.append(sat.az) self.eclip.append(sat.eclipsed) self.altitudes_rad = np.array(self.altitudes_rad) self.azimuth_rad = np.array(self.azimuth_rad) self.eclip = np.array(self.eclip) # Keep track of the ones that are up and illuminated self.above_alt_limit = np.where((self.altitudes_rad >= self.alt_limit_rad) & (self.eclip == False))[0] def fields_hit(self, mjd, fraction=False): """ Return an array that lists the number of hits in each field pointing """ mjds = mjd + self.tsteps result = self.fields_empty.copy() # convert the satellites above the limits to x,y,z and get the neighbors within the fov. for mjd in mjds: self.update_mjd(mjd) x, y, z = _xyz_from_ra_dec(self.azimuth_rad[self.above_alt_limit], self.altitudes_rad[self.above_alt_limit]) if np.size(x) > 0: indices = self.tree.query_ball_point(np.array([x, y, z]).T, self.radius) final_indices = [] for indx in indices: final_indices.extend(indx) result[final_indices] += 1 if fraction: n_hit = np.size(np.where(result > 0)[0]) result = n_hit/self.fields_empty.size return result def check_pointing(self, pointing_alt, pointing_az, mjd): """ See if a pointing has a satellite in it pointing_alt : float Altitude of pointing (degrees) pointing_az : float Azimuth of pointing (degrees) mjd : float Modified Julian Date at the start of the exposure Returns ------- in_fov : float Returns the fraction of time there is a satellite in the field of view. Values >1 mean there were on average more than one satellite in the FoV. Zero means there was no satllite in the image the entire exposure. """ mjds = mjd + self.tsteps in_fov = 0 for mjd in mjds: self.update_mjd(mjd) ang_distances = _angularSeparation(self.azimuth_rad[self.above_alt_limit], self.altitudes_rad[self.above_alt_limit], np.radians(pointing_az), np.radians(pointing_alt)) in_fov += np.size(np.where(ang_distances <= self.fov_rad)[0]) in_fov = in_fov/mjds.size return in_fov def look_ahead(self, pointing_alt, pointing_az, mjds): """ Return 1 if satellite in FoV, 0 if clear """ result = [] for mjd in mjds: self.update_mjd(mjd) ang_distances = _angularSeparation(self.azimuth_rad[self.above_alt_limit], self.altitudes_rad[self.above_alt_limit], np.radians(pointing_az), np.radians(pointing_alt)) if np.size(np.where(ang_distances <= self.fov_rad)[0]) > 0: result.append(1) else: result.append(0) return result
[ "yoachim@uw.edu" ]
yoachim@uw.edu
a694e62f4c790eab767286b4be22a9c5f5e4a41e
8b20fdc16253b2b4e07ce28f4fd3120db4566783
/pythainlp/__init__.py
47bffa93eda32cec984d87f336d8c648c66c28bf
[ "Apache-2.0", "Swift-exception" ]
permissive
johnnyduo/pythainlp
d8a850fa7b6d9dfed5eb23f84264caea1703f5fb
dbefc4c88ee8051a14e3be1a10a57670f861cd37
refs/heads/master
2021-06-19T23:49:43.564140
2017-07-06T10:36:58
2017-07-06T10:36:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
898
py
# -*- coding: utf-8 -*- from __future__ import absolute_import import six if six.PY3: """ ไว้ใส่ความสามารถที่รองรับเฉพาะ Python 3.4+ เท่านั้น """ from pythainlp.sentiment import sentiment from pythainlp.spell import hunspell,spell from pythainlp.romanization import romanization,pyicu,royin from pythainlp.tokenize import word_tokenize,tcc,etcc from pythainlp.rank import rank from pythainlp.change import texttothai,texttoeng from pythainlp.number import nttn,nttt,ntnt,ntt,ttn,ttnt,number_format,numtowords,ReadNumber from pythainlp.date import now from pythainlp.tag import old,pos_tag from pythainlp.collation import collation from pythainlp.test import TestUM from pythainlp.Text import Text from pythainlp.MetaSound import MetaSound from pythainlp.soundex import LK82,Udom83 from pythainlp.util import ngrams
[ "wannaphong@yahoo.com" ]
wannaphong@yahoo.com
11af023167cde8c35bb2c4b22b1dd4d44852c42d
e89164093c99b2be87b201804718aa73a2ffdae3
/leetcode/783. Minimum Distance Between BST Nodes.py
df5419cd15909bd4d9943cca22830c3f802cb3ea
[]
no_license
gsrr/leetcode
748d585d0219ad1a1386794910c7410b50ce3c93
992bb618b605c3345318a0eeb2d2df4d11f6a2d5
refs/heads/master
2021-07-06T12:40:03.052470
2021-05-28T17:28:43
2021-05-28T17:28:43
76,116,620
0
1
null
null
null
null
UTF-8
Python
false
false
704
py
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None def ldr(node, arr): if node.left != None: ldr(node.left, arr) arr.append(node.val) if node.right != None: ldr(node.right, arr) class Solution(object): def minDiffInBST(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 arr = [] ldr(root, arr) minval = arr[1] - arr[0] for i in xrange(2, len(arr)): minval = min(arr[i] - arr[i - 1], minval) return minval
[ "jerrycheng1128@gmail.com" ]
jerrycheng1128@gmail.com
069534b71755db5b1b403c9d65cf61f1b0a9f491
6b6e20004b46165595f35b5789e7426d5289ea48
/workers/test/test_exportactionlogsworker.py
0e4a728b421dd60c2b029851e5dfe04326ee7a91
[ "Apache-2.0" ]
permissive
anwarchk/quay
2a83d0ab65aff6a1120fbf3a45dd72f42211633b
23c5120790c619174e7d36784ca5aab7f4eece5c
refs/heads/master
2020-09-12T18:53:21.093606
2019-11-15T19:29:02
2019-11-15T19:29:02
222,517,145
0
0
Apache-2.0
2019-11-18T18:32:35
2019-11-18T18:32:35
null
UTF-8
Python
false
false
4,628
py
import json import os from datetime import datetime, timedelta import boto from httmock import urlmatch, HTTMock from moto import mock_s3_deprecated as mock_s3 from app import storage as test_storage from data import model, database from data.logs_model import logs_model from storage import S3Storage, StorageContext, DistributedStorage from workers.exportactionlogsworker import ExportActionLogsWorker, POLL_PERIOD_SECONDS from test.fixtures import * _TEST_CONTENT = os.urandom(1024) _TEST_BUCKET = 'some_bucket' _TEST_USER = 'someuser' _TEST_PASSWORD = 'somepassword' _TEST_PATH = 'some/cool/path' _TEST_CONTEXT = StorageContext('nyc', None, None, None, None) @pytest.fixture(params=['test', 'mock_s3']) def storage_engine(request): if request.param == 'test': yield test_storage else: with mock_s3(): # Create a test bucket and put some test content. boto.connect_s3().create_bucket(_TEST_BUCKET) engine = DistributedStorage( {'foo': S3Storage(_TEST_CONTEXT, 'some/path', _TEST_BUCKET, _TEST_USER, _TEST_PASSWORD)}, ['foo']) yield engine def test_export_logs_failure(initialized_db): # Make all uploads fail. test_storage.put_content('local_us', 'except_upload', 'true') repo = model.repository.get_repository('devtable', 'simple') user = model.user.get_user('devtable') worker = ExportActionLogsWorker(None) called = [{}] @urlmatch(netloc=r'testcallback') def handle_request(url, request): called[0] = json.loads(request.body) return {'status_code': 200, 'content': '{}'} def format_date(datetime): return datetime.strftime("%m/%d/%Y") now = datetime.now() with HTTMock(handle_request): with pytest.raises(IOError): worker._process_queue_item({ 'export_id': 'someid', 'repository_id': repo.id, 'namespace_id': repo.namespace_user.id, 'namespace_name': 'devtable', 'repository_name': 'simple', 'start_time': format_date(now + timedelta(days=-10)), 'end_time': format_date(now + timedelta(days=10)), 'callback_url': 'http://testcallback/', 'callback_email': None, }, test_storage) test_storage.remove('local_us', 'except_upload') assert called[0] assert called[0][u'export_id'] == 'someid' assert called[0][u'status'] == 'failed' @pytest.mark.parametrize('has_logs', [ True, False, ]) def test_export_logs(initialized_db, storage_engine, has_logs): # Delete all existing logs. database.LogEntry3.delete().execute() repo = model.repository.get_repository('devtable', 'simple') user = model.user.get_user('devtable') now = datetime.now() if has_logs: # Add new logs over a multi-day period. for index in range(-10, 10): logs_model.log_action('push_repo', 'devtable', user, '0.0.0.0', {'index': index}, repo, timestamp=now + timedelta(days=index)) worker = ExportActionLogsWorker(None) called = [{}] @urlmatch(netloc=r'testcallback') def handle_request(url, request): called[0] = json.loads(request.body) return {'status_code': 200, 'content': '{}'} def format_date(datetime): return datetime.strftime("%m/%d/%Y") with HTTMock(handle_request): worker._process_queue_item({ 'export_id': 'someid', 'repository_id': repo.id, 'namespace_id': repo.namespace_user.id, 'namespace_name': 'devtable', 'repository_name': 'simple', 'start_time': format_date(now + timedelta(days=-10)), 'end_time': format_date(now + timedelta(days=10)), 'callback_url': 'http://testcallback/', 'callback_email': None, }, storage_engine) assert called[0] assert called[0][u'export_id'] == 'someid' assert called[0][u'status'] == 'success' url = called[0][u'exported_data_url'] if url.find('http://localhost:5000/exportedlogs/') == 0: storage_id = url[len('http://localhost:5000/exportedlogs/'):] else: assert url.find('https://some_bucket.s3.amazonaws.com/some/path/exportedactionlogs/') == 0 storage_id, _ = url[len('https://some_bucket.s3.amazonaws.com/some/path/exportedactionlogs/'):].split('?') created = storage_engine.get_content(storage_engine.preferred_locations, 'exportedactionlogs/' + storage_id) created_json = json.loads(created) if has_logs: found = set() for log in created_json['logs']: if log.get('terminator'): continue found.add(log['metadata']['index']) for index in range(-10, 10): assert index in found else: assert created_json['logs'] == [{'terminator': True}]
[ "jimmy.zelinskie+git@gmail.com" ]
jimmy.zelinskie+git@gmail.com
ca87e2d4a6d85f9a84b735aec448de0ffb39330a
8ac156c3bfeb4ce28836a1820cb88959424dab14
/test/test_ocr_page_result_with_lines_with_location.py
db398b1f5b831b331b45a635bf3ed2b22f00da5b
[ "Apache-2.0" ]
permissive
Cloudmersive/Cloudmersive.APIClient.Python.OCR
7b593464d31d3038663bedca3c085a161e356f20
90acf41a9b307213ef79f63ea4c749469ef61006
refs/heads/master
2023-04-03T06:03:41.917713
2023-03-27T05:30:38
2023-03-27T05:30:38
138,450,272
6
0
null
null
null
null
UTF-8
Python
false
false
1,161
py
# coding: utf-8 """ ocrapi The powerful Optical Character Recognition (OCR) APIs let you convert scanned images of pages into recognized text. # noqa: E501 OpenAPI spec version: v1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import cloudmersive_ocr_api_client from cloudmersive_ocr_api_client.models.ocr_page_result_with_lines_with_location import OcrPageResultWithLinesWithLocation # noqa: E501 from cloudmersive_ocr_api_client.rest import ApiException class TestOcrPageResultWithLinesWithLocation(unittest.TestCase): """OcrPageResultWithLinesWithLocation unit test stubs""" def setUp(self): pass def tearDown(self): pass def testOcrPageResultWithLinesWithLocation(self): """Test OcrPageResultWithLinesWithLocation""" # FIXME: construct object with mandatory attributes with example values # model = cloudmersive_ocr_api_client.models.ocr_page_result_with_lines_with_location.OcrPageResultWithLinesWithLocation() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "35204726+Cloudmersive@users.noreply.github.com" ]
35204726+Cloudmersive@users.noreply.github.com
816c45d294921e6362d0eaa5cc2305ba0fb01d7f
a2fd604a8ef45b4e08cf832348d20b65e4468a79
/phoenix/tests/test_caches.py
a4d7e9263d733aae95b47899c92b2a290f0313d0
[]
no_license
darraes/data_structures
8ca76a3fc3e961860861cd43f5b866b8e7e50427
4ff2c60e05d9275b163db59ed37b9f46ba50f3c0
refs/heads/master
2020-04-17T10:19:59.357548
2019-02-28T21:42:44
2019-02-28T21:42:44
166,497,344
0
0
null
null
null
null
UTF-8
Python
false
false
2,679
py
import unittest from phoenix.cache import * class TestFunctions(unittest.TestCase): def test_lru_new_insertions(self): cache = LRUCache(3) cache.put("k1", "v1") self.assertEqual("v1", cache.get("k1")) cache.put("k2", "v2") self.assertEqual("v2", cache.get("k2")) cache.put("k3", "v3") self.assertEqual("v3", cache.get("k3")) cache.put("k4", "v4") self.assertEqual("v4", cache.get("k4")) self.assertEqual("v3", cache.get("k3")) self.assertEqual("v2", cache.get("k2")) self.assertEqual(None, cache.get("k1")) def test_lru_tail_to_head(self): cache = LRUCache(3) cache.put("k1", "v1") cache.put("k2", "v2") cache.put("k3", "v3") cache.put("k1", "v11") cache.put("k4", "v4") self.assertEqual(None, cache.get("k2")) self.assertEqual("v3", cache.get("k3")) cache.put("k5", "v5") self.assertEqual(None, cache.get("k1")) def test_lru_middle_to_head(self): cache = LRUCache(3) cache.put("k1", "v1") cache.put("k2", "v2") cache.put("k3", "v3") cache.put("k2", "v22") cache.put("k4", "v4") self.assertEqual(None, cache.get("k1")) self.assertEqual("v22", cache.get("k2")) cache.put("k5", "v5") self.assertEqual(None, cache.get("k3")) def test_lru_head_to_head(self): cache = LRUCache(3) cache.put("k1", "v1") cache.put("k2", "v2") cache.put("k3", "v3") cache.put("k3", "v4") cache.put("k4", "v4") self.assertEqual(None, cache.get("k1")) self.assertEqual("v4", cache.get("k4")) cache.put("k5", "v5") self.assertEqual(None, cache.get("k2")) def test_lfu_4(self): cache = LFUCache(0) cache.put(0, 0) self.assertEqual(None, cache.get(0)) def test_lfu_3(self): cache = LFUCache(2) cache.put(1, 1) cache.put(2, 2) self.assertEqual(1, cache.get(1)) cache.put(3, 3) self.assertEqual(None, cache.get(2)) self.assertEqual(3, cache.get(3)) cache.put(4, 4) self.assertEqual(None, cache.get(1)) self.assertEqual(3, cache.get(3)) self.assertEqual(4, cache.get(4)) def test_lfu_2(self): cache = LFUCache(5) cache.put("k1", "v1") cache.put("k2", "v2") cache.put("k3", "v3") cache.put("k4", "v4") cache.put("k5", "v5") cache.put("k2", "v2") cache.put("k3", "v3") cache.put("k2", "v2") cache.put("k6", "v6") cache.put("k3", "v3")
[ "daniel.arraes@gmail.com" ]
daniel.arraes@gmail.com
34177aaf3d8e4472f51189bd33d2c6658fe3cd66
9b422078f4ae22fe16610f2ebc54b8c7d905ccad
/xlsxwriter/test/comparison/test_image_bytes01.py
02dba5d0f8a119b040fad480338e187a1031b18b
[ "BSD-2-Clause-Views" ]
permissive
projectsmahendra/XlsxWriter
73d8c73ea648a911deea63cb46b9069fb4116b60
9b9d6fb283c89af8b6c89ad20f72b8208c2aeb45
refs/heads/master
2023-07-21T19:40:41.103336
2023-07-08T16:54:37
2023-07-08T16:54:37
353,636,960
0
0
NOASSERTION
2021-04-01T08:57:21
2021-04-01T08:57:20
null
UTF-8
Python
false
false
1,466
py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook from io import BytesIO class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('image01.xlsx') def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() image_file = open(self.image_dir + 'red.png', 'rb') image_data = BytesIO(image_file.read()) image_file.close() worksheet.insert_image('E9', 'red.png', {'image_data': image_data}) workbook.close() self.assertExcelEqual() def test_create_file_in_memory(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename, {'in_memory': True}) worksheet = workbook.add_worksheet() image_file = open(self.image_dir + 'red.png', 'rb') image_data = BytesIO(image_file.read()) image_file.close() worksheet.insert_image('E9', 'red.png', {'image_data': image_data}) workbook.close() self.assertExcelEqual()
[ "jmcnamara@cpan.org" ]
jmcnamara@cpan.org
3c51dcc2e73e3f43318e71887d695fe2532c06b9
a4ea525e226d6c401fdb87a6e9adfdc5d07e6020
/src/azure-cli/azure/cli/command_modules/network/aaz/latest/network/virtual_appliance/site/_delete.py
f453c8731d6e69b3932912be786b732d7da64fb3
[ "MIT", "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MPL-2.0", "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later", "BSD-2-Clause" ]
permissive
Azure/azure-cli
13340eeca2e288e66e84d393fa1c8a93d46c8686
a40fd14ad0b6e89720a2e58d4d9be3a6ce1535ca
refs/heads/dev
2023-08-17T06:25:37.431463
2023-08-17T06:00:10
2023-08-17T06:00:10
51,040,886
4,018
3,310
MIT
2023-09-14T11:11:05
2016-02-04T00:21:51
Python
UTF-8
Python
false
false
5,731
py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # # Code generated by aaz-dev-tools # -------------------------------------------------------------------------------------------- # pylint: skip-file # flake8: noqa from azure.cli.core.aaz import * @register_command( "network virtual-appliance site delete", is_preview=True, confirmation="Are you sure you want to perform this operation?", ) class Delete(AAZCommand): """Delete an Azure network virtual appliance site. :example: Delete an Azure network virtual appliance site. az network virtual-appliance site delete -n MySite -g MyRG --appliance-name MyName -y """ _aaz_info = { "version": "2021-08-01", "resources": [ ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.network/networkvirtualappliances/{}/virtualappliancesites/{}", "2021-08-01"], ] } AZ_SUPPORT_NO_WAIT = True def _handler(self, command_args): super()._handler(command_args) return self.build_lro_poller(self._execute_operations, None) _args_schema = None @classmethod def _build_arguments_schema(cls, *args, **kwargs): if cls._args_schema is not None: return cls._args_schema cls._args_schema = super()._build_arguments_schema(*args, **kwargs) # define Arg Group "" _args_schema = cls._args_schema _args_schema.appliance_name = AAZStrArg( options=["--appliance-name"], help="The name of Network Virtual Appliance.", required=True, id_part="name", ) _args_schema.resource_group = AAZResourceGroupNameArg( required=True, ) _args_schema.name = AAZStrArg( options=["-n", "--name"], help="The name of Network Virtual Appliance Site.", required=True, id_part="child_name_1", ) return cls._args_schema def _execute_operations(self): self.pre_operations() yield self.VirtualApplianceSitesDelete(ctx=self.ctx)() self.post_operations() @register_callback def pre_operations(self): pass @register_callback def post_operations(self): pass class VirtualApplianceSitesDelete(AAZHttpOperation): CLIENT_TYPE = "MgmtClient" def __call__(self, *args, **kwargs): request = self.make_request() session = self.client.send_request(request=request, stream=False, **kwargs) if session.http_response.status_code in [202]: return self.client.build_lro_polling( self.ctx.args.no_wait, session, self.on_200, self.on_error, lro_options={"final-state-via": "location"}, path_format_arguments=self.url_parameters, ) if session.http_response.status_code in [200]: return self.client.build_lro_polling( self.ctx.args.no_wait, session, self.on_200, self.on_error, lro_options={"final-state-via": "location"}, path_format_arguments=self.url_parameters, ) if session.http_response.status_code in [204]: return self.client.build_lro_polling( self.ctx.args.no_wait, session, self.on_204, self.on_error, lro_options={"final-state-via": "location"}, path_format_arguments=self.url_parameters, ) return self.on_error(session.http_response) @property def url(self): return self.client.format_url( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites/{siteName}", **self.url_parameters ) @property def method(self): return "DELETE" @property def error_format(self): return "ODataV4Format" @property def url_parameters(self): parameters = { **self.serialize_url_param( "networkVirtualApplianceName", self.ctx.args.appliance_name, required=True, ), **self.serialize_url_param( "resourceGroupName", self.ctx.args.resource_group, required=True, ), **self.serialize_url_param( "siteName", self.ctx.args.name, required=True, ), **self.serialize_url_param( "subscriptionId", self.ctx.subscription_id, required=True, ), } return parameters @property def query_parameters(self): parameters = { **self.serialize_query_param( "api-version", "2021-08-01", required=True, ), } return parameters def on_200(self, session): pass def on_204(self, session): pass class _DeleteHelper: """Helper class for Delete""" __all__ = ["Delete"]
[ "noreply@github.com" ]
Azure.noreply@github.com
60570467f232d79d8b785162fa8abe654121701e
b9dda07897d552466695c735c14d624cf89315bc
/triggerflow/service/eventsources/model.py
220393130c315f170e96204d7db7a6ce32a801ff
[ "Apache-2.0" ]
permissive
JosepSampe/triggerflow
02792ba96059f27c2d163ca88d50a10e030026ae
66d8adcd6b31692663ee861c334608b74fecf884
refs/heads/master
2023-01-12T12:12:33.007616
2020-10-20T13:14:18
2020-10-20T13:14:18
264,998,376
0
0
Apache-2.0
2020-05-18T16:32:06
2020-05-18T16:32:05
null
UTF-8
Python
false
false
383
py
from multiprocessing import Process from threading import Thread class EventSourceHook(Thread): def __init__(self, name: str, *args, **kwargs): super().__init__() self.name = name def run(self): raise NotImplementedError() def commit(self, records): raise NotImplementedError() def stop(self): raise NotImplementedError()
[ "aitor.a98@gmail.com" ]
aitor.a98@gmail.com
e378342db455f9d7483d9f6cf7982882e5d2ca99
b72596aa97a724f9f2cc6947b86a9b972846277f
/setup.py
8cba9868cc12580e64d54561b344cf8fca1cdca5
[ "MIT" ]
permissive
dumpmemory/hourglass-transformer-pytorch
698cfcbc6a1b572efef37b5926d45dd598ff457b
4be33bb41adfedf1b739cd24bec9481bc83a93e2
refs/heads/main
2023-09-03T01:45:41.994192
2021-11-10T15:49:06
2021-11-10T15:49:06
426,081,172
0
0
MIT
2021-11-10T15:55:51
2021-11-09T03:41:56
Python
UTF-8
Python
false
false
750
py
from setuptools import setup, find_packages setup( name = 'hourglass-transformer-pytorch', packages = find_packages(), version = '0.0.6', license='MIT', description = 'Hourglass Transformer', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/hourglass-transformer-pytorch', keywords = [ 'artificial intelligence', 'attention mechanism', 'transformers' ], install_requires=[ 'einops', 'torch>=1.6' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
[ "lucidrains@gmail.com" ]
lucidrains@gmail.com
523b42f752bced31bc63bb710b3b4fded293c9cf
20e3010608e40a6ec5ea56f69d122a62182e4bdb
/1 - Python-2/4 - strings functions/HW4/3. Make an IP adress unclickable.py
f6b7f30215f124961d64f2ec6f1ae189675582a4
[]
no_license
LarisaOvchinnikova/Python
ee65eac221cd03563d60110118175692564c5b2d
9cc86a260828662995dec59a6d69528f96d37e79
refs/heads/master
2021-08-22T21:41:02.351589
2021-05-25T18:37:09
2021-05-25T18:37:09
253,842,826
0
0
null
null
null
null
UTF-8
Python
false
false
149
py
# Input: address = "1.1.1.1" # Output: "1[.]1[.]1[.]1" def ip_address(address): return address.replace(".", "[.]") print(ip_address("1.1.1.1"))
[ "larisaplantation@gmail.com" ]
larisaplantation@gmail.com
caa9cb15bb5cd49e3cb59f5ace978e207c998922
db37e5eab7b60057bbc1ae153df8693f0159b02c
/examples/decoupledibpm/flapping2dRe75/run/scripts/plot_vorticity_compare_li_et_al_2015.py
63ee97afbb13882c1575b1ae99fc77dbdad3f383
[ "BSD-3-Clause" ]
permissive
stjordanis/petibm-examples
83f7212eadbc1bbfb2071d550969b252cbcfcd89
794de3613967c14750c750aed386602c988cff05
refs/heads/master
2022-04-12T20:29:33.566464
2020-02-29T22:45:39
2020-02-29T22:45:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,078
py
"""Plot the vorticity at saved time steps.""" from matplotlib import pyplot, image import numpy import pathlib import petibmpy simudir = pathlib.Path(__file__).absolute().parents[1] # simulation directory datadir = simudir / 'output' # directory with field solution files name = 'wz' # name of the variable to load and plot save_figure = True # save Matplotlib figure as PNG show_figure = True # show Matplotlib figure # Load the grid from file. filepath = datadir / 'grid.h5' grid = petibmpy.read_grid_hdf5(filepath, name) states = [2400, 2600, 2800, 3000, 3200] pyplot.rc('font', family='serif', size=14) fig, (ax1, ax2) = pyplot.subplots(nrows=2, ncols=5, figsize=(10.0, 5.0)) levels = numpy.linspace(-20.0, 20.0, num=40) # contour levels for i, state in enumerate(states): print(f'[time step {state}] Load and plot contours of {name}') # Load data from file. filepath = datadir / f'{state:0>7}.h5' data = petibmpy.read_field_hdf5(filepath, name) # Load body coordinates from file. filepath = datadir / f'ellipse_{state:0>7}.2D' body = petibmpy.read_body(filepath) # Plot the contour of the field variable. ax1[i].contour(*grid, data, levels=levels, linewidths=0.5, extend='both') ax1[i].plot(*body, color='black', linewidth=0.5) ax1[i].axis('scaled', adjustable='box') ax1[i].set_xlim(-3.5, 2.5) ax1[i].set_ylim(-5.0, 1.0) ax1[i].axis('off') # Add images from Li et al. (2015) to the figure. datadir = simudir.parent / 'data' times = [3.0, 3.25, 3.5, 3.75, 4.0] for i, time in enumerate(times): print(f'[time {time}] Display image from Li et al. (2015)') filepath = datadir / f'li_et_al_2015_flapping_wz_{time:.2f}.png' im = image.imread(str(filepath)) ax2[i].imshow(im) ax2[i].axis('off') fig.tight_layout() if save_figure: figdir = simudir / 'figures' # folder to contain PNG files figdir.mkdir(parents=True, exist_ok=True) filepath = figdir / f'wz_compare_li_et_al_2015.png' fig.savefig(filepath, dpi=300, bbox_inches='tight') if show_figure: pyplot.show()
[ "mesnardo@gwu.edu" ]
mesnardo@gwu.edu
c212488374a2e7a4dcf011707fabc37464e8b920
f79102231c83674a4c01e56e3953b2a65cb14da2
/leetcode/base/list/环形链表.py
31d0d694e9e23ee41583a99337ef25a65410b65f
[]
no_license
Activity00/Python
4971b177beaf72df0de97f7e78f400d48104dce1
166d97f36bbeea74c84ec57466bd0a65b608ed09
refs/heads/master
2020-12-24T07:53:06.782982
2020-09-29T10:55:43
2020-09-29T10:55:43
73,362,001
0
0
null
null
null
null
UTF-8
Python
false
false
1,237
py
# coding: utf-8 """ @author: 武明辉 @time: 19-3-20 下午9:35 """ """ 给定一个链表,判断链表中是否有环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 示例 1: 输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。 示例 2: 输入:head = [1,2], pos = 0 输出:true 解释:链表中有一个环,其尾部连接到第一个节点。 示例 3: 输入:head = [1], pos = -1 输出:false 解释:链表中没有环。 进阶: 你能用 O(1)(即,常量)内存解决此问题吗? """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def hasCycle(self, head): if not head: return False slow = fast = head while fast.next and fast.next.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False if __name__ == '__main__': pass
[ "1032662429@qq.com" ]
1032662429@qq.com
d294ee636acb84148e16ac385f849a18ab6a1d2d
e63f11c621ffa2c54a8bc4714c6fb0f868f902d6
/LianJia_Scrapy/item_url.py
964827b681f15e340e7a2dee5981496f848a2108
[]
no_license
aquablue1/LianJia_Scrapy
5821fd93eca796d319f408d351cc30d860a0edb4
580ced19204d5eb9614c6a8b362b2cb9eba88388
refs/heads/master
2021-05-05T22:07:14.261137
2018-01-06T05:01:43
2018-01-06T05:01:43
116,090,808
0
1
null
null
null
null
UTF-8
Python
false
false
308
py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class LianjiaScrapyItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() url = scrapy.Field()
[ "94apieceofcake@gmail.com" ]
94apieceofcake@gmail.com
94c044bdea784aa5da43326d563b722a3d5c4fc6
29da2ca6def1270be13a3096685a8e5d82828dff
/CIM14/CDPSM/GIS_Connectivity/IEC61970/Core/SubGeographicalRegion.py
0030c2438ce680b5ea6c4d046032e16e4f3f5353
[ "MIT" ]
permissive
rimbendhaou/PyCIM
75eb3bcd3729b2410c03f3d5c66d6f1e05e21df3
d578bb0bf1af344342bd23344385ed9c06c2d0ee
refs/heads/master
2022-04-28T01:16:12.673867
2020-04-16T02:19:09
2020-04-16T02:19:09
256,085,381
0
0
MIT
2020-04-16T02:15:20
2020-04-16T02:08:14
null
UTF-8
Python
false
false
3,823
py
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from CIM14.CDPSM.GIS_Connectivity.IEC61970.Core.IdentifiedObject import IdentifiedObject class SubGeographicalRegion(IdentifiedObject): """A subset of a geographical region of a power system network model. """ def __init__(self, Region=None, Lines=None, Substations=None, *args, **kw_args): """Initialises a new 'SubGeographicalRegion' instance. @param Region: The association is used in the naming hierarchy. @param Lines: A Line can be contained by a SubGeographical Region. @param Substations: The association is used in the naming hierarchy. """ self._Region = None self.Region = Region self._Lines = [] self.Lines = [] if Lines is None else Lines self._Substations = [] self.Substations = [] if Substations is None else Substations super(SubGeographicalRegion, self).__init__(*args, **kw_args) _attrs = [] _attr_types = {} _defaults = {} _enums = {} _refs = ["Region", "Lines", "Substations"] _many_refs = ["Lines", "Substations"] def getRegion(self): """The association is used in the naming hierarchy. """ return self._Region def setRegion(self, value): if self._Region is not None: filtered = [x for x in self.Region.Regions if x != self] self._Region._Regions = filtered self._Region = value if self._Region is not None: if self not in self._Region._Regions: self._Region._Regions.append(self) Region = property(getRegion, setRegion) def getLines(self): """A Line can be contained by a SubGeographical Region. """ return self._Lines def setLines(self, value): for x in self._Lines: x.Region = None for y in value: y._Region = self self._Lines = value Lines = property(getLines, setLines) def addLines(self, *Lines): for obj in Lines: obj.Region = self def removeLines(self, *Lines): for obj in Lines: obj.Region = None def getSubstations(self): """The association is used in the naming hierarchy. """ return self._Substations def setSubstations(self, value): for x in self._Substations: x.Region = None for y in value: y._Region = self self._Substations = value Substations = property(getSubstations, setSubstations) def addSubstations(self, *Substations): for obj in Substations: obj.Region = self def removeSubstations(self, *Substations): for obj in Substations: obj.Region = None
[ "rwl@thinker.cable.virginmedia.net" ]
rwl@thinker.cable.virginmedia.net
d53b1fc1e1689725994bab778b7f669f9af08d11
bd1362c60313784c90013dfc9f0169e64389bf27
/scripts/feature/min_Xhour.py
0f41041b31ea7c176d8d0c2e6714c2969c296d22
[]
no_license
ForceCry/iem
391aa9daf796591909cb9d4e60e27375adfb0eab
4b0390d89e6570b99ca83a5fa9b042226e17c1ad
refs/heads/master
2020-12-24T19:04:55.517409
2013-04-09T14:25:36
2013-04-09T14:25:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
869
py
# Generate some comparison data between ASOS sites, tricky, me thinks import iemdb import datetime import numpy import mx.DateTime ASOS = iemdb.connect('asos', bypass=True) acursor = ASOS.cursor() acursor.execute("SET TIME ZONE 'GMT'") maxv = 0 def get_data(year, station): global maxv data = {} acursor.execute("""SELECT valid, sknt from t"""+year+""" where station = %s and (extract(minute from valid) between 50 and 59 or extract(minute from valid) = 0) and sknt >= 0 ORDER by valid ASC""", (station, )) vals = [0,0,0,0] for row in acursor: vals.insert(0, row[1] ) vals.pop() if min(vals) >= maxv: print vals, min(vals), row[0] maxv = min(vals) station1 = 'DSM' for year in range(1973,2011): get_data(str(year), station1)
[ "akrherz@95f8c243-6001-0410-b151-932e6a9ed213" ]
akrherz@95f8c243-6001-0410-b151-932e6a9ed213
48c2c3dca0b6a2b6c85044a00f274533db952693
60a831fb3c92a9d2a2b52ff7f5a0f665d4692a24
/IronPythonStubs/release/stubs.min/System/Windows/Controls/__init___parts/ContextMenuEventArgs.py
ddb3667cf2693b5c400b6c59a3043b012c6b0300
[ "MIT" ]
permissive
shnlmn/Rhino-Grasshopper-Scripts
a9411098c5d1bbc55feb782def565d535b27b709
0e43c3c1d09fb12cdbd86a3c4e2ba49982e0f823
refs/heads/master
2020-04-10T18:59:43.518140
2020-04-08T02:49:07
2020-04-08T02:49:07
161,219,695
11
2
null
null
null
null
UTF-8
Python
false
false
479
py
class ContextMenuEventArgs(RoutedEventArgs): """ Provides data for the context menu event. """ CursorLeft=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the horizontal position of the mouse. Get: CursorLeft(self: ContextMenuEventArgs) -> float """ CursorTop=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the vertical position of the mouse. Get: CursorTop(self: ContextMenuEventArgs) -> float """
[ "magnetscoil@gmail.com" ]
magnetscoil@gmail.com
e821be69dbcc904309be14ca117f4bbb2b7155e6
45e376ae66b78b17788b1d3575b334b2cb1d0b1c
/tests/cloudformation/checks/resource/aws/test_ECRImmutableTags.py
2bafbbce0a26573bbd0e9e83dbbd29b4d6be0c56
[ "Apache-2.0" ]
permissive
bridgecrewio/checkov
aeb8febed2ed90e61d5755f8f9d80b125362644d
e64cbd27ffb6f09c2c9f081b45b7a821a3aa1a4d
refs/heads/main
2023-08-31T06:57:21.990147
2023-08-30T23:01:47
2023-08-30T23:01:47
224,386,599
5,929
1,056
Apache-2.0
2023-09-14T20:10:23
2019-11-27T08:55:14
Python
UTF-8
Python
false
false
827
py
import os import unittest from checkov.cloudformation.checks.resource.aws.ECRImmutableTags import check from checkov.cloudformation.runner import Runner from checkov.runner_filter import RunnerFilter class TestECRImmutableTags(unittest.TestCase): def test_summary(self): runner = Runner() current_dir = os.path.dirname(os.path.realpath(__file__)) test_files_dir = current_dir + "/example_ECRImmutableTags" report = runner.run(root_folder=test_files_dir,runner_filter=RunnerFilter(checks=[check.id])) summary = report.get_summary() self.assertEqual(summary['passed'], 1) self.assertEqual(summary['failed'], 2) self.assertEqual(summary['skipped'], 0) self.assertEqual(summary['parsing_errors'], 0) if __name__ == '__main__': unittest.main()
[ "noreply@github.com" ]
bridgecrewio.noreply@github.com
97be3b993b4f278ccdd868203a24902e3bcbe2bc
fff80cdaf12712704f36038479f50418253f42f3
/openbmc/common/recipes-rest/rest-api/files/node_bios.py
5541e54e2f792c8d93e5251ae2259776849425c1
[]
no_license
rudolfkopriva/Facebook
1ea0cfbc116f68ae0317332eeb9155461af5645a
56e4c6a83f992bb01849ad353004b28409e53eef
refs/heads/master
2023-02-14T01:54:36.519860
2021-01-05T02:09:26
2021-01-05T02:09:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
15,158
py
#!/usr/bin/env python import os.path from node import node from pal import * IOM_M2 = 1 # IOM type: M.2 IOM_IOC = 2 # IOM type: IOC PLATFORM_FILE = "/tmp/system.bin" def get_iom_type(): pal_sku_file = open(PLATFORM_FILE, "r") pal_sku = pal_sku_file.read() iom_type = int(pal_sku) & 0x3 # The IOM type is the last 2 bits if (iom_type != IOM_M2) and (iom_type != IOM_IOC): print("Rest-API: System type is unknown! Please confirm the system type.") return -1 else: return iom_type """""" """""" """""" """""" """""" """'' Main Node """ """""" """""" """""" """""" """""" "" class biosNode(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): info = {"Description": "BIOS Information"} return info def get_node_bios(name): return biosNode(name) """""" """""" """""" """""" """""" """'' Boot Order Information """ """""" """""" """""" """""" """""" "" class bios_boot_order_trunk_node(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): info = {"Description": "BIOS Boot Order Information"} return info """""" """""" """""" """""" """'' Boot Mode """ """""" """""" """""" """""" "" class bios_boot_mode_node(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): cmd = "/usr/local/bin/bios-util " + self.name + " --boot_order get --boot_mode" boot_order = Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode() boot_order = boot_order.split("\n")[0].split(": ") info = { boot_order[0]: boot_order[1], "Note #1: Actions Format:": "{ 'action': 'set', 'mode': {0,1} }", "Note #2: Boot Mode No.": "{ 0: 'Legacy', 1: 'UEFI' }", } return info def doAction(self, data, param={}): if data["action"] == "set" and len(data) == 2: cmd = ( "/usr/local/bin/bios-util " + self.name + " --boot_order set --boot_mode " + data["mode"] ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err.startswith("usage"): res = "failure" else: res = "success" else: res = "failure" result = {"result": res} return result """""" """""" """""" """""" """'' Clear CMOS """ """""" """""" """""" """""" "" class bios_clear_cmos_node(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): cmd = "/usr/local/bin/bios-util " + self.name + " --boot_order get --clear_CMOS" clear_cmos = Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode() clear_cmos = clear_cmos.split("\n")[0].split(": ") info = {clear_cmos[0]: clear_cmos[1]} return info def doAction(self, data, param={}): if data["action"] == "enable": cmd = ( "/usr/local/bin/bios-util " + self.name + " --boot_order enable --clear_CMOS" ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err.startswith("usage"): res = "failure" else: res = "success" elif data["action"] == "disable": cmd = ( "/usr/local/bin/bios-util " + self.name + " --boot_order disable --clear_CMOS" ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err.startswith("usage"): res = "failure" else: res = "success" else: res = "failure" result = {"result": res} return result """""" """""" """""" """""" """'' Force Boot BIOS Setup """ """""" """""" """""" """""" "" class bios_force_boot_setup_node(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): cmd = ( "/usr/local/bin/bios-util " + self.name + " --boot_order get --force_boot_BIOS_setup" ) force_boot_bios_setup = ( Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode() ) force_boot_bios_setup = force_boot_bios_setup.split("\n")[0].split(": ") info = {force_boot_bios_setup[0]: force_boot_bios_setup[1]} return info def doAction(self, data, param={}): if data["action"] == "enable": cmd = ( "/usr/local/bin/bios-util " + self.name + " --boot_order enable --force_boot_BIOS_setup" ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err.startswith("usage"): res = "failure" else: res = "success" elif data["action"] == "disable": cmd = ( "/usr/local/bin/bios-util " + self.name + " --boot_order disable --force_boot_BIOS_setup" ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err.startswith("usage"): res = "failure" else: res = "success" else: res = "failure" result = {"result": res} return result """""" """""" """""" """""" """'' Boot Order """ """""" """""" """""" """""" "" class bios_boot_order_node(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): cmd = "/usr/local/bin/bios-util " + self.name + " --boot_order get --boot_order" boot_order = Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode() boot_order = boot_order.split("\n")[0].split(": ") info = { boot_order[0]: boot_order[1], "Note #1: Actions Format:": "{'action': 'set', '1st': <1st_no>, '2nd': <2nd_no>, '3rd': <3rd_no>, '4th': <4th_no>, '5th': <5th_no>}", "Note #2: Boot Order No.": "{ 0: 'USB Device', 1: 'IPv4 Network', 9: 'IPv6 Network', 2: 'SATA HDD', 3: 'SATA-CDROM', 4: 'Other Removalbe Device', 255: 'Reserved' }", } return info def doAction(self, data, param={}): if data["action"] == "set" and len(data) == 6: cmd = ( "/usr/local/bin/bios-util " + self.name + " --boot_order set --boot_order " + data["1st"] + " " + data["2nd"] + " " + data["3rd"] + " " + data["4th"] + " " + data["5th"] ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err != "" or data != "": res = "failure" else: res = "success" elif data["action"] == "disable": cmd = ( "/usr/local/bin/bios-util " + self.name + " --boot_order disable --boot_order" ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err.startswith("usage"): res = "failure" else: res = "success" else: res = "failure" result = {"result": res} return result def get_node_bios_boot_order_trunk(name): return bios_boot_order_trunk_node(name) def get_node_bios_boot_mode(name): actions = ["set"] return bios_boot_mode_node(name=name, actions=actions) def get_node_bios_clear_cmos(name): actions = ["enable", "disable"] return bios_clear_cmos_node(name=name, actions=actions) def get_node_bios_force_boot_setup(name): actions = ["enable", "disable"] return bios_force_boot_setup_node(name=name, actions=actions) def get_node_bios_boot_order(name): actions = ["set", "disable"] return bios_boot_order_node(name=name, actions=actions) """""" """""" """""" """""" """""" """'' BIOS POST Code Information """ """""" """""" """""" """""" """""" "" class bios_postcode_node(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): cmd = "/usr/local/bin/bios-util " + self.name + " --postcode get" postcode = Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode() postcode = postcode.replace("\n", "").strip() info = {"POST Code": postcode} return info def get_node_bios_postcode_trunk(name): return bios_postcode_node(name) """""" """""" """""" """""" """""" """'' Platform Information """ """""" """""" """""" """""" """""" "" class bios_plat_info_node(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): cmd = "/usr/local/bin/bios-util " + self.name + " --plat_info get" data = plat_info = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) plat_info = data.stdout.read().decode() err = data.stderr.read().decode() if err.startswith("usage"): plat_info = "Currently the platform does not support plat-info\n" plat_info = plat_info.split("\n") plat_info_len = len(plat_info) info = {"Platform Information": plat_info[0 : plat_info_len - 1]} return info def get_node_bios_plat_info_trunk(name): return bios_plat_info_node(name) """""" """""" """""" """""" """""" """'' PCIe Port Configuration """ """""" """""" """""" """""" """""" "" class bios_pcie_port_config_node(node): def __init__(self, name, info=None, actions=None): self.name = name if info == None: self.info = {} else: self.info = info if actions == None: self.actions = [] else: self.actions = actions def getInformation(self, param={}): cmd = "/usr/local/bin/bios-util " + self.name + " --pcie_port_config get" data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) pcie_port_config = data.stdout.read().decode() err = data.stderr.read().decode() if err.startswith("usage"): pcie_port_config = ( "Currently the platform does not support pcie-port-config\n" ) pcie_port_config = pcie_port_config.split("\n") pcie_port_config_len = len(pcie_port_config) iom_type = get_iom_type() if iom_type == IOM_M2: info = { "PCIe Port Configuration": pcie_port_config[ 0 : pcie_port_config_len - 1 ], "Note: Actions Format:": "{'action': <enable, disable>, 'pcie_dev': <scc_ioc, flash1, flash2, nic>}", } elif iom_type == IOM_IOC: info = { "PCIe Port Configuration": pcie_port_config[ 0 : pcie_port_config_len - 1 ], "Note: Actions Format:": "{'action': <enable, disable>, 'pcie_dev': <scc_ioc, iom_ioc, nic>}", } else: info = [] return info def doAction(self, data, param={}): if data["action"] == "enable" and len(data) == 2: cmd = ( "/usr/local/bin/bios-util " + self.name + " --pcie_port_config enable --" + data["pcie_dev"] ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err.startswith("usage"): res = "failure" else: res = "success" elif data["action"] == "disable": cmd = ( "/usr/local/bin/bios-util " + self.name + " --pcie_port_config disable --" + data["pcie_dev"] ) data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) err = data.stderr.read().decode() data = data.stdout.read().decode() if err.startswith("usage"): res = "failure" else: res = "success" else: res = "failure" result = {"result": res} return result def get_node_bios_pcie_port_config_trunk(name): actions = ["enable", "disable"] return bios_pcie_port_config_node(name=name, actions=actions)
[ "nateweiler84@gmail.com" ]
nateweiler84@gmail.com
1152ab09724194cae4e2fab10d422c80f3789189
57265c1c743f5da6778d5c065e03be93d4f0c93f
/djkombu/tests/testproj/manage.py
b9066fff599f1c1260d7622099fa544098000b78
[ "BSD-3-Clause" ]
permissive
barseghyanartur/django-kombu
fb63dab46cce7048f50c5131a8edde98f0734c5e
0f7dbdbd153e7a6d9971dfbb030433a6a85dd984
refs/heads/master
2021-01-23T04:59:18.617326
2017-06-02T11:51:07
2017-06-02T11:51:07
92,947,716
0
0
null
2017-05-31T13:21:10
2017-05-31T13:21:10
null
UTF-8
Python
false
false
320
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") sys.path.insert(0, os.path.join(os.getcwd(), '..', '..', '..')) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "artur.barseghyan@gmail.com" ]
artur.barseghyan@gmail.com
c02ce5a8423e7a07dbf65307fb26cf43f7f4e06a
5fc8acc18c9436a5cd3ffd609108a51e0a259b1d
/backend/test_app_2344_dev_2466/urls.py
4994650eadd63d8204f557dbe2b404d09a5d8a44
[]
no_license
crowdbotics-apps/test-app-2344-dev-2466
1f3677880346518cd2fb9e3a908aea3339ba78e1
eb950c673394c455d4d7eeb1ec362bc596a6f444
refs/heads/master
2023-02-09T16:02:19.128443
2020-04-08T13:20:57
2020-04-08T13:20:57
254,093,628
0
0
null
2023-01-24T01:59:00
2020-04-08T13:20:29
JavaScript
UTF-8
Python
false
false
1,947
py
"""test_app_2344_dev_2466 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from allauth.account.views import confirm_email from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi urlpatterns = [ path("", include("home.urls")), path("accounts/", include("allauth.urls")), path("api/v1/", include("home.api.v1.urls")), path("admin/", admin.site.urls), path("users/", include("users.urls", namespace="users")), path("rest-auth/", include("rest_auth.urls")), # Override email confirm to use allauth's HTML view instead of rest_auth's API view path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email), path("rest-auth/registration/", include("rest_auth.registration.urls")), ] admin.site.site_header = "Test-app-2344" admin.site.site_title = "Test-app-2344 Admin Portal" admin.site.index_title = "Test-app-2344 Admin" # swagger schema_view = get_schema_view( openapi.Info( title="Test-app-2344 API", default_version="v1", description="API documentation for Test-app-2344 App", ), public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns += [ path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs") ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
4530e7da967992e4e873d204c25802ea30dd670f
9afb5742e08add8800ad2086ecddd74f017ac9a5
/tests/test_errors.py
2c27177c209173f9920701ae351953c2f5064ff8
[ "BSD-2-Clause" ]
permissive
blockdiag/sphinxcontrib-actdiag
e7fac2739b7aef862f6b0dbea69548ec51960df9
8b7ec29b310e718c4510a99fd22c624adc5b19bf
refs/heads/master
2023-04-10T07:36:45.862708
2021-12-05T14:37:35
2021-12-05T14:37:35
34,159,673
1
2
NOASSERTION
2023-03-18T23:32:50
2015-04-18T09:11:37
Python
UTF-8
Python
false
false
1,992
py
# -*- coding: utf-8 -*- from mock import patch from sphinx_testing import with_app import sys import unittest class TestSphinxcontribActdiagErrors(unittest.TestCase): @with_app(srcdir='tests/docs/basic', write_docstring=True) def test_parse_error(self, app, status, warning): """ .. actdiag:: { A -> B; """ app.builder.build_all() self.assertIn('got unexpected token:', warning.getvalue()) @with_app(srcdir='tests/docs/basic', confoverrides=dict(actdiag_html_image_format='JPG')) def test_unknown_format_error(self, app, status, warning): app.builder.build_all() self.assertIn('unknown format: JPG', warning.getvalue()) @with_app(srcdir='tests/docs/basic', confoverrides=dict(actdiag_html_image_format='PDF')) def test_reportlab_not_found_error(self, app, status, warning): try: # unload reportlab and make loading it impossible sys.modules.pop('reportlab', None) path = sys.path sys.path = [] app.builder.build_all() self.assertIn('Could not output PDF format. Install reportlab.', warning.getvalue()) finally: sys.path = path @with_app(srcdir='tests/docs/basic') @patch("actdiag.utils.rst.nodes.actdiag.processor.drawer.DiagramDraw") def test_rendering_error(self, app, status, warning, DiagramDraw): DiagramDraw.side_effect = RuntimeError("UNKNOWN ERROR!") app.builder.build_all() self.assertIn('UNKNOWN ERROR!', warning.getvalue()) @with_app(srcdir='tests/docs/basic') @patch("sphinxcontrib.actdiag.actdiag.drawer.DiagramDraw.draw") def test_font_settings_error(self, app, status, warning, draw): draw.side_effect = UnicodeEncodeError("", "", 0, 0, "") app.builder.build_all() self.assertIn('UnicodeEncodeError caught (check your font settings)', warning.getvalue())
[ "i.tkomiya@gmail.com" ]
i.tkomiya@gmail.com
da144278f9b5122abe6a2ada6e8b937379d84335
9e643d565e38de1728eabf31304e7dcbdf3ebfdd
/Python/Django/manyToMany/apps/manyToManyApp/migrations/0001_initial.py
522b5d14fb92bd5b6297d49a27747de163be6a68
[]
no_license
joeyzoland/DojoAssignments
88dca37ad1d5b585a4af1dabc49935ef34adf6a0
0cae15aa448c490af931b41939638456456cef63
refs/heads/master
2021-01-11T17:55:13.775179
2018-09-17T07:32:12
2018-09-17T07:32:12
79,875,553
0
1
null
null
null
null
UTF-8
Python
false
false
1,308
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-23 16:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Interest', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=45)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=45)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), migrations.AddField( model_name='interest', name='users', field=models.ManyToManyField(related_name='interests', to='manyToManyApp.User'), ), ]
[ "joeyzoland@gmail.com" ]
joeyzoland@gmail.com
632f50ce657bd31338db5ba020bec2b0f1357596
6e155cd7444e69b719d129e9dcaed2b788d4359b
/shop/shop/celery.py
2582d795673aac826732cb8f19387b7702df0cf7
[]
no_license
tishmanoni/My-store
0ac1beb26fd4c3176f90346b23b9e9c955e90729
79bec452be871089edd6415b00bd094dc6288443
refs/heads/master
2022-12-06T05:33:21.163835
2020-08-29T19:39:45
2020-08-29T19:39:45
291,334,250
0
0
null
null
null
null
UTF-8
Python
false
false
282
py
import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.settings') app = Celery('shop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()
[ "66375712+tishmanoni@users.noreply.github.com" ]
66375712+tishmanoni@users.noreply.github.com
7fc845ff7f633ccceb024e13feab6eda8d83a5c1
aac1b8efaeccc544d229aa52093a36802250b4cf
/pre/python/lib/python2.7/dist-packages/twisted/conch/test/test_ckeygen.py
41a02083ab4cf574d9e9fe70617cab39af519f8c
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ag1455/OpenPLi-PC
4f63bbd389ff9604ab7aaf72d10ee6552b794c87
256401ac313df2e45c516af1a4d5398f54703b9c
refs/heads/master
2023-08-22T18:20:07.491386
2023-08-14T17:29:59
2023-08-14T17:29:59
233,239,212
27
22
null
2020-12-28T22:09:26
2020-01-11T13:50:25
Python
UTF-8
Python
false
false
20,281
py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.conch.scripts.ckeygen}. """ import getpass import sys import os import subprocess from io import BytesIO, StringIO from twisted.python.compat import unicode, _PY3 from twisted.python.reflect import requireModule if requireModule('cryptography') and requireModule('pyasn1'): from twisted.conch.ssh.keys import (Key, BadKeyError, BadFingerPrintFormat, FingerprintFormats) from twisted.conch.scripts.ckeygen import ( changePassPhrase, displayPublicKey, printFingerprint, _saveKey, enumrepresentation) else: skip = "cryptography and pyasn1 required for twisted.conch.scripts.ckeygen" from twisted.python.filepath import FilePath from twisted.trial.unittest import TestCase from twisted.conch.test.keydata import ( publicRSA_openssh, privateRSA_openssh, privateRSA_openssh_encrypted, privateECDSA_openssh) def makeGetpass(*passphrases): """ Return a callable to patch C{getpass.getpass}. Yields a passphrase each time called. Use case is to provide an old, then new passphrase(s) as if requested interactively. @param passphrases: The list of passphrases returned, one per each call. @return: A callable to patch C{getpass.getpass}. """ passphrases = iter(passphrases) def fakeGetpass(_): return next(passphrases) return fakeGetpass class KeyGenTests(TestCase): """ Tests for various functions used to implement the I{ckeygen} script. """ def setUp(self): """ Patch C{sys.stdout} so tests can make assertions about what's printed. """ if _PY3: self.stdout = StringIO() else: self.stdout = BytesIO() self.patch(sys, 'stdout', self.stdout) def _testrun(self, keyType, keySize=None): filename = self.mktemp() if keySize is None: subprocess.call(['ckeygen', '-t', keyType, '-f', filename, '--no-passphrase']) else: subprocess.call(['ckeygen', '-t', keyType, '-f', filename, '--no-passphrase', '-b', keySize]) privKey = Key.fromFile(filename) pubKey = Key.fromFile(filename + '.pub') if keyType == 'ecdsa': self.assertEqual(privKey.type(), 'EC') else: self.assertEqual(privKey.type(), keyType.upper()) self.assertTrue(pubKey.isPublic()) def test_keygeneration(self): self._testrun('ecdsa', '384') self._testrun('ecdsa') self._testrun('dsa', '2048') self._testrun('dsa') self._testrun('rsa', '2048') self._testrun('rsa') def test_runBadKeytype(self): filename = self.mktemp() with self.assertRaises(subprocess.CalledProcessError): with open(os.devnull, "rb") as devnull: subprocess.check_call( ['ckeygen', '-t', 'foo', '-f', filename], stderr=devnull) def test_enumrepresentation(self): """ L{enumrepresentation} takes a dictionary as input and returns a dictionary with its attributes changed to enum representation. """ options = enumrepresentation({'format': 'md5-hex'}) self.assertIs(options['format'], FingerprintFormats.MD5_HEX) def test_enumrepresentationsha256(self): """ Test for format L{FingerprintFormats.SHA256-BASE64}. """ options = enumrepresentation({'format': 'sha256-base64'}) self.assertIs(options['format'], FingerprintFormats.SHA256_BASE64) def test_enumrepresentationBadFormat(self): """ Test for unsupported fingerprint format """ with self.assertRaises(BadFingerPrintFormat) as em: enumrepresentation({'format': 'sha-base64'}) self.assertEqual('Unsupported fingerprint format: sha-base64', em.exception.args[0]) def test_printFingerprint(self): """ L{printFingerprint} writes a line to standard out giving the number of bits of the key, its fingerprint, and the basename of the file from it was read. """ filename = self.mktemp() FilePath(filename).setContent(publicRSA_openssh) printFingerprint({'filename': filename, 'format': 'md5-hex'}) self.assertEqual( self.stdout.getvalue(), '2048 85:25:04:32:58:55:96:9f:57:ee:fb:a8:1a:ea:69:da temp\n') def test_printFingerprintsha256(self): """ L{printFigerprint} will print key fingerprint in L{FingerprintFormats.SHA256-BASE64} format if explicitly specified. """ filename = self.mktemp() FilePath(filename).setContent(publicRSA_openssh) printFingerprint({'filename': filename, 'format': 'sha256-base64'}) self.assertEqual( self.stdout.getvalue(), '2048 FBTCOoknq0mHy+kpfnY9tDdcAJuWtCpuQMaV3EsvbUI= temp\n') def test_printFingerprintBadFingerPrintFormat(self): """ L{printFigerprint} raises C{keys.BadFingerprintFormat} when unsupported formats are requested. """ filename = self.mktemp() FilePath(filename).setContent(publicRSA_openssh) with self.assertRaises(BadFingerPrintFormat) as em: printFingerprint({'filename': filename, 'format':'sha-base64'}) self.assertEqual('Unsupported fingerprint format: sha-base64', em.exception.args[0]) def test_saveKey(self): """ L{_saveKey} writes the private and public parts of a key to two different files and writes a report of this to standard out. """ base = FilePath(self.mktemp()) base.makedirs() filename = base.child('id_rsa').path key = Key.fromString(privateRSA_openssh) _saveKey(key, {'filename': filename, 'pass': 'passphrase', 'format': 'md5-hex'}) self.assertEqual( self.stdout.getvalue(), "Your identification has been saved in %s\n" "Your public key has been saved in %s.pub\n" "The key fingerprint in <FingerprintFormats=MD5_HEX> is:\n" "85:25:04:32:58:55:96:9f:57:ee:fb:a8:1a:ea:69:da\n" % ( filename, filename)) self.assertEqual( key.fromString( base.child('id_rsa').getContent(), None, 'passphrase'), key) self.assertEqual( Key.fromString(base.child('id_rsa.pub').getContent()), key.public()) def test_saveKeyECDSA(self): """ L{_saveKey} writes the private and public parts of a key to two different files and writes a report of this to standard out. Test with ECDSA key. """ base = FilePath(self.mktemp()) base.makedirs() filename = base.child('id_ecdsa').path key = Key.fromString(privateECDSA_openssh) _saveKey(key, {'filename': filename, 'pass': 'passphrase', 'format': 'md5-hex'}) self.assertEqual( self.stdout.getvalue(), "Your identification has been saved in %s\n" "Your public key has been saved in %s.pub\n" "The key fingerprint in <FingerprintFormats=MD5_HEX> is:\n" "1e:ab:83:a6:f2:04:22:99:7c:64:14:d2:ab:fa:f5:16\n" % ( filename, filename)) self.assertEqual( key.fromString( base.child('id_ecdsa').getContent(), None, 'passphrase'), key) self.assertEqual( Key.fromString(base.child('id_ecdsa.pub').getContent()), key.public()) def test_saveKeysha256(self): """ L{_saveKey} will generate key fingerprint in L{FingerprintFormats.SHA256-BASE64} format if explicitly specified. """ base = FilePath(self.mktemp()) base.makedirs() filename = base.child('id_rsa').path key = Key.fromString(privateRSA_openssh) _saveKey(key, {'filename': filename, 'pass': 'passphrase', 'format': 'sha256-base64'}) self.assertEqual( self.stdout.getvalue(), "Your identification has been saved in %s\n" "Your public key has been saved in %s.pub\n" "The key fingerprint in <FingerprintFormats=SHA256_BASE64> is:\n" "FBTCOoknq0mHy+kpfnY9tDdcAJuWtCpuQMaV3EsvbUI=\n" % ( filename, filename)) self.assertEqual( key.fromString( base.child('id_rsa').getContent(), None, 'passphrase'), key) self.assertEqual( Key.fromString(base.child('id_rsa.pub').getContent()), key.public()) def test_saveKeyBadFingerPrintformat(self): """ L{_saveKey} raises C{keys.BadFingerprintFormat} when unsupported formats are requested. """ base = FilePath(self.mktemp()) base.makedirs() filename = base.child('id_rsa').path key = Key.fromString(privateRSA_openssh) with self.assertRaises(BadFingerPrintFormat) as em: _saveKey(key, {'filename': filename, 'pass': 'passphrase', 'format': 'sha-base64'}) self.assertEqual('Unsupported fingerprint format: sha-base64', em.exception.args[0]) def test_saveKeyEmptyPassphrase(self): """ L{_saveKey} will choose an empty string for the passphrase if no-passphrase is C{True}. """ base = FilePath(self.mktemp()) base.makedirs() filename = base.child('id_rsa').path key = Key.fromString(privateRSA_openssh) _saveKey(key, {'filename': filename, 'no-passphrase': True, 'format': 'md5-hex'}) self.assertEqual( key.fromString( base.child('id_rsa').getContent(), None, b''), key) def test_saveKeyECDSAEmptyPassphrase(self): """ L{_saveKey} will choose an empty string for the passphrase if no-passphrase is C{True}. """ base = FilePath(self.mktemp()) base.makedirs() filename = base.child('id_ecdsa').path key = Key.fromString(privateECDSA_openssh) _saveKey(key, {'filename': filename, 'no-passphrase': True, 'format': 'md5-hex'}) self.assertEqual( key.fromString( base.child('id_ecdsa').getContent(), None), key) def test_saveKeyNoFilename(self): """ When no path is specified, it will ask for the path used to store the key. """ base = FilePath(self.mktemp()) base.makedirs() keyPath = base.child('custom_key').path import twisted.conch.scripts.ckeygen self.patch(twisted.conch.scripts.ckeygen, 'raw_input', lambda _: keyPath) key = Key.fromString(privateRSA_openssh) _saveKey(key, {'filename': None, 'no-passphrase': True, 'format': 'md5-hex'}) persistedKeyContent = base.child('custom_key').getContent() persistedKey = key.fromString(persistedKeyContent, None, b'') self.assertEqual(key, persistedKey) def test_displayPublicKey(self): """ L{displayPublicKey} prints out the public key associated with a given private key. """ filename = self.mktemp() pubKey = Key.fromString(publicRSA_openssh) FilePath(filename).setContent(privateRSA_openssh) displayPublicKey({'filename': filename}) displayed = self.stdout.getvalue().strip('\n') if isinstance(displayed, unicode): displayed = displayed.encode("ascii") self.assertEqual( displayed, pubKey.toString('openssh')) def test_displayPublicKeyEncrypted(self): """ L{displayPublicKey} prints out the public key associated with a given private key using the given passphrase when it's encrypted. """ filename = self.mktemp() pubKey = Key.fromString(publicRSA_openssh) FilePath(filename).setContent(privateRSA_openssh_encrypted) displayPublicKey({'filename': filename, 'pass': 'encrypted'}) displayed = self.stdout.getvalue().strip('\n') if isinstance(displayed, unicode): displayed = displayed.encode("ascii") self.assertEqual( displayed, pubKey.toString('openssh')) def test_displayPublicKeyEncryptedPassphrasePrompt(self): """ L{displayPublicKey} prints out the public key associated with a given private key, asking for the passphrase when it's encrypted. """ filename = self.mktemp() pubKey = Key.fromString(publicRSA_openssh) FilePath(filename).setContent(privateRSA_openssh_encrypted) self.patch(getpass, 'getpass', lambda x: 'encrypted') displayPublicKey({'filename': filename}) displayed = self.stdout.getvalue().strip('\n') if isinstance(displayed, unicode): displayed = displayed.encode("ascii") self.assertEqual( displayed, pubKey.toString('openssh')) def test_displayPublicKeyWrongPassphrase(self): """ L{displayPublicKey} fails with a L{BadKeyError} when trying to decrypt an encrypted key with the wrong password. """ filename = self.mktemp() FilePath(filename).setContent(privateRSA_openssh_encrypted) self.assertRaises( BadKeyError, displayPublicKey, {'filename': filename, 'pass': 'wrong'}) def test_changePassphrase(self): """ L{changePassPhrase} allows a user to change the passphrase of a private key interactively. """ oldNewConfirm = makeGetpass('encrypted', 'newpass', 'newpass') self.patch(getpass, 'getpass', oldNewConfirm) filename = self.mktemp() FilePath(filename).setContent(privateRSA_openssh_encrypted) changePassPhrase({'filename': filename}) self.assertEqual( self.stdout.getvalue().strip('\n'), 'Your identification has been saved with the new passphrase.') self.assertNotEqual(privateRSA_openssh_encrypted, FilePath(filename).getContent()) def test_changePassphraseWithOld(self): """ L{changePassPhrase} allows a user to change the passphrase of a private key, providing the old passphrase and prompting for new one. """ newConfirm = makeGetpass('newpass', 'newpass') self.patch(getpass, 'getpass', newConfirm) filename = self.mktemp() FilePath(filename).setContent(privateRSA_openssh_encrypted) changePassPhrase({'filename': filename, 'pass': 'encrypted'}) self.assertEqual( self.stdout.getvalue().strip('\n'), 'Your identification has been saved with the new passphrase.') self.assertNotEqual(privateRSA_openssh_encrypted, FilePath(filename).getContent()) def test_changePassphraseWithBoth(self): """ L{changePassPhrase} allows a user to change the passphrase of a private key by providing both old and new passphrases without prompting. """ filename = self.mktemp() FilePath(filename).setContent(privateRSA_openssh_encrypted) changePassPhrase( {'filename': filename, 'pass': 'encrypted', 'newpass': 'newencrypt'}) self.assertEqual( self.stdout.getvalue().strip('\n'), 'Your identification has been saved with the new passphrase.') self.assertNotEqual(privateRSA_openssh_encrypted, FilePath(filename).getContent()) def test_changePassphraseWrongPassphrase(self): """ L{changePassPhrase} exits if passed an invalid old passphrase when trying to change the passphrase of a private key. """ filename = self.mktemp() FilePath(filename).setContent(privateRSA_openssh_encrypted) error = self.assertRaises( SystemExit, changePassPhrase, {'filename': filename, 'pass': 'wrong'}) self.assertEqual('Could not change passphrase: old passphrase error', str(error)) self.assertEqual(privateRSA_openssh_encrypted, FilePath(filename).getContent()) def test_changePassphraseEmptyGetPass(self): """ L{changePassPhrase} exits if no passphrase is specified for the C{getpass} call and the key is encrypted. """ self.patch(getpass, 'getpass', makeGetpass('')) filename = self.mktemp() FilePath(filename).setContent(privateRSA_openssh_encrypted) error = self.assertRaises( SystemExit, changePassPhrase, {'filename': filename}) self.assertEqual( 'Could not change passphrase: Passphrase must be provided ' 'for an encrypted key', str(error)) self.assertEqual(privateRSA_openssh_encrypted, FilePath(filename).getContent()) def test_changePassphraseBadKey(self): """ L{changePassPhrase} exits if the file specified points to an invalid key. """ filename = self.mktemp() FilePath(filename).setContent(b'foobar') error = self.assertRaises( SystemExit, changePassPhrase, {'filename': filename}) if _PY3: expected = "Could not change passphrase: cannot guess the type of b'foobar'" else: expected = "Could not change passphrase: cannot guess the type of 'foobar'" self.assertEqual(expected, str(error)) self.assertEqual(b'foobar', FilePath(filename).getContent()) def test_changePassphraseCreateError(self): """ L{changePassPhrase} doesn't modify the key file if an unexpected error happens when trying to create the key with the new passphrase. """ filename = self.mktemp() FilePath(filename).setContent(privateRSA_openssh) def toString(*args, **kwargs): raise RuntimeError('oops') self.patch(Key, 'toString', toString) error = self.assertRaises( SystemExit, changePassPhrase, {'filename': filename, 'newpass': 'newencrypt'}) self.assertEqual( 'Could not change passphrase: oops', str(error)) self.assertEqual(privateRSA_openssh, FilePath(filename).getContent()) def test_changePassphraseEmptyStringError(self): """ L{changePassPhrase} doesn't modify the key file if C{toString} returns an empty string. """ filename = self.mktemp() FilePath(filename).setContent(privateRSA_openssh) def toString(*args, **kwargs): return '' self.patch(Key, 'toString', toString) error = self.assertRaises( SystemExit, changePassPhrase, {'filename': filename, 'newpass': 'newencrypt'}) if _PY3: expected = ( "Could not change passphrase: cannot guess the type of b''") else: expected = ( "Could not change passphrase: cannot guess the type of ''") self.assertEqual(expected, str(error)) self.assertEqual(privateRSA_openssh, FilePath(filename).getContent()) def test_changePassphrasePublicKey(self): """ L{changePassPhrase} exits when trying to change the passphrase on a public key, and doesn't change the file. """ filename = self.mktemp() FilePath(filename).setContent(publicRSA_openssh) error = self.assertRaises( SystemExit, changePassPhrase, {'filename': filename, 'newpass': 'pass'}) self.assertEqual( 'Could not change passphrase: key not encrypted', str(error)) self.assertEqual(publicRSA_openssh, FilePath(filename).getContent())
[ "a.g.prosat@gmail.com" ]
a.g.prosat@gmail.com
2ca74b87fb00d97fdb9b1cd2746f2e542e60938b
b65c1f6000af4ddeb7280e7d93bf861fbf1964bc
/contracts/tests/test_load_data.py
e385455a7533122a2a8978adbb1a3792d745a638
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
EricSchles/calc
ef00aaddfec010321867a8287db0a565dbb7985e
eaa1ab227a5a07f5f4f7d2c64a278977cd43cb18
refs/heads/develop
2021-01-25T14:33:58.124300
2017-10-11T19:29:20
2017-10-11T19:29:20
72,668,485
1
0
null
2016-11-02T18:17:57
2016-11-02T18:17:57
null
UTF-8
Python
false
false
483
py
import pathlib from django.core.management import call_command from django.test import TestCase from contracts.models import Contract MY_DIR = pathlib.Path(__file__).resolve().parent class LoadS70TestCase(TestCase): sample_filename = MY_DIR.parent / 'docs' / 'hourly_prices_sample.csv' def test_loads_sample(self): call_command( 'load_data', filename=self.sample_filename ) self.assertEquals(Contract.objects.count(), 79)
[ "varmaa@gmail.com" ]
varmaa@gmail.com
dba58d500dc281d3b42ffe31ba813201ef1ff43f
e4abeab73f2aa2de037aa84d195dce986af5208a
/lmp/script/sample_from_dataset.py
758446f580908db34133a1f847dfbd2745eb7d72
[ "Beerware" ]
permissive
france5289/language-model-playground
1792fc712bace3ca3e7a0b8b3ba4745b2d6c9b5c
02181561107dac13d52e411bc970e245277854d4
refs/heads/main
2023-08-07T01:59:56.928232
2021-09-22T06:57:28
2021-09-22T06:57:28
409,092,012
0
0
NOASSERTION
2021-09-22T06:39:53
2021-09-22T06:39:52
null
UTF-8
Python
false
false
2,896
py
r"""Sample dataset using index. Tool for observing data point in specified dataset. Use index to sample from dataset. See Also ======== lmp.dset All available dataset. Examples ======== The following example sample index ``0`` from :py:class:`lmp.dset.WikiText2Dset` ``train`` dataset. .. code-block:: sh python -m lmp.script.sample_from_dataset wikitext-2 The following example sample index ``1`` from :py:class:`lmp.dset.WikiText2Dset` ``train`` dataset. .. code-block:: sh python -m lmp.script.sample_from_dataset wikitext-2 --idx 1 The following example sample index ``1`` from :py:class:`lmp.dset.WikiText2Dset` ``test`` dataset. .. code-block:: sh python -m lmp.script.sample_from_dataset wikitext-2 --idx 1 --ver test Use ``-h`` or ``--help`` options to get list of available dataset. .. code-block:: sh python -m lmp.script.sample_from_dataset -h Use ``-h`` or ``--help`` options on specific dataset to get a list of available versions. .. code-block:: sh python -m lmp.script.sample_from_dataset wikitext-2 -h """ import argparse import lmp.util.dset from lmp.dset import DSET_OPTS def parse_arg() -> argparse.Namespace: r"""Parse arguments from CLI. Argument must begin with a dataset name ``dset_name``. The following arguments are optional: --ver Version of the dataset. Default to ``dset``'s default version. --idx Sample index. Default to ``0``. Returns ======= argparse.Namespace Arguments from CLI. """ # Create parser. parser = argparse.ArgumentParser( 'python -m lmp.script.sample_from_dataset', description='Sample dataset using index.', ) # Create subparser for each dataset. subparsers = parser.add_subparsers(dest='dset_name', required=True) for dset_name, dset_clss in DSET_OPTS.items(): # Use dataset name as CLI argument. dset_parser = subparsers.add_parser( dset_name, description=f'Sample {dset_name} dataset using index.', ) # Optional arguments. dset_parser.add_argument( '--idx', default=0, help='Sample index.', type=int, ) dset_parser.add_argument( '--ver', default=None, help=' '.join([ f'Version of the {dset_name} dataset.', f'Defaults to {dset_clss.df_ver}.', ]), choices=dset_clss.vers, type=str, ) return parser.parse_args() def main() -> None: r"""Script entry point.""" # Parse command-line argument. args = parse_arg() # Get dataset instance with specified version. dset = lmp.util.dset.load(dset_name=args.dset_name, ver=args.ver) # Output sample result. print(dset[args.idx]) if __name__ == '__main__': main()
[ "ProFatXuanAll@gmail.com" ]
ProFatXuanAll@gmail.com
0d1cb7925a58261d9e23d04bfa835151026b290e
d968882c6bdecb2347307aea7381b9495911a0a6
/microconventions/type_conventions.py
743a0db4e8a8e19220b9f89b9415898b16077566
[]
no_license
fagan2888/microconventions
a070bddf94c0788ed4ff3ab31941d0daccf30fd5
037f9fcc67caa28916c6b81f4742a68afaf296b0
refs/heads/master
2022-11-10T21:52:53.632179
2020-07-02T14:28:59
2020-07-02T14:28:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
204
py
from typing import List, Union, Any, Optional KeyList = List[Optional[str]] NameList = List[Optional[str]] Value = Union[str,int] ValueList = List[Optional[Value]] DelayList = List[Optional[int]]
[ "info@3za.org" ]
info@3za.org
88c524a2aa42d1c53e01946abb653c80c94e0e38
7a0acc1c2e808c7d363043546d9581d21a129693
/selenium/src/py/lib/epydoc/docwriter/html.py
352d45d89179d2f5cf75d6da437d6060d4ff70aa
[ "Apache-2.0" ]
permissive
epall/selenium
39b9759f8719a168b021b28e500c64afc5f83582
273260522efb84116979da2a499f64510250249b
refs/heads/master
2022-06-25T22:15:25.493076
2010-03-11T00:43:02
2010-03-11T00:43:02
552,908
3
0
Apache-2.0
2022-06-10T22:44:36
2010-03-08T19:10:45
C
UTF-8
Python
false
false
123,261
py
# # epydoc -- HTML output generator # Edward Loper # # Created [01/30/01 05:18 PM] # $Id: html.py 1210 2006-04-10 13:25:50Z edloper $ # """ The HTML output generator for epydoc. The main interface provided by this module is the L{HTMLWriter} class. """ __docformat__ = 'epytext en' import re, os, sys, codecs, sre_constants, pprint import urllib from epydoc.apidoc import * import epydoc.docstringparser import time, epydoc, epydoc.markup from epydoc.docwriter.html_colorize import colorize_re from epydoc.docwriter.html_colorize import PythonSourceColorizer from epydoc.docwriter import html_colorize from epydoc.docwriter.html_css import STYLESHEETS from epydoc.docwriter.html_help import HTML_HELP from epydoc.docwriter.dotgraph import * from epydoc import log from epydoc.util import plaintext_to_html, is_src_filename from epydoc.compat import * # Backwards compatibility ###################################################################### ## Template Compiler ###################################################################### # The compile_tempalte() method defined in this section is used to # define several of HTMLWriter's methods. def compile_template(docstring, template_string, output_function='out', debug=epydoc.DEBUG): """ Given a template string containing inline python source code, return a python function that will fill in the template, and output the result. The signature for this function is taken from the first line of C{docstring}. Output is generated by making repeated calls to the output function with the given name (which is typically one of the function's parameters). The templating language used by this function passes through all text as-is, with three exceptions: - If every line in the template string is indented by at least M{x} spaces, then the first M{x} spaces are stripped from each line. - Any line that begins with '>>>' (with no indentation) should contain python code, and will be inserted as-is into the template-filling function. If the line begins a control block (such as 'if' or 'for'), then the control block will be closed by the first '>>>'-marked line whose indentation is less than or equal to the line's own indentation (including lines that only contain comments.) - In any other line, any expression between two '$' signs will be evaluated and inserted into the line (using C{str()} to convert the result to a string). Here is a simple example: >>> TEMPLATE = ''' ... <book> ... <title>$book.title$</title> ... <pages>$book.count_pages()$</pages> ... >>> for chapter in book.chapters: ... <chaptername>$chapter.name$</chaptername> ... >>> #endfor ... </book> >>> write_book = compile_template('write_book(out, book)', TEMPLATE) @newfield acknowledgements: Acknowledgements @acknowledgements: The syntax used by C{compile_template} is loosely based on Cheetah. """ # Extract signature from the docstring: signature = docstring.lstrip().split('\n',1)[0].strip() func_name = signature.split('(',1)[0].strip() # Regexp to search for inline substitutions: INLINE = re.compile(r'\$([^\$]+)\$') # Regexp to search for python statements in the template: COMMAND = re.compile(r'(^>>>.*)\n?', re.MULTILINE) # Strip indentation from the template. template_string = strip_indent(template_string) # If we're debugging, then we'll store the generated function, # so we can print it along with any tracebacks that depend on it. if debug: signature = re.sub(r'\)\s*$', ', __debug=__debug)', signature) # Funciton declaration line pysrc_lines = ['def %s:' % signature] indents = [-1] if debug: pysrc_lines.append(' try:') indents.append(-1) commands = COMMAND.split(template_string.strip()+'\n') for i, command in enumerate(commands): if command == '': continue # String literal segment: if i%2 == 0: pieces = INLINE.split(command) for j, piece in enumerate(pieces): if j%2 == 0: # String piece pysrc_lines.append(' '*len(indents)+ '%s(%r)' % (output_function, piece)) else: # Variable piece pysrc_lines.append(' '*len(indents)+ '%s(unicode(%s))' % (output_function, piece)) # Python command: else: srcline = command[3:].lstrip() # Update indentation indent = len(command)-len(srcline) while indent <= indents[-1]: indents.pop() # Add on the line. srcline = srcline.rstrip() pysrc_lines.append(' '*len(indents)+srcline) if srcline.endswith(':'): indents.append(indent) if debug: pysrc_lines.append(' except Exception,e:') pysrc_lines.append(' pysrc, func_name = __debug ') pysrc_lines.append(' lineno = sys.exc_info()[2].tb_lineno') pysrc_lines.append(' print ("Exception in template %s() on "') pysrc_lines.append(' "line %d:" % (func_name, lineno))') pysrc_lines.append(' print pysrc[lineno-1]') pysrc_lines.append(' raise') pysrc = '\n'.join(pysrc_lines)+'\n' if debug: localdict = {'__debug': (pysrc_lines, func_name)} else: localdict = {} try: exec pysrc in globals(), localdict except SyntaxError: log.error('Error in script:\n' + pysrc + '\n') raise template_func = localdict[func_name] template_func.__doc__ = docstring return template_func def strip_indent(s): """ Given a multiline string C{s}, find the minimum indentation for all non-blank lines, and return a new string formed by stripping that amount of indentation from all lines in C{s}. """ # Strip indentation from the template. minindent = sys.maxint lines = s.split('\n') for line in lines: stripline = line.lstrip() if stripline: minindent = min(minindent, len(line)-len(stripline)) return '\n'.join([l[minindent:] for l in lines]) ###################################################################### ## HTML Writer ###################################################################### class HTMLWriter: #//////////////////////////////////////////////////////////// # Table of Contents #//////////////////////////////////////////////////////////// # # 1. Interface Methods # # 2. Page Generation -- write complete web page files # 2.1. Module Pages # 2.2. Class Pages # 2.3. Trees Page # 2.4. Indices Page # 2.5. Help Page # 2.6. Frames-based table of contents pages # 2.7. Homepage (index.html) # 2.8. CSS Stylesheet # 2.9. Javascript file # # 3. Page Element Generation -- write pieces of a web page file # 3.1. Page Header # 3.2. Page Footer # 3.3. Navigation Bar # 3.4. Breadcrumbs # 3.5. Summary Tables # # 4. Helper functions def __init__(self, docindex, **kwargs): """ Construct a new HTML writer, using the given documentation index. @param docmap: The documentation index. @type prj_name: C{string} @keyword prj_name: The name of the project. Defaults to none. @type prj_url: C{string} @keyword prj_url: The target for the project hopeage link on the navigation bar. If C{prj_url} is not specified, then no hyperlink is created. @type prj_link: C{string} @keyword prj_link: The label for the project link on the navigation bar. This link can contain arbitrary HTML code (e.g. images). By default, a label is constructed from C{prj_name}. @type top_page: C{string} @keyword top_page: The top page for the documentation. This is the default page shown main frame, when frames are enabled. C{top} can be a URL, the name of a module, the name of a class, or one of the special strings C{"trees.html"}, C{"indices.html"}, or C{"help.html"}. By default, the top-level package or module is used, if there is one; otherwise, C{"trees"} is used. @type css: C{string} @keyword css: The CSS stylesheet file. If C{css} is a file name, then the specified file's conents will be used. Otherwise, if C{css} is the name of a CSS stylesheet in L{epydoc.docwriter.html_css}, then that stylesheet will be used. Otherwise, an error is reported. If no stylesheet is specified, then the default stylesheet is used. @type help_file: C{string} @keyword help_file: The name of the help file. If no help file is specified, then the default help file will be used. @type show_private: C{boolean} @keyword show_private: Whether to create documentation for private objects. By default, private objects are documented. @type show_frames: C{boolean}) @keyword show_frames: Whether to create a frames-based table of contents. By default, it is produced. @type show_imports: C{boolean} @keyword show_imports: Whether or not to display lists of imported functions and classes. By default, they are not shown. @type variable_maxlines: C{int} @keyword variable_maxlines: The maximum number of lines that should be displayed for the value of a variable in the variable details section. By default, 8 lines are displayed. @type variable_linelength: C{int} @keyword variable_linelength: The maximum line length used for displaying the values of variables in the variable details sections. If a line is longer than this length, then it will be wrapped to the next line. The default line length is 70 characters. @type variable_summary_linelength: C{int} @keyword variable_summary_linelength: The maximum line length used for displaying the values of variables in the summary section. If a line is longer than this length, then it will be truncated. The default is 40 characters. @type variable_tooltip_linelength: C{int} @keyword variable_tooltip_linelength: The maximum line length used for tooltips for the values of variables. If a line is longer than this length, then it will be truncated. The default is 600 characters. @type property_function_linelength: C{int} @keyword property_function_linelength: The maximum line length used to dispaly property functions (C{fget}, C{fset}, and C{fdel}) that contain something other than a function object. The default length is 40 characters. @type inheritance: C{string} @keyword inheritance: How inherited objects should be displayed. If C{inheritance='grouped'}, then inherited objects are gathered into groups; if C{inheritance='listed'}, then inherited objects are listed in a short list at the end of their group; if C{inheritance='included'}, then inherited objects are mixed in with non-inherited objects. The default is 'grouped'. @type include_sourcecode: C{boolean} @param include_sourcecode: If true, then generate colorized source code files for each python module. """ self.docindex = docindex # Process keyword arguments. self._show_private = kwargs.get('show_private', 1) """Should private docs be included?""" self._prj_name = kwargs.get('prj_name', None) """The project's name (for the project link in the navbar)""" self._prj_url = kwargs.get('prj_url', None) """URL for the project link in the navbar""" self._prj_link = kwargs.get('prj_link', None) """HTML code for the project link in the navbar""" self._top_page = kwargs.get('top_page', None) """The 'main' page""" self._css = kwargs.get('css') """CSS stylesheet to use""" self._helpfile = kwargs.get('help_file', None) """Filename of file to extract help contents from""" self._frames_index = kwargs.get('show_frames', 1) """Should a frames index be created?""" self._show_imports = kwargs.get('show_imports', False) """Should imports be listed?""" self._propfunc_linelen = kwargs.get('property_function_linelength', 40) """[XXX] Not used!""" self._variable_maxlines = kwargs.get('variable_maxlines', 8) """Max lines for variable values""" self._variable_linelen = kwargs.get('variable_linelength', 70) """Max line length for variable values""" self._variable_summary_linelen = \ kwargs.get('variable_summary_linelength', 55) """Max length for variable value summaries""" self._variable_tooltip_linelen = \ kwargs.get('variable_tooltip_linelength', 600) """Max length for variable tooltips""" self._inheritance = kwargs.get('inheritance', 'listed') """How should inheritance be displayed? 'listed', 'included', or 'grouped'""" self._incl_sourcecode = kwargs.get('include_source_code', True) """Should pages be generated for source code of modules?""" self._mark_docstrings = kwargs.get('mark_docstrings', False) """Wrap <span class='docstring'>...</span> around docstrings?""" self._graph_types = kwargs.get('graphs', ()) or () """Graphs that we should include in our output.""" # For use with select_variables(): if self._show_private: self._public_filter = None else: self._public_filter = True # Make sure inheritance has a sane value. if self._inheritance not in ('listed', 'included', 'grouped'): raise ValueError, 'Bad value for inheritance' # Create the project homepage link, if it was not specified. if (self._prj_name or self._prj_url) and not self._prj_link: self._prj_link = plaintext_to_html(self._prj_name or 'Project Homepage') # Add a hyperlink to _prj_url, if _prj_link doesn't already # contain any hyperlinks. if (self._prj_link and self._prj_url and not re.search(r'<a[^>]*\shref', self._prj_link)): self._prj_link = ('<a class="navbar" target="_top" href="'+ self._prj_url+'">'+self._prj_link+'</a>') # Precompute lists & sets of APIDoc objects that we're # interested in. self.valdocs = valdocs = sorted(docindex.reachable_valdocs( imports=False, packages=False, bases=False, submodules=False, subclasses=False, private=self._show_private)) self.module_list = [d for d in valdocs if isinstance(d, ModuleDoc)] """The list of L{ModuleDoc}s for the documented modules.""" self.module_set = set(self.module_list) """The set of L{ModuleDoc}s for the documented modules.""" self.class_list = [d for d in valdocs if isinstance(d, ClassDoc)] """The list of L{ClassDoc}s for the documented classes.""" self.class_set = set(self.class_list) """The set of L{ClassDoc}s for the documented classes.""" self.routine_list = [d for d in valdocs if isinstance(d, RoutineDoc)] """The list of L{RoutineDoc}s for the documented routines.""" self.indexed_docs = [] """The list of L{APIDoc}s for variables and values that should be included in the index.""" # Construct the value for self.indexed_docs. self.indexed_docs += [d for d in valdocs if not isinstance(d, GenericValueDoc)] for doc in valdocs: if isinstance(doc, NamespaceDoc): self.indexed_docs += [doc for doc in doc.variables.values() if isinstance(doc.value, GenericValueDoc)] self.indexed_docs.sort() # Figure out the url for the top page. self._top_page_url = self._find_top_page(self._top_page) # Figure out how many output files there will be (for progress # reporting). self.modules_with_sourcecode = set() for doc in self.module_list: if isinstance(doc, ModuleDoc) and is_src_filename(doc.filename): self.modules_with_sourcecode.add(doc) self._num_files = len(self.class_list) + 2*len(self.module_list) + 9 if self._incl_sourcecode: self._num_files += len(self.modules_with_sourcecode) def _find_top_page(self, pagename): """ Find the top page for the API documentation. This page is used as the default page shown in the main frame, when frames are used. When frames are not used, this page is copied to C{index.html}. @param pagename: The name of the page, as specified by the keyword argument C{top} to the constructor. @type pagename: C{string} @return: The URL of the top page. @rtype: C{string} """ # If a page name was specified, then we need to figure out # what it points to. if pagename: # If it's a URL, then use it directly. if pagename.lower().startswith('http:'): return pagename # If it's an object, then use that object's page. try: doc = self.docindex.get_valdoc(pagename) return self.url(doc) except: pass # Otherwise, give up. log.warning('Could not find top page %r; using trees.html ' 'instead' % pagename) # If no page name was specified, then try to choose one # automatically. else: root = [val_doc for val_doc in self.docindex.root if isinstance(val_doc, (ClassDoc, ModuleDoc))] if len(root) == 0: # No docs?? Try the trees page. return 'trees.html' elif len(root) == 1: # One item in the root; use that. return self.url(root[0]) else: # Multiple root items; if they're all in one package, # then use that. Otherwise, use trees.html root = sorted(root, key=lambda v:len(v.canonical_name)) top = root[0] for doc in root[1:]: if not top.canonical_name.dominates(doc.canonical_name): return 'trees.html' else: return self.url(top) #//////////////////////////////////////////////////////////// #{ 1. Interface Methods #//////////////////////////////////////////////////////////// def write(self, directory=None): """ Write the documentation to the given directory. @type directory: C{string} @param directory: The directory to which output should be written. If no directory is specified, output will be written to the current directory. If the directory does not exist, it will be created. @rtype: C{None} @raise OSError: If C{directory} cannot be created. @raise OSError: If any file cannot be created or written to. """ # For progress reporting: self._files_written = 0. # Keep track of failed xrefs, and report them at the end. self._failed_xrefs = {} # Create destination directories, if necessary if not directory: directory = os.curdir self._mkdir(directory) self._directory = directory # Write the CSS file. self._files_written += 1 log.progress(self._files_written/self._num_files, 'epydoc.css') self.write_css(directory, self._css) # Write the Javascript file. self._files_written += 1 log.progress(self._files_written/self._num_files, 'epydoc.js') self.write_javascript(directory) # Write the term & identifier indices self._write(self.write_indices, directory, 'indices.html') # Write the trees file (package & class hierarchies) self._write(self.write_trees, directory, 'trees.html') # Write the help file. self._write(self.write_help, directory,'help.html') # Write the frames-based table of contents. self._write(self.write_frames_index, directory, 'frames.html') self._write(self.write_toc, directory, 'toc.html') self._write(self.write_project_toc, directory, 'toc-everything.html') for doc in self.module_list: filename = 'toc-%s' % urllib.unquote(self.url(doc)) self._write(self.write_module_toc, directory, filename, doc) # Write the object documentation. for doc in self.module_list: filename = urllib.unquote(self.url(doc)) self._write(self.write_module, directory, filename, doc) for doc in self.class_list: filename = urllib.unquote(self.url(doc)) self._write(self.write_class, directory, filename, doc) # Write source code files. if self._incl_sourcecode: for doc in self.modules_with_sourcecode: filename = urllib.unquote(self.pysrc_url(doc)) self._write(self.write_sourcecode, directory, filename, doc) # Write the index.html files. # (this must be done last, since it might copy another file) self._files_written += 1 log.progress(self._files_written/self._num_files, 'index.html') self.write_homepage(directory) # Report any failed crossreferences if self._failed_xrefs: estr = 'Failed identifier crossreference targets:\n' failed_identifiers = self._failed_xrefs.keys() failed_identifiers.sort() for identifier in failed_identifiers: names = self._failed_xrefs[identifier].keys() names.sort() estr += '- %s' % identifier estr += '\n' for name in names: estr += ' (from %s)\n' % name log.docstring_warning(estr) def _write(self, write_func, directory, filename, *args): # Display our progress. self._files_written += 1 log.progress(self._files_written/self._num_files, filename) path = os.path.join(directory, filename) f = codecs.open(path, 'w', 'ascii', errors='xmlcharrefreplace') write_func(f.write, *args) f.close() def _mkdir(self, directory): """ If the given directory does not exist, then attempt to create it. @rtype: C{None} """ if not os.path.isdir(directory): if os.path.exists(directory): raise OSError('%r is not a directory' % directory) os.mkdir(directory) #//////////////////////////////////////////////////////////// #{ 2.1. Module Pages #//////////////////////////////////////////////////////////// def write_module(self, out, doc): """ Write an HTML page containing the API documentation for the given module to C{out}. @param doc: A L{ModuleDoc} containing the API documentation for the module that should be described. """ longname = doc.canonical_name shortname = doc.canonical_name[-1] # Write the page header (incl. navigation bar & breadcrumbs) self.write_header(out, str(longname)) self.write_navbar(out, doc) self.write_breadcrumbs(out, doc, self.url(doc)) # Write the name of the module we're describing. if doc.is_package is True: typ = 'Package' else: typ = 'Module' if longname[0].startswith('script-'): shortname = str(longname)[7:] typ = 'Script' out('<!-- ==================== %s ' % typ.upper() + 'DESCRIPTION ==================== -->\n') out('<h2 class="%s">%s %s' % (typ.lower(), typ, shortname)) src_link = self.pysrc_link(doc) if src_link: out('\n<br/>' + src_link) out('</h2>\n') # If the module has a description, then list it. if doc.descr not in (None, UNKNOWN): out(self.descr(doc, 2)+'<br /><br />\n\n') # Write any standarad metadata (todo, author, etc.) if doc.metadata is not UNKNOWN and doc.metadata: out('<hr />\n') self.write_standard_fields(out, doc) # If it's a package, then list the modules it contains. if doc.is_package is True: self.write_module_list(out, doc) # Write summary tables describing the variables that the # module defines. self.write_summary_table(out, "Classes", doc, "class") self.write_summary_table(out, "Functions", doc, "function") self.write_summary_table(out, "Variables", doc, "other") # Write a list of all imported objects. if self._show_imports: self.write_imports(out, doc) # Write detailed descriptions of functions & variables defined # in this module. self.write_details_list(out, "Function Details", doc, "function") self.write_details_list(out, "Variables Details", doc, "other") # Write the page footer (including navigation bar) self.write_navbar(out, doc) self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.??. Source Code Pages #//////////////////////////////////////////////////////////// def write_sourcecode(self, out, doc): filename = doc.filename name = str(doc.canonical_name) # Header self.write_header(out, name) self.write_navbar(out, doc) self.write_breadcrumbs(out, doc, self.pysrc_url(doc)) # Source code listing out('<h2 class="py-src">Source Code for %s</h2>\n' % self.href(doc, label='%s %s' % (self.doc_kind(doc), name))) out('<div class="py-src">\n') out('<pre class="py-src">\n') out(PythonSourceColorizer(filename, name, self.docindex, self.indexed_docs, self.url).colorize()) out('</pre>\n</div>\n<br />\n') # Footer self.write_navbar(out, doc) self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.2. Class Pages #//////////////////////////////////////////////////////////// def write_class(self, out, doc): """ Write an HTML page containing the API documentation for the given class to C{out}. @param doc: A L{ClassDoc} containing the API documentation for the class that should be described. """ longname = doc.canonical_name shortname = doc.canonical_name[-1] # Write the page header (incl. navigation bar & breadcrumbs) self.write_header(out, str(longname)) self.write_navbar(out, doc) self.write_breadcrumbs(out, doc, self.url(doc)) # Write the name of the class we're describing. if doc.is_type(): typ = 'Type' elif doc.is_exception(): typ = 'Exception' else: typ = 'Class' out('<!-- ==================== %s ' % typ.upper() + 'DESCRIPTION ==================== -->\n') out('<h2 class="%s">%s %s' % (typ.lower(), typ, shortname)) src_link = self.pysrc_link(doc) if src_link: out('\n<br/>' + src_link) out('</h2>\n') if ((doc.bases not in (UNKNOWN, None) and len(doc.bases) > 0) or (doc.subclasses not in (UNKNOWN,None) and len(doc.subclasses)>0)): # Display bases graphically, if requested. if 'umlclasstree' in self._graph_types: linker = _HTMLDocstringLinker(self, doc) graph = uml_class_tree_graph(doc, linker, doc) out('<center>\n%s</center>\n' % self.render_graph(graph)) elif 'classtree' in self._graph_types: linker = _HTMLDocstringLinker(self, doc) graph = class_tree_graph([doc], linker, doc) out('<center>\n%s</center>\n' % self.render_graph(graph)) # Otherwise, use ascii-art. else: # Write the base class tree. if doc.bases not in (UNKNOWN, None) and len(doc.bases) > 0: out('<pre class="base-tree">\n%s</pre>\n\n' % self.base_tree(doc)) # Write the known subclasses if (doc.subclasses not in (UNKNOWN, None) and len(doc.subclasses) > 0): out('<dl><dt>Known Subclasses:</dt>\n<dd>\n ') out(',\n '.join([self.href(c, context=doc) for c in doc.subclasses])) out('\n</dd></dl>\n\n') out('<hr />\n') # If the class has a description, then list it. if doc.descr not in (None, UNKNOWN): out(self.descr(doc, 2)+'<br /><br />\n\n') # Write any standarad metadata (todo, author, etc.) if doc.metadata is not UNKNOWN and doc.metadata: out('<hr />\n') self.write_standard_fields(out, doc) # Write summary tables describing the variables that the # class defines. self.write_summary_table(out, "Nested Classes", doc, "class") self.write_summary_table(out, "Instance Methods", doc, "instancemethod") self.write_summary_table(out, "Class Methods", doc, "classmethod") self.write_summary_table(out, "Static Methods", doc, "staticmethod") self.write_summary_table(out, "Class Variables", doc, "classvariable") self.write_summary_table(out, "Instance Variables", doc, "instancevariable") self.write_summary_table(out, "Properties", doc, "property") # Write a list of all imported objects. if self._show_imports: self.write_imports(out, doc) # Write detailed descriptions of functions & variables defined # in this class. # [xx] why group methods into one section but split vars into two? # seems like we should either group in both cases or split in both # cases. self.write_details_list(out, "Method Details", doc, "method") self.write_details_list(out, "Class Variable Details", doc, "classvariable") self.write_details_list(out, "Instance Variable Details", doc, "instancevariable") self.write_details_list(out, "Property Details", doc, "property") # Write the page footer (including navigation bar) self.write_navbar(out, doc) self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.3. Trees page #//////////////////////////////////////////////////////////// def write_trees(self, out): """ Write an HTML page containing the module and class hierarchies to the given streams. @param public: The output stream for the public version of the page. @param private: The output stream for the private version of the page. """ # Header material. self.write_header(out, 'Trees') self.write_navbar(out, 'trees') self.write_breadcrumbs(out, 'trees', 'trees.html') # Write the module hierarchy out('<!-- ==================== ' 'MODULE HIERARCHY ==================== -->\n') out('<h2>Module Hierarchy</h2>\n') self.write_module_tree(out) # Does the project define any classes? defines_classes = len(self.class_list) > 0 # Write the class hierarchy if defines_classes: out('<!-- ==================== ' 'CLASS HIERARCHY ==================== -->\n') out('<h2>Class Hierarchy</h2>\n') self.write_class_tree(out) # Footer material. self.write_navbar(out, 'trees') self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.4. Indices page #//////////////////////////////////////////////////////////// def write_indices(self, out): """ Write an HTML page containing the term and identifier indices to the given streams. @bug: If there are private indexed terms, but no public indexed terms, then this function will still write a header for the Term Index to the public stream. @param public: The output stream for the public version of the page. @param private: The output stream for the private version of the page. """ # Header material. self.write_header(out, 'Index') self.write_navbar(out, 'indices') self.write_breadcrumbs(out, 'indices', 'indices.html') out('<br />\n') terms = self._extract_term_index() if terms: self.write_term_index(out, terms) # [xx] this will only find variables if they have values. # (e.g., it won't list any instance variables.) identifiers = [] for doc in self.indexed_docs: name = doc.canonical_name if self.url(doc) is None: continue key = name[-1].lower() key = (key[:1] in 'abcdefghijklmnopqrstuvwxyz', key) identifiers.append( (key, name, doc) ) identifiers.sort() if identifiers: self.write_identifier_index(out, identifiers) # Footer material. self.write_navbar(out, 'indices') self.write_footer(out) write_identifier_index_header = compile_template( """ write_identifier_index_header(self, out) """, # /------------------------- Template -------------------------\ ''' <!-- ==================== IDENTIFIER INDEX ==================== --> <table class="index" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="index"><th colspan="2"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr><th class="index">Identifier&nbsp;Index</th> <td width="100%" align="right"> [ <a href="#_">_</a> >>> for c in "abcdefghijklmnopqrstuvwxyz": <a href="#$c$">$c$</a> >>> #endfor ] </td> </tr></table> </th></tr> ''') # \------------------------------------------------------------/ write_identifier_index = compile_template( """ write_identifier_index(self, out, index) """, # /------------------------- Template -------------------------\ ''' >>> #self.write_table_header(out, "index", "Identifier Index") >>> self.write_identifier_index_header(out) >>> letters = "abcdefghijklmnopqrstuvwxyz" <a name="_"></a> >>> for sortkey, name, doc in index: >>> if self._doc_or_ancestor_is_private(doc): >>> if not self._show_private: continue <tr class="private"><td width="15%"> >>> else: <tr><td width="15%"> >>> #endif >>> while letters and letters[0] <= name[-1][:1].lower(): <a name="$letters[0]$"></a> >>> letters = letters[1:] >>> #endif $self.href(doc, name[-1])$ </td> <td>$self.doc_kind(doc)$ >>> container_name = name.container() >>> if container_name is not None: >>> container = self.docindex.get_valdoc(container_name) >>> if container is not None: in $self.doc_kind(container)$ $self.href(container)$ >>> #endif >>> #endif </td> </tr> >>> #endfor </table> >>> for letter in letters: <a name="$letter$"></a> >>> #endfor <br /> ''') # \------------------------------------------------------------/ write_term_index = compile_template( """ write_term_index(self, out, index) """, # /------------------------- Template -------------------------\ ''' >>> if not index: return >>> self.write_table_header(out, "index", "Term Index") >>> for (key, term, links) in index: <tr><td width="15%">$term.to_plaintext(None)$</td> <td> >>> for link in links[:-1]: <em>$self.href(link)$</em>, >>> #endfor <em>$self.href(links[-1])$</em> </td> </tr> >>> #endfor </table> <br /> ''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ 2.5. Help Page #//////////////////////////////////////////////////////////// def write_help(self, out): """ Write an HTML help file to the given stream. If C{self._helpfile} contains a help file, then use it; otherwise, use the default helpfile from L{epydoc.docwriter.html_help}. @param public: The output stream for the public version of the page. @param private: The output stream for the private version of the page. """ # todo: optionally parse .rst etc help files? # Get the contents of the help file. if self._helpfile: if os.path.exists(self._helpfile): try: help = open(self._helpfile).read() except: raise IOError("Can't open help file: %r" % self._helpfile) else: raise IOError("Can't find help file: %r" % self._helpfile) else: if self._prj_name: thisprj = self._prj_name else: thisprj = 'this project' help = HTML_HELP % {'this_project':thisprj} # Insert the help contents into a webpage. self.write_header(out, 'Help') self.write_navbar(out, 'help') self.write_breadcrumbs(out, 'help', 'help.html') out(help) self.write_navbar(out, 'help') self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.6. Frames-based Table of Contents #//////////////////////////////////////////////////////////// write_frames_index = compile_template( """ write_frames_index(self, out) Write the frames index file for the frames-based table of contents to the given streams. """, # /------------------------- Template -------------------------\ ''' <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "DTD/xhtml1-frameset.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title> $self._prj_name or "API Documentation"$ </title> </head> <frameset cols="20%,80%"> <frameset rows="30%,70%"> <frame src="toc.html" name="moduleListFrame" id="moduleListFrame" /> <frame src="toc-everything.html" name="moduleFrame" id="moduleFrame" /> </frameset> <frame src="$self._top_page_url$" name="mainFrame" id="mainFrame" /> </frameset> </html> ''') # \------------------------------------------------------------/ write_toc = compile_template( """ write_toc(self, out) """, # /------------------------- Template -------------------------\ ''' >>> self.write_header(out, "Table of Contents") <h1 class="tocheading">Table&nbsp;of&nbsp;Contents</h1> <hr /> <p class="toc"> <a target="moduleFrame" href="toc-everything.html">Everything</a> </p> >>> self.write_toc_section(out, "Modules", self.module_list) <hr /> >>> if self._show_private: $self.PRIVATE_LINK$ >>> #endif >>> self.write_footer(out, short=True) ''') # \------------------------------------------------------------/ def write_toc_section(self, out, name, docs, fullname=True): if not docs: return # Assign names to each item, and sort by name. if fullname: docs = [(str(d.canonical_name), d) for d in docs] else: docs = [(str(d.canonical_name[-1]), d) for d in docs] docs.sort() out(' <h2 class="tocheading">%s</h2>\n' % name) for label, doc in docs: doc_url = self.url(doc) toc_url = 'toc-%s' % doc_url is_private = self._doc_or_ancestor_is_private(doc) if is_private: if not self._show_private: continue out(' <div class="private">\n') out(' <p class="toc">\n') if isinstance(doc, ModuleDoc): out(' <a target="moduleFrame" href="%s"\n' ' onclick="setFrame(\'%s\',\'%s\');"' ' >%s</a></p>' % (toc_url, toc_url, doc_url, label)) else: out(' <a target="mainFrame" href="%s"\n' ' >%s</a></p>' % (doc_url, label)) if is_private: out(' </div>\n') def write_project_toc(self, out): self.write_header(out, "Everything") out('<h1 class="tocheading">Everything</h1>\n') out('<hr />\n') # List the classes. self.write_toc_section(out, "All Classes", self.class_list) # List the functions. funcs = [d for d in self.routine_list if not isinstance(self.docindex.container(d), (ClassDoc, types.NoneType))] self.write_toc_section(out, "All Functions", funcs) # List the variables. vars = [] for doc in self.module_list: vars += doc.select_variables(value_type='other', imported=False, public=self._public_filter) self.write_toc_section(out, "All Variables", vars) # Footer material. out('<hr />\n') if self._show_private: out(self.PRIVATE_LINK+'\n') self.write_footer(out, short=True) def write_module_toc(self, out, doc): """ Write an HTML page containing the table of contents page for the given module to the given streams. This page lists the modules, classes, exceptions, functions, and variables defined by the module. @param public: The output stream for the public version of the page. @param private: The output stream for the private version of the page. """ name = doc.canonical_name[-1] self.write_header(out, name) out('<h1 class="tocheading">Module %s</h1>\n' % name) out('<hr />\n') # List the classes. classes = doc.select_variables(value_type='class', imported=False, public=self._public_filter) self.write_toc_section(out, "Classes", classes, fullname=False) # List the functions. funcs = doc.select_variables(value_type='function', imported=False, public=self._public_filter) self.write_toc_section(out, "Functions", funcs, fullname=False) # List the variables. variables = doc.select_variables(value_type='other', imported=False, public=self._public_filter) self.write_toc_section(out, "Variables", variables, fullname=False) # Footer material. out('<hr />\n') if self._show_private: out(self.PRIVATE_LINK+'\n') self.write_footer(out, short=True) #//////////////////////////////////////////////////////////// #{ 2.7. Project homepage (index.html) #//////////////////////////////////////////////////////////// def write_homepage(self, directory): """ Write an C{index.html} file in the given directory. The contents of this file are copied or linked from an existing page, so this method must be called after all pages have been written. The page used is determined by L{_frames_index} and L{_top_page}: - If L{_frames_index} is true, then C{frames.html} is copied. - Otherwise, the page specified by L{_top_page} is copied. """ filename = os.path.join(directory, 'index.html') if self._frames_index: top = 'frames.html' else: top = self._top_page_url # Copy the non-frames index file from top, if it's internal. if top[:5] != 'http:' and '/' not in top: try: # Read top into `s`. topfile = os.path.join(directory, top) s = open(topfile, 'r').read() # Write the output file. open(filename, 'w').write(s) return except: log.error('Warning: error copying index; ' 'using a redirect page') # Use a redirect if top is external, or if we faild to copy. name = self._prj_name or 'this project' f = open(filename, 'w') self.write_redirect_index(f.write, top, name) f.close() write_redirect_index = compile_template( """ write_redirect_index(self, out, top, name) """, # /------------------------- Template -------------------------\ ''' <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title> Redirect </title> <meta http-equiv="refresh" content="1;url=$top$" /> <link rel="stylesheet" href="epydoc.css" type="text/css"></link> </head> <body> <p>Redirecting to the API documentation for <a href="$top$">$self._prj_name or "this project"$</a>...</p> </body> </html> ''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ 2.8. Stylesheet (epydoc.css) #//////////////////////////////////////////////////////////// def write_css(self, directory, cssname): """ Write the CSS stylesheet in the given directory. If C{cssname} contains a stylesheet file or name (from L{epydoc.docwriter.html_css}), then use that stylesheet; otherwise, use the default stylesheet. @rtype: C{None} """ filename = os.path.join(directory, 'epydoc.css') # Get the contents for the stylesheet file. if cssname is None: css = STYLESHEETS['default'][0] else: if os.path.exists(cssname): try: css = open(cssname).read() except: raise IOError("Can't open CSS file: %r" % cssname) elif STYLESHEETS.has_key(cssname): css = STYLESHEETS[cssname][0] else: raise IOError("Can't find CSS file: %r" % cssname) # Write the stylesheet. cssfile = open(filename, 'w') cssfile.write(css) cssfile.close() #//////////////////////////////////////////////////////////// #{ 2.9. Javascript (epydoc.js) #//////////////////////////////////////////////////////////// def write_javascript(self, directory): jsfile = open(os.path.join(directory, 'epydoc.js'), 'w') print >> jsfile, self.TOGGLE_PRIVATE_JS print >> jsfile, self.GET_COOKIE_JS print >> jsfile, self.SET_FRAME_JS print >> jsfile, self.HIDE_PRIVATE_JS print >> jsfile, self.TOGGLE_CALLGRAPH_JS print >> jsfile, html_colorize.PYSRC_JAVASCRIPTS jsfile.close() #: A javascript that is used to show or hide the API documentation #: for private objects. In order for this to work correctly, all #: documentation for private objects should be enclosed in #: C{<div class="private">...</div>} elements. TOGGLE_PRIVATE_JS = ''' function toggle_private() { // Search for any private/public links on this page. Store // their old text in "cmd," so we will know what action to // take; and change their text to the opposite action. var cmd = "?"; var elts = document.getElementsByTagName("a"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "privatelink") { cmd = elts[i].innerHTML; elts[i].innerHTML = ((cmd=="show private")?"hide private": "show private"); } } // Update all DIVs containing private objects. var elts = document.getElementsByTagName("div"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "private") { elts[i].style.display = ((cmd=="hide private")?"none":"block"); } } // Update all table rowss containing private objects. Note, we // use "" instead of "block" becaue IE & firefox disagree on what // this should be (block vs table-row), and "" just gives the // default for both browsers. var elts = document.getElementsByTagName("tr"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "private") { elts[i].style.display = ((cmd=="hide private")?"none":""); } } // Update all list items containing private objects. var elts = document.getElementsByTagName("li"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "private") { elts[i].style.display = ((cmd=="hide private")?"none":"list-item"); } } // Update all list items containing private objects. var elts = document.getElementsByTagName("ul"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "private") { elts[i].style.display = ((cmd=="hide private")?"none":"block"); } } // Set a cookie to remember the current option. document.cookie = "EpydocPrivate="+cmd; } '''.strip() #: A javascript that is used to read the value of a cookie. This #: is used to remember whether private variables should be shown or #: hidden. GET_COOKIE_JS = ''' function getCookie(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin != 0) return null; } else { begin += 2; } var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } return unescape(dc.substring(begin + prefix.length, end)); } '''.strip() #: A javascript that is used to set the contents of two frames at #: once. This is used by the project table-of-contents frame to #: set both the module table-of-contents frame and the main frame #: when the user clicks on a module. SET_FRAME_JS = ''' function setFrame(url1, url2) { parent.frames[1].location.href = url1; parent.frames[2].location.href = url2; } '''.strip() #: A javascript that is used to hide private variables, unless #: either: (a) the cookie says not to; or (b) we appear to be #: linking to a private variable. HIDE_PRIVATE_JS = ''' function checkCookie() { var cmd=getCookie("EpydocPrivate"); if (cmd!="show private" && location.href.indexOf("#_") < 0) toggle_private(); } '''.strip() TOGGLE_CALLGRAPH_JS = ''' function toggleCallGraph(id) { var elt = document.getElementById(id); if (elt.style.display == "none") elt.style.display = "block"; else elt.style.display = "none"; } '''.strip() #//////////////////////////////////////////////////////////// #{ 2.10. Graphs #//////////////////////////////////////////////////////////// # [xx] use DotGraph.to_html?? def render_graph(self, graph, css='graph-without-title'): if graph is None: return '' graph.caption = graph.title = None image_url = '%s.gif' % graph.uid image_file = os.path.join(self._directory, image_url) return graph.to_html(image_file, image_url) def render_callgraph(self, callgraph): graph_html = self.render_graph(callgraph, css='graph-with-title') if graph_html == '': return '' return ('<div style="display:none" id="%s-div"><center>\n' '<table border="0" cellpadding="0" cellspacing="0">\n' ' <tr><td>%s</td></tr>\n' ' <tr><th>Call Graph</th></tr>\n' '</table><br />\n</center></div>\n' % (callgraph.uid, graph_html)) def callgraph_link(self, callgraph): if callgraph is None: return '' return ('<br /><span class="codelink"><a href="javascript: void(0);" ' 'onclick="toggleCallGraph(\'%s-div\');return false;">' 'call&nbsp;graph</a></span>&nbsp;' % callgraph.uid) #//////////////////////////////////////////////////////////// #{ 3.1. Page Header #//////////////////////////////////////////////////////////// write_header = compile_template( """ write_header(self, out, title) Generate HTML code for the standard page header, and write it to C{out}. C{title} is a string containing the page title. It should be appropriately escaped/encoded. """, # /------------------------- Template -------------------------\ ''' <?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>$title$</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> ''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ 3.2. Page Footer #//////////////////////////////////////////////////////////// write_footer = compile_template( """ write_footer(self, out, short=False) Generate HTML code for the standard page footer, and write it to C{out}. """, # /------------------------- Template -------------------------\ ''' >>> if not short: <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer">Generated by Epydoc $epydoc.__version__$ on $time.asctime()$</td> <td align="right" class="footer"> <a href="http://epydoc.sourceforge.net">http://epydoc.sf.net</a> </td> </tr> </table> >>> #endif <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie() // --> </script> </body> </html> ''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ 3.3. Navigation Bar #//////////////////////////////////////////////////////////// write_navbar = compile_template( """ write_navbar(self, out, context) Generate HTML code for the navigation bar, and write it to C{out}. The navigation bar typically looks like:: [ Home Trees Index Help Project ] @param context: A value indicating what page we're generating a navigation bar for. If we're generating an API documentation page for an object, then C{context} is a L{ValueDoc} containing the documentation for that object; otherwise, C{context} is a string name for the page. The following string names are recognized: C{'tree'}, C{'index'}, and C{'help'}. """, # /------------------------- Template -------------------------\ ''' <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> >>> if self._top_page_url not in ("trees.html", "indices.html", "help.html"): <!-- Home link --> >>> if (isinstance(context, ValueDoc) and >>> self._top_page_url == self.url(context.canonical_name)): <th bgcolor="#70b0f0" class="navselect" >&nbsp;&nbsp;&nbsp;Home&nbsp;&nbsp;&nbsp;</th> >>> else: <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="$self._top_page_url$">Home</a>&nbsp;&nbsp;&nbsp;</th> >>> #endif <!-- Tree link --> >>> if context == "trees": <th bgcolor="#70b0f0" class="navselect" >&nbsp;&nbsp;&nbsp;Trees&nbsp;&nbsp;&nbsp;</th> >>> else: <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="trees.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> >>> #endif <!-- Index link --> >>> if context == "indices": <th bgcolor="#70b0f0" class="navselect" >&nbsp;&nbsp;&nbsp;Index&nbsp;&nbsp;&nbsp;</th> >>> else: <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="indices.html">Index</a>&nbsp;&nbsp;&nbsp;</th> >>> #endif <!-- Help link --> >>> if context == "help": <th bgcolor="#70b0f0" class="navselect" >&nbsp;&nbsp;&nbsp;Help&nbsp;&nbsp;&nbsp;</th> >>> else: <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> >>> #endif >>> if self._prj_link: <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center"> <p class="nomargin"> $self._prj_link$ </p></th></tr></table></th> >>> else: <th class="navbar" width="100%"></th> >>> #endif </tr> </table> ''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ 3.4. Breadcrumbs #//////////////////////////////////////////////////////////// write_breadcrumbs = compile_template( """ write_breadcrumbs(self, out, context, context_url) Generate HTML for the breadcrumbs line, and write it to C{out}. The breadcrumbs line is an invisible table with a list of pointers to the current object's ancestors on the left; and the show/hide private selector and the frames/noframes selector on the right. @param context: The API documentation for the object whose breadcrumbs we should generate. @type context: L{ValueDoc} """, # /------------------------- Template -------------------------\ ''' <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> >>> if isinstance(context, APIDoc): <td width="100%"> <span class="breadcrumbs"> >>> crumbs = self.breadcrumbs(context) >>> for crumb in crumbs[:-1]: $crumb$ :: >>> #endfor $crumbs[-1]$ </span> </td> >>> else: <td width="100%">&nbsp;</td> >>> #endif <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> >>> if self._show_private: <tr><td align="right">$self.PRIVATE_LINK$</td></tr> >>> #endif <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="$context_url$" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> ''') # \------------------------------------------------------------/ def breadcrumbs(self, doc): crumbs = [self._crumb(doc)] # Generate the crumbs for uid's ancestors. while True: container = self.docindex.container(doc) if container is None: if doc.canonical_name is UNKNOWN: return ['??']+crumbs elif isinstance(doc, ModuleDoc): return ['Package&nbsp;%s' % ident for ident in doc.canonical_name[:-1]]+crumbs else: return list(doc.canonical_name)+crumbs else: label = self._crumb(container) name = container.canonical_name crumbs.insert(0, self.href(container, label)) # [xx] code=0?? doc = container def _crumb(self, doc): if (len(doc.canonical_name)==1 and doc.canonical_name[0].startswith('script-')): return 'Script&nbsp;%s' % doc.canonical_name[0][7:] return '%s&nbsp;%s' % (self.doc_kind(doc), doc.canonical_name[-1]) #//////////////////////////////////////////////////////////// #{ 3.5. Summary Tables #//////////////////////////////////////////////////////////// def write_summary_table(self, out, heading, doc, value_type): """ Generate HTML code for a summary table, and write it to C{out}. A summary table is a table that includes a one-row description for each variable (of a given type) in a module or class. @param heading: The heading for the summary table; typically, this indicates what kind of value the table describes (e.g., functions or classes). @param doc: A L{ValueDoc} object containing the API documentation for the module or class whose variables we should summarize. @param value_type: A string indicating what type of value should be listed in this summary table. This value is passed on to C{doc}'s C{select_variables()} method. """ # inh_var_groups is a dictionary used to hold "inheritance # pseudo-groups", which are created when inheritance is # 'grouped'. It maps each base to a list of vars inherited # from that base. grouped_inh_vars = {} # Divide all public variables of the given type into groups. groups = [(plaintext_to_html(group_name), doc.select_variables(group=group_name, imported=False, value_type=value_type, public=self._public_filter)) for group_name in doc.group_names()] # Discard any empty groups; and return if they're all empty. groups = [(g,vars) for (g,vars) in groups if vars] if not groups: return # Write a header self.write_table_header(out, "summary", heading) # Write a section for each group. for name, var_docs in groups: self.write_summary_group(out, doc, name, var_docs, grouped_inh_vars) # Write a section for each inheritance pseudo-group (used if # inheritance=='grouped') if grouped_inh_vars: for base in doc.mro(): if base in grouped_inh_vars: hdr = 'Inherited from %s' % self.href(base, context=doc) tr_class = '' if len([v for v in grouped_inh_vars[base] if v.is_public]) == 0: tr_class = ' class="private"' self.write_group_header(out, hdr, tr_class) for var_doc in grouped_inh_vars[base]: self.write_summary_line(out, var_doc, doc) # Write a footer for the table. out(self.TABLE_FOOTER) out('\n<br />\n') def write_summary_group(self, out, doc, name, var_docs, grouped_inh_vars): # Split up the var_docs list, according to the way each var # should be displayed: # - listed_inh_vars -- for listed inherited variables. # - grouped_inh_vars -- for grouped inherited variables. # - normal_vars -- for all other variables. listed_inh_vars = {} normal_vars = [] for var_doc in var_docs: if var_doc.container != doc: base = var_doc.container if (base not in self.class_set or self._inheritance == 'listed'): listed_inh_vars.setdefault(base,[]).append(var_doc) elif self._inheritance == 'grouped': grouped_inh_vars.setdefault(base,[]).append(var_doc) else: normal_vars.append(var_doc) else: normal_vars.append(var_doc) # Write a header for the group. if name != '': tr_class = '' if len([v for v in var_docs if v.is_public]) == 0: tr_class = ' class="private"' self.write_group_header(out, name, tr_class) # Write a line for each normal var: for var_doc in normal_vars: self.write_summary_line(out, var_doc, doc) # Write a subsection for inherited vars: if listed_inh_vars: self.write_inheritance_list(out, doc, listed_inh_vars) def write_inheritance_list(self, out, doc, listed_inh_vars): out(' <tr>\n <td colspan="2">\n') for base in doc.mro(): if base not in listed_inh_vars: continue public_vars = [v for v in listed_inh_vars[base] if v.is_public] private_vars = [v for v in listed_inh_vars[base] if not v.is_public] if public_vars: out(' <p class="varlist">' '<span class="varlist-header">Inherited ' 'from <code>%s</code></span>:\n' % self.href(base, context=doc)) self.write_var_list(out, public_vars) out(' </p>\n') if private_vars and self._show_private: out(' <div class="private">') out(' <p class="varlist">' '<span class="varlist-header">Inherited ' 'from <code>%s</code></span> (private):\n' % self.href(base, context=doc)) self.write_var_list(out, private_vars) out(' </p></div>\n') out(' </td>\n </tr>\n') def write_var_list(self, out, vardocs): out(' ') out(',\n '.join(['<code>%s</code>' % self.href(v,v.name) for v in vardocs])+'\n') def write_summary_line(self, out, var_doc, container): """ Generate HTML code for a single line of a summary table, and write it to C{out}. See L{write_summary_table} for more information. @param var_doc: The API documentation for the variable that should be described by this line of the summary table. @param container: The API documentation for the class or module whose summary table we're writing. """ # If it's a private variable, then mark its <tr>. if var_doc.is_public: tr_class = '' else: tr_class = ' class="private"' # Convert the summary to HTML. summary = self.summary(var_doc, indent=6) # If it's inherited, then add a note to the summary. if var_doc.container != container and self._inheritance=="included": summary += ("\n <em>(Inherited from " + self.href(var_doc.container) + ")</em>") if isinstance(var_doc.value, RoutineDoc): if summary: summary = '<br />'+summary self.write_function_summary_line(out, var_doc, tr_class, summary) else: # This is used for nested classes, properties, & variables self.write_variable_summary_line(out, var_doc, tr_class, summary) write_function_summary_line = compile_template( """ write_function_summary_line(self, out, var_doc, tr_class, summary) Generate HTML code for a single line of a summary table, describing a variable whose value is a function, and write it to C{out}. @param var_doc: The API documentation for the variable that should be described by this line of the summary table. @param container: The API documentation for the class or module whose summary table we're writing. """, # /------------------------- Template -------------------------\ ''' <tr$tr_class$> <td width="15%" align="right" valign="top" class="rtype"> $self.rtype(var_doc, indent=6) or "&nbsp;"$ </td> <td> $self.function_signature(var_doc, link_name=True)$ $summary$ </td> </tr> ''') # \------------------------------------------------------------/ write_variable_summary_line = compile_template( ''' write_variable_summary_line(self, out, var_doc, tr_class, summary) ''', # /------------------------- Template -------------------------\ ''' <tr$tr_class$> <td width="15%"> <strong>$self.href(var_doc)$</strong></td> <td>$summary or "&nbsp;"$</td> </tr> ''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ 3.6. Details Lists #//////////////////////////////////////////////////////////// def write_details_list(self, out, heading, doc, value_type): # Get a list of the VarDocs we should describe. if isinstance(doc, ClassDoc): var_docs = doc.select_variables(value_type=value_type, imported=False, inherited=False, public=self._public_filter) else: var_docs = doc.select_variables(value_type=value_type, imported=False, public=self._public_filter) if not var_docs: return # Write a header self.write_table_header(out, "details", heading) out(self.TABLE_FOOTER) for var_doc in var_docs: self.write_details_entry(out, var_doc) out('<br />\n') def write_details_entry(self, out, var_doc): descr = self.descr(var_doc, indent=2) if var_doc.is_public: div_class = '' else: div_class = ' class="private"' # Functions if isinstance(var_doc.value, RoutineDoc): rtype = self.rtype(var_doc, indent=10) rdescr = self.return_descr(var_doc, indent=10) arg_descrs = [] # [xx] if we have a @type but no @param, this won't list it! # [xx] put them in the right order?? for (arg_names, arg_descr) in var_doc.value.arg_descrs: lhs = ', '.join([self.arg_name_to_html(var_doc.value, n) for n in arg_names]) rhs = self.docstring_to_html(arg_descr, var_doc.value, 10) arg_descrs.append( (lhs, rhs) ) # Perpare the call-graph, if requested if 'callgraph' in self._graph_types: linker = _HTMLDocstringLinker(self, var_doc.value) callgraph = call_graph([var_doc.value], self.docindex, linker, var_doc, add_callers=True, add_callees=True) if callgraph is not None and len(callgraph.nodes) == 0: callgraph = None else: callgraph = None self.write_function_details_entry(out, var_doc, descr, callgraph, rtype, rdescr, arg_descrs, div_class) # Properties elif isinstance(var_doc.value, PropertyDoc): prop_doc = var_doc.value accessors = [(name, self.property_accessor_to_html(val_doc), self.summary(val_doc)) for (name, val_doc) in [('Get', prop_doc.fget), ('Set', prop_doc.fset), ('Delete', prop_doc.fdel)]] self.write_property_details_entry(out, var_doc, descr, accessors, div_class) # Variables else: self.write_variable_details_entry(out, var_doc, descr, div_class) def labelled_list_item(self, lhs, rhs): # If the RHS starts with a paragraph, then move the # paragraph-start tag to the beginning of the lhs instead (so # there won't be a line break after the '-'). m = re.match(r'^<p( [^>]+)?>', rhs) if m: lhs = m.group() + lhs rhs = rhs[m.end():] return '<li>%s - %s</li>' % (lhs, rhs) def property_accessor_to_html(self, val_doc): if val_doc not in (None, UNKNOWN): if isinstance(val_doc, RoutineDoc): return self.function_signature(val_doc, css_class= "summary-sig") elif isinstance(val_doc, GenericValueDoc): if val_doc.parse_repr is not UNKNOWN: return plaintext_to_html(val_doc.parse_repr) else: pyval_repr = val_doc.pyval_repr() if pyval_repr is not UNKNOWN: return plaintext_to_html(pyval_repr) else: return self.href(val_doc) else: return self.href(val_doc) else: return '??' def arg_name_to_html(self, func_doc, arg_name): """ A helper function used to format an argument name, for use in the argument description list under a routine's details entry. This just wraps strong & code tags around the arg name; and if the arg name is associated with a type, then adds it parenthetically after the name. """ s = '<strong class="pname"><code>%s</code></strong>' % arg_name if arg_name in func_doc.arg_types: typ = func_doc.arg_types[arg_name] typ_html = self.docstring_to_html(typ, func_doc, 10) s += " (<code>%s</code>)" % typ_html return s write_function_details_entry = compile_template( ''' write_function_details_entry(self, out, var_doc, descr, callgraph, \ rtype, rdescr, arg_descrs, div_class) ''', # /------------------------- Template -------------------------\ ''' >>> func_doc = var_doc.value <a name="$var_doc.name$"></a> <div$div_class$> <table width="100%" class="func-details" bgcolor="#e0e0e0"><tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3>$self.function_signature(var_doc)$ >>> if var_doc.name in self.SPECIAL_METHODS: <br /><em class="fname">($self.SPECIAL_METHODS[var_doc.name]$)</em> >>> #endif </h3> </td><td align="right" valign="top" >$self.pysrc_link(func_doc)$&nbsp;</span >$self.callgraph_link(callgraph)$</td> </table> $self.render_callgraph(callgraph)$ $descr$ <dl><dt></dt><dd> >>> # === parameters === >>> if arg_descrs: <dl><dt>Parameters:</dt></dl> <ul> >>> for lhs, rhs in arg_descrs: $self.labelled_list_item(lhs, rhs)$ >>> #endfor </ul> >>> #endif >>> # === return type === >>> if rdescr and rtype: <dl><dt>Returns: <code>$rtype$</code></dt> <dd>$rdescr$</dd></dl> >>> elif rdescr: <dl><dt>Returns:</dt> <dd>$rdescr$</dd></dl> >>> elif rtype: <dl><dt>Returns: <code>$rtype$</code></dt></dl> >>> #endif >>> # === exceptions === >>> if func_doc.exception_descrs not in (None, UNKNOWN, (), []): <dl><dt>Raises:</dt></dl> <ul> >>> for name, descr in func_doc.exception_descrs: $self.labelled_list_item( "<code><strong class=\'fraise\'>" + self.href(name) + "</strong></code>", self.docstring_to_html(descr, func_doc, 8))$ >>> #endfor </ul> >>> #endif >>> # === overrides === >>> if var_doc.overrides not in (None, UNKNOWN): <dl><dt>Overrides: $self.href(var_doc.overrides.value, context=var_doc)$ >>> if (func_doc.docstring in (None, UNKNOWN) and >>> var_doc.overrides.value.docstring not in (None, UNKNOWN)): <dd><em class="note">(inherited documentation)</em></dd> >>> #endif </dt></dl> >>> #endif >>> # === metadata === >>> self.write_standard_fields(out, func_doc) </dd></dl> </td></tr></table> </div> ''') # \------------------------------------------------------------/ # Names for the __special__ methods. SPECIAL_METHODS ={ '__init__': 'Constructor', '__del__': 'Destructor', '__add__': 'Addition operator', '__sub__': 'Subtraction operator', '__and__': 'And operator', '__or__': 'Or operator', '__repr__': 'Representation operator', '__call__': 'Call operator', '__getattr__': 'Qualification operator', '__getitem__': 'Indexing operator', '__setitem__': 'Index assignment operator', '__delitem__': 'Index deletion operator', '__delslice__': 'Slice deletion operator', '__setslice__': 'Slice assignment operator', '__getslice__': 'Slicling operator', '__len__': 'Length operator', '__cmp__': 'Comparison operator', '__eq__': 'Equality operator', '__in__': 'Containership operator', '__gt__': 'Greater-than operator', '__lt__': 'Less-than operator', '__ge__': 'Greater-than-or-equals operator', '__le__': 'Less-than-or-equals operator', '__radd__': 'Right-side addition operator', '__hash__': 'Hashing function', '__contains__': 'In operator', '__nonzero__': 'Boolean test operator', '__str__': 'Informal representation operator', } write_property_details_entry = compile_template( ''' write_property_details_entry(self, out, var_doc, descr, \ accessors, div_class) ''', # /------------------------- Template -------------------------\ ''' >>> prop_doc = var_doc.value <a name="$var_doc.name$"></a> <div$div_class$> <table width="100%" class="prop-details" bgcolor="#e0e0e0"><tr><td> <h3>$var_doc.name$</h3> $descr$ <dl><dt></dt><dd> >>> if prop_doc.type_descr not in (None, UNKNOWN): <dl><dt>Type:</dt> <dd>$self.type_descr(var_doc, indent=6)$</dd></dl> >>> #endif >>> for (name, val, summary) in accessors: <dt>$name$ Method:</dt> <dd>$val$ >>> if summary: - $summary$ >>> #endif </dd> >>> #endfor </dd></dl> </td></tr></table> </div> ''') # \------------------------------------------------------------/ write_variable_details_entry = compile_template( ''' write_variable_details_entry(self, out, var_doc, descr, div_class) ''', # /------------------------- Template -------------------------\ ''' <a name="$var_doc.name$"></a> <div$div_class$> <table width="100%" class="var-details" bgcolor="#e0e0e0"><tr><td> <h3>$var_doc.name$</h3> $descr$ <dl><dt></dt><dd> >>> if var_doc.type_descr not in (None, UNKNOWN): <dl><dt>Type:</dt> <dd>$self.type_descr(var_doc, indent=6)$</dd></dl> >>> #endif >>> tooltip = self.variable_tooltip(var_doc) >>> if var_doc.value is not UNKNOWN: <dl$tooltip$><dt>Value:</dt> <dd><table><tr><td><pre class="variable"> $self.pprint_value(var_doc.value)$ </pre></td></tr></table></dd> </dl> >>> #endif </dd></dl> </td></tr></table> </div> ''') # \------------------------------------------------------------/ _variable_linelen = 70 _variable_maxlines = 3 _variable_tooltip_linelen = 70 def variable_tooltip(self, var_doc): if var_doc.value in (None, UNKNOWN): return '' else: pyval_repr = var_doc.value.pyval_repr() if pyval_repr is not UNKNOWN: s = pyval_repr elif var_doc.value.parse_repr is not UNKNOWN: s = var_doc.value.parse_repr else: return '' if len(s) > self._variable_tooltip_linelen: s = s[:self._variable_tooltip_linelen-3]+'...' return ' title="%s"' % plaintext_to_html(s) def pprint_value(self, val_doc, multiline=True, summary_linelen=0): if val_doc.pyval is not UNKNOWN: return self.pprint_pyval(val_doc.pyval, multiline, summary_linelen) elif val_doc.parse_repr is not UNKNOWN: s = plaintext_to_html(val_doc.parse_repr) return self._linewrap_html(s, self._variable_linelen, self._variable_maxlines) else: return self.href(val_doc) def pprint_pyval(self, pyval, multiline=True, summary_linelen=0): # Handle the most common cases first. The following types # will never need any line wrapping, etc; and they cover most # variable values (esp int, for constants). I leave out # LongType on purpose, since long values may need line- # wrapping. if (type(pyval) is types.IntType or type(pyval) is types.FloatType or type(pyval) is types.NoneType or type(pyval) is types.ComplexType): # none of these should contain '&', '<' or '>'. vstr = repr(pyval) return vstr + '&nbsp;' * (self._variable_linelen-len(vstr)) # For strings, use repr. Use tripple-quoted-strings where # appropriate. elif type(pyval) is types.StringType: vstr = repr(pyval) if vstr.find(r'\n') >= 0 and multiline: body = vstr[1:-1].replace(r'\n', '\n') vstr = ('<span class="variable-quote">'+vstr[0]*3+'</span>'+ plaintext_to_html(body) + '<span class="variable-quote">'+vstr[0]*3+'</span>') else: vstr = ('<span class="variable-quote">'+vstr[0]+'</span>'+ plaintext_to_html(vstr[1:-1])+ '<span class="variable-quote">'+vstr[0]+'</span>') # For lists, tuples, and dicts, use pprint. When possible, # restrict the amount of stuff that pprint needs to look at, # since pprint is surprisingly slow. elif type(pyval) is types.TupleType or type(pyval) is types.ListType: try: vstr = repr(pyval) except: vstr = '...' if multiline and len(vstr) > self._variable_linelen: vstr = pprint.pformat(pyval[:self._variable_maxlines+1]) vstr = plaintext_to_html(vstr) elif type(pyval) is type({}): try: vstr = repr(pyval) except: vstr = '...' if multiline and len(vstr) > self._variable_linelen: if len(pyval) < self._variable_maxlines+50: vstr = pprint.pformat(pyval) else: shortval = {} for (k,v) in pyval.items()[:self._variable_maxlines+1]: shortval[k]=v vstr = pprint.pformat(shortval) vstr = plaintext_to_html(vstr) # For regexps, use colorize_re. elif type(pyval).__name__ == 'SRE_Pattern': try: vstr = colorize_re(pyval) except TypeError, sre_constants.error: try: vstr = plaintext_to_html(repr(pyval)) except: vstr = '...' # For other objects, use repr to generate a representation. else: try: vstr = plaintext_to_html(repr(pyval)) except: vstr = '...' # For the summary table, just return the value; don't # bother to word-wrap. if not multiline: vstr = vstr.replace('\n', '') # Change spaces to &nbsp; (except spaces in html tags) vstr = vstr.replace(' ', '&nbsp;') vstr = vstr.replace('<span&nbsp;', '<span ') vstr = self._linewrap_html(vstr, summary_linelen, 1) return '<code>%s</code>\n' % vstr # Do line-wrapping. return self._linewrap_html(vstr, self._variable_linelen, self._variable_maxlines) def _linewrap_html(self, s, linelen, maxlines): """ Add line-wrapping to the HTML string C{s}. Line length is determined by C{linelen}; and the maximum number of lines to display is determined by C{maxlines}. This function treats HTML entities (e.g., C{&amp;}) as single characters; and ignores HTML tags (e.g., C{<p>}). """ LINEWRAP_MARKER = r'<span class="variable-linewrap">\</span>' ELLIPSIS_MARKER = r'<span class="variable-ellipsis">...</span>' open_elements = [] # tag stack lines = [] start = end = cnum = 0 while len(lines) <= maxlines and end < len(s): # Skip over HTML tags. if s[end] == '<': newend = s.find('>', end) tag = s[end+1:newend] if tag[-1]!="/": # non-empty tag tagname = tag.split(None,1)[0] if tagname[0] == "/": open_elements.pop() else: open_elements.append(tagname) end = newend cnum -= 1 # HTML entities just count as 1 char. elif s[end] == '&': end = s.find(';', end) # Go on to the next character. cnum += 1 end += 1 # Check for end-of-line. if s[end-1] == '\n': lines.append(s[start:end-1]) cnum = 0 start = end # Check for line-wrap if cnum == linelen and end<len(s) and s[end] != '\n': if maxlines == 1: closing_tags = "" for tag in open_elements: closing_tags += "</%s>" % (tag,) return s[start:end]+closing_tags+ELLIPSIS_MARKER lines.append(s[start:end]+LINEWRAP_MARKER) cnum = 0 start = end # Add on anything that's left. if end == len(s): lines.append(s[start:end]) # Use the ellipsis marker if the string is too long. if len(lines) > maxlines: closing_tags = "" for tag in open_elements: closing_tags += "</%s>" % (tag,) lines[-1] = closing_tags+ELLIPSIS_MARKER cnum = 3 # Pad the last line to linelen. lines[-1] += ' '*(linelen-cnum+1) return ('\n').join(lines) #//////////////////////////////////////////////////////////// #{ Base Tree #//////////////////////////////////////////////////////////// def base_tree(self, doc, width=None, postfix='', context=None): """ @return: The HTML code for a class's base tree. The tree is drawn 'upside-down' and right justified, to allow for multiple inheritance. @rtype: C{string} """ if context is None: context = doc if width == None: width = self.find_tree_width(doc, context) if isinstance(doc, ClassDoc) and doc.bases != UNKNOWN: bases = doc.bases else: bases = [] if postfix == '': # [XX] use var name instead of canonical name? s = (' '*(width-2) + '<strong class="uidshort">'+ self.contextual_label(doc, context)+'</strong>\n') else: s = '' for i in range(len(bases)-1, -1, -1): base = bases[i] label = self.contextual_label(base, context) s = (' '*(width-4-len(label)) + self.href(base, label) +' --+'+postfix+'\n' + ' '*(width-4) + ' |'+postfix+'\n' + s) if i != 0: s = (self.base_tree(base, width-4, ' |'+postfix)+s) else: s = (self.base_tree(base, width-4, ' '+postfix)+s) return s def find_tree_width(self, doc, context): """ Helper function for L{base_tree}. @return: The width of a base tree, when drawn right-justified. This is used by L{base_tree} to determine how far to indent lines of the base tree. @rtype: C{int} """ if not isinstance(doc, ClassDoc): return 2 if doc.bases == UNKNOWN: return 2 width = 2 for base in doc.bases: width = max(width, len(self.contextual_label(base, context))+4, self.find_tree_width(base, context)+4) return width def contextual_label(self, doc, context): """ Return the label for L{doc} to be shown in C{context}. """ context = context.canonical_name if context is not UNKNOWN: context = context.container() return str(doc.canonical_name.contextualize(context)) #//////////////////////////////////////////////////////////// #{ Function Signatures #//////////////////////////////////////////////////////////// def function_signature(self, api_doc, css_class='sig', link_name=False): # [XX] clean this up! if isinstance(api_doc, VariableDoc): func_doc = api_doc.value # This should never happen, but just in case: if api_doc.value in (None, UNKNOWN): return (('<span class="%s"><span class="%s-name">%s'+ '</span>(...)</span>') % (css_class, css_class, api_doc.name)) # Get the function's name. if link_name: name = self.href(api_doc, css_class=css_class+'-name') else: name = ('<span class="%s-name">%s</span>' % (css_class, api_doc.name)) else: func_doc = api_doc name = self.href(api_doc, css_class=css_class+'-name') if func_doc.posargs == UNKNOWN: args = ['...'] else: args = [self.func_arg(n, d, css_class) for (n, d) in zip(func_doc.posargs, func_doc.posarg_defaults)] if func_doc.vararg: if func_doc.vararg == '...': args.append('<span class="%s-arg">...</span>' % css_class) else: args.append('<span class="%s-arg">*%s</span>' % (css_class, func_doc.vararg)) if func_doc.kwarg: args.append('<span class="%s-arg">**%s</span>' % (css_class, func_doc.kwarg)) return ('<span class="%s">%s(%s)</span>' % (css_class, name, ',\n '.join(args))) # [xx] tuple args??? def func_arg(self, name, default, css_class): name = self._arg_name(name) s = '<span class="%s-arg">%s</span>' % (css_class, name) if default is not None: if default.parse_repr is not UNKNOWN: s += ('=<span class="%s-default">%s</span>' % (css_class, plaintext_to_html(default.parse_repr))) else: pyval_repr = default.pyval_repr() if pyval_repr is not UNKNOWN: s += ('=<span class="%s-default">%s</span>' % (css_class, plaintext_to_html(pyval_repr))) else: s += '=<span class="%s-default">??</span>' % css_class return s def _arg_name(self, arg): if isinstance(arg, basestring): return arg elif len(arg) == 1: return '(%s,)' % self._arg_name(arg[0]) else: return '(%s)' % (', '.join([self._arg_name(a) for a in arg])) #//////////////////////////////////////////////////////////// #{ Import Lists #//////////////////////////////////////////////////////////// def write_imports(self, out, doc): assert isinstance(doc, NamespaceDoc) imports = doc.select_variables(imported=True, public=self._public_filter) if not imports: return out('<p class="imports">') out('<span class="varlist-header">Imports:</span>\n ') out(',\n '.join([self._import(v, doc) for v in imports])) out('\n</p>\n') def _import(self, var_doc, context): if var_doc.imported_from not in (None, UNKNOWN): return self.href(var_doc.imported_from, context=context) elif (var_doc.value not in (None, UNKNOWN) and not isinstance(var_doc.value, GenericValueDoc)): return self.href(var_doc.value, context=context) else: return plaintext_to_html(var_doc.name) #//////////////////////////////////////////////////////////// #{ Function Attributes #//////////////////////////////////////////////////////////// #//////////////////////////////////////////////////////////// #{ Module Trees #//////////////////////////////////////////////////////////// def write_module_tree(self, out): if not self.module_list: return # Write entries for all top-level modules/packages. out('<ul>\n') for doc in self.module_list: if (doc.package in (None, UNKNOWN) or doc.package not in self.module_set): self.write_module_tree_item(out, doc) out('</ul>\n') def write_module_list(self, out, doc): if len(doc.submodules) == 0: return self.write_table_header(out, "details", "Submodules") for group_name in doc.group_names(): if not doc.submodule_groups[group_name]: continue if group_name: self.write_group_header(out, group_name) out(' <tr><td><ul>\n') for submodule in doc.submodule_groups[group_name]: self.write_module_tree_item(out, submodule, package=doc) out(' </ul></td></tr>\n') out(self.TABLE_FOOTER+'\n<br />\n') def write_module_tree_item(self, out, doc, package=None): # If it's a private variable, then mark its <li>. var = package and package.variables.get(doc.canonical_name[-1]) if var is not None: priv = var.is_public is False else: priv = doc.canonical_name[-1].startswith('_') out(' <li%s> <strong class="uidlink">%s</strong>' % (priv and ' class="private"' or '', self.href(doc))) if doc.summary not in (None, UNKNOWN): out(': <em class="summary">'+ self.description(doc.summary, doc, 8)+'</em>') out('</li>\n') if doc.submodules != UNKNOWN and doc.submodules: out(' <ul%s>\n' % (priv and ' class="private"' or '')) for submodule in doc.submodules: self.write_module_tree_item(out, submodule, package=doc) out(' </ul>\n </li>\n') #//////////////////////////////////////////////////////////// #{ Class trees #//////////////////////////////////////////////////////////// def write_class_tree(self, out): """ Write HTML code for a nested list showing the base/subclass relationships between all documented classes. Each element of the top-level list is a class with no (documented) bases; and under each class is listed all of its subclasses. Note that in the case of multiple inheritance, a class may appear multiple times. This is used by L{write_trees} to write the class hierarchy. @todo: For multiple inheritance, don't repeat subclasses the second time a class is mentioned; instead, link to the first mention. """ # [XX] backref for multiple inheritance? if not self.class_list: return # Build a set containing all classes that we should list. # This includes everything in class_list, plus any of those # class' bases, but not undocumented subclasses. class_set = self.class_set.copy() for doc in self.class_list: if doc.bases != UNKNOWN: for base in doc.bases: if base not in class_set: if isinstance(base, ClassDoc): class_set.update(base.mro()) else: # [XX] need to deal with this -- how? pass #class_set.add(base) out('<ul>\n') for doc in sorted(class_set): if doc.bases != UNKNOWN and len(doc.bases)==0: self.write_class_tree_item(out, doc, class_set) out('</ul>\n') write_class_tree_item = compile_template( ''' write_class_tree_item(self, out, doc, class_set) ''', # /------------------------- Template -------------------------\ ''' >>> if doc.summary in (None, UNKNOWN): <li> <strong class="uidlink">$self.href(doc)$</strong> >>> else: <li> <strong class="uidlink">$self.href(doc)$</strong>: <em class="summary">$self.description(doc.summary, doc, 8)$</em> >>> # endif >>> if doc.subclasses: <ul> >>> for subclass in set(doc.subclasses): >>> if subclass in class_set: >>> self.write_class_tree_item(out, subclass, class_set) >>> #endif >>> #endfor </ul> >>> #endif </li> ''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ Standard Fields #//////////////////////////////////////////////////////////// def write_standard_fields(self, out, doc): """ Write HTML code containing descriptions of any standard markup fields that are defined by the given L{APIDoc} object (such as C{@author} and C{@todo} fields). @param doc: The L{APIDoc} object containing the API documentation for the object whose standard markup fields should be described. """ fields = [] field_values = {} #if _sort_fields: fields = STANDARD_FIELD_NAMES [XX] for (field, arg, descr) in doc.metadata: if field not in field_values: fields.append(field) if field.takes_arg: subfields = field_values.setdefault(field,{}) subfields.setdefault(arg,[]).append(descr) else: field_values.setdefault(field,[]).append(descr) for field in fields: if field.takes_arg: for arg, descrs in field_values[field].items(): self.write_standard_field(out, doc, field, descrs, arg) else: self.write_standard_field(out, doc, field, field_values[field]) write_standard_field = compile_template( """ write_standard_field(self, out, doc, field, descrs, arg='') """, # /------------------------- Template -------------------------\ """ >>> if arg: arglabel = ' (%s)' % arg >>> else: arglabel = '' >>> if len(descrs) == 1: <p><strong>$field.singular+arglabel$:</strong> $self.description(descrs[0], doc, 8)$ </p> >>> elif field.short: <dl><dt>$field.plural+arglabel$:</dt> <dd> >>> for descr in descrs[:-1]: $self.description(descr, doc, 10)$, >>> # end for $self.description(descrs[-1], doc, 10)$ </dd> </dl> >>> else: <p><strong>$field.plural+arglabel$:</strong> <ul> >>> for descr in descrs: <li> $self.description(descr, doc, 8)$ </li> >>> # end for </ul> >>> # end else >>> # end for """) # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ Term index generation #//////////////////////////////////////////////////////////// def _get_index_terms(self, parsed_docstring, link, terms, links): """ A helper function for L{_extract_term_index}. For each index term M{t} with key M{k} in C{parsed_docstring}, modify C{terms} and C{links} as follows: - Set C{terms[M{k}] = t} (if C{terms[M{k}]} doesn't exist). - Append C{link} to C{links[M{k}]}. """ if parsed_docstring in (None, UNKNOWN): return for term in parsed_docstring.index_terms(): key = self._term_index_to_anchor(term) if not terms.has_key(key): terms[key] = term links[key] = [] links[key].append(link) def _term_index_to_anchor(self, term): """ Given the name of an inline index item, construct a URI anchor. These anchors are used to create links from the index page to each index item. """ # Include "-" so we don't accidentally collide with the name # of a python identifier. s = re.sub(r'\s\s+', '-', term.to_plaintext(None)) return "index-"+re.sub("[^a-zA-Z0-9]", "_", s) def _extract_term_index(self): """ Extract the set of terms that should be indexed from all documented docstrings. Return the extracted set as a list of tuples of the form C{(key, term, [links])}. This list is used by L{write_indices()} to construct the term index. @rtype: C{list} of C{(string, ParsedDocstring, list of ValueDoc)} """ terms = {} links = {} for doc in self.valdocs: self._get_index_terms(doc.descr, doc, terms, links) if doc.metadata not in (None, UNKNOWN): for (field, arg, descr) in doc.metadata: self._get_index_terms(descr, doc, terms, links) # [xx] summary? type_descr? others? if isinstance(doc, NamespaceDoc): for var in doc.variables.values(): self._get_index_terms(var.descr, var, terms, links) for (field, arg, descr) in var.metadata: self._get_index_terms(descr, var, terms, links) elif isinstance(doc, RoutineDoc): self._get_index_terms(doc.return_descr, doc, terms, links) self._get_index_terms(doc.return_type, doc, terms, links) if doc.arg_descrs not in (None, UNKNOWN): for arg, descr in doc.arg_descrs: self._get_index_terms(descr, doc, terms, links) if doc.arg_types not in (None, UNKNOWN): for arg, descr in doc.arg_types.items(): self._get_index_terms(descr, doc, terms, links) if doc.exception_descrs not in (None, UNKNOWN): for excname, descr in doc.exception_descrs: self._get_index_terms(descr, doc, terms, links) elif isinstance(doc, PropertyDoc): self._get_index_terms(doc.type_descr, doc, terms, links) # Combine terms & links into one list keys = terms.keys() keys.sort() return [(k, terms[k], links[k]) for k in keys] #//////////////////////////////////////////////////////////// #{ Helper functions #//////////////////////////////////////////////////////////// # [XX] Is it worth-while to pull the anchor tricks that I do here? # Or should I just live with the fact that show/hide private moves # stuff around? write_table_header = compile_template( ''' write_table_header(self, out, css_class, heading=None, \ private_link=True) ''', # /------------------------- Template -------------------------\ ''' >>> if heading is not None: >>> anchor = "section-%s" % re.sub("\W", "", heading) <!-- ==================== $heading.upper()$ ==================== --> <a name="$anchor$"></a> >>> #endif <table class="$css_class$" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> >>> if heading is not None: <tr bgcolor="#70b0f0" class="$css_class$"> >>> if private_link: <td colspan="2"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <th align="left" class="$css_class$">$heading$</th> <td align="right" valign="top" ><span class="options">[<a href="#$anchor$" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> >>> else: <th align="left" colspan="2" class="$css_class$">$heading$</th> >>> #endif </tr> >>> #endif ''') # \------------------------------------------------------------/ TABLE_FOOTER = '</table>\n' PRIVATE_LINK = ''' <span class="options">[<a href="javascript: void(0);" class="privatelink" onclick="toggle_private();">hide private</a>]</span> '''.strip() write_group_header = compile_template( ''' write_group_header(self, out, group, tr_class='') ''', # /------------------------- Template -------------------------\ ''' <tr bgcolor="#e8f0f8" $tr_class$> <th colspan="2" class="group" >&nbsp;&nbsp;&nbsp;&nbsp;$group$</th></tr> ''') # \------------------------------------------------------------/ def url(self, obj): """ Return the URL for the given object, which can be a C{VariableDoc}, a C{ValueDoc}, or a C{DottedName}. """ # Module: <canonical_name>-module.html if isinstance(obj, ModuleDoc): if obj not in self.module_set: return None return urllib.quote('%s'%obj.canonical_name) + '-module.html' # Class: <canonical_name>-class.html elif isinstance(obj, ClassDoc): if obj not in self.class_set: return None return urllib.quote('%s'%obj.canonical_name) + '-class.html' # Variable elif isinstance(obj, VariableDoc): val_doc = obj.value if isinstance(val_doc, (ModuleDoc, ClassDoc)): return self.url(val_doc) elif obj.container in (None, UNKNOWN): if val_doc in (None, UNKNOWN): return None return self.url(val_doc) elif obj.is_imported == True: if obj.imported_from is not UNKNOWN: return self.url(obj.imported_from) else: return None else: container_url = self.url(obj.container) if container_url is None: return None return '%s#%s' % (container_url, urllib.quote('%s'%obj.name)) # Value (other than module or class) elif isinstance(obj, ValueDoc): container = self.docindex.container(obj) if container is None: return None # We couldn't find it! else: container_url = self.url(container) if container_url is None: return None anchor = urllib.quote('%s'%obj.canonical_name[-1]) return '%s#%s' % (container_url, anchor) # Dotted name: look up the corresponding APIDoc elif isinstance(obj, DottedName): val_doc = self.docindex.get_valdoc(obj) if val_doc is None: return None return self.url(val_doc) # Special pages: elif obj == 'indices': return 'indices.html' elif obj == 'help': return 'help.html' elif obj == 'trees': return 'trees.html' else: raise ValueError, "Don't know what to do with %r" % obj def pysrc_link(self, api_doc): if not self._incl_sourcecode: return '' url = self.pysrc_url(api_doc) if url is not None: return ('<span class="codelink"><a href="%s">source&nbsp;' 'code</a></span>' % url) else: return '' def pysrc_url(self, api_doc): if isinstance(api_doc, VariableDoc): if api_doc.value not in (None, UNKNOWN): return pysrc_link(api_doc.value) else: return None elif isinstance(api_doc, ModuleDoc): if api_doc in self.modules_with_sourcecode: return ('%s-pysrc.html' % urllib.quote('%s' % api_doc.canonical_name)) else: return None else: module = api_doc.defining_module if module == UNKNOWN: return None module_pysrc_url = self.pysrc_url(module) if module_pysrc_url is None: return None module_name = module.canonical_name if not module_name.dominates(api_doc.canonical_name, True): log.debug('%r is in %r but name does not dominate' % (api_doc, module)) return module_pysrc_url mname_len = len(module.canonical_name) anchor = '%s' % api_doc.canonical_name[mname_len:] return '%s#%s' % (module_pysrc_url, urllib.quote(anchor)) # We didn't find it: return None # [xx] add code to automatically do <code> wrapping or the like? def href(self, target, label=None, css_class=None, context=None): """ Return the HTML code for an HREF link to the given target (which can be a C{VariableDoc}, a C{ValueDoc}, or a C{DottedName}. If a C{NamespaceDoc} C{context} is specified, the target label is contextualized to it. """ assert isinstance(target, (APIDoc, DottedName)) # Pick a label, if none was given. if label is None: if isinstance(target, VariableDoc): label = target.name elif (isinstance(target, ValueDoc) and target.canonical_name is not UNKNOWN): label = target.canonical_name elif isinstance(target, DottedName): label = target else: raise ValueError("Unable to find a label for %r" % target) if context is not None and isinstance(label, DottedName): label = label.contextualize(context.canonical_name.container()) label = plaintext_to_html(str(label)) # Munge names for scripts & unreachable values if label.startswith('script-'): label = label[7:] + ' (script)' if label.startswith('??'): label = '<i>unreachable</i>' + label[2:] label = re.sub(r'-\d+$', '', label) # Get the url for the target. url = self.url(target) if url is None: return label # Construct a string for the class attribute. if css_class is None: css = '' else: css = ' class="%s"' % css_class return '<a href="%s"%s>%s</a>' % (url, css, label) def summary(self, api_doc, indent=0): assert isinstance(api_doc, APIDoc) if (isinstance(api_doc, VariableDoc) and api_doc.summary in (None, UNKNOWN)): if api_doc.value in (None, UNKNOWN): return '' api_doc = api_doc.value if api_doc.summary in (None, UNKNOWN): return '' return self.docstring_to_html(api_doc.summary, api_doc, indent) def descr(self, api_doc, indent=0): assert isinstance(api_doc, APIDoc) if (isinstance(api_doc, VariableDoc) and api_doc.descr in (None, UNKNOWN)): if api_doc.value in (None, UNKNOWN): return '' api_doc = api_doc.value if api_doc.descr in (None, UNKNOWN): return '' return self.docstring_to_html(api_doc.descr, api_doc, indent) def type_descr(self, api_doc, indent=0): assert isinstance(api_doc, APIDoc) if (isinstance(api_doc, VariableDoc) and api_doc.type_descr in (None, UNKNOWN)): if api_doc.value in (None, UNKNOWN): return '' api_doc = api_doc.value if api_doc.type_descr in (None, UNKNOWN): return '' return self.docstring_to_html(api_doc.type_descr, api_doc, indent) def rtype(self, api_doc, indent=0): if isinstance(api_doc, VariableDoc): if api_doc.value in (None, UNKNOWN): return '' api_doc = api_doc.value assert isinstance(api_doc, RoutineDoc) if api_doc.return_type in (None, UNKNOWN): return '' return self.docstring_to_html(api_doc.return_type, api_doc, indent) def return_descr(self, api_doc, indent=0): if isinstance(api_doc, VariableDoc): if api_doc.value in (None, UNKNOWN): return '' api_doc = api_doc.value assert isinstance(api_doc, RoutineDoc) if api_doc.return_descr in (None, UNKNOWN): return '' return self.docstring_to_html(api_doc.return_descr, api_doc, indent) def docstring_to_html(self, parsed_docstring, where=None, indent=0): if parsed_docstring in (None, UNKNOWN): return '' linker = _HTMLDocstringLinker(self, where) s = parsed_docstring.to_html(linker, indent=indent, directory=self._directory, docindex=self.docindex, context=where).strip() if self._mark_docstrings: s = '<span class="docstring">%s</span><!--end docstring-->' % s return s # [XX] Just use docstring_to_html??? def description(self, parsed_docstring, where=None, indent=0): assert isinstance(where, (APIDoc, type(None))) if parsed_docstring in (None, UNKNOWN): return '' linker = _HTMLDocstringLinker(self, where) descr = parsed_docstring.to_html(linker, indent=indent, directory=self._directory, docindex=self.docindex, context=where).strip() if descr == '': return '&nbsp;' return descr # [xx] Should this be defined by the APIDoc classes themselves?? def doc_kind(self, doc): if isinstance(doc, ModuleDoc) and doc.is_package == True: return 'Package' elif (isinstance(doc, ModuleDoc) and doc.canonical_name[0].startswith('script')): return 'Script' elif isinstance(doc, ModuleDoc): return 'Module' elif isinstance(doc, ClassDoc): return 'Class' elif isinstance(doc, ClassMethodDoc): return 'Class Method' elif isinstance(doc, StaticMethodDoc): return 'Static Method' elif isinstance(doc, RoutineDoc): if isinstance(self.docindex.container(doc), ClassDoc): return 'Method' else: return 'Function' else: return 'Variable' def _doc_or_ancestor_is_private(self, api_doc): name = api_doc.canonical_name for i in range(len(name), 0, -1): var_doc = self.docindex.get_vardoc(name[:i]) if var_doc is not None and var_doc.is_public == False: return True return False class _HTMLDocstringLinker(epydoc.markup.DocstringLinker): def __init__(self, htmlwriter, container): self.htmlwriter = htmlwriter self.docindex = htmlwriter.docindex self.container = container def translate_indexterm(self, indexterm): key = self.htmlwriter._term_index_to_anchor(indexterm) return ('<a name="%s"></a><i class="indexterm">%s</i>' % (key, indexterm.to_html(self))) def translate_identifier_xref(self, identifier, label=None): # Pick a label for this xref. if label is None: label = plaintext_to_html(identifier) # Find the APIDoc for it (if it's available). doc = self.docindex.find(identifier, self.container) # Translate it into HTML. if doc is None: return '<code class="link">%s</code>' % label else: return self.htmlwriter.href(doc, label, 'link') # [xx] Should this be added to the DocstringLinker interface??? def url_for(self, identifier): if isinstance(identifier, (basestring, DottedName)): doc = self.docindex.find(identifier, self.container) if doc: return self.htmlwriter.url(doc) else: # [xx] ignore if it's inside an import?? # Record that we failed to find it. failed_xrefs = self.htmlwriter._failed_xrefs context = self.container.canonical_name failed_xrefs.setdefault(identifier,{})[context] = 1 elif isinstance(identifier, APIDoc): return self.htmlwriter.url(identifier) doc = identifier else: raise TypeError('Expected string or APIDoc')
[ "simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9" ]
simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9
d38ad13d5b90a52d56ed6d9da5384a5f4df4d21f
746bf62ae3599f0d2dcd620ae37cd11370733cc3
/leetcode/spiralmatrixtwo.py
c0075822c99847054ebdbfc8e1a03cd68cd9c653
[]
no_license
wanglinjie/coding
ec0e614343b39dc02191455165eb1a5c9e6747ce
350f28cad5ec384df476f6403cb7a7db419de329
refs/heads/master
2021-04-22T14:00:48.825959
2017-05-02T12:49:05
2017-05-02T12:49:05
48,011,510
0
0
null
null
null
null
UTF-8
Python
false
false
2,106
py
#!/usr/bin/env python # -*- coding:utf-8 -*- # date:20160711 class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] """ if not n: return [] rows = n columns = n loop = 0 if n & 0x1: loop = n / 2 + 1 else: loop = n / 2 # 为什么使用下面创建数组,matrix[1][2]=1赋值,会将第2列的值都赋值为1? # matrix = [[0] * n] * n matrix = [] for i in xrange(n): matrix.append([0] * n) number = 1 for i in xrange(loop): row = i column = i read_num = 0 read_rows = rows - 2 * i read_columns = columns - 2 * i if (read_rows == 1) or (read_columns == 1): read_num = read_rows * read_columns else: read_num = 2 * read_rows + 2 * (read_columns - 2) while read_num: read_num -= 1 matrix[row][column] = number # print matrix # print row, column, number # print number += 1 if (row == i) and (column < (columns - i - 1)): column += 1 elif (column == (columns - i - 1)) and (row < (rows - i - 1)): row += 1 elif (row == (rows - i - 1)) and (column > i): column -= 1 elif (column == i) and (row > i): row -= 1 return matrix n = 3 # so = Solution() # print so.generateMatrix(n) matrix = [[0] * n] * n # matrix = [] # for i in xrange(n): # matrix.append([0]*n) # matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] print matrix matrix[0][1] = 1 print matrix print matrix[0][2] matrix[0][2] = 2 print matrix
[ "hitwhwlj@163.com" ]
hitwhwlj@163.com
2541bc3717df13f38034e534423c96eec29b2d31
9cadeb694a677c4ad567d514eee042891c65eeaf
/apiServer/wsgi.py
64aabb0e27969ed54fed3cc2e2a79148e4e57375
[]
no_license
epikjjh/Stock-Seeker
b8267fda13df6579f3883f66f94007d6ca11187a
934d97c0ceb89c1fcdfb469c1807d09c2671cc67
refs/heads/master
2022-12-22T23:38:24.947593
2020-09-22T11:50:56
2020-09-22T11:50:56
297,632,451
0
0
null
null
null
null
UTF-8
Python
false
false
397
py
""" WSGI config for stockSeeker project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apiServer.settings') application = get_wsgi_application()
[ "epikjjh@gmail.com" ]
epikjjh@gmail.com
49ea9ed475b06f56c31886fdda4e54704aaed67f
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/8/uyw.py
29818697f710297c138205642ed9c41a60d45a3c
[]
no_license
G4te-Keep3r/HowdyHackers
46bfad63eafe5ac515da363e1c75fa6f4b9bca32
fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2
refs/heads/master
2020-08-01T12:08:10.782018
2016-11-13T20:45:50
2016-11-13T20:45:50
73,624,224
0
1
null
null
null
null
UTF-8
Python
false
false
486
py
import sys def printFunction(lineRemaining): if lineRemaining[0] == '"' and lineRemaining[-1] == '"': if len(lineRemaining) > 2: #data to print lineRemaining = lineRemaining[1:-1] print ' '.join(lineRemaining) else: print def main(fileName): with open(fileName) as f: for line in f: data = line.split() if data[0] == 'uYW': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
[ "juliettaylorswift@gmail.com" ]
juliettaylorswift@gmail.com
079530b221e8520dbec1afc70e82ce7bd75f45fa
786de89be635eb21295070a6a3452f3a7fe6712c
/CalibManager/tags/V00-00-34/src/GUIMetrology.py
4a583bd900a6318fb105b38bb6814264be14a4b0
[]
no_license
connectthefuture/psdmrepo
85267cfe8d54564f99e17035efe931077c8f7a37
f32870a987a7493e7bf0f0a5c1712a5a030ef199
refs/heads/master
2021-01-13T03:26:35.494026
2015-09-03T22:22:11
2015-09-03T22:22:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
22,961
py
#-------------------------------------------------------------------------- # File and Version Information: # $Id$ # # Description: # Module GUIMetrology... # #------------------------------------------------------------------------ """Renders the main GUI for the CalibManager. This software was developed for the SIT project. If you use all or part of it, please give an appropriate acknowledgment. @see RelatedModule @version $Id:$ @author Mikhail S. Dubrovin """ #------------------------------ # Module's version from CVS -- #------------------------------ __version__ = "$Revision: 4 $" # $Source$ #-------------------------------- # Imports of standard modules -- #-------------------------------- import sys import os from PyQt4 import QtGui, QtCore #import time # for sleep(sec) #----------------------------- # Imports for other modules -- #----------------------------- from ConfigParametersForApp import cp from Logger import logger from FileNameManager import fnm from GUIFileBrowser import * from GUIRunRange import * import GlobalUtils as gu from xlsx_parser import convert_xlsx_to_text from OpticAlignmentCspadV1 import * #--------------------- # Class definition -- #--------------------- class GUIMetrology ( QtGui.QWidget ) : """Main GUI for main button bar. @see BaseClass @see OtherClass """ def __init__ (self, parent=None, app=None) : self.name = 'GUIMetrology' self.myapp = app QtGui.QWidget.__init__(self, parent) self.fname_prefix = cp.fname_prefix self.fname_metrology_xlsx = cp.fname_metrology_xlsx self.fname_metrology_text = cp.fname_metrology_text self.img_arr = None self.list_of_calib_types = ['center', 'tilt', 'geometry'] cp.setIcons() self.setGeometry(10, 25, 725, 200) self.setWindowTitle('Metrology') #self.setWindowIcon(cp.icon_monitor) self.palette = QtGui.QPalette() self.resetColorIsSet = False self.setFrame() self.setParams() #self.titFileXlsx = QtGui.QLabel('File xlsx:') self.ediFileXlsx = QtGui.QLineEdit ( fnm.path_metrology_xlsx() ) self.ediFileXlsx.setReadOnly(True) self.ediFileText = QtGui.QLineEdit ( fnm.path_metrology_text() ) self.ediFileText.setReadOnly(True) self.butFileXlsx = QtGui.QPushButton(' 1. Select xlsx file:') self.butConvert = QtGui.QPushButton(' 2. Convert xlsx to text file(s)') self.butFileText = QtGui.QPushButton(' 3. Select text file:') self.butEvaluate = QtGui.QPushButton(' 4. Evaluate') self.butDeploy = QtGui.QPushButton(' 5. Deploy') self.butList = QtGui.QPushButton('List') self.butRemove = QtGui.QPushButton('Remove') self.butViewOffice= QtGui.QPushButton('View xlsx') self.butViewText = QtGui.QPushButton('View text') self.butScript = QtGui.QPushButton(self.script + cp.char_expand ) self.butSrc = QtGui.QPushButton(self.source_name + cp.char_expand ) self.labSrc = QtGui.QLabel('for detector') self.labScript = QtGui.QLabel('using script') self.guirunrange = GUIRunRange() self.butViewOffice .setIcon(cp.icon_monitor) self.butViewText .setIcon(cp.icon_monitor) #self.butConvert .setIcon(cp.icon_convert) self.grid = QtGui.QGridLayout() self.grid_row = 0 self.grid.addWidget(self.butFileXlsx, self.grid_row, 0) self.grid.addWidget(self.ediFileXlsx, self.grid_row, 1, 1, 8) self.grid.addWidget(self.butViewOffice, self.grid_row, 8) self.grid.addWidget(self.butConvert, self.grid_row+1, 0) self.grid.addWidget(self.butList, self.grid_row+1, 1, 1, 1) self.grid.addWidget(self.butRemove, self.grid_row+1, 2, 1, 1) self.grid.addWidget(self.butFileText, self.grid_row+2, 0) self.grid.addWidget(self.ediFileText, self.grid_row+2, 1, 1, 8) self.grid.addWidget(self.butViewText, self.grid_row+2, 8) self.grid.addWidget(self.butEvaluate, self.grid_row+3, 0) self.grid.addWidget(self.labScript, self.grid_row+3, 1) self.grid.addWidget(self.butScript, self.grid_row+3, 2) self.grid.addWidget(self.butDeploy, self.grid_row+4, 0) self.grid.addWidget(self.labSrc, self.grid_row+4, 1) self.grid.addWidget(self.butSrc, self.grid_row+4, 2) self.grid.addWidget(self.guirunrange, self.grid_row+4, 3, 1, 5) #self.setLayout(self.grid) self.vbox = QtGui.QVBoxLayout() self.vbox.addLayout(self.grid) self.vbox.addStretch(1) self.setLayout(self.vbox) self.connect( self.butFileXlsx, QtCore.SIGNAL('clicked()'), self.onButFileXlsx ) self.connect( self.butFileText, QtCore.SIGNAL('clicked()'), self.onButFileText ) self.connect( self.butViewOffice, QtCore.SIGNAL('clicked()'), self.onButViewOffice ) self.connect( self.butViewText, QtCore.SIGNAL('clicked()'), self.onButViewText ) self.connect( self.butConvert, QtCore.SIGNAL('clicked()'), self.onButConvert ) self.connect( self.butRemove, QtCore.SIGNAL('clicked()'), self.onButRemove ) self.connect( self.butList, QtCore.SIGNAL('clicked()'), self.onButList ) self.connect( self.butEvaluate, QtCore.SIGNAL('clicked()'), self.onButEvaluate ) self.connect( self.butDeploy, QtCore.SIGNAL('clicked()'), self.onButDeploy ) self.connect( self.butScript, QtCore.SIGNAL('clicked()'), self.onButScript ) self.connect( self.butSrc, QtCore.SIGNAL('clicked()'), self.onButSrc ) self.showToolTips() self.setStyle() cp.guimetrology = self #self.move(10,25) #print 'End of init' #------------------- # Private methods -- #------------------- def showToolTips(self): #pass self.ediFileXlsx .setToolTip('Persistent path to xlsx file') self.butFileXlsx .setToolTip('Open file browser dialog window\nand select xlsx file. This file is\nusually e-mailed from detector group.') self.butViewOffice.setToolTip('Open openoffice.org window') self.butViewText .setToolTip('Open file viewer window') self.butFileText .setToolTip('Open file browser dialog window\nand select metrology text file') self.ediFileText .setToolTip('Path to the text metrology file which\nis used to evaluate calibration constants.') self.butConvert .setToolTip('Convert xlsx to text metrology file(s)') self.butList .setToolTip('List temporarty metrology text file(s)') self.butRemove .setToolTip('Remove temporarty metrology text file(s)') self.butEvaluate .setToolTip('Run quality check script and\nevaluate geometry alignment parameters') self.butDeploy .setToolTip('Deploy geometry alignment parameters') self.butScript .setToolTip('Select the script to process optic metrology file') self.butSrc .setToolTip('Select name of the detector') def setFrame(self): self.frame = QtGui.QFrame(self) self.frame.setFrameStyle( QtGui.QFrame.Box | QtGui.QFrame.Sunken ) #Box, Panel | Sunken, Raised self.frame.setLineWidth(0) self.frame.setMidLineWidth(1) self.frame.setGeometry(self.rect()) #self.frame.setVisible(False) def setParams(self) : #if self.path_fm_selected != '' : # self.path_fm_selected = os.path.dirname(self.path_fm_selected) self.str_run_from = '0' self.str_run_to = 'end' self.source_name = 'Select' self.script = 'Select' self.calib_type = 'Select' def setStyle(self): self.setMinimumSize(725,200) self.setMaximumSize(800,200) self. setStyleSheet(cp.styleBkgd) self.butViewOffice.setStyleSheet(cp.styleButton) self.butViewText .setStyleSheet(cp.styleButton) #self.butViewOffice.setFixedWidth(200) #self.butViewOffice.setMinimumHeight(60) #self.butViewOffice.setMinimumSize(180,60) self.butFileXlsx .setStyleSheet(cp.styleButtonLeft) self.butConvert .setStyleSheet(cp.styleButtonLeft) self.butFileText .setStyleSheet(cp.styleButtonLeft) self.butEvaluate .setStyleSheet(cp.styleButtonLeft) self.butDeploy .setStyleSheet(cp.styleButtonLeft) self.ediFileXlsx.setFixedWidth(400) self.ediFileXlsx.setStyleSheet(cp.styleEditInfo) self.ediFileXlsx.setEnabled(False) self.ediFileText.setFixedWidth(400) self.ediFileText.setStyleSheet(cp.styleEditInfo) self.ediFileText.setEnabled(False) self.labSrc .setStyleSheet(cp.styleLabel) self.labScript .setStyleSheet(cp.styleLabel) #self.butFBrowser.setVisible(False) #self.butSave.setText('') #self.butExit.setText('') #self.butExit.setFlat(True) self.setStyleButtons() def setStyleButtons(self): if self.source_name == 'Select' : self.butSrc.setStyleSheet(cp.stylePink) else : self.butSrc.setStyleSheet(cp.styleButton) if self.script == 'Select' : self.butScript.setStyleSheet(cp.stylePink) else : self.butScript.setStyleSheet(cp.styleButton) def resizeEvent(self, e): #logger.debug('resizeEvent', self.name) self.frame.setGeometry(self.rect()) #print 'GUIMetrology.resizeEvent: %s' % str(self.size()) def moveEvent(self, e): #logger.debug('moveEvent', self.name) #self.position = self.mapToGlobal(self.pos()) #self.position = self.pos() #logger.debug('moveEvent - pos:' + str(self.position), __name__) pass def closeEvent(self, event): logger.debug('closeEvent', self.name) try : cp.guifilebrowser.close() except : pass def onExit(self): logger.debug('onExit', self.name) self.close() def onButFileXlsx(self): logger.debug('onButFileXlsx', __name__) but = self.butFileXlsx edi = self.ediFileXlsx par = self.fname_metrology_xlsx #prefix = self.fname_prefix.value() filter = 'Text files (*.xlsx )\nAll files (*)' self.onButFile(but, edi, par, filter, set_path=True) def onButFileText(self): logger.debug('onButFileText', __name__) but = self.butFileText edi = self.ediFileText par = self.fname_metrology_text basename = os.path.basename( fnm.path_metrology_ptrn() ) fname, ext = os.path.splitext(basename) filter = 'Text files (' + fname + '*' + ext + ')\nAll files (*)' self.onButFile(but, edi, par, filter, set_path=False) def onButFile(self, but, edi, par, filter, set_path=True): logger.debug('onButFile', __name__) path = str( edi.displayText() ) dname, fname = os.path.split(path) msg = 'dir : %s file : %s' % (dname, fname) logger.info(msg, __name__) path = str( QtGui.QFileDialog.getOpenFileName(self, 'Open file', dname, filter=filter) ) dname, fname = os.path.split(path) if dname == '' or fname == '' : logger.info('Input directiry name or file name is empty... use default values', __name__) return else : edi.setText(path) if set_path : par.setValue(path) else : par.setValue(fname) logger.info('Selected file: %s' % path, __name__) def onButViewOffice(self): logger.debug('onLogger', self.name) try : #cp.viewoffice.close() #del cp.viewoffice self.butViewOffice.setStyleSheet(cp.styleButton) #self.butViewOffice.setText('Open openoffice') cmd = 'openoffice.org %s &' % fnm.path_metrology_xlsx() msg = 'Confirm command: %s' % cmd resp = gu.confirm_or_cancel_dialog_box(parent=self.butViewOffice, text=msg, title='Please confirm or cancel!') if resp : logger.info('Approved command:\n' + cmd, __name__) self.commandInSubproc(cmd) else : logger.info('Command is cancelled', __name__) except : self.butViewOffice.setStyleSheet(cp.styleButtonGood) #self.butViewOffice.setText('Close openoffice') #cp.viewoffice = MaskEditor(**pars) #cp.viewoffice.move(self.pos().__add__(QtCore.QPoint(820,-7))) # open window with offset w.r.t. parent #cp.viewoffice.show() def onButViewText(self): logger.debug('onButViewText', __name__) try : cp.guifilebrowser.close() #self.but_view.setStyleSheet(cp.styleButtonBad) except : #self.but_view.setStyleSheet(cp.styleButtonGood) list_of_files = fnm.get_list_of_metrology_text_files() if self.script != 'Select' : list_of_files += self.list_metrology_alignment_const_fnames() cp.guifilebrowser = GUIFileBrowser(None, list_of_files, fnm.path_metrology_text()) cp.guifilebrowser.move(self.pos().__add__(QtCore.QPoint(880,40))) # open window with offset w.r.t. parent cp.guifilebrowser.show() def onButConvert(self): logger.debug('onButConvert', __name__) #ifname = fnm.path_metrology_xlsx() #ofname = fnm.path_metrology_text() list_ofnames = convert_xlsx_to_text(fnm.path_metrology_xlsx(), fnm.path_metrology_ptrn(), print_bits=0) msg = 'File %s is converted to the temporarty metrology text file(s):\n' % fnm.path_metrology_xlsx() for name in list_ofnames : msg += ' %s\n' % name logger.info(msg, __name__) def onButRemove(self): #logger.debug('onButRemove', __name__) cmd = 'rm' for fname in fnm.get_list_of_metrology_text_files() : cmd += ' %s' % fname msg = 'Confirm command: %s' % cmd resp = gu.confirm_or_cancel_dialog_box(parent=self.butViewOffice, text=msg, title='Please confirm or cancel!') if resp : logger.info('Approved command:\n' + cmd, __name__) self.commandInSubproc(cmd) else : logger.info('Command is cancelled', __name__) def onButList(self): msg = 'List of metrology text files in %s\n' % fnm.path_dir_work() for fname in fnm.get_list_of_metrology_text_files() : msg += ' %s\n' % fname logger.info(msg, __name__) def get_detector_selected(self): lst = cp.list_of_dets_selected() len_lst = len(lst) msg = '%d detector(s) selected: %s' % (len_lst, str(lst)) #logger.info(msg, __name__ ) if len_lst !=1 : msg += ' Select THE ONE!' logger.warning(msg, __name__ ) return None return lst[0] def onButScript(self): logger.debug('onButScript', __name__ ) det = self.get_detector_selected() if det is None : return if det != cp.list_of_dets[0] : logger.warning('Scripts are implemented for CSPAD ONLY !!!: ', __name__) lst = cp.dict_of_metrology_scripts[det] selected = gu.selectFromListInPopupMenu(lst) if selected is None : return # selection is cancelled if selected is self.script : return # the same txt = str(selected) self.setScript(txt) self.setSrc() self.setStyleButtons() def onButSrc(self): logger.debug('onButSrc', __name__ ) det = self.get_detector_selected() if det is None : return try : lst = ru.list_of_sources_for_det(det) except : lst = cp.dict_of_det_sources[det] selected = gu.selectFromListInPopupMenu(lst) if selected is None : return # selection is cancelled if selected is self.source_name : return # the same txt = str(selected) self.setSrc(txt) self.setStyleButtons() def setScript(self,txt='Select'): self.script = txt self.butScript.setText( txt + cp.char_expand ) logger.info('Script is selected: ' + txt, __name__) def setSrc(self,txt='Select'): self.source_name = txt self.butSrc.setText( txt + cp.char_expand ) logger.info('Source selected: ' + txt, __name__) def onButEvaluate(self): logger.debug('onButEvaluate', __name__) det = self.get_detector_selected() if det is None : return list_of_metrology_scripts = cp.dict_of_metrology_scripts[det] if self.script == 'Select' : msg = 'Script for processing metrology file is not selected. Select it first...' logger.warning(msg, __name__) return #print 'list_of_metrology_scripts', list_of_metrology_scripts #for CSPAD script CSPADV1 if det == cp.list_of_dets[0] and self.script == list_of_metrology_scripts[0] : msg = 'Evaluate parameters for %s using script %s' % (det, self.script) logger.info(msg, __name__) self.procCspadV1() # for other detectors and scripts for now... else : msg = 'Script %s is not yet implemented for detector %s...' % (self.script, det) logger.warning(msg, __name__) return def procCspadV1(self): """Create and save interim files for calibration types""" self.list_of_calib_types = ['center', 'tilt', 'geometry'] fname_metrology = fnm.path_metrology_text() msg = 'procCspadV1 for metrology data in file %s' % fname_metrology logger.info(msg, __name__) optal = OpticAlignmentCspadV1(fname_metrology, print_bits=0, plot_bits=0) txt_qc_table_xy = optal.txt_qc_table_xy() txt_qc_table_z = optal.txt_qc_table_z() txt_center = optal.txt_center_pix_formatted_array() txt_tilt = optal.txt_tilt_formatted_array() txt_geometry = optal.txt_geometry() logger.info('Quality check in X-Y plane:\n'+txt_qc_table_xy, __name__) logger.info('Quality check in Z:\n'+txt_qc_table_z, __name__) logger.info('parameters of type "center":\n'+txt_center, __name__) logger.info('parameters of type "tilt":\n'+txt_tilt, __name__) logger.info('parameters of type "geometry":\n'+txt_geometry, __name__) # Save calibration files in work directory dic_type_fname = self.dict_metrology_alignment_const_fname_for_type() gu.save_textfile(txt_center, dic_type_fname['center']) gu.save_textfile(txt_tilt, dic_type_fname['tilt']) gu.save_textfile(txt_geometry, dic_type_fname['geometry']) msg = 'Save interim metrology alignment files:' for type in self.list_of_calib_types : msg += '\n %s %s' % (type.ljust(16), dic_type_fname[type]) logger.info(msg, __name__) def dict_metrology_alignment_const_fname_for_type(self) : #lst_const_types = cp.const_types_cspad # ex. ['center', 'tilt',...] lst_const_types = self.list_of_calib_types lst_of_insets = ['%s-%s' % (self.script,type) for type in lst_const_types] # ex. ['CSPADV1-tilt', ...] lst_of_const_fnames = gu.get_list_of_files_for_list_of_insets(fnm.path_metrology_alignment_const(), lst_of_insets) return dict(zip(lst_const_types, lst_of_const_fnames)) def list_metrology_alignment_const_fnames(self) : return self.dict_metrology_alignment_const_fname_for_type().values() def onButDeploy(self): logger.debug('onButDeploy', __name__) if self.script == 'Select' : msg = 'Script for processing metrology file is not selected.... Select it first and evaluate constants (Item 4)' logger.warning(msg, __name__) return if self.source_name == 'Select' : msg = 'Detector is not selected. Select it first...' logger.warning(msg, __name__) return list_of_cmds = self.list_of_copy_cmds() txt = '\nList of commands for tentetive file deployment:' for cmd in list_of_cmds : txt += '\n' + cmd logger.info(txt, __name__) msg = 'Approve commands \njust printed in the logger' if self.approveCommand(self.butDeploy, msg) : for cmd in list_of_cmds : fd.procDeployCommand(cmd, 'metrology-alignment') #print 'Command for deployer: ', cmd if cp.guistatus is not None : cp.guistatus.updateStatusInfo() def approveCommand(self, but, msg): resp = gu.confirm_or_cancel_dialog_box(parent=but, text=msg, title='Please confirm or cancel!') if resp : logger.info('Commands approved', __name__) else : logger.info('Command is cancelled', __name__) return resp def list_of_copy_cmds(self): det = self.get_detector_selected() if det is None : return dst_calib_dir = fnm.path_to_calib_dir() dst_calib_type = cp.dict_of_det_calib_types[det] dst_source = self.source_name dst_fname = '%s.data' % cp.guirunrange.getRunRange() #print 'dst_calib_dir ', dst_calib_dir #print 'dst_calib_type ', dst_calib_type #print 'dst_source ', dst_source #print 'dst_fname ', dst_fname list_of_cmds = [] for type, fname in self.dict_metrology_alignment_const_fname_for_type().iteritems() : dst_path = os.path.join(dst_calib_dir, dst_calib_type, dst_source, type, dst_fname) cmd = 'cp %s %s' % (fname, dst_path) list_of_cmds.append(cmd) return list_of_cmds def commandInSubproc(self, cmd): cmd_seq = cmd.split() msg = 'Command: ' + cmd #out, err = gu.subproc(cmd_seq) #if err != '' : msg += '\nERROR: ' + err #if out != '' : msg += '\nRESPONCE: ' + out os.system(cmd) logger.info(msg, __name__) #os.system('chmod 670 %s' % path) #----------------------------- # In case someone decides to run this module # if __name__ == "__main__" : app = QtGui.QApplication(sys.argv) ex = GUIMetrology() ex.show() app.exec_() #-----------------------------
[ "dubrovin@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7" ]
dubrovin@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7
440bfdebbceb6eaef3277aca9941a759e42ae116
7beff965d7b0e6155d6d52b27d71c557421d5ada
/aoj/grl_7_a.py
830ad7ec1ba09ea22f3deb70e180d4910bd89f7e
[]
no_license
uk-ar/competitive_programming
82a53a1007798843ac006b9c7d313826e6cb45c3
d2523cf303f47644cada3b03e9eed2349bdbe394
refs/heads/master
2023-03-28T13:20:07.728861
2021-03-30T20:25:55
2021-03-30T20:25:55
249,638,234
0
0
null
null
null
null
UTF-8
Python
false
false
1,613
py
#!/usr/bin/env python3 # N,M = map(int,sys.stdin.readline().split()) # a = tuple(map(int,sys.stdin.readline().split())) # single line with multi param # a = tuple(int(sys.stdin.readline()) for _ in range(N)) # multi line with single param # a = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(N)) # multi line with multi param # s = sys.stdin.readline().rstrip() # N = int(sys.stdin.readline()) # INF = float("inf") import sys,collections sys.setrecursionlimit(100000) INF = float("inf") X,Y,E = map(int,sys.stdin.readline().split()) xy = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(E)) # multi line with multi param #uvc = [[0,1,1],[0,2,3],[1,2,1],[2,3,2]] #xy = [[0,0],[1,2],[2,2],[1,3]] V = X+Y+2 uvc = [[x+1,y+X+1,1] for x,y in xy] for i in range(X): uvc.append([0,i+1,1]) for i in range(Y): uvc.append([X+i+1,V-1,1]) G = {i:{} for i in range(V)} mG = {i:{} for i in range(V)} for u,v,c in uvc: G[u][v] = c G[v][u] = 0 # reverse edge mG[u][v] = 0 mG[v][u] = 0 # print(G) # print(mG) def dfs(current,flow): if current == V-1: return flow visited.add(current) for nex,nex_c in G[current].items(): if not nex in visited and nex_c != 0: f = dfs(nex,min(flow,nex_c)) if f != 0: mG[current][nex] = mG[current][nex] + f G[current][nex] = G[current][nex] - f G[nex][current] = G[nex][current] + f return f return 0 visited = set() while dfs(0,INF) != 0: visited = set() pass print(sum(mG[0].values()))
[ "yuuki.ari@gmail.com" ]
yuuki.ari@gmail.com
d973a98d468f699d88ed22bda3be21818e1727e8
4c44c593048fa4e00fb0334209632a286886efd9
/import_template_supplierinfo/wizards/import_file.py
6e86c4502afe621620950784d04bcf17a2bff77f
[]
no_license
treytux/trey-addons
0c3fec43c584d46bd299b4bca47dcc334bedca60
1cda42c0eae702684badce769f9ec053c59d6e42
refs/heads/12.0
2023-06-08T21:56:09.945084
2023-05-29T10:05:53
2023-05-29T10:05:53
114,281,765
19
49
null
2023-05-29T10:05:55
2017-12-14T18:10:39
Python
UTF-8
Python
false
false
1,065
py
############################################################################### # For copyright and license notices, see __manifest__.py file in root directory ############################################################################### import base64 import io import logging from odoo import models _log = logging.getLogger(__name__) try: import pandas as pd except (ImportError, IOError) as err: _log.debug(err) class ImportFile(models.TransientModel): _inherit = 'import.file' def dataframe_get(self): self.ensure_one() if self.template_id.model_id.model == 'import.template.supplierinfo': buf = io.BytesIO() buf.write(base64.b64decode(self.file)) ext = self.file_filename.split('.')[-1:][0] if ext in ['xlsx', 'xls']: df = pd.read_excel( buf, engine='xlrd', encoding='utf-8', na_values=['NULL'], converters={'name': str}) return df.where((pd.notnull(df)), None) return super().dataframe_get()
[ "roberto@trey.es" ]
roberto@trey.es
da88288f281baad769af1ccbf83b2777ed6a91a0
3f7c27ccd0ab1fcbd2583cf4b764b81bd27dd718
/apps/members/urls.py
03acc1cb09f082fefdc65dd6e430675e3a4ac2b6
[]
no_license
adamtlord/foreverland
001ca1a91a3cc468405efb80fe7981e75b82021c
8206ddeeb8cfbd2752ef6fa9839424718cb96e07
refs/heads/master
2020-04-16T00:50:51.582008
2016-09-21T03:27:39
2016-09-21T03:27:39
11,668,672
0
0
null
2016-09-04T03:46:51
2013-07-25T19:05:55
Python
UTF-8
Python
false
false
144
py
from django.conf.urls import patterns, url urlpatterns = patterns('members.views', url(r'^$', 'list_members', {}, name='list_members'), )
[ "adam.lord@gmail.com" ]
adam.lord@gmail.com
269093e40a4014ea89ecd80de5f371b123bd4fa7
8acffb8c4ddca5bfef910e58d3faa0e4de83fce8
/ml-flask/Lib/site-packages/srsly/tests/cloudpickle/cloudpickle_file_test.py
02c568f8652ef647b699a151dff037527a6e8836
[ "MIT" ]
permissive
YaminiHP/SimilitudeApp
8cbde52caec3c19d5fa73508fc005f38f79b8418
005c59894d8788c97be16ec420c0a43aaec99b80
refs/heads/master
2023-06-27T00:03:00.404080
2021-07-25T17:51:27
2021-07-25T17:51:27
389,390,951
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:a058ea411ee874062513e922cfd60cc7f362eda3000cc849fc6af9c828f1412b size 3430
[ "yamprakash130@gmail.com" ]
yamprakash130@gmail.com
c3df0ac58a6da679590d7b4d309dd0b86190657c
863a1f5091f1faad2beaf2a6037e3a5c0ebdc194
/Backuper.glyphsPlugin/Contents/Resources/plugin.py
8a21cdbee8b408df2b4ca9d675f6a38770426e11
[]
no_license
schriftgestalt/Backuper
e65f08ec016770564131c05dbd888fe6841c6612
2b738600c4a8cb288184ae2c216bcfcbf64e266b
refs/heads/master
2023-07-17T19:50:00.265070
2021-09-01T21:38:34
2021-09-01T21:38:34
109,949,694
1
0
null
null
null
null
UTF-8
Python
false
false
1,699
py
# encoding: utf-8 ########################################################################################################### # # # General Plugin # # Read the docs: # https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates/General%20Plugin # # ########################################################################################################### from __future__ import print_function import objc from GlyphsApp import * from GlyphsApp.plugins import * from Foundation import NSFileManager import os class Backuper(GeneralPlugin): @objc.python_method def start(self): Glyphs.addCallback(self.doBackup_, DOCUMENTOPENED) def doBackup_(self, sender): document = sender.object() if document.fileURL() is None: return importedVersion = document.valueForKey_("importedVersion") if importedVersion != None and int(Glyphs.buildNumber) > int(importedVersion): documentPath = document.fileURL().path() fileName = os.path.basename(documentPath) bachupFolder = os.path.join(os.path.dirname(documentPath), "Backup") bachupPath = os.path.join(bachupFolder, importedVersion + "_" + fileName) fileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath_isDirectory_(bachupFolder, None) == (False, False): if not fileManager.createDirectoryAtPath_withIntermediateDirectories_attributes_error_(bachupFolder, True, None, None): print("Could not make backup folder") if fileManager.isReadableFileAtPath_(documentPath): NSFileManager.defaultManager().copyItemAtPath_toPath_error_(documentPath, bachupPath, None) @objc.python_method def __file__(self): """Please leave this method unchanged""" return __file__
[ "georg.seifert@mac.com" ]
georg.seifert@mac.com
8e8d6e02afe119d471e20a1ce2cf4091b144d836
f045faa2ce09bebd4f878b1219fc4983587c8c79
/flearn/models/femnist/cnn2.py
d180ebb0906dc9c036d8928bea56241b44227a69
[]
no_license
eepLearning/federated-learning
9db7babb9453fd20dc0dcac0202d4a806287754f
b647689bb035929f2661ebe3e8a3b0c94423bcf2
refs/heads/master
2023-01-12T19:13:56.108284
2020-08-06T15:35:56
2020-08-06T15:35:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
15,708
py
import tensorflow as tf import tqdm import numpy as np from flearn.models.base_model import BaseModel class Model(BaseModel): def __init__(self, num_classes, image_size, options, optimizer, seed=1): # params self.num_classes = num_classes self.image_size = image_size # 使用 mini-batch 的数量 self.num_inner_steps = options['num_inner_steps'] self.batch_size = options['batch_size'] self.inner_lr = options['lr'] super(Model, self).__init__(optimizer=optimizer, seed=seed, options=options) def create_conv_variables(self, kernel_size, in_dim, out_dim, conv_name, kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d): """ 创建卷积层的变量 :param kernel_size: :param in_dim: :param out_dim: :param conv_name: :param kernel_initializer: :return: """ w = tf.get_variable(conv_name + '_w', [kernel_size, kernel_size, in_dim, out_dim], initializer=kernel_initializer()) b = tf.get_variable(conv_name + '_b', initializer=tf.zeros([out_dim])) return (w, b) def create_fc_variables(self, in_dim, out_dim, fc_name, weight_initializer=tf.contrib.layers.xavier_initializer): """ 创建 dense 层的相关变量 :param in_dim: :param out_dim: :param fc_name: :param weight_initializer: :return: """ w = tf.get_variable(fc_name + '_w', [in_dim, out_dim], initializer=weight_initializer()) b = tf.get_variable(fc_name + '_b', initializer=tf.zeros([out_dim])) return (w, b) def create_params(self): """ 创建网路的参数. 网络的参数保存在 :param input_channel: :param kernel_size: :return: 参数 dict: Dict[name] -> variable """ weights = {} with tf.variable_scope('MAML', reuse=tf.AUTO_REUSE): (weights['conv1w'], weights['conv1b']) = self.create_conv_variables(5, 1, 32, 'conv1') (weights['conv2w'], weights['conv2b']) = self.create_conv_variables(5, 32, 64, 'conv2') (weights['fc1w'], weights['fc1b']) = self.create_fc_variables(7 * 7 * 64, 2048, 'fc1') (weights['fc2w'], weights['fc2b']) = self.create_fc_variables(2048, self.num_classes, 'fc2') return weights def conv_block(self, x, weight, bias, scope): """ build a block with conv2d->pooling. 暂时删除 batch_norm 的设置 :param x: 输入的张量 :param weight: conv2d 的 weight :param bias: conv2d 的 bias :param scope: :return: """ # conv x = tf.nn.conv2d(x, weight, [1, 1, 1, 1], 'SAME', name=scope + '_conv2d') + bias x = tf.nn.relu(x, name=scope + '_relu') # pooling x = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], 'VALID', name=scope + '_pool') return x def fc_block(self, x, weight, bias, name, flatten=False, act=tf.nn.relu): """ 前向操作 :param x: :param weight: :param bias: :param name: :param flatten: 是否扁平化输入 :param act: 输出之前的激活函数 :return: """ if flatten: x = tf.reshape(x, [-1, np.prod([int(dim) for dim in x.get_shape()[1:]])], name=name + '_flatten') x = tf.add(tf.matmul(x, weight), bias, name=name + '_out') if act is not None: x = act(x, name=name + '_act') return x def forward(self, x, weights): """ 输入到输出的定义 :param x: :param weights: :return: """ hidden1 = self.conv_block(x, weights['conv1w'], weights['conv1b'], 'conv1') hidden2 = self.conv_block(hidden1, weights['conv2w'], weights['conv2b'], 'conv2') output = self.fc_block(hidden2, weights['fc1w'], weights['fc1b'], name='fc1', flatten=True) output = self.fc_block(output, weights['fc2w'], weights['fc2b'], name='fc2', act=None, flatten=False) return output def create_model(self): """ 创建基本你的模型 :param optimizer: :return: """ support_features = tf.placeholder(tf.float32, shape=[self.num_inner_steps, self.batch_size, self.image_size * self.image_size], name='support_features') query_features = tf.placeholder(tf.float32, shape=[self.num_inner_steps, self.batch_size, self.image_size * self.image_size], name='query_features') # 转换为张量 support_labels = tf.placeholder(tf.int64, shape=[self.num_inner_steps, self.batch_size], name='support_labels') query_labels = tf.placeholder(tf.int64, shape=[self.num_inner_steps, self.batch_size], name='query_labels') # 基于 support, 计算一次参数 self.weights = self.create_params() def support_update(inputx): # inputx: 第一个维度为 batch_size one_support_features_batch, one_support_label_batch = inputx one_support_features_batch_reshaped = tf.reshape(one_support_features_batch, [-1, self.image_size, self.image_size, 1]) one_support_label_batch_onehot = tf.one_hot(one_support_label_batch, depth=self.num_classes) # 利用网络进行前向 support_pred_logitis = self.forward(one_support_features_batch_reshaped, self.weights) support_correct_count = tf.count_nonzero( tf.equal(tf.argmax(one_support_label_batch_onehot, axis=1), tf.argmax(tf.nn.softmax(support_pred_logitis, dim=1), axis=1))) support_loss = tf.nn.softmax_cross_entropy_with_logits(logits=support_pred_logitis, labels=one_support_label_batch_onehot) support_loss_mean = tf.reduce_mean(support_loss) # 这里计算一次梯度 grads = tf.gradients(support_loss_mean, list(self.weights.values())) # 更新当前的网络参数 gradients = dict(zip(self.weights.keys(), grads)) fast_weights = dict( zip(self.weights.keys(), [self.weights[key] - self.inner_lr * gradients[key] for key in self.weights.keys()])) # 将 fast weight 更新到 weights self.weights = fast_weights return (support_loss_mean, support_correct_count) def query_calc_loss(inputx): # inputx: 第一个维度为 batch_size one_support_features_batch, one_support_label_batch = inputx one_support_features_batch_reshaped = tf.reshape(one_support_features_batch, [-1, self.image_size, self.image_size, 1]) one_support_label_batch_onehot = tf.one_hot(one_support_label_batch, depth=self.num_classes) # 利用网络进行前向 support_pred_logitis = self.forward(one_support_features_batch_reshaped, self.weights) support_correct_count = tf.count_nonzero( tf.equal(tf.argmax(one_support_label_batch_onehot, axis=1), tf.argmax(tf.nn.softmax(support_pred_logitis, dim=1), axis=1)), dtype=tf.int64) support_loss = tf.nn.softmax_cross_entropy_with_logits(logits=support_pred_logitis, labels=one_support_label_batch_onehot) support_loss_mean = tf.reduce_mean(support_loss) # 这里计算一次梯度 grads = tf.gradients(support_loss_mean, list(self.weights.values())) # # 更新当前的网络参数 # gradients = dict(zip(self.weights.keys(), grads)) return (support_loss_mean, support_correct_count, grads) # TODO 无法在另外一个 loop 中应用先前的变量: https://www.shuzhiduo.com/A/q4zVZejWzK/ num_weights = len(self.weights) output_shape = (tf.float32, tf.int64) # 这两个均为向量, 长度为循环的次数 sprt_losses, sprt_corrects = tf.map_fn(support_update, dtype=output_shape, elems=(support_features, support_labels), parallel_iterations=self.num_inner_steps) output_shape = (tf.float32, tf.int64, [tf.float32] * num_weights) qry_losses, qry_corrects, grads = tf.map_fn(query_calc_loss, dtype=output_shape, elems=(query_features, query_labels), parallel_iterations=self.num_inner_steps) # 这里的 loss 需要平均一下, 按照 return (support_features, query_features), (support_labels, query_labels), None, grads, qry_corrects, qry_losses def create_model_bak(self): """ 创建基本你的模型 :param optimizer: :return: """ support_features = tf.placeholder(tf.float32, shape=[None, self.image_size * self.image_size], name='support_features') query_features = tf.placeholder(tf.float32, shape=[None, self.image_size * self.image_size], name='query_features') # 转换为张量 support_input_layer = tf.reshape(support_features, [-1, self.image_size, self.image_size, 1], name='support_features_reshaped') query_input_layer = tf.reshape(query_features, [-1, self.image_size, self.image_size, 1], name='query_features_reshaped') support_labels = tf.placeholder(tf.int64, shape=[None], name='support_labels') query_labels = tf.placeholder(tf.int64, shape=[None], name='query_labels') support_labels_onehot = tf.one_hot(support_labels, depth=self.num_classes, name='support_labels_onehot') query_labels_onehot = tf.one_hot(query_labels, depth=self.num_classes, name='query_labels_onehot') # 基于 support, 计算一次参数 self.weights = self.create_params() # self.adam_optimizer.create_momtems(self.weights) ###### 直接定义参数 ###### support_pred_logitis = self.forward(support_input_layer, self.weights) support_correct_count = tf.count_nonzero( tf.equal(tf.argmax(support_labels_onehot, axis=1), tf.argmax(tf.nn.softmax(support_pred_logitis, dim=1), axis=1))) support_loss = tf.nn.softmax_cross_entropy_with_logits(logits=support_pred_logitis, labels=support_labels_onehot) # 这个用来验证是否求了在query阶段求了二阶导数, sparse 没有二阶导数的实现. 如果没有报错误, 说明没有求得二阶导数 # support_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=support_pred_logitis, labels=support_labels) # theta' = theta - alpha * grads, 这里能否使用 adam? # fast_weights = dict(zip(self.weights.keys(), [self.weights[key] - self.options['lr'] * gvs[key] for key in self.weights.keys()])) #### # 这里的 loss 是向量. 现在就是希望能够模拟一个 Adam 的过程 support_loss_mean = tf.reduce_mean(support_loss) grads = tf.gradients(support_loss_mean, list(self.weights.values())) gvs = dict(zip(self.weights.keys(), grads)) fast_weights = dict(zip(self.weights.keys(), [self.weights[key] - self.options['lr'] * gvs[key] for key in self.weights.keys()])) # train_op = self.optimizer.apply_gradients(adam_gvs) #### # TODO 这种方式行不通!! 根本没有计算二阶导数 # support_loss_mean = tf.reduce_mean(support_loss) # adam_gvs = self.optimizer.compute_gradients(support_loss_mean) # train_op = self.optimizer.apply_gradients(adam_gvs) ### # # 接着是基于 query # query_pred = self.forward(query_input_layer, fast_weights) # # 计算损失函数 L(f_theta'(D')) # query_loss = tf.nn.softmax_cross_entropy_with_logits(logits=query_pred, labels=query_labels_onehot) # # 基于这个 query 定义优化器 # # gvs = self.optimizer.compute_gradients(query_loss) # # train_op = self.optimizer.apply_gradients(gvs) # # grads, _ = zip(*gvs) # # # eval_metric_ops = tf.count_nonzero(tf.equal(labels, predictions["classes"])) # # return features, labels, train_op, grads, eval_metric_ops, loss # second_order_grads = tf.gradients(query_loss, list(self.weights.values())) # query_correct_count = tf.count_nonzero( # tf.equal(tf.argmax(query_labels_onehot, axis=1), tf.argmax(tf.nn.softmax(query_pred, dim=1), axis=1))) query_pred = self.forward(query_input_layer, fast_weights) # 计算损失函数 L(f_theta'(D')) query_loss = tf.nn.softmax_cross_entropy_with_logits(logits=query_pred, labels=query_labels_onehot) # query_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=query_pred, labels=query_labels) query_loss_mean = tf.reduce_mean(query_loss) second_order_grads = tf.gradients(query_loss_mean, list(self.weights.values())) query_correct_count = tf.count_nonzero( tf.equal(tf.argmax(query_labels_onehot, axis=1), tf.argmax(tf.nn.softmax(query_pred, dim=1), axis=1))) return (support_features, query_features), (support_labels, query_labels), None, second_order_grads, (support_correct_count, query_correct_count), (support_loss_mean, query_loss_mean) def solve_sgd_meta_one_batch(self, sp, qr): """ 运行一次 SGD :param mini_batch_data: :return: """ self.adam_optimizer.increase_n() with self.graph.as_default(): grads, loss = self.sess.run([self.grads, self.loss], feed_dict={self.features[0]: sp[0], self.features[1]: qr[0], self.labels[0]: sp[1], self.labels[1]: qr[1]}) sz = len(sp[1]) + len(qr[1]) comp = sz * self.flops return grads, loss, comp, sz def solve_sgd_meta_full_data(self, sp, qr): """ 运行一次 SGD :param mini_batch_data: :return: """ self.adam_optimizer.increase_n() with self.graph.as_default(): grads, loss = self.sess.run([self.grads, self.loss], feed_dict={self.features[0]: sp['x'], self.features[1]: qr['x'], self.labels[0]: sp['y'], self.labels[1]: qr['y']}) sz = len(sp['y']) + len(qr['y']) comp = sz * self.flops return grads, loss, comp, sz def test_meta(self, sp, qr): all_x = np.concatenate((sp['x'], qr['x']), axis=0) all_y = np.concatenate((sp['y'], qr['y']), axis=0) with self.graph.as_default(): # tot_correct, loss = self.sess.run([self.eval_metric_ops, self.loss], # feed_dict={self.features[0]: sp[0], # self.features[1]: qr[0], # self.labels[0]: sp[1], # self.labels[1]: qr[1]}) tot_correct, loss = self.sess.run([self.eval_metric_ops[0], self.loss[0]], feed_dict={self.features[0]: all_x, self.labels[0]: all_y}) return tot_correct, loss
[ "wangshu214@live.cn" ]
wangshu214@live.cn
ffa39f22831b11734d04b3e3eea7856437400115
e23a4f57ce5474d468258e5e63b9e23fb6011188
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetcodePythonProject_with_solution/leetcode_0401_0450/LeetCode422_ValidWordSquare.py
ee694477735ad1d5c38aa096a5f0bfdceae3713d
[]
no_license
syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
2023-02-16T03:08:10
2019-11-09T02:58:47
Python
UTF-8
Python
false
false
449
py
''' Created on Apr 13, 2017 @author: MT ''' c_ Solution(o.. ___ validWordSquare words __ n.. words: r.. F.. ___ i, word1 __ e..(words word2 '' ___ j __ r..(l..(word1: __ j >_ l..(words r.. F.. __ i >_ l..(words[j] r.. F.. word2 += words[j][i] __ word1 !_ word2: r.. F.. r.. T..
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
23936645c5429dbbbaad5e2fbb69f5df836ab631
dd4d1a61ec680a86d4b569490bf2a898ea0d7557
/appengine/predator/common/model/chrome_crash_analysis.py
4473ea72c94ffcc660fa5ff6418f3923faf801aa
[ "BSD-3-Clause" ]
permissive
mcgreevy/chromium-infra
f1a68914b47bcbe3cd8a424f43741dd74fedddf4
09064105713603f7bf75c772e8354800a1bfa256
refs/heads/master
2022-10-29T23:21:46.894543
2017-05-16T06:22:50
2017-05-16T06:22:50
91,423,078
1
1
BSD-3-Clause
2022-10-01T18:48:03
2017-05-16T06:23:34
Python
UTF-8
Python
false
false
1,079
py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from google.appengine.ext import ndb from common.model.crash_analysis import CrashAnalysis class ChromeCrashAnalysis(CrashAnalysis): # pylint: disable=W0223 """Represents an analysis of a Chrome Crash (Cracas or Fracas).""" # Customized properties for Fracas crash. historical_metadata = ndb.JsonProperty(indexed=False) channel = ndb.StringProperty(indexed=False) def Reset(self): super(ChromeCrashAnalysis, self).Reset() self.historical_metadata = None self.channel = None def Initialize(self, crash_data): """(Re)Initializes a CrashAnalysis ndb.Model from ``ChromeCrashData``.""" super(ChromeCrashAnalysis, self).Initialize(crash_data) self.channel = crash_data.channel self.historical_metadata = crash_data.historical_metadata @property def customized_data(self): return {'historical_metadata': self.historical_metadata, 'channel': self.channel}
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d926c78d9ca4a0ffd80d8aefc3bac5797f7db7a1
d2c4934325f5ddd567963e7bd2bdc0673f92bc40
/tests/model_control/detailed/transf_BoxCox/model_control_one_enabled_BoxCox_LinearTrend_BestCycle_AR.py
b8625fb2fc2806fe6e615c6b2e4052c583dac9c1
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jmabry/pyaf
797acdd585842474ff4ae1d9db5606877252d9b8
afbc15a851a2445a7824bf255af612dc429265af
refs/heads/master
2020-03-20T02:14:12.597970
2018-12-17T22:08:11
2018-12-17T22:08:11
137,104,552
0
0
BSD-3-Clause
2018-12-17T22:08:12
2018-06-12T17:15:43
Python
UTF-8
Python
false
false
155
py
import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['BoxCox'] , ['LinearTrend'] , ['BestCycle'] , ['AR'] );
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
38c15c39a97e7ab3d51118f6386f186dda7696d8
a0f1bfea522d5917ae6f18d3a4ab980870feac77
/modules/hs/analysis/instruction.py
9c6896ba3c8d225b4552a2b47164300ff9cdddce
[ "MIT" ]
permissive
sinsai/Sahana_eden
1d9768d19266010caf2753b66d17925fe708007a
798688dcf206fc81d586d9af1c57a99e6f1573c5
refs/heads/master
2020-06-07T21:10:17.416723
2011-06-10T08:57:23
2011-06-10T08:57:23
1,659,383
3
0
null
null
null
null
UTF-8
Python
false
false
4,114
py
""" Healthscapes Geolytics Module @author: Nico Preston <nicopresto@gmail.com> @author: Colin Burreson <kasapo@gmail.com> @author: Zack Krejci <zack.krejci@gmail.com> @copyright: (c) 2010 Healthscapes @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import enum from utils import keygen class Instruction: def __init__ (self, mode, procedure, dst, *args): self.mode = mode self.procedure = procedure self.dst = dst self.args = args
[ "fran@aidiq.com" ]
fran@aidiq.com
50ac2e045886d2069bb686e25b1fb783ace85abf
97f38bc0dff9498c43d13f15f4b26000874a840f
/pysp/plugins/ecksteincombettesextension.py
36809dee8e435aa6869ed8d825e77d580a587f94
[ "BSD-3-Clause" ]
permissive
tayucanjujieyihan/pysp
2975330f3a7f1c2aa56d9a69be2bdd08a632d3e9
98dbc9f6d500b0b2485a89bb22813e6c51b64411
refs/heads/main
2023-05-06T17:33:07.306607
2021-05-26T22:44:28
2021-05-26T22:44:28
442,712,534
1
0
NOASSERTION
2021-12-29T08:43:26
2021-12-29T08:43:26
null
UTF-8
Python
false
false
25,631
py
# ___________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and # Engineering Solutions of Sandia, LLC, the U.S. Government retains certain # rights in this software. # This software is distributed under the 3-clause BSD License. # ___________________________________________________________________________ import pyomo.common.plugin from six import iteritems, print_ import random from pysp import phextension from pysp.convergence import ConvergenceBase from pyomo.core.base import minimize import math # the converger for the class - everything (primal and dual) is # contained in the (u,v) vector of the Eckstein-Combettes extension. class EcksteinCombettesConverger(ConvergenceBase): def __init__(self, *args, **kwds): ConvergenceBase.__init__(self, *args, **kwds) self._name = "Eckstein-Combettes (u,v) norm" # the plugin computes the metric, so we'll just provide # it a place to stash the latest computed value. self._last_computed_uv_norm_value = None def computeMetric(self, ph, scenario_tree, instances): return self._last_computed_uv_norm_value # the primary Eckstein-Combettes extension class class EcksteinCombettesExtension(pyomo.common.plugin.SingletonPlugin): pyomo.common.plugin.implements(phextension.IPHExtension) pyomo.common.plugin.alias("ecksteincombettesextension") def __init__(self): import random random.seed(1234) print("Kludge warning: set random seed to 1234") self._check_output = False self._JName = "PhiSummary.csv" self._subproblems_to_queue = [] # various configuration options. # if this is True, then the number of sub-problems # returned may be less than the buffer length. self._queue_only_negative_subphi_subproblems = False # track the total number of projection steps performed (and, implicitly, # the current projection step) in addition to the last projection step # at which a scenario sub-problem was incorporated. self._total_projection_steps = 0 self._projection_step_of_last_update = {} # maps scenarios to projection step number self._converger = None def check_optimality_conditions(self, ph): print("Checking optimality conditions for Eckstein-Combettes plugin") for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: for variable_id in tree_node._standard_variable_ids: expected_y = 0.0 for scenario in tree_node._scenarios: expected_y += ((scenario._y[variable_id] * scenario._probability) / tree_node._probability) # the expected value of the y vector should be 0 if the solution is optimal def compute_updates(self, ph, subproblems, scenario_solve_counts): scale_factor = 1.0 # This should be a command-line parameter self._total_projection_steps += 1 print("Initiating projection step: %d" % self._total_projection_steps) print("Computing updates given solutions to the following sub-problems:") for subproblem in subproblems: print("%s" % subproblem) print("") for subproblem in subproblems: self._projection_step_of_last_update[subproblem] = self._total_projection_steps ######################################## ##### compute y values and u values #### ##### these are scenario-based ## ######################################## # NOTE: z is initiaized to be xbar in the code above, but it is *not* xbar. # NOTE: v is essentailly y bar # NOTE: lambda is 1/rho xxxxxxxxxxxxx so if you see 1/lamba in a latex file, use rho in the py file # ASSUME W is the Eckstein W, not the PH W for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: if ph._dual_mode is True: raise RuntimeError("***dual_mode not supported by compute_y in plugin ") tree_node_averages = tree_node._averages tree_node_zs = tree_node._z for scenario in tree_node._scenarios: weight_values = scenario._w[tree_node._name] rho_values = scenario._rho[tree_node._name] var_values = scenario._x[tree_node._name] for variable_id in tree_node._standard_variable_ids: varval = var_values[variable_id] if varval is not None: if scenario._objective_sense == minimize: if scenario._name in subproblems: # CRITICAL: Y depends on the z and weight values that were used when solving the scenario! z_for_solve = scenario._xbars_for_solve[tree_node._name][variable_id] w_for_solve = scenario._ws_for_solve[tree_node._name][variable_id] scenario._y[variable_id] = rho_values[variable_id] * (z_for_solve - varval) - w_for_solve # check it! #print("THIS %s SHOULD EQUAL THIS %s" % (varval + (1.0/rho_values[variable_id])*scenario._y[variable_id],z_for_solve-(1.0/rho_values[variable_id])*w_for_solve)) scenario._u[variable_id] = varval - tree_node_averages[variable_id] else: raise RuntimeError("***maximize not supported by compute_y in plugin ") if self._check_output: print("Y VALUES:") for scenario in ph._scenario_tree._scenarios: print(scenario._y) print("U VALUES:") for scenario in ph._scenario_tree._scenarios: print(scenario._u) # self.check_optimality_conditions(ph) ########################################### # compute v values - these are node-based # ########################################### for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: for variable_id in tree_node._standard_variable_ids: expected_y = 0.0 for scenario in tree_node._scenarios: expected_y += ((scenario._y[variable_id] * scenario._probability) / tree_node._probability) tree_node._v[variable_id] = expected_y if self._check_output: print("V VALUES:") for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: print(tree_node._v) ########################################### # compute norms and test for convergence # ########################################### p_unorm = 0.0 p_vnorm = 0.0 for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: for variable_id in tree_node._standard_variable_ids: for scenario in tree_node._scenarios: this_v_val = tree_node._v[variable_id] p_vnorm += tree_node._probability * this_v_val * this_v_val this_u_val = scenario._u[variable_id] p_unorm += scenario._probability * this_u_val * this_u_val if self._check_output : print("unorm^2 = " + str(p_unorm) + " vnorm^2 = " + str(p_vnorm)) p_unorm = math.sqrt(p_unorm) p_vnorm = math.sqrt(p_vnorm) ##################################################### # compute phi; if greater than zero, update z and w # ##################################################### print("") print("Initiating projection calculations...") with open(self._JName,"a") as f: f.write("%10d" % (ph._current_iteration)) phi = 0.0 sub_phi_map = {} for scenario in ph._scenario_tree._scenarios: cumulative_sub_phi = 0.0 for tree_node in scenario._node_list[:-1]: tree_node_zs = tree_node._z for variable_id in tree_node._standard_variable_ids: var_values = scenario._x[tree_node._name] varval = var_values[variable_id] weight_values = scenario._w[tree_node._name] if not scenario.is_variable_stale(tree_node, variable_id): this_sub_phi_term = scenario._probability * ((tree_node_zs[variable_id] - varval) * (scenario._y[variable_id] + weight_values[variable_id])) cumulative_sub_phi += this_sub_phi_term with open(self._JName,"a") as f: f.write(", %10f" % (cumulative_sub_phi)) sub_phi_map[scenario._name] = cumulative_sub_phi phi += cumulative_sub_phi with open(self._JName,"a") as f: for subproblem in subproblems: f.write(", %s" % subproblem) f.write("\n") print("Computed sub-phi values, by scenario:") for scenario_name in sorted(sub_phi_map.keys()): print(" %30s %16e" % (scenario_name, sub_phi_map[scenario_name])) print("") print("Computed phi: %16e" % phi) if phi > 0: tau = 1.0 # this is the over-relaxation parameter - we need to do something more useful denominator = p_unorm*p_unorm + scale_factor*p_vnorm*p_vnorm if self._check_output : print("denominator = " + str(denominator)) theta = phi/denominator print("Computed theta: %16e" % theta) for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: if self._check_output: print("TREE NODE ZS BEFORE: %s" % tree_node._z) print("TREE NODE VS BEFORE: %s" % tree_node._v) tree_node_zs = tree_node._z for variable_id in tree_node._standard_variable_ids: for scenario in tree_node._scenarios: rho_values = scenario._rho[tree_node._name] weight_values = scenario._w[tree_node._name] if self._check_output: print("WEIGHT VALUE PRIOR TO MODIFICATION=",weight_values[variable_id]) print("U VALUE PRIOR TO MODIFICATION=",scenario._u[variable_id]) # print("SUBTRACTING TERM TO Z=%s" % (tau * theta * tree_node._v[variable_id])) tree_node._z[variable_id] -= (tau * theta * scale_factor * tree_node._v[variable_id]) weight_values[variable_id] += (tau * theta * scenario._u[variable_id]) if self._check_output: print("NEW WEIGHT FOR VARIABLE=",variable_id,"FOR SCENARIO=",scenario._name,"EQUALS",weight_values[variable_id]) # print("TREE NODE ZS AFTER: %s" % tree_node._z) elif phi == 0.0: print("***PHI WAS ZERO - NOT DOING ANYTHING - NO MOVES - DOING CHECK BELOW!") pass else: # WE MAY NOT BE SCREWED, BUT WE'LL ASSUME SO FOR NOW. print("***PHI IS NEGATIVE - NOT DOING ANYTHING") if self._check_output: print("Z VALUES:") for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: print("TREE NODE=%s",tree_node._name) print("Zs:",tree_node._z) # CHECK HERE - PHI SHOULD BE 0 AT THIS POINT - THIS IS JUST A CHECK with open(self._JName,"a") as f: f.write("%10d" % (ph._current_iteration)) # the z's have been updated - copy these to PH scenario tree xbar maps, # so they can be correctly transmitted to instances - this plugin is # responsible for xbar updates. for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: for variable_id in tree_node._z: tree_node._xbars[variable_id] = tree_node._z[variable_id] ######################################################################################### # compute the normalizers for unorm and vnorm, now that we have updated w and z values. # ######################################################################################### unorm_normalizer = 0.0 for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: this_node_unorm_normalizer = 0.0 for variable_id in tree_node._standard_variable_ids: this_z_value = tree_node._z[variable_id] this_node_unorm_normalizer += this_z_value**2 unorm_normalizer += tree_node._probability * this_node_unorm_normalizer vnorm_normalizer = 0.0 for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: for scenario in tree_node._scenarios: this_scenario_vnorm_normalizer = 0.0 this_scenario_ws = scenario._w[tree_node._name] for variable_id in tree_node._standard_variable_ids: this_scenario_vnorm_normalizer += this_scenario_ws[variable_id]**2 vnorm_normalizer += scenario._probability * this_scenario_vnorm_normalizer unorm_normalizer = math.sqrt(unorm_normalizer) vnorm_normalizer = math.sqrt(vnorm_normalizer) # print("p_unorm=",p_unorm) # print("p_unorm_normalizer=",unorm_normalizer) # print("p_vnorm=",p_vnorm) # print("p_vnorm_normalizer=",vnorm_normalizer) p_unorm /= unorm_normalizer p_vnorm /= vnorm_normalizer scalarized_norm = math.sqrt(p_unorm*p_unorm + p_vnorm*p_vnorm) print("Computed separator norm: (%e,%e) - scalarized norm=%e" % (p_unorm, p_vnorm, scalarized_norm)) self._converger._last_computed_uv_norm_value = scalarized_norm # if p_unorm < delta and p_vnorm < epsilon: # print("Separator norm dropped below threshold (%e,%e)" % (delta, epsilon)) # return print("") print("Initiating post-projection calculations...") phi = 0.0 sub_phi_to_scenario_map = {} for scenario in ph._scenario_tree._scenarios: cumulative_sub_phi = 0.0 for tree_node in scenario._node_list[:-1]: tree_node_zs = tree_node._z for variable_id in tree_node._standard_variable_ids: var_values = scenario._x[tree_node._name] varval = var_values[variable_id] weight_values = scenario._w[tree_node._name] if not scenario.is_variable_stale(tree_node, variable_id): this_sub_phi_term = scenario._probability * ((tree_node_zs[variable_id] - varval) * (scenario._y[variable_id] + weight_values[variable_id])) cumulative_sub_phi += this_sub_phi_term with open(self._JName,"a") as f: f.write(", %10f" % (cumulative_sub_phi)) if not cumulative_sub_phi in sub_phi_to_scenario_map: sub_phi_to_scenario_map[cumulative_sub_phi] = [] sub_phi_to_scenario_map[cumulative_sub_phi].append(scenario._name) phi += cumulative_sub_phi print("Computed sub-phi values (scenario, phi, iters-since-last-incorporated):") for sub_phi in sorted(sub_phi_to_scenario_map.keys()): print_(" %16e: " % sub_phi, end="") for scenario_name in sub_phi_to_scenario_map[sub_phi]: print("%30s %4d" % (scenario_name, self._total_projection_steps - self._projection_step_of_last_update[scenario_name])) print("") print("Computed phi: %16e" % phi) with open(self._JName,"a") as f: f.write("\n") negative_sub_phis = [sub_phi for sub_phi in sub_phi_to_scenario_map if sub_phi < 0.0] if len(negative_sub_phis) == 0: print("**** YIKES! QUEUING SUBPROBLEMS AT RANDOM****") # TBD - THIS ASSUMES UNIQUE PHIS, WHICH IS NOT ALWAYS THE CASE. all_phis = sub_phi_to_scenario_map.keys() random.shuffle(all_phis) for phi in all_phis[0:ph._async_buffer_length]: scenario_name = sub_phi_to_scenario_map[phi][0] if ph._scenario_tree.contains_bundles(): print("****HERE****") print("SCENARIO=",scenario_name) print("SCENARIO BUNDLE=",self._scenario_tree.get_scenario_bundle(scenario_name)) foobar else: print("Queueing sub-problem=%s" % scenario_name) self._subproblems_to_queue.append(scenario_name) else: if self._queue_only_negative_subphi_subproblems: print("Queueing sub-problems whose scenarios possess the most negative phi values:") else: print("Queueing sub-problems whose scenarios possess the smallest phi values:") sorted_phis = sorted(sub_phi_to_scenario_map.keys()) for phi in sorted_phis[0:ph._async_buffer_length]: if ((self._queue_only_negative_subphi_subproblems) and (phi < 0.0)) or (not self._queue_only_negative_subphi_subproblems): scenario_name = sub_phi_to_scenario_map[phi][0] print_("%30s %16e" % (scenario_name,phi), end="") self._subproblems_to_queue.append(scenario_name) print("") def reset(self, ph): self.__init__() def pre_ph_initialization(self, ph): """Called before PH initialization""" pass def post_instance_creation(self, ph): """Called after the instances have been created""" with open(self._JName,"w") as f: f.write("Phi Summary; generally two lines per iteration\n") f.write("Iteration ") for scenario in ph._scenario_tree._scenarios: f.write(", %10s" % (scenario._name)) f.write(", Subproblems Returned") f.write("\n") def post_ph_initialization(self, ph): """Called after PH initialization""" # IMPORTANT: if the Eckstein-Combettes extension plugin is enabled, # then make sure PH is in async mode - otherwise, nothing # will work! if not ph._async_mode: raise RuntimeError("PH is not in async mode - this is required for the Eckstein-Combettes extension") self._total_projection_steps = 0 for scenario in ph._scenario_tree._scenarios: self._projection_step_of_last_update[scenario._name] = 0 # NOTE: we don't yet have a good way to get keyword options into # plugins - so this is mildy hack-ish. more hackish, but # useful, would be to extract the value from an environment # variable - similar to what is done in the bounds extension. # the convergence threshold should obviously be parameterized self._converger = EcksteinCombettesConverger(convergence_threshold=1e-5) ph._convergers.append(self._converger) ########################################################## # the following callbacks are specific to synchronous PH # ########################################################## def post_iteration_0_solves(self, ph): """Called after the iteration 0 solves""" # we want the PH estimates of the weights initially, but we'll compute them afterwards. ph._ph_weight_updates_enabled = False # we will also handle xbar updates (z). ph._ph_xbar_updates_enabled = False def post_iteration_0(self, ph): """Called after the iteration 0 solves, averages computation, and weight computation""" print("POST ITERATION 0 CALLBACK") # define y and u parameters for each non-leaf variable in each scenario. print("****ADDING Y, U, V, and Z PARAMETERS") for scenario in ph._scenario_tree._scenarios: scenario._y = {} scenario._u = {} # instance = scenario._instance for tree_node in scenario._node_list[:-1]: nodal_index_set = tree_node._standard_variable_ids assert nodal_index_set is not None scenario._y.update((variable_id, 0.0) for variable_id in nodal_index_set) scenario._u.update((variable_id, 0.0) for variable_id in nodal_index_set) # print "YS AFTER UPDATE:",scenario._y # define v and z parameters for each non-leaf variable in the tree. for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: nodal_index_set = tree_node._standard_variable_ids assert nodal_index_set is not None tree_node._v = dict((i,0) for i in nodal_index_set) tree_node._z = dict((i,tree_node._averages[i]) for i in nodal_index_set) # copy z to xbar in the scenario tree, as we've told PH we will be taking care of it. for stage in ph._scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: nodal_index_set = tree_node._standard_variable_ids assert nodal_index_set is not None tree_node._xbars = dict((i,tree_node._z[i]) for i in nodal_index_set) # mainly to set up data structures. for subproblem in ph._scenario_tree.subproblems: self.asynchronous_pre_scenario_queue(ph, subproblem.name) # pick subproblems at random - we need a number equal to the async buffer length, # although we need all of them initially (PH does - not this particular plugin). async_buffer_length = ph._async_buffer_length all_subproblems = [subproblem.name for subproblem in ph._scenario_tree.subproblems] random.shuffle(all_subproblems) self._subproblems_to_queue = all_subproblems[0:ph._async_buffer_length] def pre_iteration_k_solves(self, ph): """Called before each iteration k solve""" pass def post_iteration_k_solves(self, ph): """Called after the iteration k solves""" pass def post_iteration_k(self, ph): """Called after the iteration k is finished""" pass ########################################################## ########################################################### # the following callbacks are specific to asynchronous PH # ########################################################### def pre_asynchronous_solves(self, ph): """Called before the asynchronous solve loop is executed""" pass def asynchronous_pre_scenario_queue(self, ph, subproblem_name): """Called right before each subproblem solve is been queued""" scenarios_to_process = [] if ph._scenario_tree.contains_bundles(): for scenario_name in ph._scenario_tree.get_bundle(subproblem_name).scenario_names: scenarios_to_process.append(ph._scenario_tree.get_scenario(scenario_name)) else: scenarios_to_process.append(ph._scenario_tree.get_scenario(subproblem_name)) # we need to cache the z and w that were used when solving the input scenario. for scenario in scenarios_to_process: scenario._xbars_for_solve = {} for tree_node in scenario._node_list[:-1]: scenario._xbars_for_solve[tree_node._name] = dict((k,v) for k,v in iteritems(tree_node._z)) scenario._ws_for_solve = {} for tree_node in scenario._node_list[:-1]: scenario._ws_for_solve[tree_node._name] = dict((k,v) for k,v in iteritems(scenario._w[tree_node._name])) def post_asynchronous_var_w_update(self, ph, subproblems, scenario_solve_counts): """Called after a batch of asynchronous sub-problems are solved and corresponding statistics are updated""" print("") print("Computing updates in Eckstein-Combettes extension") self.compute_updates(ph, subproblems, scenario_solve_counts) def post_asynchronous_solves(self, ph): """Called after the asynchronous solve loop is executed""" pass def asynchronous_subproblems_to_queue(self, ph): """Called after subproblems within buffer length window have been processed""" result = self._subproblems_to_queue self._subproblems_to_queue = [] return result ########################################################### def post_ph_execution(self, ph): """Called after PH has terminated""" pass
[ "jsiirola@users.noreply.github.com" ]
jsiirola@users.noreply.github.com
dfea669c4519269a2654b492fe8a992552b69e3a
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/python/scipy/py2/scipy/optimize/tests/test__basinhopping.py
84deeb847253a4b53ed032c0aaecd9b4a43171a0
[ "Python-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "Qhull", "BSD-3-Clause", "Apache-2.0", "BSD-2-Clause" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
Python
false
false
15,398
py
""" Unit tests for the basin hopping global minimization algorithm. """ from __future__ import division, print_function, absolute_import import copy from numpy.testing import assert_almost_equal, assert_equal, assert_ from pytest import raises as assert_raises import numpy as np from numpy import cos, sin from scipy.optimize import basinhopping, OptimizeResult from scipy.optimize._basinhopping import ( Storage, RandomDisplacement, Metropolis, AdaptiveStepsize) def func1d(x): f = cos(14.5 * x - 0.3) + (x + 0.2) * x df = np.array(-14.5 * sin(14.5 * x - 0.3) + 2. * x + 0.2) return f, df def func2d_nograd(x): f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0] return f def func2d(x): f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0] df = np.zeros(2) df[0] = -14.5 * sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2 df[1] = 2. * x[1] + 0.2 return f, df def func2d_easyderiv(x): f = 2.0*x[0]**2 + 2.0*x[0]*x[1] + 2.0*x[1]**2 - 6.0*x[0] df = np.zeros(2) df[0] = 4.0*x[0] + 2.0*x[1] - 6.0 df[1] = 2.0*x[0] + 4.0*x[1] return f, df class MyTakeStep1(RandomDisplacement): """use a copy of displace, but have it set a special parameter to make sure it's actually being used.""" def __init__(self): self.been_called = False super(MyTakeStep1, self).__init__() def __call__(self, x): self.been_called = True return super(MyTakeStep1, self).__call__(x) def myTakeStep2(x): """redo RandomDisplacement in function form without the attribute stepsize to make sure everything still works ok """ s = 0.5 x += np.random.uniform(-s, s, np.shape(x)) return x class MyAcceptTest(object): """pass a custom accept test This does nothing but make sure it's being used and ensure all the possible return values are accepted """ def __init__(self): self.been_called = False self.ncalls = 0 self.testres = [False, 'force accept', True, np.bool_(True), np.bool_(False), [], {}, 0, 1] def __call__(self, **kwargs): self.been_called = True self.ncalls += 1 if self.ncalls - 1 < len(self.testres): return self.testres[self.ncalls - 1] else: return True class MyCallBack(object): """pass a custom callback function This makes sure it's being used. It also returns True after 10 steps to ensure that it's stopping early. """ def __init__(self): self.been_called = False self.ncalls = 0 def __call__(self, x, f, accepted): self.been_called = True self.ncalls += 1 if self.ncalls == 10: return True class TestBasinHopping(object): def setup_method(self): """ Tests setup. Run tests based on the 1-D and 2-D functions described above. """ self.x0 = (1.0, [1.0, 1.0]) self.sol = (-0.195, np.array([-0.195, -0.1])) self.tol = 3 # number of decimal places self.niter = 100 self.disp = False # fix random seed np.random.seed(1234) self.kwargs = {"method": "L-BFGS-B", "jac": True} self.kwargs_nograd = {"method": "L-BFGS-B"} def test_TypeError(self): # test the TypeErrors are raised on bad input i = 1 # if take_step is passed, it must be callable assert_raises(TypeError, basinhopping, func2d, self.x0[i], take_step=1) # if accept_test is passed, it must be callable assert_raises(TypeError, basinhopping, func2d, self.x0[i], accept_test=1) def test_1d_grad(self): # test 1d minimizations with gradient i = 0 res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs, niter=self.niter, disp=self.disp) assert_almost_equal(res.x, self.sol[i], self.tol) def test_2d(self): # test 2d minimizations with gradient i = 1 res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, niter=self.niter, disp=self.disp) assert_almost_equal(res.x, self.sol[i], self.tol) assert_(res.nfev > 0) def test_njev(self): # test njev is returned correctly i = 1 minimizer_kwargs = self.kwargs.copy() # L-BFGS-B doesn't use njev, but BFGS does minimizer_kwargs["method"] = "BFGS" res = basinhopping(func2d, self.x0[i], minimizer_kwargs=minimizer_kwargs, niter=self.niter, disp=self.disp) assert_(res.nfev > 0) assert_equal(res.nfev, res.njev) def test_jac(self): # test jacobian returned minimizer_kwargs = self.kwargs.copy() # BFGS returns a Jacobian minimizer_kwargs["method"] = "BFGS" res = basinhopping(func2d_easyderiv, [0.0, 0.0], minimizer_kwargs=minimizer_kwargs, niter=self.niter, disp=self.disp) assert_(hasattr(res.lowest_optimization_result, "jac")) # in this case, the jacobian is just [df/dx, df/dy] _, jacobian = func2d_easyderiv(res.x) assert_almost_equal(res.lowest_optimization_result.jac, jacobian, self.tol) def test_2d_nograd(self): # test 2d minimizations without gradient i = 1 res = basinhopping(func2d_nograd, self.x0[i], minimizer_kwargs=self.kwargs_nograd, niter=self.niter, disp=self.disp) assert_almost_equal(res.x, self.sol[i], self.tol) def test_all_minimizers(self): # test 2d minimizations with gradient. Nelder-Mead, Powell and COBYLA # don't accept jac=True, so aren't included here. i = 1 methods = ['CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP'] minimizer_kwargs = copy.copy(self.kwargs) for method in methods: minimizer_kwargs["method"] = method res = basinhopping(func2d, self.x0[i], minimizer_kwargs=minimizer_kwargs, niter=self.niter, disp=self.disp) assert_almost_equal(res.x, self.sol[i], self.tol) def test_all_nograd_minimizers(self): # test 2d minimizations without gradient. Newton-CG requires jac=True, # so not included here. i = 1 methods = ['CG', 'BFGS', 'L-BFGS-B', 'TNC', 'SLSQP', 'Nelder-Mead', 'Powell', 'COBYLA'] minimizer_kwargs = copy.copy(self.kwargs_nograd) for method in methods: minimizer_kwargs["method"] = method res = basinhopping(func2d_nograd, self.x0[i], minimizer_kwargs=minimizer_kwargs, niter=self.niter, disp=self.disp) tol = self.tol if method == 'COBYLA': tol = 2 assert_almost_equal(res.x, self.sol[i], decimal=tol) def test_pass_takestep(self): # test that passing a custom takestep works # also test that the stepsize is being adjusted takestep = MyTakeStep1() initial_step_size = takestep.stepsize i = 1 res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, niter=self.niter, disp=self.disp, take_step=takestep) assert_almost_equal(res.x, self.sol[i], self.tol) assert_(takestep.been_called) # make sure that the built in adaptive step size has been used assert_(initial_step_size != takestep.stepsize) def test_pass_simple_takestep(self): # test that passing a custom takestep without attribute stepsize takestep = myTakeStep2 i = 1 res = basinhopping(func2d_nograd, self.x0[i], minimizer_kwargs=self.kwargs_nograd, niter=self.niter, disp=self.disp, take_step=takestep) assert_almost_equal(res.x, self.sol[i], self.tol) def test_pass_accept_test(self): # test passing a custom accept test # makes sure it's being used and ensures all the possible return values # are accepted. accept_test = MyAcceptTest() i = 1 # there's no point in running it more than a few steps. basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, niter=10, disp=self.disp, accept_test=accept_test) assert_(accept_test.been_called) def test_pass_callback(self): # test passing a custom callback function # This makes sure it's being used. It also returns True after 10 steps # to ensure that it's stopping early. callback = MyCallBack() i = 1 # there's no point in running it more than a few steps. res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, niter=30, disp=self.disp, callback=callback) assert_(callback.been_called) assert_("callback" in res.message[0]) assert_equal(res.nit, 10) def test_minimizer_fail(self): # test if a minimizer fails i = 1 self.kwargs["options"] = dict(maxiter=0) self.niter = 10 res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs, niter=self.niter, disp=self.disp) # the number of failed minimizations should be the number of # iterations + 1 assert_equal(res.nit + 1, res.minimization_failures) def test_niter_zero(self): # gh5915, what happens if you call basinhopping with niter=0 i = 0 basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs, niter=0, disp=self.disp) def test_seed_reproducibility(self): # seed should ensure reproducibility between runs minimizer_kwargs = {"method": "L-BFGS-B", "jac": True} f_1 = [] def callback(x, f, accepted): f_1.append(f) basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs, niter=10, callback=callback, seed=10) f_2 = [] def callback2(x, f, accepted): f_2.append(f) basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs, niter=10, callback=callback2, seed=10) assert_equal(np.array(f_1), np.array(f_2)) def test_monotonic_basin_hopping(self): # test 1d minimizations with gradient and T=0 i = 0 res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs, niter=self.niter, disp=self.disp, T=0) assert_almost_equal(res.x, self.sol[i], self.tol) class Test_Storage(object): def setup_method(self): self.x0 = np.array(1) self.f0 = 0 minres = OptimizeResult() minres.x = self.x0 minres.fun = self.f0 self.storage = Storage(minres) def test_higher_f_rejected(self): new_minres = OptimizeResult() new_minres.x = self.x0 + 1 new_minres.fun = self.f0 + 1 ret = self.storage.update(new_minres) minres = self.storage.get_lowest() assert_equal(self.x0, minres.x) assert_equal(self.f0, minres.fun) assert_(not ret) def test_lower_f_accepted(self): new_minres = OptimizeResult() new_minres.x = self.x0 + 1 new_minres.fun = self.f0 - 1 ret = self.storage.update(new_minres) minres = self.storage.get_lowest() assert_(self.x0 != minres.x) assert_(self.f0 != minres.fun) assert_(ret) class Test_RandomDisplacement(object): def setup_method(self): self.stepsize = 1.0 self.displace = RandomDisplacement(stepsize=self.stepsize) self.N = 300000 self.x0 = np.zeros([self.N]) def test_random(self): # the mean should be 0 # the variance should be (2*stepsize)**2 / 12 # note these tests are random, they will fail from time to time x = self.displace(self.x0) v = (2. * self.stepsize) ** 2 / 12 assert_almost_equal(np.mean(x), 0., 1) assert_almost_equal(np.var(x), v, 1) class Test_Metropolis(object): def setup_method(self): self.T = 2. self.met = Metropolis(self.T) def test_boolean_return(self): # the return must be a bool. else an error will be raised in # basinhopping ret = self.met(f_new=0., f_old=1.) assert isinstance(ret, bool) def test_lower_f_accepted(self): assert_(self.met(f_new=0., f_old=1.)) def test_KeyError(self): # should raise KeyError if kwargs f_old or f_new is not passed assert_raises(KeyError, self.met, f_old=1.) assert_raises(KeyError, self.met, f_new=1.) def test_accept(self): # test that steps are randomly accepted for f_new > f_old one_accept = False one_reject = False for i in range(1000): if one_accept and one_reject: break ret = self.met(f_new=1., f_old=0.5) if ret: one_accept = True else: one_reject = True assert_(one_accept) assert_(one_reject) def test_GH7495(self): # an overflow in exp was producing a RuntimeWarning # create own object here in case someone changes self.T met = Metropolis(2) with np.errstate(over='raise'): met.accept_reject(0, 2000) class Test_AdaptiveStepsize(object): def setup_method(self): self.stepsize = 1. self.ts = RandomDisplacement(stepsize=self.stepsize) self.target_accept_rate = 0.5 self.takestep = AdaptiveStepsize(takestep=self.ts, verbose=False, accept_rate=self.target_accept_rate) def test_adaptive_increase(self): # if few steps are rejected, the stepsize should increase x = 0. self.takestep(x) self.takestep.report(False) for i in range(self.takestep.interval): self.takestep(x) self.takestep.report(True) assert_(self.ts.stepsize > self.stepsize) def test_adaptive_decrease(self): # if few steps are rejected, the stepsize should increase x = 0. self.takestep(x) self.takestep.report(True) for i in range(self.takestep.interval): self.takestep(x) self.takestep.report(False) assert_(self.ts.stepsize < self.stepsize) def test_all_accepted(self): # test that everything works OK if all steps were accepted x = 0. for i in range(self.takestep.interval + 1): self.takestep(x) self.takestep.report(True) assert_(self.ts.stepsize > self.stepsize) def test_all_rejected(self): # test that everything works OK if all steps were rejected x = 0. for i in range(self.takestep.interval + 1): self.takestep(x) self.takestep.report(False) assert_(self.ts.stepsize < self.stepsize)
[ "arcadia-devtools@yandex-team.ru" ]
arcadia-devtools@yandex-team.ru
a794b38e5b1c9bc25dfef36a9d955d9cf54a7d8b
2f0aa66e14c6595289f6a0de2bdf71e9922052a7
/nextApi/user/migrations/0003_auto_20200818_2008.py
6d6e0a8b8d3ab39d197ff070024c08b0dd3e56ff
[]
no_license
aimethierry/NextApi
8f83a2b0f499fdf5118eb930baa051584cfd9aa5
90884ee6d900ce71116b40276dda0e97bec0b521
refs/heads/master
2022-12-11T09:03:54.981284
2020-09-19T12:40:36
2020-09-19T12:40:36
296,866,571
0
0
null
null
null
null
UTF-8
Python
false
false
943
py
# Generated by Django 3.1 on 2020-08-18 18:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0002_companyacc'), ] operations = [ migrations.AddField( model_name='companyacc', name='email', field=models.CharField(blank=True, max_length=120, null=True), ), migrations.AddField( model_name='companyacc', name='password', field=models.CharField(blank=True, max_length=120, null=True), ), migrations.AddField( model_name='companyacc', name='usesrname', field=models.CharField(blank=True, max_length=120, null=True), ), migrations.AlterField( model_name='companyacc', name='company', field=models.CharField(blank=True, max_length=120, null=True), ), ]
[ "aime.thierry97@gmail.com" ]
aime.thierry97@gmail.com
803331d02c81b15dd9eeeb88fb58de707d4c9897
287c663c97e7840239794fbe84ce285773b72985
/virtual/bin/mako-render
ff06d7a97fb70f3f26a64dd2325bf6138e8c7d31
[ "MIT" ]
permissive
mzazakeith/flask-blog
ea8e5b2da9a581eb026564c1b9e500fa0532ee88
2833404cc5e96ffdbfb767f35b9caf2bdcce7997
refs/heads/master
2020-03-21T21:24:57.296282
2018-07-02T20:20:24
2018-07-02T20:20:24
139,062,052
0
0
null
null
null
null
UTF-8
Python
false
false
253
#!/home/mzaza/Desktop/flask_blog/virtual/bin/python3.6 # -*- coding: utf-8 -*- import re import sys from mako.cmd import cmdline if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(cmdline())
[ "mzazakeith@gmail.com" ]
mzazakeith@gmail.com
e650793603ccf2cefac008d1c76270721b8d1367
57061e611a549f9afe4f5201730a85d76a7e505f
/setup.py
5323723ba2f8215b16c769148b156602f63760fc
[ "MIT" ]
permissive
briostack/chrome-printtopdf
35ee5da836878107f7586a7e61f1adf6b7d8c4cb
6b4f91ab50cbc3570c27cfd8511f3964387c356e
refs/heads/master
2022-03-08T14:58:51.843698
2022-03-01T22:32:14
2022-03-01T22:32:14
94,803,813
1
0
null
2017-06-19T17:38:03
2017-06-19T17:38:03
null
UTF-8
Python
false
false
1,069
py
#!/usr/bin/env python from __future__ import print_function import os import codecs from setuptools import setup, find_packages def read(*parts): filename = os.path.join(os.path.dirname(__file__), *parts) with codecs.open(filename, encoding='utf-8') as fp: return fp.read() setup( name="chrome-printtopdf", version='0.0.2', url='https://github.com/stefanw/chrome-printtopdf', license='MIT', description="Get PDFs from URLs using chrome", long_description=read('README.md'), author='Stefan Wehrmeyer', author_email='mail@stefanwehrmeyer.com', packages=find_packages(), install_requires=['aiohttp'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities', ] )
[ "mail@stefanwehrmeyer.com" ]
mail@stefanwehrmeyer.com
4020c3b3e7e7165b0196c1585615c9b95e9e33fd
11211916f39b9d98027b64d778e52743d0c519a1
/L3/tmp/assignments/outline.py
e7bba9d3d9acf2c3e969914fff659f06fe1cd781
[]
no_license
mantasruigys3000/Group-Task
87baf1bc2747323c0508f6f32ef733c3f4b50978
6790d74ae7fa0fe6b13733efcd75a9f4aca70ab0
refs/heads/master
2020-04-23T20:54:09.696659
2019-02-22T01:29:53
2019-02-22T01:29:53
171,454,102
0
0
null
2019-02-19T10:31:09
2019-02-19T10:31:08
null
UTF-8
Python
false
false
343
py
Amet velit etincidunt porro est quaerat etincidunt. Velit ut velit dolor consectetur est dolor. Voluptatem quisquam quiquia quisquam sed ut. Non voluptatem voluptatem etincidunt. Username: Marcus Password: titten Dolorem velit labore velit amet ipsum ipsum adipisci. Quaerat labore est dolore quaerat aliquam. Amet sit consectetur labore sed.
[ "mantasruigys101@gmail.com" ]
mantasruigys101@gmail.com
d205eeabe1230372e52454c55429cccf3659b362
614cad3588af9c0e51e0bb98963075e3195e92f5
/utils/completeness.py
bd6b0845fa36983abbad225f1ed473385db12e64
[]
no_license
dragonlong/haoi-pose
2810dae7f9afd0a26b3d0a5962fd9ae8a5abac58
43388efd911feecde588b27a753de353b8e28265
refs/heads/master
2023-07-01T14:18:29.029484
2021-08-10T10:57:42
2021-08-10T10:57:42
294,602,794
0
0
null
null
null
null
UTF-8
Python
false
false
3,738
py
import argparse import os import torch import numpy as np from scipy.spatial import cKDTree as KDTree import trimesh import glob from joblib import Parallel, delayed def directed_hausdorff(point_cloud1:torch.Tensor, point_cloud2:torch.Tensor, reduce_mean=True): """ :param point_cloud1: (B, 3, N) :param point_cloud2: (B, 3, M) :return: directed hausdorff distance, A -> B """ n_pts1 = point_cloud1.shape[2] n_pts2 = point_cloud2.shape[2] pc1 = point_cloud1.unsqueeze(3) pc1 = pc1.repeat((1, 1, 1, n_pts2)) # (B, 3, N, M) pc2 = point_cloud2.unsqueeze(2) pc2 = pc2.repeat((1, 1, n_pts1, 1)) # (B, 3, N, M) l2_dist = torch.sqrt(torch.sum((pc1 - pc2) ** 2, dim=1)) # (B, N, M) shortest_dist, _ = torch.min(l2_dist, dim=2) hausdorff_dist, _ = torch.max(shortest_dist, dim=1) # (B, ) if reduce_mean: hausdorff_dist = torch.mean(hausdorff_dist) return hausdorff_dist def nn_distance(query_points, ref_points): ref_points_kd_tree = KDTree(ref_points) one_distances, one_vertex_ids = ref_points_kd_tree.query(query_points) return one_distances def completeness(query_points, ref_points, thres=0.03): a2b_nn_distance = nn_distance(query_points, ref_points) percentage = np.sum(a2b_nn_distance < thres) / len(a2b_nn_distance) return percentage def process_one(shape_dir): # load generated shape pc_paths = glob.glob(os.path.join(shape_dir, "fake-z*.ply")) pc_paths = sorted(pc_paths) gen_pcs = [] for path in pc_paths: sample_pts = trimesh.load(path) sample_pts = np.asarray(sample_pts.vertices) # sample_pts = torch.tensor(sample_pts.vertices).transpose(1, 0) gen_pcs.append(sample_pts) # load partial input partial_path = os.path.join(shape_dir, "raw.ply") partial_pc = trimesh.load(partial_path) partial_pc = np.asarray(partial_pc.vertices) # partial_pc = torch.tensor(partial_pc.vertices).transpose(1, 0) # completeness percentage gen_comp = 0 for sample_pts in gen_pcs: comp = completeness(partial_pc, sample_pts) gen_comp += comp gen_comp = gen_comp / len(gen_pcs) # unidirectional hausdorff gen_pcs = [torch.tensor(pc).transpose(1, 0) for pc in gen_pcs] gen_pcs = torch.stack(gen_pcs, dim=0) partial_pc = torch.tensor(partial_pc).transpose(1, 0) partial_pc = partial_pc.unsqueeze(0).repeat((gen_pcs.size(0), 1, 1)) hausdorff = directed_hausdorff(partial_pc, gen_pcs, reduce_mean=True).item() return gen_comp, hausdorff def func(args): shape_names = sorted(os.listdir(args.src)) all_shape_dir = [os.path.join(args.src, name) for name in shape_names] results = Parallel(n_jobs=args.process, verbose=2)(delayed(process_one)(path) for path in all_shape_dir) res_comp, res_hausdorff = zip(*results) res_comp = np.mean(res_comp) res_hausdorff = np.mean(res_hausdorff) return res_hausdorff, res_comp def main(): parser = argparse.ArgumentParser() parser.add_argument("--src", type=str) parser.add_argument("-p", "--process", type=int, default=10) parser.add_argument("-o", "--output", type=str) args = parser.parse_args() if args.output is None: args.output = args.src + '-eval_UHD.txt' res_hausdorff, res_comp = func(args) print("Avg Unidirectional Hausdorff Distance: {}".format(res_hausdorff)) print("Avg Completeness: {}".format(res_comp)) with open(args.output, "a") as fp: fp.write("SRC: {}\n".format(args.src)) fp.write("Avg Unidirectional Hausdorff Distance: {}\n".format(res_hausdorff)) fp.write("Avg Completeness: {}\n".format(res_comp)) if __name__ == '__main__': main()
[ "lxiaol9@vt.edu" ]
lxiaol9@vt.edu
3a471239801b8078837935c47ac052742afca2fb
0e61a484a3a4fc61fe2b660e25fad5744232773b
/avx2-hps4096821/bitpermutations/applications/squaring_mod_GF2N.py
993a88bdda647d86ccc7491da1dc512403d8093f
[ "CC0-1.0" ]
permissive
OussamaDanba/ntru
3278dae5bd18ddc9d93acb9eb4221bfec3e7ca06
da413076b3b0fb377c3174c331462c3293193580
refs/heads/master
2020-04-24T08:17:40.665914
2019-08-31T17:11:35
2019-08-31T17:11:35
171,826,066
0
0
CC0-1.0
2019-02-21T07:55:03
2019-02-21T07:55:01
Python
UTF-8
Python
false
false
11,740
py
from bitpermutations.data import (ONE, ZERO, Register, Mask, IndicesMask, MaskRegister, AllocationError) import bitpermutations.instructions as x86 from bitpermutations.printing import print_memfunc from bitpermutations.utils import reg_to_memfunc, split_in_size_n import argparse import functools from collections import OrderedDict def gen_sequence(e, N): def interleave(seq): if len(seq) % 2 == 0: return [x for t in zip(seq[:len(seq) // 2], seq[len(seq) // 2:]) for x in t] else: return ([x for t in zip(seq[:len(seq) // 2], seq[len(seq) // 2 + 1:]) for x in t] + [seq[len(seq) // 2]]) seq = list(range(N)) for i in range(e): seq = interleave(seq) return seq def registers_to_sequence(registers): result = sum((x.value for x in registers), []) while result[-1] is ZERO: result.pop() if not result: break return result def square_821_patience(out_data, in_data, n, callee_saved=0): x = list(range(821)) + 203*[ZERO] regs = split_in_size_n(x, 64) seq = gen_sequence(n, 821) + 203*[ZERO] seq_r = split_in_size_n(seq, 64) moved = [False] * len(seq_r) r = Register(64) t1 = Register(64) for i in range(callee_saved): x86.push_callee_saved(64) maskcache = OrderedDict() def mask_to_register(mask): mask = Mask.as_immediate(mask) if mask in maskcache: maskcache.move_to_end(mask) return maskcache[mask] try: maskreg = MaskRegister(64, mask) except AllocationError: _, maskreg = maskcache.popitem(False) x86.mov(maskreg, mask) maskcache[mask] = maskreg return maskreg for j, inreg in enumerate(regs): x86.mov(r, in_data[j]) for i, seqreg in enumerate(seq_r): piledict = {} for rotation in range(64): ror_seqreg = seqreg[rotation:] + seqreg[:rotation] piles = [] overlap = [x for x in ror_seqreg if x in inreg and x != ZERO] for x in overlap: for pile in piles: try: if pile[-1] <= x: pile.append(x) break except IndexError: # pile is empty pass else: # doesn't fit on any existing pile: start a new pile piles.append([x]) piledict[rotation] = piles min_pile_key = min(piledict, key=lambda x: len(piledict.get(x))) if len(piledict[0]) == len(piledict[min_pile_key]): min_pile_key = 0 if min_pile_key > 0: ror_seqreg = seqreg[min_pile_key:] + seqreg[:min_pile_key] else: ror_seqreg = seqreg for pile in piledict[min_pile_key]: emask = [ZERO] * 64 for bit in pile: emask[inreg.index(bit)] = ONE dmask = [ZERO] * 64 for bit in pile: dmask[ror_seqreg.index(bit)] = ONE # For consecutive bits, we do not even need pext/pdep if (Mask.consec(dmask) and Mask.consec(emask) and (Mask.degree(emask) < 32 or Mask.degree(dmask) < 32)): delta = (Mask.degree(dmask) - Mask.degree(emask)) % 64 x86.mov(t1, r) if Mask.degree(emask) < 32: x86.iand(t1, Mask.as_immediate(emask)) x86.rol(t1, delta + min_pile_key) min_pile_key = 0 # to avoid two rols else: x86.rol(t1, delta) x86.iand(t1, Mask.as_immediate(dmask)) else: # if we can extract using AND instead.. if Mask.consec(emask, True) and Mask.degree(emask) < 32: x86.mov(t1, r) x86.iand(t1, Mask.as_immediate(emask)) else: x86.pext(t1, r, mask_to_register(emask)) x86.pdep(t1, t1, mask_to_register(dmask)) if min_pile_key > 0: x86.rol(t1, min_pile_key) if moved[i]: # stored per i, as it's not the outer loop x86.xor(out_data[i], t1) else: x86.mov(out_data[i], t1) moved[i] = True x86.movq(out_data[13], 0) # to fill up all 1024 bits x86.movq(out_data[14], 0) # to fill up all 1024 bits x86.movq(out_data[15], 0) # to fill up all 1024 bits for mask in maskcache.values(): mask.free() for i in range(callee_saved): x86.pop_callee_saved(64) def square_821_shufbytes(out_data, in_data, n): r = Register() out = [Register() for _ in range(4)] moved = [False] * 4 t1 = Register() t2 = Register() t3 = Register() t4 = Register() t5 = Register() seq = gen_sequence(n, 821) + 203*[ZERO] seq_regvalues = split_in_size_n(seq, 256) for in_data_fragment in in_data: x86.vmovdqa(r, in_data_fragment) shift_in = shifted = r offset = 0 for delta in range(8): # 8 possible rotations may be necessary rol_meta = None if delta > 0: # if we've made the previous rotation persistent if shift_in is shifted: shifted = t4 if shifted is t3 else t3 d_nett = delta - offset rol_meta = len(x86.INSTRUCTIONS), str(shifted), str(t1) x86.macro_v256rol(shifted, shift_in, d_nett, t1, t2) rotated = [b for d in range(d_nett) for b in shifted[d::64]] # vpshufb cannot cross over xmm lanes for swap_xmms in [False, True]: if swap_xmms: swapped = t5 x86.vpermq(swapped, shifted, '01001110') else: swapped = shifted r_bytes = split_in_size_n(swapped, 8) while True: # could be necessary to extract twice from same r bitmask = [[] for _ in range(len(seq_regvalues))] shufmask = [None] * 32 for k, seq_value in enumerate(seq_regvalues): s_bytes = split_in_size_n(seq_value, 8) s_xmms = split_in_size_n(s_bytes, 16) r_xmms = split_in_size_n(r_bytes, 16) for i, (s128, r128) in enumerate(zip(s_xmms, r_xmms)): for l, s_byte in enumerate(s128): for m, r_byte in enumerate(r128): # if this byte is already taken; if (shufmask[i*16 + l] is not None and shufmask[i*16 + l] != m): continue bits = [ONE if x == y and x != ZERO else ZERO for x, y in zip(r_byte, s_byte)] if ONE not in bits: continue shufmask[i*16 + l] = m bitmask[k] += bits break else: bitmask[k] += [ZERO] * 8 continue for m, (x, y) in enumerate(zip(bits, s_byte)): if x == ONE: seq_regvalues[k][i*128+l*8 + m] = None s_bytes = split_in_size_n(seq_regvalues[k], 8) if all(x is None for x in shufmask): break x86.vpshufb(t2, swapped, IndicesMask(shufmask)) for k, seq_value in enumerate(seq_regvalues): if ONE not in bitmask[k]: continue if not moved[k]: x86.vpand(out[k], t2, Mask(bitmask[k])) moved[k] = True else: x86.vpand(t1, t2, Mask(bitmask[k])) x86.vpxor(out[k], out[k], t1) # check if we used any of the rotated bits for maskbit, bit in zip(bitmask[k], t2): if delta > 0 and bit in rotated and maskbit is ONE: rol_meta = None # TODO this is an ugly hack that should be abstracted if rol_meta is not None: i, dest, temp = rol_meta del x86.INSTRUCTIONS[i] # delete srlq x86.INSTRUCTIONS[i] = x86.INSTRUCTIONS[i].replace(temp, dest) del x86.INSTRUCTIONS[i+1] # delete permq del x86.INSTRUCTIONS[i+1] # delete xor else: # if we're keeping the rotation, make it persistent so that the # next rotation is smaller (and thus more likely ignorable) shift_in = shifted offset = delta for m, r in zip(out_data, out): x86.vmovdqa(m, r) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Output squaring routines.') parser.add_argument('no_of_squarings', type=int, help='the number of repeated squarings') parser.add_argument('--callee', type=int, dest='callee', default=0, help='the number of callee-saved registers to save') parser.add_argument('--patience', dest='patience', action='store_true', help='always use the patience-sort method') parser.add_argument('--shufbytes', dest='shufbytes', action='store_true', help='always use the shufbytes method') parser.add_argument('--raw-name', dest='raw_name', action='store_true', help='use minimal function name (square_N_821)') parser.set_defaults(patience=False) args = parser.parse_args() if args.shufbytes: f = functools.partial(square_821_shufbytes, n=args.no_of_squarings) if args.raw_name: f.__name__ = "square_{}_821".format(args.no_of_squarings) else: f.__name__ = "square_{}_821_shufbytes".format(args.no_of_squarings) print_memfunc(f, 4, 4, initialize=True) elif args.patience: f = functools.partial(square_821_patience, n=args.no_of_squarings, callee_saved=args.callee) if args.raw_name: f.__name__ = "square_{}_821".format(args.no_of_squarings) else: f.__name__ = "square_{}_821_patience".format(args.no_of_squarings) print_memfunc(f, 16, 16, per_reg=64) elif args.no_of_squarings in permutations: f = permutations[args.no_of_squarings] print_memfunc(f, 4, 4) else: raise NotImplementedError( "There is no dedicated implementation for {} squarings. " "Please specify either --shufbytes or --patience." .format(args.no_of_squarings) )
[ "jschanck@uwaterloo.ca" ]
jschanck@uwaterloo.ca
d1e535da617f09a037448c3df23b3b182bcedd53
c0578b14ebaef889ffc75551ebcc7e5c80b6069e
/src/811_subdomain_visit_count.py
87eb66cd63973d2c0ce2d010c3afb1f86145ce1f
[]
no_license
BrianQcq/LeetCode
88ee122aa2b358c61d6980c159008e8ccac6cc8c
127ca7d82fa15214da8d5e9fbc461831cdb6b60b
refs/heads/master
2020-06-10T04:20:33.798787
2019-11-12T07:56:58
2019-11-12T07:56:58
193,580,067
1
0
null
null
null
null
UTF-8
Python
false
false
326
py
class Solution(object): def subdomainVisit(self, cpdomains): d = {} for item in cpdomains: n, domains = item.split() n, domains = int(n), domains.split('.') for i in range(len(domains)): temp = '.'.join(domains[i:]) d[temp] = d[temp] + n if temp in d else n return [str(d[i]) + ' ' + i for i in d]
[ "qiuchuanqin@gmail.com" ]
qiuchuanqin@gmail.com
40b606a75f2a3ea6ee7f290d627b798e157e9894
2b31366107bd56244564c196c852f39ff024e278
/example.py
095c2818d3c45494ec74d905b086705256aa66a9
[ "BSD-3-Clause" ]
permissive
toastdriven/pubsubittyhub
444a7b0d5b26abf0a1cd820d3d57a1d92346a4c4
8d3a0b135b0a284f52234c06cfc586cc5e6f5c6d
refs/heads/master
2020-05-05T01:39:51.073435
2009-12-17T09:22:31
2009-12-17T09:22:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
842
py
import urllib2 import sys from urllib import urlencode try: import json except ImportError: import simplejson as json print 'Testing index...' content = urllib2.urlopen('http://localhost:8080/').read() print 'Creating a channel...' content = urllib2.urlopen('http://localhost:8080/channels', data={}).read() print content channel_id = json.loads(content)['id'] print "Adding subscriber to channel '%s'..." % channel_id body = urlencode({'data': json.dumps({'channel': channel_id, 'url': sys.argv[1]})}) content = urllib2.urlopen('http://localhost:8080/subscribers', data=body).read() print content print "Posting message to channel '%s'..." % channel_id body = urlencode({'data': json.dumps({'channel': channel_id, 'message': 'O HAI'})}) content = urllib2.urlopen('http://localhost:8080/messages', data=body).read() print content
[ "daniel@toastdriven.com" ]
daniel@toastdriven.com
ee66c9dd4a0d630c6ecb661c22a3acf967691125
58ce8a45d03ec24b89e7502f149bef42d77ad777
/tests/test_models_artist.py
96a9afac325c6d5076dbf3cec399a9ae628b3fc7
[ "MIT" ]
permissive
AndyTempel/spotify.py
db9ba8523d6dbd9bf233f963ea04fac4bf555d5e
d5a18ee59ddffd9026b36f510b45b4cc391ac557
refs/heads/master
2022-12-12T14:46:41.780249
2020-08-28T23:35:09
2020-08-28T23:35:09
291,162,036
0
0
MIT
2020-08-28T23:02:23
2020-08-28T23:02:22
null
UTF-8
Python
false
false
618
py
import asyncio import unittest from types import ModuleType from common import * class TestArtist(unittest.TestCase): @async_with_client(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET) async def test_artist(self, *, client): for artist_uri in TEST_ARTISTS: artist = await client.get_artist(artist_uri) await async_chain([ artist.get_albums(), artist.get_all_albums(), artist.total_albums(), artist.top_tracks(), artist.related_artists() ]) if __name__ == '__main__': unittest.main()
[ "m3nta1@yahoo.com" ]
m3nta1@yahoo.com
b2763a3a3c9318b24e36592eed8791533faf27d4
4786216d2a8e9221cc3624366152f47ae513e5c7
/北京房屋交易/00.py
3738ce39b9fbe67fc5d1c47c31d9d290e2cc619a
[]
no_license
injuredangel/-
b6a2502ee026320b96947d41c223edebe3ec65cc
7988c6aa5e825504ff59b006c37d4383b3bb1da8
refs/heads/master
2020-05-25T02:21:15.654253
2019-05-20T06:27:42
2019-05-20T06:27:42
187,575,531
0
0
null
null
null
null
UTF-8
Python
false
false
1,050
py
import requests from bs4 import BeautifulSoup url = 'http://www.bjjs.gov.cn/bjjs/fwgl/fdcjy/fwjy/index.shtml' headers = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding':'gzip, deflate', 'Accept-Language':'zh-CN,zh;q=0.9', 'Cache-Control':'max-age=0', 'Connection':'keep-alive', 'Cookie':'wdcid=55e47ea030f84764; _gscu_1677760547=4060476218oivg24; _gscbrs_1677760547=1; Hm_lvt_9ac0f18d7ef56c69aaf41ca783fcb10c=1540604763,1540621692; wdlast=1540624935; _gscs_1677760547=t406249357bbz3224|pv:1; Hm_lpvt_9ac0f18d7ef56c69aaf41ca783fcb10c=1540624935', 'Host':'www.bjjs.gov.cn', 'Upgrade-Insecure-Requests':'1', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36', } response = requests.get(url=url,headers=headers).text print(response) # html_doc = BeautifulSoup(response,'lxml')
[ "you@example.com" ]
you@example.com
07e55ee3fd2c3c2e3b690cf0132a7e10a918ba60
5b3d8f56f4d18dc8809f9f5aa7d2a7089cdbf489
/.c9/metadata/workspace/Interview/InterviewRQ3.py
7e7c06281c2528a512f1728fa32de5e30a67c06d
[]
no_license
heyliljill/edpsych-cloned
89ba1a827ed66651b7387b25bc2c188ff344e8d1
ba02e4789e390bb6488b11608b994ee5678a4b30
refs/heads/master
2020-07-26T00:51:41.004018
2019-09-14T17:26:45
2019-09-14T17:26:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
444
py
{"filter":false,"title":"InterviewRQ3.py","tooltip":"/Interview/InterviewRQ3.py","ace":{"folds":[],"scrolltop":186,"scrollleft":909,"selection":{"start":{"row":38,"column":26},"end":{"row":38,"column":325},"isBackwards":false},"options":{"guessTabSize":true,"useWrapMode":false,"wrapToView":true},"firstLineState":0},"hash":"26c2c4b2d3dc5419ba398fd9a9d5dc56af9b3cc6","undoManager":{"mark":-1,"position":-1,"stack":[]},"timestamp":1403036614000}
[ "jillyma@gmail.com" ]
jillyma@gmail.com
7e74fa3054af9e5c296cb668f23cc4c208dcaf83
98b63e3dc79c75048163512c3d1b71d4b6987493
/tensorflow/python/distribute/multi_process_runner.py
95841b8ee902049af7e05da8109e06d2221e1413
[ "Apache-2.0" ]
permissive
galeone/tensorflow
11a4e4a3f42f4f61a65b432c429ace00401c9cc4
1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206
refs/heads/master
2022-11-13T11:56:56.143276
2020-11-10T14:35:01
2020-11-10T14:35:01
310,642,488
21
12
Apache-2.0
2020-11-06T16:01:03
2020-11-06T16:01:02
null
UTF-8
Python
false
false
55,559
py
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Multi-process runner for testing purpose.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import contextlib import json import os import signal import sys import threading import time import unittest import weakref from absl import logging import six from six.moves import queue as Queue from tensorflow.python import tf2 from tensorflow.python.compat import v2_compat from tensorflow.python.distribute import multi_process_lib from tensorflow.python.eager import context from tensorflow.python.util.tf_export import tf_export multiprocessing = multi_process_lib.multiprocessing # pylint: disable=g-import-not-at-top try: # `faulthandler` is not available in py2. import faulthandler except ImportError: faulthandler = None # TODO(b/150264776): Remove after resolving CI issue. try: import dill except ImportError: dill = None # TODO(b/150264776): Remove after resolving CI issue. try: import tblib.pickling_support # For pickling traceback objects. tblib.pickling_support.install() except ImportError: pass # _ProcessStatusInfo contains process status information. When is_successful # attribute is True, the subprocess has ended successfully, or if False, the # exception stack trace info is stored in exc_info to pass on to parent process # to be re-raised. _ProcessStatusInfo = collections.namedtuple( '_ProcessStatusInfo', ['task_type', 'task_id', 'is_successful', 'exc_info', 'return_value']) # Information returned from a successful MultiProcessRunner run. MultiProcessRunnerResult = collections.namedtuple('MultiProcessRunnerResult', ['return_value', 'stdout']) TestEnvironment = collections.namedtuple('TestEnvironment', [ 'task_type', 'task_id', 'cluster_spec', 'rpc_layer', 'grpc_fail_fast', 'v2_enabled', 'executing_eagerly' ]) # Resources for communication between worker processes and the main process. # # `process_status_queue` is used by `multi_process_runner` internally for # communication from subprocesses to the parent process for whether it's been # successful, and if not what the error stack trace is. # `parent_to_sub_queue` is used for communications from parent to subprocess. # Currently this is only used to terminate subprocesses. # TODO(rchao): Remove this once subprocess is terminated by SIGKILL. # `streaming_pipe_w` is to stream stdout and stderr from subprocesses to parent # process. # `barrier` is a barrier for the party of all subprocesses. Resources = collections.namedtuple('Resources', [ 'process_status_queue', 'parent_to_sub_queue', 'streaming_pipe_w', 'barrier' ]) # Default time out sec is selected so that it's handled before the default # "medium" timeout of the test runs. _DEFAULT_TIMEOUT_SEC = 200 # The timeout in seconds to wait to force kill a child process. When a child # process times out we first try to SIGTERM it so that it has a chance to dump # stacktraces. However dumping stacktrace can take a long time. _FORCE_KILL_WAIT_SEC = 30 class MultiProcessRunner(object): """A utility class to start multiple processes to simulate a cluster. We need to use multiple processes to simulate a cluster in TF 2.0 tests because TF 2.0 has some process-global data structures that have to be separated by processes. We also need child processes to test out our fault tolerance because shutting down a standard TensorFlow server within its process is not supported. Note: the main test program that uses this runner class must run main program via `test_main` defined in this file. Using this runner in non-test binaries is not supported yet. This class is not thread-safe. Child processes will inherit TF2 behavior flag. """ def __init__(self, fn, cluster_spec, rpc_layer=None, max_run_time=None, grpc_fail_fast=None, stream_output=True, return_output=False, use_dill_for_args=True, daemon=False, dependence_on_chief=True, auto_restart=False, args=None, kwargs=None): """Instantiation of a `MultiProcessRunner`. Args: fn: Function to be run on child processes. This will be run on processes for all task types. cluster_spec: Dict for cluster spec. The utility function `tf.__internal__.distribute.multi_process_runner.create_cluster_spec` can be conveniently used to create such dict. The following is an example of cluster with three workers and two ps's. {"worker": ["worker0.example.com:2222", "worker1.example.com:2222", "worker2.example.com:2222"], "ps": ["ps0.example.com:2222", "ps1.example.com:2222"]} rpc_layer: RPC layer to use. Default value is 'grpc'. max_run_time: `None` or integer. If not `None`, child processes are forced to exit at approximately this many seconds after this utility is called. We achieve this through `signal.alarm()` api. Note that this is best effort at Python level since Python signal handler does not get executed when it runs lower level C/C++ code. So it can be delayed for arbitrarily long time. If any of the child process is still running when `max_run_time` is up, they will be force-terminated and an `UnexpectedSubprocessExitError` may be raised. If `None`, child processes are not forced to exit. grpc_fail_fast: Whether GRPC connection between processes should fail without retrying. Defaults to None, in which case the environment variable is not explicitly set. stream_output: True if the output/error from the subprocesses should be streamed to be printed in parent process' log. Defaults to True. return_output: If True, the output/error from the subprocesses should be collected to be attached to the resulting namedtuple returned from `join()`. The list of output can be retrieved via `stdout` attribute. Defaults to False. use_dill_for_args: Whether to use dill to pickle `args` and `kwargs`. dill can pickle more objects, but doesn't work with types in `multiprocessing` library like `Mutex`. daemon: Whether to start processes as daemons. dependence_on_chief: Whether to terminates the cluster if the chief exits. If auto_restart is True, it only terminates the cluster if the chief exits with a zero exit code. auto_restart: Whether to automatically restart processes that exit with non-zero exit code. args: Positional arguments to be sent to `fn` run on subprocesses. kwargs: Keyword arguments to be sent to `fn` run on subprocesses. Raises: RuntimeError: if `multi_process_runner.test_main()` is not called. ValueError: if there are more than one chief in the `cluster_spec`. """ assert cluster_spec is not None if 'chief' in cluster_spec and len(cluster_spec['chief']) > 1: raise ValueError('If chief exists in the cluster, there must be at most ' 'one chief. Current `cluster_spec` has {} chiefs.' .format(len(cluster_spec['chief']))) if not multi_process_lib.initialized(): raise NotInitializedError( '`multi_process_runner` is not initialized. ' 'Please call `tf.__internal__.distribute.multi_process_runner.' 'test_main()` within `if __name__ == \'__main__\':` block ' 'in your python module to properly initialize ' '`multi_process_runner`.') if not callable(fn): raise ValueError('fn is not a callable') self._fn = fn self._cluster_spec = cluster_spec self._rpc_layer = rpc_layer or 'grpc' self._max_run_time = max_run_time self._grpc_fail_fast = grpc_fail_fast self._stream_output = stream_output # TODO(rchao): Revisit return_output argument to consider other solution. self._return_output = return_output self._dependence_on_chief = dependence_on_chief self._use_dill_for_args = use_dill_for_args self._daemon = daemon self._auto_restart = auto_restart self._args = args or () self._kwargs = kwargs or {} # Child processes should have the same v2 and eager behavior. self._v2_enabled = tf2.enabled() self._executing_eagerly = context.executing_eagerly() self._joined = False self._process_lock = threading.Lock() # Guarded by self._process_lock. self._processes = {} # Record which processes are terminated. Due to a bug in Python<3.7, # terminated processes return 255 exit code, which should cause an exception # in join(). # https://bugs.python.org/issue30589 # Guarded by self._process_lock. self._terminated = set() self._reading_threads = [] self._manager = manager() self._process_status_queue = self._manager.Queue() self._parent_to_sub_queue = self._manager.Queue() parties = sum(len(addresses) for addresses in self._cluster_spec.values()) self._barrier = self._manager.Barrier(parties) # We use a queue to collect outputs from worker processes since it's thread # safe. self._streaming_queue = self._manager.Queue() self._watchdog_thread = None def set_args(self, args=None, kwargs=None): self._args = args or self._args self._kwargs = kwargs or self._kwargs def _continuously_readline_from_sub(self, pipe_r, task_type, task_id): """Function to continuously read lines from subprocesses.""" with os.fdopen(pipe_r.fileno(), 'r', closefd=False) as reader: for line in reader: task_string = '[{}-{}]:'.format(task_type, task_id) formatted_line = '{} {}'.format(task_string.ljust(14), line) if self._stream_output: # TODO(rchao): Use a lock here to ensure the printed lines are not # broken. print(formatted_line, end='', flush=True) if self._return_output: self._streaming_queue.put(formatted_line) def _start_subprocess_and_reading_thread(self, task_type, task_id, cluster_spec=None, fn=None, args=None, kwargs=None): """Start a subprocess and a thread the reads lines from the subprocess.""" if dill is None: raise unittest.SkipTest( 'TODO(b/150264776): Resolve dependency issue in CI') test_env = TestEnvironment( task_type=task_type, task_id=task_id, cluster_spec=cluster_spec or self._cluster_spec, rpc_layer=self._rpc_layer, grpc_fail_fast=self._grpc_fail_fast, v2_enabled=self._v2_enabled, executing_eagerly=self._executing_eagerly, ) pipe_r, pipe_w = multiprocessing.Pipe(duplex=False) resources = Resources( process_status_queue=self._process_status_queue, parent_to_sub_queue=self._parent_to_sub_queue, streaming_pipe_w=pipe_w, barrier=self._barrier, ) if fn is None: fn, args, kwargs = self._fn, self._args, self._kwargs # Always use dill to pickle fn so that we support more callable # types, e.g. lambda. fn = dill.dumps(fn, dill.HIGHEST_PROTOCOL) if self._use_dill_for_args: args = dill.dumps(args, dill.HIGHEST_PROTOCOL) kwargs = dill.dumps(kwargs, dill.HIGHEST_PROTOCOL) p = _Process( test_env=test_env, target=_ProcFunc(), args=(resources, test_env, fn, args, kwargs, self._use_dill_for_args), daemon=self._daemon) p.start() self._processes[(task_type, task_id)] = p self._terminated.discard((task_type, task_id)) # For each subprocess, we dedicate a thread continuously reading lines # from them. thread = threading.Thread( # pylint: disable=unexpected-keyword-arg target=self._continuously_readline_from_sub, args=(pipe_r, task_type, task_id)) thread.start() self._reading_threads.append(thread) if self._watchdog_thread is None or not self._watchdog_thread.is_alive(): self._watchdog_thread = threading.Thread(target=self._process_watchdog) self._watchdog_thread.start() def start(self): """Starts processes, one for each task in `cluster_spec`. Note that this is best effort by the applicable multiprocessing library, and it may take up to seconds for a subprocess to be successfully started. """ with self._process_lock: if self._processes: raise ValueError('MultiProcessRunner already started.') if self._joined: raise ValueError('cannot start new processes after' 'MultiProcessRunner.join() is called') for task_type, addresses in self._cluster_spec.items(): for task_id, _ in enumerate(addresses): self._start_subprocess_and_reading_thread(task_type, task_id) # TODO(rchao): Remove the need of using SIGALRM if possible. At this time, # without this the tests become very flaky. if self._max_run_time is not None: def handler(signum, frame): del signum, frame self.terminate_all() signal.signal(signal.SIGALRM, handler) signal.alarm(self._max_run_time) def start_in_process_as(self, as_task_type, as_task_id): """Start the processes, with the specified task run in main process. This is similar to `start()` except that the task with task_type `as_task_type` and task_id `as_task_id` is run in the main process. This method is particularly useful when debugging tool such as `pdb` is needed in some specific task. Note that since this method is blocking until that specific task exits, additional actions would need a thread to be called: ```python def fn(): # user code to be run import pdb; pdb.set_trace() def follow_ups(): time.sleep(5) mpr.start_single_process( task_type='evaluator', task_id=0) mpr = multi_process_runner.MultiProcessRunner( fn, multi_worker_test_base.create_cluster_spec( has_chief=True, num_workers=1)) threading.Thread(target=follow_ups).start() mpr.start_in_process_as(as_task_type='chief', as_task_id=0) mpr.join() ``` Note that if `return_output=True`, the logs/stdout by task run by the main process is not available in result.stdout. Args: as_task_type: The task type to be run in the main process. as_task_id: The task id to be run in the main process. """ if self._processes: raise ValueError('MultiProcessRunner already started.') with self._process_lock: if self._joined: raise ValueError('cannot start new processes after' 'MultiProcessRunner.join() is called') for task_type, addresses in self._cluster_spec.items(): for task_id, _ in enumerate(addresses): if not (task_type == as_task_type and task_id == as_task_id): self._start_subprocess_and_reading_thread(task_type, task_id) _set_tf_config(as_task_type, as_task_id, self._cluster_spec, self._rpc_layer) self._fn(*self._args, **self._kwargs) def start_single_process(self, task_type, task_id, cluster_spec=None, fn=None, args=None, kwargs=None): """Starts a single process. This starts a process in the cluster with the task type, task id, and the process function (`fn`). If process function is `None`, the function provided at `__init__` will be used. If `cluster_spec` is `None`, the cluster spec provided at `__init__` will be used. TODO(rchao): It is meant that all subprocesses will be updated with the new cluster spec, but this has yet to be implemented. At this time only the newly started subprocess picks up this updated cluster spec. Args: task_type: The task type. task_id: The task id. cluster_spec: The cluster spec to be used on the newly started process. If `None`, the cluster spec provided at `__init__` will be used. fn: The process function to be run on the newly started process. If specified, specify `args` and `kwargs` as well. If `None`, the function provided at `__init__` will be used. args: Optional positional arguments to be supplied in `fn`. kwargs: Optional keyword arguments to be supplied in `fn`. """ with self._process_lock: if self._joined: raise ValueError('cannot start new processes after' 'MultiProcessRunner.join() is called') self._start_subprocess_and_reading_thread( task_type, task_id, cluster_spec=cluster_spec, fn=fn, args=args or (), kwargs=kwargs or {}) def _queue_to_list(self, queue_to_convert): """Convert `queue.Queue` to `list`.""" list_to_return = [] # Calling `queue.empty()` is not reliable. while True: try: list_to_return.append(queue_to_convert.get(block=False)) except Queue.Empty: break return list_to_return def _get_process_statuses(self): # One worker may have multiple statuses. We only keep the last one. statuses = {} for status in self._queue_to_list(self._process_status_queue): statuses[(status.task_type, status.task_id)] = status return statuses def get_process_id(self, task_type, task_id): """Returns the subprocess id given the task type and task id.""" with self._process_lock: p = self._processes.get((task_type, task_id), None) return p.pid if p else None def get_process_exit_code(self, task_type, task_id): """Returns the subprocess exit code given the task type and task id. Args: task_type: The task type. task_id: The task id. Returns: The subprocess exit code; `None` if the subprocess has not exited yet. Raises: KeyError: If the corresponding subprocess is not found with `task_type` and `task_id`. """ with self._process_lock: p = self._processes[(task_type, task_id)] return p.exitcode if p else None def process_exists(self, task_type, task_id): """Returns whether the subprocess still exists given the task type and id. Args: task_type: The task type. task_id: The task id. Returns: Boolean; whether the subprocess still exists. If the subprocess has exited, this returns False. """ return self.get_process_exit_code(task_type, task_id) is None def _process_watchdog(self): """Simulates a cluster management system. - If auto_restart is True, it restarts processes that exit with a non-zero exit code. Note that when join() times out it overrides auto_restart to False. - If dependence_on_chief is True, it terminates all processes once the chief exits. If auto_restart is also True, it only terminates all processes if the chief exit with a zero exit code, otherwise it restarts the chief. This runs in self._watchdog_thread. """ while True: time.sleep(1) with self._process_lock: chief = self._processes.get(('chief', 0), None) # Terminate the cluster when _dependence_on_chief is True if either: # - chief has exited with zero exit code. # - chief has exited with non-zero exit code and self._auto_restart is # False. if chief and self._dependence_on_chief and chief.exitcode is not None: if chief.exitcode == 0 or (not self._auto_restart): for p in self._processes.values(): # Give other processes a chance to exit on their own. p.join(timeout=3) self._terminate_all() for p in self._processes.values(): p.join() return # Auto restart failed processes if self._auto_restart is True. if self._auto_restart: has_failure = False for (task_type, task_id), p in self._processes.items(): if p.exitcode is not None and p.exitcode != 0: has_failure = True logging.info('Restarting failed %s-%d', task_type, task_id) self._start_subprocess_and_reading_thread(task_type, task_id) if has_failure: continue # Exit the thread if all processes have exited at this point. if all(p.exitcode is not None for p in self._processes.values()): return def _reraise_if_subprocess_error(self, process_statuses): for process_status in process_statuses.values(): assert isinstance(process_status, _ProcessStatusInfo) if not process_status.is_successful: process_status.exc_info[1].mpr_result = self._get_mpr_result( process_statuses) six.reraise(*process_status.exc_info) def join(self, timeout=_DEFAULT_TIMEOUT_SEC): """Joins all the processes with timeout. If any of the subprocesses does not exit approximately after `timeout` seconds has passed after `join` call, this raises a `SubprocessTimeoutError`. Note: At timeout, it uses SIGTERM to terminate the subprocesses, in order to log the stack traces of the subprocesses when they exit. However, this results in timeout when the test runs with tsan (thread sanitizer); if tsan is being run on the test targets that rely on timeout to assert information, `MultiProcessRunner.terminate_all()` must be called after `join()`, before the test exits, so the subprocesses are terminated with SIGKILL, and data race is removed. Args: timeout: optional integer or `None`. If provided as an integer, and not all processes report status within roughly `timeout` seconds, a `SubprocessTimeoutError` exception will be raised. If `None`, `join` never times out. Returns: A `MultiProcessRunnerResult` object, which has two attributes, `return_value` and `stdout`. `return_value` always contains a list of return values from the subprocesses, although the order is not meaningful. If `return_output` argument is True at `__init__`, `stdout` is available that contains a list of all messages from subprocesses' stdout and stderr. Raises: SubprocessTimeoutError: if not all processes report status approximately within `timeout` seconds. When this is raised, a `MultiProcessRunnerResult` object can be retrieved by `SubprocessTimeoutError`'s mpr_result attribute, which has the same structure as above 'Returns' section describes. UnexpectedSubprocessExitError: If any of the subprocesses did not exit properly (for example, they exit on SIGTERM or SIGKILL signal). When this is raised, a `MultiProcessRunnerResult` object can be retrieved by `UnexpectedSubprocessExitError`'s mpr_result attribute, which has the same structure as above 'Returns' section describes. If `max_run_time` is not `None`, it is expected that some subprocesses may be force-killed when `max_run_time` is up, and this is raised in those cases. Exception: if there is an Exception propagated from any subprocess. When this is raised, a `MultiProcessRunnerResult` object can be retrieved by `UnexpectedSubprocessExitError`'s mpr_result attribute, which has the same structure as above 'Returns' section describes. """ if timeout and not isinstance(timeout, int): raise ValueError('`timeout` must be an integer or `None`.') with self._process_lock: if self._joined: raise ValueError("MultiProcessRunner can't be joined twice.") self._joined = True self._watchdog_thread.join(timeout) if self._watchdog_thread.is_alive(): # Timeout. Force termination to dump worker processes stack trace. with self._process_lock: self._auto_restart = False logging.error('Timeout when joining for child processes. Terminating...') self.terminate_all(sig=signal.SIGTERM) # Wait for the processes to terminate by themselves first, so they have a # chance to dump stacktraces. After _FORCE_KILL_WAIT_SEC, we SIGKILL them. self._watchdog_thread.join(_FORCE_KILL_WAIT_SEC) if self._watchdog_thread.is_alive(): logging.error('Timeout when waiting for child processes to ' 'print stacktrace. Sending SIGKILL...') self.terminate_all() self._watchdog_thread.join() process_statuses = self._get_process_statuses() self._reraise_if_subprocess_error(process_statuses) raise SubprocessTimeoutError( 'One or more subprocesses timed out, where timeout was set to {}s. ' 'Please change the `timeout` argument for ' '`MultiProcessRunner.join()` or `multi_process_runner.run()` ' 'if it should be adjusted.'.format(timeout), self._get_mpr_result(process_statuses)) for (task_type, task_id), p in self._processes.items(): logging.info('%s-%d exit code: %s', task_type, task_id, p.exitcode) process_statuses = self._get_process_statuses() self._reraise_if_subprocess_error(process_statuses) # Checking all the processes that are expected to exit properly. for (task_type, task_id), p in self._processes.items(): # Successfully exiting process has exit code 0. We ignore processes that # are terminated. assert p.exitcode is not None if (p.exitcode > 0 and (task_type, task_id) not in self._terminated): raise UnexpectedSubprocessExitError( 'Subprocess %s-%d exited with exit code %s. See logs for details.' % (task_type, task_id, p.exitcode), self._get_mpr_result(process_statuses)) logging.info('Joining log reading threads.') for thread in self._reading_threads: thread.join() logging.info('Joined log reading threads.') # Clear the alarm. signal.alarm(0) return self._get_mpr_result(process_statuses) def _get_mpr_result(self, process_statuses): stdout = self._queue_to_list(self._streaming_queue) return_values = [] for process_status in process_statuses.values(): if process_status.return_value is not None: return_values.append(process_status.return_value) return MultiProcessRunnerResult(stdout=stdout, return_value=return_values) def terminate(self, task_type, task_id): """Terminates the process with `task_type` and `task_id`. If auto_retart=True, the terminated task will be restarted unless the chief has already exited with zero exit code. Args: task_type: the task type. task_id: the task id. """ with self._process_lock: p = self._processes.get((task_type, task_id), None) if p is None: raise ValueError('{}-{} does not exist'.format(task_type, task_id)) self._terminated.add((task_type, task_id)) # TODO(crccw): change to use Process.terminate() as well. self._parent_to_sub_queue.put('terminate {} {}'.format( task_type, task_id)) p.join() def _terminate_all(self, sig=None): """Terminates all subprocesses. The caller is required to hold self._process_lock. Args: sig: the signal used to terminate the process. The default is SIGKILL. """ # Use SIGKILL as default. In systems where that's unavailable such as # windows, use SIGTERM. sig = sig or getattr(signal, 'SIGKILL', signal.SIGTERM) for (task_type, task_id), p in self._processes.items(): if p.exitcode is not None: logging.info('%s-%d has already exited. Not terminating.', task_type, task_id) continue try: os.kill(p.pid, sig) self._terminated.add((task_type, task_id)) logging.info('%s-%d terminated with signal %r.', task_type, task_id, sig) except ProcessLookupError: logging.info('Attempting to kill %s-%d but it does not exist.', task_type, task_id) def terminate_all(self, sig=None): """Terminates all subprocesses.""" with self._process_lock: self._terminate_all(sig) class _Process(multi_process_lib.Process): """A modified `multiprocessing.Process` that can set up environment variables.""" # TODO(crccw): consider moving other logics in _ProcFunc to _Process. def __init__(self, test_env, **kwargs): super(_Process, self).__init__(**kwargs) self._test_env = test_env self._actual_run = getattr(self, 'run') self.run = self._run_with_setenv def _run_with_setenv(self): # We need to set environment variables before doing anything because # setenv() is not thread-safe. test_env = self._test_env if test_env.grpc_fail_fast is not None: os.environ['GRPC_FAIL_FAST'] = str(test_env.grpc_fail_fast) _set_tf_config(test_env.task_type, test_env.task_id, test_env.cluster_spec, test_env.rpc_layer) return self._actual_run() class _ProcFunc(object): """Represents a callable to run in a subprocess.""" @contextlib.contextmanager def _runtime_mode(self, executing_eagerly): if executing_eagerly: with context.eager_mode(): yield else: with context.graph_mode(): yield def _message_checking_func(self, task_type, task_id): """A function that regularly checks messages from parent process.""" # TODO(rchao): Remove this once parent uses SIGKILL to terminate subprocess. while True: try: message = self._resources.parent_to_sub_queue.get(block=False) # Currently the only possible message is termination. if not message.startswith('terminate'): raise ValueError('Unrecognized message: {}'.format(message)) if message == 'terminate {} {}'.format(task_type, task_id): break else: # If the message is not targeting this process, put it back to the # queue. self._resources.parent_to_sub_queue.put(message) time.sleep(1) except Queue.Empty: time.sleep(0.1) self._resources.process_status_queue.put( _ProcessStatusInfo( task_type=task_type, task_id=task_id, is_successful=True, exc_info=None, return_value=None)) # `os._exit(1)` is used to more reliably terminate a subprocess. os._exit(1) # pylint: disable=protected-access def _close_streaming(self): """Close stdout, stderr and streaming pipe. We need to explicitly close them since Tensorflow may take a while to exit, so that the reading threads in the main process can exit more quickly. """ sys.stdout.flush() sys.stderr.flush() sys.stdout.close() sys.stderr.close() self._resources.streaming_pipe_w.close() def __call__(self, resources, test_env, fn, args, kwargs, use_dill_for_args): """The wrapper function that actually gets run in child process(es).""" global _barrier self._resources = resources _barrier = self._resources.barrier fn = dill.loads(fn) if use_dill_for_args: args = dill.loads(args) kwargs = dill.loads(kwargs) if faulthandler is not None: faulthandler.enable() faulthandler.register(signal.SIGTERM, chain=True) # All logging should go to stderr to be streamed to the main process. logging.set_stderrthreshold(logging.DEBUG) # Assign sys.stdout and sys.stderr as duplicates of `streaming_pipe_w` so # print() and logging.*() write directly to `streaming_pipe_w`. # Unfortunately since we cannot prepend task_type and task_id information to # the streamed logs we will need a thread per subprocess to distinguish # where the piece of message is from. os.dup2(resources.streaming_pipe_w.fileno(), sys.stdout.fileno()) os.dup2(resources.streaming_pipe_w.fileno(), sys.stderr.fileno()) pid = os.getpid() logging.info('Subprocess with PID %d (%s, %d) is now being started.', pid, test_env.task_type, test_env.task_id) # The thread will be dedicated to checking messages from the parent process. threading.Thread( # pylint: disable=unexpected-keyword-arg target=self._message_checking_func, args=(test_env.task_type, test_env.task_id), daemon=True).start() if test_env.v2_enabled: v2_compat.enable_v2_behavior() with self._runtime_mode(test_env.executing_eagerly): info = _run_contained(test_env.task_type, test_env.task_id, fn, args, kwargs) self._resources.process_status_queue.put(info) # Re-raise the exception in addition to reporting it to the parent # process, so that even if `--test_timeout` flag is set and the # error doesn't make it to be shown in parent process before bazel's # timeout, the log would still show what happens in this subprocess, # instead of silently suppressing the error due to early bazel # timeout. Raising an error in the subprocess produces stack trace in # the log, but the program continues running. if not info.is_successful: six.reraise(*info.exc_info) self._close_streaming() # Exit with code 0 as it's considered successful exit at this point. sys.exit(0) # Active MultiProcessPoolRunner. We need to shut them down when the program # exits, and this is by setting the `tearDownModule` of the module containing # `__main__`. Note this it set in both the parent process and the subprocesses. _active_pool_runners = weakref.WeakSet() def _shutdown_all_pool_runners(): for pool in _active_pool_runners: pool.shutdown() def is_oss(): """Returns whether the test is run under OSS.""" return len(sys.argv) >= 1 and 'bazel' in sys.argv[0] class MultiProcessPoolRunner(object): """A utility class to start a process pool to simulate a cluster. It's similar to MultiProcessRunner, but uses a pool of processes to avoid the expensive initialization cost of Tensorflow. """ def __init__(self, cluster_spec, initializer=None): """Creates a multi-process pool runner. Args: cluster_spec: Dict for cluster spec. The following is an example of cluster with three workers. {"worker": ["worker0.example.com:2222", "worker1.example.com:2222", "worker2.example.com:2222"]} initializer: a callable to called at the startup of worker processes. Raises: RuntimeError: if `multi_process_runner.test_main()` is not called. ValueError: if there are more than one chief in the `cluster_spec`. """ _active_pool_runners.add(self) self._cluster_spec = cluster_spec self._initializer = initializer self._conn = {} self._runner = None def __del__(self): self.shutdown() def shutdown(self): """Shuts down the worker pool.""" for conn in self._conn.values(): conn.close() self._conn = {} if self._runner is not None: try: self._runner.join() except Exception as e: # pylint: disable=broad-except logging.error( 'Ignoring exception when shutting down MultiProcessPoolRunner: %s', e) self._runner = None def _start(self): """Starts the worker pool.""" # We need different arguments for different processes so we're passing a # no-op fn here and use start_single_process instead. if dill is None: raise unittest.SkipTest( 'TODO(b/150264776): Resolve dependency issue in CI') self._runner = MultiProcessRunner( fn=lambda: None, cluster_spec=self._cluster_spec, use_dill_for_args=False) if self._initializer: initializer = dill.dumps(self._initializer, dill.HIGHEST_PROTOCOL) else: initializer = None for task_type, addresses in self._cluster_spec.items(): for task_id, _ in enumerate(addresses): conn1, conn2 = multiprocessing.Pipe(duplex=True) self._conn[(task_type, task_id)] = conn1 self._runner.start_single_process( task_type, task_id, fn=_pool_runner_worker, args=(task_type, task_id, initializer, conn2)) def run(self, fn, args=None, kwargs=None): """Runs `fn` with `args` and `kwargs` on all jobs. Args: fn: The function to be run. args: Optional positional arguments to be supplied in `fn`. kwargs: Optional keyword arguments to be supplied in `fn`. Returns: A list of return values. """ # TODO(b/150264776): skip in OSS until it's implemented. multi_process_lib.Process() if self._runner is None: self._start() fn = dill.dumps(fn, dill.HIGHEST_PROTOCOL) for conn in self._conn.values(): conn.send((fn, args or [], kwargs or {})) process_statuses = [] for (task_type, task_id), conn in self._conn.items(): logging.info('Waiting for the result from %s-%d', task_type, task_id) try: process_statuses.append(conn.recv()) except EOFError: # This shouldn't happen due to exceptions in fn. This usually # means bugs in the runner. self.shutdown() raise RuntimeError('Unexpected EOF. Worker process may have died. ' 'Please report a bug') return_values = [] for process_status in process_statuses: assert isinstance(process_status, _ProcessStatusInfo) if not process_status.is_successful: six.reraise(*process_status.exc_info) if process_status.return_value is not None: return_values.append(process_status.return_value) return return_values def _pool_runner_worker(task_type, task_id, initializer, conn): """Function that runs on the workers in a pool. It listens for callables to run and returns the result until `conn` is closed. It captures the exceptions during executing the callable and return it through `conn`. Args: task_type: the task type. task_id: the task index. initializer: a callable to execute during startup. conn: a multiprocessing.Connection object to listen for tasks and send results. """ if initializer: initializer = dill.loads(initializer) initializer() while True: try: fn, args, kwargs = conn.recv() except EOFError: break fn = dill.loads(fn) info = _run_contained(task_type, task_id, fn, args, kwargs) sys.stdout.flush() sys.stderr.flush() conn.send(info) def _run_contained(task_type, task_id, fn, args, kwargs): """Runs `fn` with `args` and `kwargs`. The function returns _ProcessStatusInfo which captures the return value and the exception. Args: task_type: the task type. task_id: the task index. fn: the function to be run. args: optional positional arguments to be supplied in `fn`. kwargs: optional keyword arguments to be supplied in `fn`. Returns: a _ProcessStatusInfo. """ is_successful = False return_value = None exc_info = None try: return_value = fn(*args, **kwargs) is_successful = True return _ProcessStatusInfo( task_type=task_type, task_id=task_id, is_successful=is_successful, exc_info=exc_info, return_value=return_value) # If `fn` ends up exiting with `sys.exit()`, the `SystemExit` is not # handled here. except Exception: # pylint: disable=broad-except exc_info = sys.exc_info() return _ProcessStatusInfo( task_type=task_type, task_id=task_id, is_successful=is_successful, exc_info=exc_info, return_value=return_value) @tf_export('__internal__.distribute.multi_process_runner' '.SubprocessTimeoutError', v1=[]) class SubprocessTimeoutError(RuntimeError): """An error that indicates there is at least one subprocess timing out. When this is raised, a namedtuple object representing the multi-process run result can be retrieved by `tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError`'s `mpr_result` attribute. See `tf.__internal__.distribute.multi_process_runner.run` for more information. """ def __init__(self, msg, mpr_result): super(SubprocessTimeoutError, self).__init__(msg) self.mpr_result = mpr_result @tf_export('__internal__.distribute.multi_process_runner' '.UnexpectedSubprocessExitError', v1=[]) class UnexpectedSubprocessExitError(RuntimeError): """An error indicating there is at least one subprocess with unexpected exit. When this is raised, a namedtuple object representing the multi-process run result can be retrieved by `tf.__internal__.distribute.multi_process_runner .UnexpectedSubprocessExitError`'s `mpr_result` attribute. See `tf.__internal__.distribute.multi_process_runner.run` for more information. """ def __init__(self, msg, mpr_result): super(UnexpectedSubprocessExitError, self).__init__(msg) self.mpr_result = mpr_result @tf_export( '__internal__.distribute.multi_process_runner.NotInitializedError', v1=[]) class NotInitializedError(RuntimeError): """An error indicating `multi_process_runner.run` is used without init. When this is raised, user is supposed to call `tf.__internal__.distribute.multi_process_runner.test_main()` within `if __name__ == '__main__':` block to properly initialize `multi_process_runner.run`. """ pass def _set_tf_config(task_type, task_id, cluster_spec, rpc_layer=None): """Set TF_CONFIG environment variable.""" tf_config_dict = { 'cluster': cluster_spec, 'task': { 'type': task_type, 'index': task_id, }, } if rpc_layer is not None: tf_config_dict['rpc_layer'] = rpc_layer os.environ['TF_CONFIG'] = json.dumps(tf_config_dict) @tf_export('__internal__.distribute.multi_process_runner.run', v1=[]) def run(fn, cluster_spec, rpc_layer=None, max_run_time=None, return_output=False, timeout=_DEFAULT_TIMEOUT_SEC, args=None, kwargs=None): """Run `fn` in multiple processes according to `cluster_spec`. Given a callable `fn`, `tf.__internal__.distribute.multi_process_runner.run` launches multiple processes, each of which runs `fn`. These processes are referred to as "subprocesses" or "child processes". Each of those subprocesses will have their `TF_CONFIG` environment variable set, according to `cluster_spec` and their task types. The stdout of the subprocesses are streamed to the main process' and thus available in logs (if `stream_output` is True), with [type-id] prefix. `tf.__internal__.distribute.multi_process_runner.run` will block until all subprocesses have successfully exited, and return a namedtuple object that represents the run result. This object has a `return_value` attribute, which is a list that contains subprocesses `fn`'s return values, for those subprocesses that successfully returned from `fn`. The order of `return_value` list is not meaningful. If an optional arg `return_output` (default to False) is set to True, the namedtuple object will have an additional attribute `stdout`, which is a list containing the stdout of the subprocesses. If any subprocess' `fn` ends up raising an error, that error will be reraised from `tf.__internal__.distribute.multi_process_runner.run`, and the aforementioned namedtuple object will be available through the exception's `mpr_result` attribute. This utility is used for simulating running TensorFlow programs across multiple task types, and each of the task type may contain more than one task (except for "chief" where more than one task is prohibited). Test coverage of multi-worker training is the main application of this utility, where code written for multi-worker training can be realistically covered in unit tests. Any test module that uses `tf.__internal__.distribute.multi_process_runner.run()` must call `tf.__internal__.distribute.multi_process_runner.test_main()` instead of regular `test.main()` inside `if __name__ == '__main__':` block for proper initialization. Args: fn: Function to be run on child processes. This will be run on processes for all task types. cluster_spec: Dict for cluster spec. The utility function `tf.__internal__.distribute.multi_process_runner.create_cluster_spec` can be conveniently used to create such dict. The following is an example of cluster with three workers and two ps's. {"worker": ["worker0.example.com:2222", "worker1.example.com:2222", "worker2.example.com:2222"], "ps": ["ps0.example.com:2222", "ps1.example.com:2222"]} rpc_layer: RPC layer to use. Default value is 'grpc'. max_run_time: `None` or integer. If not `None`, child processes are forced to exit at approximately this many seconds after this utility is called. We achieve this through `signal.alarm()` api. Note that this is best effort at Python level since Python signal handler does not get executed when it runs lower level C/C++ code. So it can be delayed for arbitrarily long time. If any of the child process is still running when `max_run_time` is up, they will be force-terminated and an `tf.__internal__.distribute.multi_process_runner .UnexpectedSubprocessExitError` may be raised. If `None`, child processes are not forced to exit. return_output: If True, the output/error from the subprocesses should be collected to be attached to the resulting namedtuple returned from this utility. The list of output can be retrieved via `stdout` attribute. Defaults to False. timeout: optional integer or `None`. If provided as an integer, and not all processes report status within roughly `timeout` seconds, a `tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError` exception will be raised. If `None`, `tf.__internal__.distribute.multi_process_runner.run` never times out. Defaults to the constant `_DEFAULT_TIMEOUT_SEC` defined in `multi_process_runner` module. args: Positional arguments to be sent to `fn` run on subprocesses. kwargs: Keyword arguments to be sent to `fn` run on subprocesses. Returns: A namedtuple object, which has two attributes, `return_value` and `stdout`. `return_value` always contains a list of returnvalues from the subprocesses, although the order is not meaningful. If `return_output` argument is True, `stdout` is available that contains a list of all messages from subprocesses' stdout and stderr, and the order is mostly chronological. Raises: RuntimeError: if `tf.__internal__.distribute.multi_process_runner.test_main()` is not called in test's `if __name__ == '__main__':` block. ValueError: if there are more than one chief in the `cluster_spec`. tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError: if not all processes report status approximately within `timeout` seconds. When this is raised, a namedtuple object can be retrieved by `tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError`'s `mpr_result` attribute, which has the same structure as above 'Returns' section describes. tf.__internal__.distribute.multi_process_runner .UnexpectedSubprocessExitError: If any of the subprocesses did not exit properly (for example, they exit on SIGTERM or SIGKILL signal). When this is raised, a namedtuple object can be retrieved by `tf.__internal__.distribute.multi_process_runner .UnexpectedSubprocessExitError`'s `mpr_result` attribute, which has the same structure as above 'Returns' section describes. If `max_run_time` is not `None`, it is expected that some subprocesses may be force-killed when `max_run_time` is up, and this is raised in those cases. Exception: if there is an Exception propagated from any subprocess. When this is raised, a namedtuple object can be retrieved by `tf.__internal__.distribute.multi_process_runner .UnexpectedSubprocessExitError` `mpr_result` attribute, which has the same structure as above 'Returns' section describes. Examples: ```python class SimpleMultiProcessTest(tf.test.TestCase): def test_simple_printing_and_return(self): def fn(): resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver() # This will print "[chief-0]: Task type: chief , task id: 0" # for chief, for example. logging.info('Task type: %s, task id: %d', resolver.task_type, resolver.task_id) return resolver.task_type result = tf.__internal__.distribute.multi_process_runner.run( fn=fn, cluster_spec=( tf.__internal__ .distribute.multi_process_runner.create_cluster_spec( has_chief=True, num_workers=2))) assert sorted(result.return_value) == ['chief', 'worker', 'worker'] def test_error_from_fn(self): def fn(): resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver() raise ValueError('Task type {}, task id {} is errors out'.format( resolver.task_type, resolver.task_id)) with self.assertRaisesRegexp(ValueError, 'Task type worker, task id 0 is errors out'): cluster_spec = ( tf.__internal__.distribute.multi_process_runner.create_cluster_spec( num_workers=1)) tf.__internal__.distribute.multi_process_runner.run( fn=fn, cluster_spec=cluster_spec) if __name__ == '__main__': tf.__internal__.distribute.multi_process_runner.test_main() ``` """ runner = MultiProcessRunner( fn, cluster_spec, rpc_layer, max_run_time=max_run_time, return_output=return_output, args=args, kwargs=kwargs) runner.start() return runner.join(timeout) # This is set by MultiProcessRunner in worker processes. _barrier = None @tf_export('__internal__.distribute.multi_process_runner.get_barrier', v1=[]) def get_barrier(): """Returns a `multiprocessing.Barrier` for `multi_process_runner.run`. `tf.__internal__.distribute.multi_process_runner.get_barrier()` returns a `multiprocessing.Barrier` object which can be used within `fn` of `tf.__internal__.distribute.multi_process_runner` to wait with `barrier.wait()` call until all other tasks have also reached the `barrier.wait()` call, before they can proceed individually. Note that all tasks (subprocesses) have to reach `barrier.wait()` call to proceed. Currently it is not supported to block on only a subset of tasks in the cluster. Example: ```python def fn(): some_work_to_be_done_by_all_tasks() tf.__internal__.distribute.multi_process_runner.get_barrier().wait() # The barrier guarantees that at this point, all tasks have finished # `some_work_to_be_done_by_all_tasks()` some_other_work_to_be_done_by_all_tasks() result = tf.__internal__.distribute.multi_process_runner.run( fn=fn, cluster_spec=( tf.__internal__ .distribute.multi_process_runner.create_cluster_spec( num_workers=2))) ``` Returns: A `multiprocessing.Barrier` for `multi_process_runner.run`. """ if _barrier is None: raise ValueError( 'barrier is not defined. It is likely because you are calling ' 'get_barrier() in the main process. get_barrier() can only be called ' 'in the subprocesses.' ) return _barrier _manager = None _manager_lock = threading.Lock() def manager(): """Returns the multiprocessing manager object for concurrency tools. The manager object is useful as it controls a server process that holds the python objects that can be shared across processes. This can be used for parent-subprocess communication: ```python manager = multi_process_runner.manager() some_event_happening_in_subprocess = manager.Event() mpr = multi_process_runner.MultiProcessRunner(fn, cluster_spec, args=(some_event_happening_in_subprocess,)) mpr.start() some_event_happening_in_subprocess.wait() # Do something that only should after some event happens in subprocess. ``` Note that the user of multi_process_runner should not create additional `multiprocessing.Manager()` objects; doing so can result in segfault in some cases. This method should only be called after multi_process_runner.test_main() is called. """ global _manager with _manager_lock: if _manager is None: _manager = multiprocessing.Manager() return _manager @tf_export('__internal__.distribute.multi_process_runner.test_main', v1=[]) def test_main(): """Main function to be called within `__main__` of a test file. Any test module that uses `tf.__internal__.distribute.multi_process_runner.run()` must call this instead of regular `test.main()` inside `if __name__ == '__main__':` block, or an error will be raised when `tf.__internal__.distribute.multi_process_runner.run()` is used. This method takes care of needed initialization for launching multiple subprocesses. Example: ```python class MyTestClass(tf.test.TestCase): def testSomething(self): # Testing code making use of # `tf.__internal__.distribute.multi_process_runner.run()`. if __name__ == '__main__': tf.__internal__.distribute.multi_process_runner.test_main() ``` """ # Inject tearDownModule() to shut down all pool runners. Active pool runners # will block the program from exiting. This is necessary for global pool # runners. We tried atexit in the past, and it doesn't work in some # deployment. old_tear_down_module = getattr(sys.modules['__main__'], 'tearDownModule', None) def tear_down_module(): _shutdown_all_pool_runners() if old_tear_down_module is not None: old_tear_down_module() setattr(sys.modules['__main__'], 'tearDownModule', tear_down_module) multi_process_lib.test_main()
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org