Skip to content

Commit

Permalink
mavftp: first, read-only version
Browse files Browse the repository at this point in the history
  • Loading branch information
Williangalvani committed Jun 20, 2024
1 parent 869ee8d commit b16dea5
Show file tree
Hide file tree
Showing 7 changed files with 935 additions and 0 deletions.
9 changes: 9 additions & 0 deletions core/services/ardupilot_manager/ArduPilotManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,15 @@ async def start_mavlink_manager(self, device: Endpoint) -> None:
persistent=True,
protected=True,
),
Endpoint(
name="MavFTP",
owner=self.settings.app_name,
connection_type=EndpointType.UDPClient,
place="127.0.0.1",
argument=14555,
persistent=True,
protected=True,
),
]
for endpoint in default_endpoints:
try:
Expand Down
1 change: 1 addition & 0 deletions core/services/install-services.sh
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ SERVICES=(
ping
versionchooser
wifi
mavftp
)

# We need to install loguru, appdirs and pydantic since they may be used inside setup.py
Expand Down
74 changes: 74 additions & 0 deletions core/services/mavftp/ftp_op.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import struct
from typing import Optional

OP_None = 0
OP_TerminateSession = 1
OP_ResetSessions = 2
OP_ListDirectory = 3
OP_OpenFileRO = 4
OP_ReadFile = 5
OP_CreateFile = 6
OP_WriteFile = 7
OP_RemoveFile = 8
OP_CreateDirectory = 9
OP_RemoveDirectory = 10
OP_OpenFileWO = 11
OP_TruncateFile = 12
OP_Rename = 13
OP_CalcFileCRC32 = 14
OP_BurstReadFile = 15
OP_Ack = 128
OP_Nack = 129


# pylint: disable=too-many-arguments
# pylint: disable=too-many-instance-attributes


class FTP_OP:
def __init__(
self,
seq: int,
session: int,
opcode: int,
size: int,
req_opcode: int,
burst_complete: int,
offset: int,
payload: Optional[bytearray],
):
self.seq = seq
self.session = session
self.opcode = opcode
self.size = size
self.req_opcode = req_opcode
self.burst_complete = burst_complete
self.offset = offset
self.payload = payload

def pack(self) -> bytearray:
"""pack message"""
ret = struct.pack(
"<HBBBBBBI",
self.seq,
self.session,
self.opcode,
self.size,
self.req_opcode,
self.burst_complete,
0,
self.offset,
)
if self.payload is not None:
ret += self.payload
ret = bytearray(ret)
return ret

def __str__(self) -> str:
plen = 0
if self.payload is not None:
plen = len(self.payload)
ret = f"OP seq:{self.seq} sess:{self.session} opcode:{self.opcode} req_opcode:{self.req_opcode} size:{self.size} bc:{self.burst_complete} ofs:{self.offset} plen={plen}"
if self.payload is not None and plen > 0:
ret += f" [{self.payload[0]}]"
return ret
154 changes: 154 additions & 0 deletions core/services/mavftp/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
#!/usr/bin/env python

import errno
import os
import time
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from typing import Any, Dict, Optional

from fuse import FUSE, FuseOSError, LoggingMixIn, Operations
from loguru import logger
from pymavlink import mavutil

from mavftp import FTPModule

# this allows us to support acessing the special files
base_file_paths = ["/", "@ROMFS", "@SYS"]


class MAVFTP(LoggingMixIn, Operations):
def __init__(self, mav: Any) -> None:
self.mav = mav
self.files: Dict[str, Dict[str, int]] = {
path: {
"st_mode": 0o40755,
"st_nlink": 2,
"st_size": 0,
# we need some timestamp for filebrowser be happy
"st_ctime": int(time.time()),
"st_mtime": int(time.time()),
"st_atime": int(time.time()),
}
for path in base_file_paths
}
self.ftp = FTPModule(mav)

def fix_path(self, path: str) -> str:
if path.startswith("/@"):
return path[1:]
return path

def getattr(self, path: str, _fh: int = 0) -> Any:
path_fixed = self.fix_path(path)
logger.info(f"Fuse: getattr {path_fixed}")
if path_fixed in self.files:
return self.files[path_fixed]

parent_dir = ("/" + "/".join(path.split("/")[:-1])).replace("//", "/")
logger.debug(f"cache miss, asking for {parent_dir}")
self.readdir(parent_dir)
if path not in self.files:
raise FuseOSError(errno.ENOENT)
return self.files[path]

def read(self, path: str, size: int, offset: int, _fh: int = 0) -> Optional[bytes]:
buf = self.ftp.read_sector(self.fix_path(path), offset, size)
# logger.info(f"read result: {buf}")
return buf

def readdir(self, path: str, _fh: int = 0) -> Any:
path_fixed = self.fix_path(path)
logger.info(f"Fuse: readdir {path_fixed}")
directory = self.ftp.list(path_fixed)
if directory is None or len(directory) == 0:
return []
ret = {}
for item in directory:
if item.name in [".", ".."]:
continue
if not item.is_dir:
new_item = {"st_mode": (0o100444), "st_size": item.size_b}
else:
new_item = {
"st_mode": (0o46766),
"st_nlink": 2, # Self-link and parent link
"st_size": 0, # Size 0 for simplicity
# current timestamp for filebrowswer to be happy
"st_ctime": int(time.time()), # Current time
"st_mtime": int(time.time()), # Current time
"st_atime": int(time.time()), # Current time
}
ret[item.name] = new_item
new_path = path if path.endswith("/") else path + "/"
self.files[new_path + item.name] = new_item
self.files[path] = {"st_mode": (0o46766), "st_size": 0}
return ret

def create(self, path: str, fi: int = 0) -> None:
logger.info(f"Fuse: create {path}, fi={fi}")
raise FuseOSError(errno.ENOENT)

def mknod(self, path: str) -> None:
logger.error(f"Fuse: lookup {path}")
raise FuseOSError(errno.ENOENT)

def write(self, path: str, _data: bytes, _offset: int, _fh: int) -> None:
logger.error(f"Fuse: write {path}")
raise FuseOSError(errno.EROFS)

def mkdir(self, path: str, _mode: int) -> None:
logger.error(f"Fuse: mkdir {path}")
raise FuseOSError(errno.EROFS)

def rmdir(self, path: str) -> None:
logger.error(f"Fuse: rmdir {path}")
raise FuseOSError(errno.EROFS)

def unlink(self, path: str) -> None:
logger.error(f"Fuse: unlink {path}")
raise FuseOSError(errno.EROFS)

def rename(self, old: str, new: str) -> None:
logger.error(f"Fuse: rename {old} -> {new}")
raise FuseOSError(errno.EROFS)

def chmod(self, path: str, _mode: int) -> None:
logger.error(f"Fuse: chmod {path}")
raise FuseOSError(errno.EROFS)

def chown(self, path: str, _uid: int, _gid: int) -> None:
logger.error(f"Fuse: chown {path}")
raise FuseOSError(errno.EROFS)

def truncate(self, path: str) -> None:
logger.info(f"Fuse: truncate {path}")
raise FuseOSError(errno.EROFS)


if __name__ == "__main__":
# logging.basicConfig(level=logging.DEBUG)
parser = ArgumentParser(description="MAVLink FTP", formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument(
"-m",
"--mavlink",
default="udpin:127.0.0.1:14555",
help="MAVLink connection specifier",
)
parser.add_argument(
"--mountpoint",
help="Path to the mountpoint",
)

args = parser.parse_args()

if not os.path.exists(args.mountpoint):
os.makedirs(args.mountpoint)

fuse = FUSE(
MAVFTP(mavutil.mavlink_connection(args.mavlink)),
args.mountpoint,
foreground=True,
ro=True,
nothreads=True,
allow_other=True,
)
Loading

0 comments on commit b16dea5

Please sign in to comment.