open-remora

Open Remora, a free secondary dive computer for Apple Watch Ultra
git clone https://git.schurger.org/open-remora.git
Log | Files | Refs | README | LICENSE

shearwater_decode.py (5120B)


      1 # SPDX-License-Identifier: GPL-2.0-only
      2 """Decodes the Shearwater Cloud export (dive_data.db, sw-pnf format) to JSON.
      3 Usage: python3 -I shearwater_decode.py path/dive_data.db [output.json] [--dump N]
      4 Sample fields as per libdivecomputer (shearwater_predator_parser.c, PNF format)."""
      5 import gzip, json, sqlite3, struct, sys
      6 
      7 def records(blob):
      8     data = gzip.decompress(blob[4:])
      9     return [data[i:i + 32] for i in range(0, len(data), 32)]
     10 
     11 def number(text):
     12     """Shearwater Cloud writes numbers with the locale of the phone: '5,945122' on a French one."""
     13     try: return float(str(text).replace(",", "."))
     14     except ValueError: return None
     15 
     16 MODES = {0: "cc", 1: "oc-tec", 2: "gauge", 3: "ppo2-gauge", 4: "sc", 5: "cc2", 6: "oc-rec", 7: "freedive"}
     17 MODELS = {0: "GF", 1: "VPM-B", 2: "VPM-B/GFS", 3: "DCIEM"}
     18 
     19 def decode(db_path):
     20     db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
     21     details = {r[0]: r for r in db.execute("select DiveId, DiveNumber, Site, Depth, DiveLengthTime, DiveDate from dive_details")}
     22     dives = []
     23     for log_id, name, blob, calc in db.execute("select log_id, file_name, data_bytes_1, calculated_values_from_samples from log_data order by log_id"):
     24         recs = records(blob)
     25         byt = {r[0]: r for r in recs if r[0] != 0x01}
     26         o0, o1, o5 = byt.get(0x10), byt.get(0x11), byt.get(0x15)
     27         o2, o3, o4 = byt.get(0x12), byt.get(0x13), byt.get(0x14)
     28         d = details.get(log_id)
     29         dive = {
     30             "id": log_id, "file": name, "number": d[1] if d else None, "site": d[2] if d else None,
     31             "date": d[5] if d else None, "cloud_max_depth": number(d[3]) if d else None,
     32             "gf_low": o0[4], "gf_high": o0[5], "imperial": o0[8],
     33             "surface_mbar": struct.unpack(">H", o1[16:18])[0],
     34             # Deco model, water density (kg/m³) and dive mode: opening records 2, 3 and 4.
     35             "model": MODELS.get(o2[18], str(o2[18])) if o2 else None,
     36             "density": struct.unpack(">H", o3[3:5])[0] if o3 else None,
     37             "mode": MODES.get(o4[1], str(o4[1])) if o4 else None,
     38             "computer": name.split("[")[0],
     39             "sample_ms": (struct.unpack(">H", o5[23:25])[0] if o5 else 0) or 10000,   # not logged before version 9: 10 s
     40             "raw_opening": {f"{k:02x}": v.hex() for k, v in sorted(byt.items()) if k < 0x20},
     41             "calc": json.loads(calc) if calc else None, "samples": [], "tissues": [],
     42         }
     43         # Imperial logs: depths in feet (stops every 10 ft). Everything is written in metres, the stops
     44         # on the nearest whole metre (10 ft -> 3 m) so that they compare with a 3 m grid.
     45         unit = 0.3048 if o0[8] else 1.0
     46         buf = b""
     47         for r in recs:
     48             if 0x70 <= r[0] <= 0x75:
     49                 # Tissue snapshot, about every 5 min (log version 13 and later): 16 nitrogen pressures
     50                 # then 16 helium pressures (bar, little-endian floats) spread over six records.
     51                 buf += r[4:32]
     52                 if r[0] == 0x75:
     53                     dive["tissues"].append({"index": len(dive["samples"]),
     54                                             "n2": [round(x, 5) for x in struct.unpack("<16f", buf[:64])],
     55                                             "he": [round(x, 5) for x in struct.unpack("<16f", buf[64:128])]})
     56                     buf = b""
     57                 continue
     58             if r[0] != 0x01: continue
     59             stop_depth = struct.unpack(">H", r[3:5])[0]
     60             dive["samples"].append({
     61                 "depth": round(struct.unpack(">H", r[1:3])[0] / 10 * unit, 2), "stop_depth": round(stop_depth * unit),
     62                 "tts": struct.unpack(">H", r[5:7])[0], "ppo2": r[7] / 100, "o2": r[8], "he": r[9],
     63                 "ndl_or_stop": r[10], "status": r[12], "temp": struct.unpack("b", r[14:15])[0],
     64                 "cns": r[23], "ceiling": r[24], "gf99": r[25],
     65             })
     66         dives.append(dive)
     67     return dives
     68 
     69 if __name__ == "__main__":
     70     dives = decode(sys.argv[1])
     71     if "--dump" in sys.argv:
     72         n = int(sys.argv[sys.argv.index("--dump") + 1])
     73         d = dives[n]
     74         print({k: v for k, v in d.items() if k not in ("samples", "raw_opening")})
     75         for i, s in enumerate(d["samples"]):
     76             if i % max(1, len(d["samples"]) // 40) == 0: print(i, s)
     77     else:
     78         for d in dives:
     79             s = d["samples"]
     80             print(d["number"], d["date"], d["site"], d["computer"], d["mode"], d["model"], "GF", d["gf_low"], d["gf_high"],
     81                   "density", d["density"], "ft" if d["imperial"] else "m", "surf", d["surface_mbar"],
     82                   "step", d["sample_ms"], "n", len(s), "max", max(x["depth"] for x in s), "cloud", d["cloud_max_depth"],
     83                   "O2/He", sorted({(x["o2"], x["he"]) for x in s}), "snapshots", len(d["tissues"]), "NDLmin", min(x["ndl_or_stop"] for x in s if x["stop_depth"] == 0),
     84                   "stops", sorted({x["stop_depth"] for x in s}), "temp", min(x["temp"] for x in s))
     85         if len(sys.argv) > 2 and not sys.argv[2].startswith("--"):
     86             json.dump(dives, open(sys.argv[2], "w"))
     87             print("wrote", sys.argv[2])