50 lines
2.3 KiB
Python
50 lines
2.3 KiB
Python
#!/usr/bin/env python3
|
||
# --------------------------------------------------------------
|
||
# Re‑interpret a list of DINT‑strings as IEEE‑754 REALs
|
||
# --------------------------------------------------------------
|
||
import json, struct
|
||
from pathlib import Path
|
||
|
||
# --------------------------------------------------------------
|
||
# 1. Load the JSON you already have
|
||
# --------------------------------------------------------------
|
||
source_file = Path("/Users/nico/Downloads/response_1772033457123.json") # <-- your file
|
||
data = json.loads(source_file.read_text())
|
||
|
||
# The data you showed is a dict with one key; get the list
|
||
raw_ts = data["vessel_2_oil_flow_rate"]
|
||
|
||
# --------------------------------------------------------------
|
||
# 2. Helper: reinterpret a 32‑bit signed int as a float
|
||
# --------------------------------------------------------------
|
||
def dint_str_to_real(value_str: str) -> float:
|
||
"""Return the IEEE‑754 float that has the same 4‑byte bit pattern."""
|
||
# Convert the string to a signed 32‑bit integer
|
||
dint = int(value_str) # Python ints are unbounded; pack will truncate
|
||
# Pack into 4 bytes (little‑endian) and unpack as a float
|
||
return struct.unpack("<f", struct.pack("<i", dint))[0]
|
||
|
||
# --------------------------------------------------------------
|
||
# 3. Walk the list and add a new field with the real value
|
||
# --------------------------------------------------------------
|
||
for point in raw_ts:
|
||
try:
|
||
point["value"] = dint_str_to_real(point["value"])
|
||
except Exception as exc:
|
||
# In the unlikely event the string is not an int
|
||
point["value_real"] = None
|
||
point["value_error"] = str(exc)
|
||
|
||
# --------------------------------------------------------------
|
||
# 4. (Optional) Sort by timestamp – the sample you posted was
|
||
# in descending order, but most time‑series libs expect ascending.
|
||
# --------------------------------------------------------------
|
||
raw_ts.sort(key=lambda p: p["ts"])
|
||
|
||
# --------------------------------------------------------------
|
||
# 5. Dump the corrected data back to JSON (or whatever you prefer)
|
||
# --------------------------------------------------------------
|
||
output_file = Path("/Users/nico/Downloads/response_1772033457123_corrected.json")
|
||
output_file.write_text(json.dumps(data, indent=2, sort_keys=False))
|
||
|
||
print(f"✔ Converted {len(raw_ts)} points – written to {output_file}") |