XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

AutoMiningScript

【SpaceEngineer】全自动挖矿脚本

公开
关注 0 Fork 0 Star 0
UTF-8
"""Record actual AMS flight state and motion without losing case-sensitive minified field names."""
import argparse
import datetime as dt
import json
import os
from pathlib import Path
import subprocess
import sys
import time

# Each mapping is checked against that exact minifier output. Never accept a
# new hash merely because a previous build happened to use the same names.
BASE = dict(state="Ԙ", flight="أ", job="ا", entry="ŏ", report="ب", progress="ؾ",
            command="ψ", attitude="χ", clearance="φ", scanIndex="Ͼ", blocked="ϭ",
            problem="ſ", camera="Ѕ", cameraDetail="І", obstacle="Ї")
MAPPINGS = {
    "2cc105a720ecd1552791816a0edf106cfab91b501a1e8048421b7f23382d333a": BASE,
    "b191430cf9ab7fe2b21569344ebcdc927bfa52847b84632440bdc68f3e5abc73": BASE,
    "2aed54ad323c588852f626455df0bb61c0e6565970c173dd5ed7007d832d259f":
        dict(state="Ԛ", flight="إ", job="ة", entry="Ő", report="ت", progress="ـ",
             command="ω", attitude="ψ", clearance="χ", scanIndex="Ͽ", blocked="Ϯ",
             problem="ƀ", camera="І", cameraDetail="Ї", obstacle="Ј"),
    "1146850d83e9d165d436828c2f526c212aa9e2928abe6eb447102cc4d3e7f2e3":
        dict(state="Ԝ", flight="ا", job="ث", entry="Ő", report="ج", progress="ق",
             command="ύ", attitude="ό", clearance="ϋ", scanIndex="Ѓ", blocked="ϲ",
             problem="ƅ", camera="Њ", cameraDetail="Ћ", obstacle="Ќ"),
}
# Capture extension changes no inspected declarations; checked against the new export.
MAPPINGS["9553e0ec92de8fc93c814852f37ff088f579c038ca8bdcf6c06b57e0f44d28ab"] = MAPPINGS[
    "1146850d83e9d165d436828c2f526c212aa9e2928abe6eb447102cc4d3e7f2e3"]
# Travel-heading and return-speed changes retain these declarations; verified
# against the exact packed export and its 86 mapped symbols.
MAPPINGS["e16d74c9a281749e6efb0ae21e0f143981270cd178ad5b326678d8f2069de56a"] = MAPPINGS[
    "9553e0ec92de8fc93c814852f37ff088f579c038ca8bdcf6c06b57e0f44d28ab"]
# Fixed-bearing breadcrumb compression adds a separate field; the inspected
# declarations above were checked unchanged in this export.
MAPPINGS["0deb647028dd43c0b7afe1dcbdacae7bc05fa93b7314bc75821429ef846cdbd1"] = MAPPINGS[
    "e16d74c9a281749e6efb0ae21e0f143981270cd178ad5b326678d8f2069de56a"]
# Sorter cargo classification changes no mapped fields or state identifiers.
MAPPINGS["39ca17bb98ca99d96df420b2586ff0bd7900684b95dfeea3073fd9a584a74a16"] = MAPPINGS[
    "0deb647028dd43c0b7afe1dcbdacae7bc05fa93b7314bc75821429ef846cdbd1"]
# Compared with the previous installed export: only the wait text changes from
# priority probing to priority mining. All inspected symbols are byte-identical.
MAPPINGS["9b130c141a8ce9d2fc22234fb5bd93d87f0bd41f7eb1c5b36a233ac7c1f9e917"] = MAPPINGS[
    "39ca17bb98ca99d96df420b2586ff0bd7900684b95dfeea3073fd9a584a74a16"]
# Full-depth entry checks and short traffic detours: miner, flight and job
# declarations plus both enum bodies compared against the installed export.
MAPPINGS["ea2550131391196849d3aceef1b3e62b74c9e44a94d4aa265f5f023e12578e9d"] = MAPPINGS[
    "9b130c141a8ce9d2fc22234fb5bd93d87f0bd41f7eb1c5b36a233ac7c1f9e917"]
# Mining transit progress watchdog: the same declaration/enum comparison passed.
MAPPINGS["71a1e718f76e079cef8b61a44b77456aa2fda8ee8caad383ccfd21c2a2c72269"] = MAPPINGS[
    "ea2550131391196849d3aceef1b3e62b74c9e44a94d4aa265f5f023e12578e9d"]
# Camera fallback parameters shift the miner declaration. Flight, job and enum
# symbols were checked separately in this exact packed export.
MAPPINGS["60c51c6c050b0a4ec23b67e27c0d7f0d2e6a388befdaa7f46c2a8f671e6e03ba"] = dict(
    state="Ԟ", flight="ة", job="ح", entry="Ő", report="خ", progress="ل",
    command="ύ", attitude="ό", clearance="ϋ", scanIndex="Ѓ", blocked="ϲ",
    problem="ƅ", camera="Њ", cameraDetail="Ћ", obstacle="Ќ")
# Nearby return-loop removal: all four declaration prefixes and both enums
# compared byte-for-byte (ignoring whitespace) with the preceding deployed source.
MAPPINGS["4e17863776b7c281547852d3e73a9921d7787852d5e992e4a4d5d720b8981ec7"] = MAPPINGS[
    "60c51c6c050b0a4ec23b67e27c0d7f0d2e6a388befdaa7f46c2a8f671e6e03ba"]
# Dock window interruptions no longer consume capture retries; declarations and
# enum bodies again verified against the preceding deployed export.
MAPPINGS["6ce28ca6329bc4b654d3c4d20f09a1ea8e9cd232132f859f100951ad1035139b"] = MAPPINGS[
    "4e17863776b7c281547852d3e73a9921d7787852d5e992e4a4d5d720b8981ec7"]
# Save only unfinished return breadcrumbs. Root/miner/flight declarations, job
# class and both enum bodies compared with the preceding export.
MAPPINGS["0938c9871de8facf78485a129a6d360be5213b1bea8e4590d7c2964cc67d3603"] = MAPPINGS[
    "6ce28ca6329bc4b654d3c4d20f09a1ea8e9cd232132f859f100951ad1035139b"]
STATES = {"î": "Boot", "ï": "Docked", "ð": "Servicing", "ñ": "Ready",
          "ò": "Departing", "ó": "Transit", "ô": "Survey", "õ": "Align",
          "ö": "Drilling", "ø": "Retreat", "ù": "Returning", "ú": "Holding",
          "û": "DockAlign", "ü": "DockApproach", "ý": "DockRetreat",
          "þ": "Paused", "ÿ": "Manual", "u": "Fault"}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--block", required=True)
    parser.add_argument("--grid", required=True)
    parser.add_argument("--seconds", type=float, default=30)
    parser.add_argument("--interval", type=float, default=1)
    parser.add_argument("--out", type=Path, required=True)
    parser.add_argument("--pipe")
    parser.add_argument("--cli", type=Path, default=os.environ.get("XFE_SE_AGENT_CLI"),
                        help="Path to xfe-se.exe; defaults to XFE_SE_AGENT_CLI.")
    args = parser.parse_args()
    if not 0 < args.seconds <= 600 or not .1 <= args.interval <= 30:
        parser.error("seconds must be 0..600 and interval must be 0.1..30")
    if args.cli is None:
        parser.error("Provide --cli <path to xfe-se.exe> or set XFE_SE_AGENT_CLI.")
    cli = args.cli.expanduser().resolve()
    if not cli.is_file():
        parser.error("Agent CLI executable was not found: " + str(cli))

    def call(method, parameters):
        command = [str(cli), "call", method, "--params", json.dumps(parameters)]
        if args.pipe:
            command += ["--pipe", args.pipe]
        process = subprocess.run(command, capture_output=True, encoding="utf-8", timeout=35)
        response = json.loads(process.stdout)
        if process.returncode or "error" in response:
            raise RuntimeError(response.get("error", process.stderr))
        return response["result"]

    program = call("pb.read", {"entityId": args.block})
    if program["sha256"] not in MAPPINGS:
        raise RuntimeError("Unrecognized AMS export " + program["sha256"] + "; derive a new field mapping for this source before tracing.")
    mapping = MAPPINGS[program["sha256"]]
    args.out.parent.mkdir(parents=True, exist_ok=True)
    started = time.monotonic()
    samples, previous = 0, None
    with args.out.open("x", encoding="utf-8") as output:
        while time.monotonic() - started < args.seconds:
            fields = call("pb.inspect", {"entityId": args.block, "fields": ["E", "H"], "depth": 3})["fields"]
            grid = call("grids.get", {"entityId": args.grid})
            role = fields["H"]
            flight = role[mapping["flight"]]
            job = role[mapping["job"]]
            state = role[mapping["state"]]
            sample = {"utc": dt.datetime.now(dt.timezone.utc).isoformat(), "time": fields["E"],
                      "state": state, "stateName": STATES.get(state, state),
                      "sourceSha256": program["sha256"], "reason": role["l"], "position": grid["pose"]["position"],
                      "actualSpeed": grid["speed"], "commandSpeed": flight[mapping["command"]],
                      "clearance": flight[mapping["clearance"]], "attitudeError": flight[mapping["attitude"]],
                      "scanIndex": flight[mapping["scanIndex"]], "scanBlocked": flight[mapping["blocked"]],
                      "problem": flight[mapping["problem"]], "camera": flight[mapping["camera"]],
                      "cameraDetail": flight[mapping["cameraDetail"]], "obstacle": flight[mapping["obstacle"]],
                      "jobId": job.get("g") if job else None, "jobEntry": job.get(mapping["entry"]) if job else None,
                      "progressAge": fields["E"] - role[mapping["progress"]],
                      "lastReport": role[mapping["report"]], "integrity": grid.get("integrity"), "fields": fields}
            output.write(json.dumps(sample, ensure_ascii=False, separators=(",", ":")) + "\n")
            output.flush()
            state = (sample["state"], sample["reason"])
            if state != previous:
                print(json.dumps({k: sample[k] for k in ("time", "state", "reason", "actualSpeed", "commandSpeed", "scanIndex")}, ensure_ascii=False), flush=True)
                previous = state
            samples += 1
            time.sleep(args.interval)
    print(json.dumps({"samples": samples, "output": str(args.out.resolve())}), flush=True)


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    main()