Files
HP_InHand_IG502/code snippets/measures_to_alarms.py

96 lines
3.1 KiB
Python
Executable File
Raw 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
"""
filter_and_expand_csv.py
Reads a CSV, keeps rows whose first column ends in "_alm",
and writes a new CSV with the desired columns and boilerplate values.
"""
import csv
import sys
from pathlib import Path
import traceback
# ------------------------------------------------------------
# The boilerplate column values (in the order requested)
DEFAULTS = {
"AlarmLevel" : "5",
"Condition1" : "eq",
"Operand1" : "1",
"CombineMethod": "none",
"Condition2" : "eq",
"Operand2" : "", # empty string -> CSV blank
"AlarmContent" : "ALARMED",
"AlarmTag" : "default"
}
# ------------------------------------------------------------
def main(input_csv: Path, output_csv: Path):
with open(input_csv, newline='', encoding='utf-8') as fin, \
open(output_csv, 'w', newline='', encoding='utf-8') as fout:
reader = csv.reader(fin)
writer = csv.writer(fout)
# write the header
writer.writerow([
"AlarmName", "ControllerName", "MeasuringPointName",
"AlarmLevel", "Condition1", "Operand1", "CombineMethod",
"Condition2", "Operand2", "AlarmContent", "AlarmTag"
])
# process each row
for row in reader:
if not row: # skip empty rows
continue
alarm_name = row[0].strip()
# keep only rows that end with "_alm"
if not alarm_name.endswith("_alm"):
continue
# Column 2 might not exist guard against it
controller = row[1].strip() if len(row) > 1 else ""
# Build the new row
new_row = [
alarm_name, # AlarmName
controller, # ControllerName
alarm_name, # MeasuringPointName
DEFAULTS["AlarmLevel"],
DEFAULTS["Condition1"],
DEFAULTS["Operand1"],
DEFAULTS["CombineMethod"],
DEFAULTS["Condition2"],
DEFAULTS["Operand2"],
DEFAULTS["AlarmContent"],
DEFAULTS["AlarmTag"]
]
writer.writerow(new_row)
print(f"✓ Finished. Result written to {output_csv}")
# ------------------------------------------------------------
if __name__ == "__main__":
# Usage: python csv_to_json.py input.json output.csv
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} <input.csv> <output.csv>", file=sys.stderr)
sys.exit(1)
# ------------------------------------------------------------
# Configuration change if your input is somewhere else
input_csv = Path(sys.argv[1]) # source JSON file
output_csv = Path(sys.argv[2]) # destination CSV file
if not input_csv.exists():
print(f"❌ File not found: {input_csv}", file=sys.stderr)
sys.exit(1)
try:
main(input_csv,output_csv)
except Exception as exc:
traceback.print_exc()
sys.exit(1)