Skip to content

Add tlog back, default to while arm #3181

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 11 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ module.exports = {
extends: [
'eslint:recommended',
'plugin:vue/recommended',
'plugin:vue/typescript',
'@vue/airbnb',
'@vue/typescript/recommended',
],
Expand All @@ -26,12 +27,13 @@ module.exports = {
'func-style': ['error', 'declaration'],
'import/extensions': 'off',
'import/order': 'off',
'import/no-unresolved': 'error',
'max-len': ['error', { code: 120 }],
'no-alert': 'off',
'no-bitwise': 'off',
'no-console': 'off',
'no-continue': 'off',
"no-else-return": ["error", { "allowElseIf": false }],
'no-else-return': ['error', { allowElseIf: false }],
'no-extra-parens': ['error', 'all'],
'no-mixed-operators': 'off',
// modified https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb-base/rules/style.js#L339
Expand Down Expand Up @@ -102,6 +104,9 @@ module.exports = {
node: {
extensions: ['.js', '.json', '.jsx', '.ts', '.tsx', '.vue'],
},
vite: {
viteConfig: require('./vite.config').viteConfigObj, // named export of the Vite config object.
},
},
},
}
1 change: 1 addition & 0 deletions core/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
"@vue/eslint-config-typescript": "^11.0.2",
"eslint": "^8.33.0",
"eslint-import-resolver-typescript": "^3.5.3",
"eslint-import-resolver-vite": "^2.1.0",
"eslint-plugin-html": "^7.1.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-simple-import-sort": "^10.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export async function fetchAvailableEndpoints(): Promise<void> {
try {
const response = await back_axios({
method: 'get',
url: `${autopilot.API_URL}/endpoints`,
url: `${autopilot.API_URL}/endpoints/`,
timeout: 10000,
})
const available_endpoints = response.data
Expand Down
6 changes: 5 additions & 1 deletion core/frontend/src/types/autopilot/px4/metadata-fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ async function fetchPX4Metadata(): Promise<PX4ParametersMetadata[]> {
try {
metadata = await fetchPX4MetadataFromBoard()
} catch (e) {
metadata = (await import('@/PX4-parameters/master/parameters.json')).parameters
const response = await fetch('/PX4-parameters/master/parameters.json');
if (!response.ok) {
throw new Error(`Failed to fetch PX4 metadata: ${response.statusText}`);
}
metadata = (await response.json()).parameters;
}

return metadata as PX4ParametersMetadata[]
Expand Down
1 change: 0 additions & 1 deletion core/frontend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"baseUrl": ".",
"experimentalDecorators": true,
"types": [
"webpack-env",
"vite/client"
],
"paths": {
Expand Down
8 changes: 8 additions & 0 deletions core/frontend/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ const assert = require('assert');
// TODO: check if it works with https once we have something that does
assert.ok(SERVER_ADDRESS.startsWith('http://'), 'SERVER_ADDRESS must start with http://');

export const viteConfigObj = {
resolve: {
alias: {
_: path.resolve(__dirname, 'src'),
},
},
}

export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
Expand Down
13 changes: 13 additions & 0 deletions core/services/ardupilot_manager/api/v1/routers/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from fastapi_versioning import versioned_api_route
from loguru import logger

from ardupilot_manager.mavlink_proxy.AbstractRouter import TLogCondition
from autopilot_manager import AutoPilotManager
from exceptions import InvalidFirmwareFile, NoDefaultFirmwareAvailable
from typedefs import (
Expand Down Expand Up @@ -255,6 +256,18 @@ def preferred_router() -> Any:
return autopilot.load_preferred_router()


@index_router_v1.post("/tlog_condition", summary="Set the condition for when to write Tlog files.")
def set_tlog_condition(condition: TLogCondition) -> Any:
logger.debug("Setting Tlog condition")
autopilot.set_tlog_condition(condition)
logger.debug(f"Tlog write condition set to {condition}")


@index_router_v1.get("/tlog_condition", summary="Retrieve Tlog file write condition")
def tlog_condition() -> Any:
return autopilot.get_tlog_condition()


@index_router_v1.get("/available_routers", summary="Retrieve preferred router")
@index_to_http_exception
def available_routers() -> Any:
Expand Down
7 changes: 7 additions & 0 deletions core/services/ardupilot_manager/autopilot_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from firmware.FirmwareManagement import FirmwareManager
from flight_controller_detector.Detector import Detector as BoardDetector
from flight_controller_detector.linux.linux_boards import LinuxFlightController
from mavlink_proxy.AbstractRouter import TLogCondition
from mavlink_proxy.Endpoint import Endpoint, EndpointType
from mavlink_proxy.exceptions import EndpointAlreadyExists
from mavlink_proxy.Manager import Manager as MavlinkManager
Expand Down Expand Up @@ -390,6 +391,12 @@ def load_preferred_router(self) -> Optional[str]:
def get_available_routers(self) -> List[str]:
return [router.name() for router in self.mavlink_manager.available_interfaces()]

def get_tlog_condition(self) -> TLogCondition:
return self.mavlink_manager.tlog_condition()

def set_tlog_condition(self, tlog_condition: TLogCondition) -> None:
self.mavlink_manager.set_tlog_condition(tlog_condition)

async def start_sitl(self) -> None:
self._current_board = BoardDetector.detect_sitl()
if not self.firmware_manager.is_firmware_installed(self._current_board):
Expand Down
15 changes: 15 additions & 0 deletions core/services/ardupilot_manager/mavlink_proxy/AbstractRouter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import shlex
import shutil
import tempfile
from enum import Enum
from typing import Any, List, Optional, Set, Type

from loguru import logger
Expand All @@ -18,6 +19,13 @@
)


class TLogCondition(str, Enum):
"""When to write tlog files."""

Always = "always"
WhileArmed = "while_armed"


class AbstractRouter(metaclass=abc.ABCMeta):
def __init__(self) -> None:
self._endpoints: Set[Endpoint] = set()
Expand All @@ -28,6 +36,7 @@ def __init__(self) -> None:
# to avoid any problem in __del__
self._binary = shutil.which(self.binary_name())
self._logdir = pathlib.Path(tempfile.gettempdir())
self._tlog_condition = TLogCondition.WhileArmed
self._version = self._get_version()

@staticmethod
Expand Down Expand Up @@ -183,6 +192,12 @@ def set_logdir(self, directory: pathlib.Path) -> None:
raise ValueError(f"Logging directory {directory} does not exist.")
self._logdir = directory

def tlog_condition(self) -> TLogCondition:
return self._tlog_condition

def set_tlog_condition(self, tlog_condition: TLogCondition) -> None:
self._tlog_condition = tlog_condition

def add_endpoint(self, endpoint: Endpoint) -> None:
self._validate_endpoint(endpoint)

Expand Down
21 changes: 19 additions & 2 deletions core/services/ardupilot_manager/mavlink_proxy/MAVLinkRouter.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import configparser
import re
import subprocess
import tempfile
from typing import Optional

from mavlink_proxy.AbstractRouter import AbstractRouter
from mavlink_proxy.AbstractRouter import AbstractRouter, TLogCondition
from mavlink_proxy.Endpoint import Endpoint, EndpointType


Expand All @@ -21,6 +23,21 @@ def _get_version(self) -> Optional[str]:

return None

def _write_configuration_file(self) -> str:
def convert_tlog_condition(tlog_condition: TLogCondition) -> str:
match tlog_condition:
case TLogCondition.Always:
return "always"
case TLogCondition.WhileArmed:
return "while-armed"

config = configparser.ConfigParser()
config["General"] = {"LogMode": convert_tlog_condition(self.tlog_condition())}

with tempfile.NamedTemporaryFile("w", suffix=".conf", delete=False) as temp_file:
config.write(temp_file, space_around_delimiters=True)
return temp_file.name

def assemble_command(self, master_endpoint: Endpoint) -> str:
# Convert endpoint format to mavlink-router format
def convert_endpoint(endpoint: Endpoint) -> str:
Expand Down Expand Up @@ -63,7 +80,7 @@ def convert_endpoint(endpoint: Endpoint) -> str:
f"Master endpoint of type {master_endpoint.connection_type} not supported on MavlinkRouter."
)

return f"{self.binary()} {convert_endpoint(master_endpoint)} {endpoints} -l {self.logdir()} -T {self.logdir()}"
return f"{self.binary()} {convert_endpoint(master_endpoint)} {endpoints} -l {self.logdir()} -T {self.logdir()} -c {self._write_configuration_file()}"

@staticmethod
def name() -> str:
Expand Down
16 changes: 14 additions & 2 deletions core/services/ardupilot_manager/mavlink_proxy/MAVLinkServer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import subprocess
from typing import Optional

from mavlink_proxy.AbstractRouter import AbstractRouter
from mavlink_proxy.AbstractRouter import AbstractRouter, TLogCondition
from mavlink_proxy.Endpoint import Endpoint, EndpointType


Expand Down Expand Up @@ -37,8 +37,20 @@ def convert_endpoint(endpoint: Endpoint) -> str:
return f"zenoh:{endpoint.place}:{endpoint.argument}"
raise ValueError(f"Endpoint of type {endpoint.connection_type} not supported on MAVLink-Server.")

def convert_tlog_condition(tlog_condition: TLogCondition) -> str:
match tlog_condition:
case TLogCondition.Always:
return "?when=always"
case TLogCondition.WhileArmed:
return "?when=while_armed"

filtered_endpoints = Endpoint.filter_enabled(self.endpoints())
endpoints = " ".join([convert_endpoint(endpoint) for endpoint in [master_endpoint, *filtered_endpoints]])
str_endpoints = [convert_endpoint(endpoint) for endpoint in [master_endpoint, *filtered_endpoints()]]

tlog_condition_arg = convert_tlog_condition(self.tlog_condition())
logging_endpoint = f"tlogwriter://{self.logdir()}{tlog_condition_arg}"

endpoints = " ".join([*str_endpoints, logging_endpoint])

return f"{self.binary()} {endpoints}"

Expand Down
8 changes: 7 additions & 1 deletion core/services/ardupilot_manager/mavlink_proxy/Manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import mavlink_proxy.MAVLinkServer
import mavlink_proxy.MAVP2P
import mavlink_proxy.MAVProxy
from mavlink_proxy.AbstractRouter import AbstractRouter
from mavlink_proxy.AbstractRouter import AbstractRouter, TLogCondition
from mavlink_proxy.Endpoint import Endpoint
from mavlink_proxy.exceptions import (
EndpointAlreadyExists,
Expand Down Expand Up @@ -171,6 +171,12 @@ def router_name(self) -> str:
def set_logdir(self, log_dir: pathlib.Path) -> None:
self.tool.set_logdir(log_dir)

def tlog_condition(self) -> TLogCondition:
return self.tool.tlog_condition()

def set_tlog_condition(self, tlog_condtion: TLogCondition) -> None:
self.tool.set_tlog_condition(tlog_condtion)

async def auto_restart_router(self) -> None:
"""Auto-restart Mavlink router process if it dies."""
while True:
Expand Down
Loading