Files
ThingsBoard/Code Snippets/add_alarms.py
2024-07-31 14:02:59 -05:00

92 lines
3.6 KiB
Python

import json,uuid
# Load the existing JSON data from the file
path = "ek_chemical.json"
with open(path, 'r') as f:
data = json.load(f)
# Define the new keys to add as alarms
new_keys = {
"vfd_01_faulted_alm": {"severity": "CRITICAL", "alarmType": "VFD 01 Faulted Alarm"},
"vfd_01_status_alm": {"severity": "CRITICAL", "alarmType": "VFD 01 Status Alarm"},
"vfd_01_undervoltage_alm": {"severity": "CRITICAL", "alarmType": "VFD 01 Undervoltage Alarm"},
"vfd_02_faulted_alm": {"severity": "CRITICAL", "alarmType": "VFD 02 Faulted Alarm"},
"vfd_02_status_alm": {"severity": "CRITICAL", "alarmType": "VFD 02 Status Alarm"},
"vfd_02_undervoltage_alm": {"severity": "CRITICAL", "alarmType": "VFD 02 Undervoltage Alarm"}
}
def checkDuplicates(key, alarms):
if alarms:
for alarm in alarms:
if alarm["clearRule"]["condition"]["condition"][0]["key"]["key"] == key:
return False
return True
# Loop through the new keys and create a new alarm based on the existing ones
for key, value in new_keys.items():
if checkDuplicates(key, data["profileData"]["alarms"]):
id = str(uuid.uuid4())
createRules = {
value["severity"]: {
"condition": {
"condition": [
{
"key": {"type": "TIME_SERIES", "key": key},
"valueType": "BOOLEAN",
"value": None,
"predicate": {"type": "BOOLEAN", "operation": "EQUAL", "value": {"defaultValue": True, "userValue": None, "dynamicValue": None}}
}
],
"spec": {"type": "SIMPLE"}
},
"schedule": None,
"alarmDetails": "",
"dashboardId": None
}
}
clearRule = {
"condition": {
"condition": [
{
"key": {"type": "TIME_SERIES", "key": key},
"valueType": "BOOLEAN",
"value": None,
"predicate": {"type": "BOOLEAN", "operation": "EQUAL", "value": {"defaultValue": False, "userValue": None, "dynamicValue": None}}
}
],
"spec": {"type": "DURATION", "unit": "MINUTES", "predicate": {"defaultValue": 30, "userValue": None, "dynamicValue": None}}
},
"schedule": None,
"alarmDetails": None,
"dashboardId": None
}
propagate = False
propagateToOwner = False
propagateToOwnerHierarchy = False
propagateToTenant = False
propagateRelationTypes = None
# Create a new alarm with the updated createRules and clearRule
new_alarm = {
"id": id,
"alarmType": value["alarmType"],
"createRules": createRules,
"clearRule": clearRule,
"propagate": propagate,
"propagateToOwner": propagateToOwner,
"propagateToOwnerHierarchy": propagateToOwnerHierarchy,
"propagateToTenant": propagateToTenant,
"propagateRelationTypes": propagateRelationTypes
}
# Add the new alarm to the existing alarms array
if not data["profileData"]["alarms"]:
data["profileData"]["alarms"] = []
data["profileData"]["alarms"].append(new_alarm)
print(f"Added {value['severity']} alarm for {key}")
else:
print(f"Skipped {key}")
# Save the updated JSON data back to the file
with open(path, 'w') as f:
json.dump(data, f, indent=4)