Files
HP_InHand_IG502/code snippets/convertDINTtoREAL.py
2026-03-10 13:22:03 -05:00

50 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# --------------------------------------------------------------
# Reinterpret a list of DINTstrings as IEEE754 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 32bit signed int as a float
# --------------------------------------------------------------
def dint_str_to_real(value_str: str) -> float:
"""Return the IEEE754 float that has the same 4byte bit pattern."""
# Convert the string to a signed 32bit integer
dint = int(value_str) # Python ints are unbounded; pack will truncate
# Pack into 4 bytes (littleendian) 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 timeseries 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}")