[Feature Request]: Import Tusa DC Solar logs

オープン
#4,529 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 2 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
40/100
issue の種類
機能追加
明瞭さ
おおむね明確
活発さ
停滞
技術スタック
python, sqlite
領域
databases, desktop

調査の方向性

Start with the attached jp-tabata-divinglog-backup.zip and the supplied Python converter, inspecting the SQLite DIVING_LOG_TB schema and its field mappings. Compare the generated Subsurface XML with the application's supported import formats. Done means Tusa DC Solar logs can be imported with the relevant dive data preserved and verified in Subsurface.

索引モデルが issue の本文から書いたものです。

説明

Problem Statement

The Tusa DC Solar is currently not supported by Subsurface.

Description

While connecting to the computer via Blutooth might be difficult. It is possible to export the dive logs from the computer which gives you a zip file that contains an sqlite DB with all the dive data. The DB can also be reimported.

jp-tabata-divinglog-backup.zip

Alternative Solutions

I have created a basic python script to conver the sqlite db into subsurface xml:

#!/usr/bin/env python3
"""
Tusa sqlite to Subsurface XML Converter
Converts diving log data from Tusa sqlite database to Subsurface XML format.
"""

import sqlite3
import xml.etree.ElementTree as ET
from datetime import datetime
import argparse
import sys
from pathlib import Path


class DivingLogConverter:
    """Converter class for transforming Tusa sqlite diving logs to Subsurface XML format."""

    def __init__(self):
        self.root = None
        self.divelog = None
        self.dives = None

    def create_xml_structure(self):
        """Create the basic XML structure for Subsurface format."""
        self.root = ET.Element("divelog")
        self.root.set("program", "subsurface")
        self.root.set("version", "3")

        settings = ET.SubElement(self.root, "settings")

        self.dives = ET.SubElement(self.root, "dives")

    def parse_timestamp(self, timestamp_str):
        """Parse timestamp from milliseconds to datetime format."""
        try:
            if timestamp_str is not None:
                if isinstance(timestamp_str, (int, float)):
                    timestamp_ms = timestamp_str
                else:
                    timestamp_str = str(timestamp_str).strip()
                    if not timestamp_str:
                        return None
                    timestamp_ms = float(timestamp_str)

                timestamp_s = timestamp_ms / 1000
                dt = datetime.fromtimestamp(timestamp_s)
                return dt.strftime("%Y-%m-%d %H:%M:%S")
        except (ValueError, TypeError):
            pass
        return None

    def parse_profile_data(self, depth_str, temp_str):
        """Parse depth and temperature profile data."""
        depth_points = []
        temp_points = []

        # Parse depth data
        if depth_str and depth_str.strip():
            try:
                depths = [float(d.strip()) for d in depth_str.split(",") if d.strip()]
                depth_points = depths
            except ValueError:
                pass

        # Parse temperature data
        if temp_str and temp_str.strip():
            try:
                temps = [float(t.strip()) for t in temp_str.split(",") if t.strip()]
                temp_points = temps
            except ValueError:
                pass

        return depth_points, temp_points

    def convert_pressure(self, pressure_str):
        """Convert pressure value, assuming it's in bar."""
        try:
            if pressure_str is not None:
                if isinstance(pressure_str, (int, float)):
                    return float(pressure_str)
                elif str(pressure_str).strip():
                    return float(pressure_str)
        except (ValueError, TypeError):
            pass
        return None

    def add_dive(self, row):
        """Add a single dive to the XML structure."""
        dive = ET.SubElement(self.dives, "dive")

        # Set dive number
        dive_id = row.get("_ID", "")
        if dive_id:
            dive.set("number", str(dive_id))

        # Set date and time
        date_str = row.get("DATE", "")
        time_str = row.get("CREATE_DATE", "")

        if date_str and str(date_str).strip():
            try:
                if isinstance(date_str, (int, float)) or (
                    "." in str(date_str) and len(str(date_str)) > 10
                ):
                    timestamp_ms = float(date_str)
                    timestamp_s = timestamp_ms / 1000
                    dt = datetime.fromtimestamp(timestamp_s)
                    dive.set("date", dt.strftime("%Y-%m-%d"))
                    dive.set("time", dt.strftime("%H:%M:%S"))
                else:
                    dive.set("date", str(date_str))
            except (ValueError, TypeError):
                dive.set("date", str(date_str))

        parsed_time = self.parse_timestamp(time_str)
        if parsed_time and not dive.get("date"):
            dive.set("date", parsed_time.split(" ")[0])
            dive.set("time", parsed_time.split(" ")[1])

        duration = row.get("BOTTOM_TIME_MINUTE", "")
        if duration:
            try:
                duration_min = float(duration)
                duration_sec = int(duration_min * 60)
                dive.set("duration", f"{duration_sec}:00 min")
            except ValueError:
                pass

        # Add visibility and current as dive attributes
        visibility = row.get("TRANSPARENCY", "")
        if (
            visibility
            and str(visibility).strip()
            and str(visibility) != "-999"
            and str(visibility) != "-999.0"
        ):
            try:
                visibility_val = float(visibility)
                if visibility_val > 0:
                    dive.set("visibility", str(int(visibility_val)))
            except ValueError:
                pass

        current_type = row.get("CURRENT_TYPE", "")
        if (
            current_type
            and str(current_type).strip()
            and str(current_type) != "-999"
            and str(current_type) != "-999.0"
            and str(current_type) != "0"
        ):
            try:
                current_val = int(current_type)
                dive.set("current", str(current_val))
            except ValueError:
                pass

        location = row.get("LOCATION", "")
        point = row.get("POINT", "")
        if location or point:
            location_text = f"{location} - {point}".strip(" -")
            if location_text:
                ET.SubElement(dive, "location").text = location_text

        lat = row.get("POINT_LATITUDE", "")
        lon = row.get("POINT_LONGITUDE", "")
        if lat and lon:
            try:
                gps = ET.SubElement(dive, "gps")
                gps.set("lat", str(float(lat)))
                gps.set("lon", str(float(lon)))
            except ValueError:
                pass

        # Add cylinder information
        start_pressure = self.convert_pressure(row.get("START_PRESSURE", ""))
        end_pressure = self.convert_pressure(row.get("END_PRESSURE", ""))
        tank_size = row.get("TANK_SIZE", "")

        if start_pressure or end_pressure or tank_size:
            cylinder = ET.SubElement(dive, "cylinder")
            if tank_size:
                try:
                    size_l = float(tank_size)
                    cylinder.set("size", f"{size_l:.1f} l")
                except ValueError:
                    pass
            if start_pressure:
                cylinder.set("start", f"{start_pressure:.0f} bar")
            if end_pressure:
                cylinder.set("end", f"{end_pressure:.0f} bar")

        # Add weight system
        weight = row.get("WEIGHT", "")
        if (
            weight
            and str(weight).strip()
            and str(weight) != "-999"
            and str(weight) != "-999.0"
        ):
            try:
                weight_kg = float(weight)
                if weight_kg > 0:
                    weightsystem = ET.SubElement(dive, "weightsystem")
                    weightsystem.set("weight", f"{weight_kg:.1f} kg")
                    weightsystem.set("description", "Weight")
            except ValueError:
                pass

        # Add air temperature as divetemperature
        air_temp = row.get("TEMP", "")
        if (
            air_temp
            and str(air_temp).strip()
            and str(air_temp) != "-999"
            and str(air_temp) != "-999.0"
        ):
            try:
                temp_c = float(air_temp)
                if temp_c > -100:  # Reasonable temperature check
                    divetemperature = ET.SubElement(dive, "divetemperature")
                    divetemperature.set("air", f"{temp_c:.1f} C")
            except ValueError:
                pass

        # Create divecomputer element for profile data and water temperature
        divecomputer = ET.SubElement(dive, "divecomputer")

        # Add water temperature inside divecomputer
        water_temp = row.get("WATER_TEMP", "")
        if water_temp:
            try:
                temp_c = float(water_temp)
                temperature = ET.SubElement(divecomputer, "temperature")
                temperature.set("water", f"{temp_c:.1f} C")
            except ValueError:
                pass

        # Add depth information
        max_depth = row.get("MAX_DEPTH", "")
        if max_depth:
            try:
                depth_m = float(max_depth)
                depth_elem = ET.SubElement(divecomputer, "depth")
                depth_elem.set("max", f"{depth_m:.1f} m")
            except ValueError:
                pass

        depth_data, temp_data = self.parse_profile_data(
            row.get("DEPTH_CSV_STR", ""), row.get("TEMP_CSV_STR", "")
        )

        if depth_data:
            max_samples = max(len(depth_data), len(temp_data))
            sample_interval = 20  # 20 second intervals

            for i in range(max_samples):
                sample = ET.SubElement(divecomputer, "sample")
                time_seconds = i * sample_interval
                minutes = time_seconds // 60
                seconds = time_seconds % 60
                sample.set("time", f"{minutes}:{seconds:02d} min")

                if i < len(depth_data):
                    sample.set("depth", f"{depth_data[i]:.1f} m")

                if i < len(temp_data):
                    sample.set("temp", f"{temp_data[i]:.1f} C")
        suit_thickness = row.get("SUIT_THICKNESS", "")
        suit_type = row.get("SUIT_TYPE", "")

        if (
            suit_thickness
            and str(suit_thickness).strip()
            and str(suit_thickness) != "-999.0"
        ):
            try:
                thickness_mm = float(suit_thickness)
                if thickness_mm > 0:
                    suit = ET.SubElement(dive, "suit")
                    suit.text = f"{thickness_mm:.1f} mm"
            except ValueError:
                pass

        notes_parts = []

        for field, label in [
            ("INSTRUCTOR_NAME", "Instructor"),
            ("BUDDY", "Buddy"),
            ("MEMO", "Notes"),
            ("NITROX_RATIO", "Nitrox %"),
            ("WEATHER_TYPE", "Weather"),
            ("WAVE_TYPE", "Wave"),
            ("WIND_TYPE", "Wind"),
        ]:
            value = row.get(field, "")
            if (
                value
                and str(value).strip()
                and str(value) != "-999"
                and str(value) != "-999.0"
            ):
                notes_parts.append(f"{label}: {value}")

        if suit_type and suit_type.strip() and suit_type != "0" and suit_type != "-999":
            suit_type_desc = f"Suit Type: {suit_type}"
            notes_parts.append(suit_type_desc)

        if notes_parts:
            notes = ET.SubElement(dive, "notes")
            notes.text = "\n".join(notes_parts)

    def convert_db_to_xml(self, db_file_path, output_file_path=None):
        """Convert SQLite database to Subsurface XML format."""
        self.create_xml_structure()

        try:
            conn = sqlite3.connect(db_file_path)
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()

            cursor.execute("SELECT * FROM DIVING_LOG_TB ORDER BY _ID")

            dive_count = 0
            for row in cursor.fetchall():
                row_dict = dict(row)
                self.add_dive(row_dict)
                dive_count += 1

            conn.close()
            print(f"Processed {dive_count} dives")

        except sqlite3.Error as e:
            print(f"Error reading SQLite database: {e}")
            return False
        except FileNotFoundError:
            print(f"Error: Database file '{db_file_path}' not found")
            return False
        except Exception as e:
            print(f"Error processing database: {e}")
            import traceback

            traceback.print_exc()
            return False

        if output_file_path is None:
            output_file_path = str(Path(db_file_path).with_suffix(".xml"))

        try:
            self.indent_xml(self.root)
            tree = ET.ElementTree(self.root)
            tree.write(output_file_path, encoding="utf-8", xml_declaration=True)
            print(f"Successfully converted to: {output_file_path}")
            return True

        except Exception as e:
            print(f"Error writing XML file: {e}")
            return False

    def indent_xml(self, elem, level=0):
        """Add pretty formatting to XML."""
        indent = "\n" + level * "  "
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = indent + "  "
            if not elem.tail or not elem.tail.strip():
                elem.tail = indent
            for elem in elem:
                self.indent_xml(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = indent
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = indent


def main():
    """Main function to run the converter."""
    parser = argparse.ArgumentParser(
        description="Convert diving log SQLite database to Subsurface XML format"
    )
    parser.add_argument("db_file", help="Path to the SQLite database file to convert")
    parser.add_argument("-o", "--output", help="Output XML file path (optional)")

    args = parser.parse_args()

    if not Path(args.db_file).exists():
        print(f"Error: File '{args.db_file}' does not exist")
        sys.exit(1)

    converter = DivingLogConverter()
    success = converter.convert_db_to_xml(args.db_file, args.output)

    if success:
        print("Conversion completed successfully!")
        sys.exit(0)
    else:
        print("Conversion failed!")
        sys.exit(1)


if __name__ == "__main__":
    main()
Mentions

No response

主要言語
C++
スター
3.2k
フォーク
623
平均マージ
1日 23時間
マージ済み PR(30日)
66

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

subsurface/subsurface のほかの issue

subsurface/subsurface の issue をすべて見る

似ている issue

C++ の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。