This article describes how to capture an Event Rules alarm/notification data and use it in your 3rd party application to perform an appropriate action in response to the triggered Event Rule.
When an Event Rule is triggered with the appropriate Action set, it is broadcasted by the Nx Meta Server in the transaction bus. Third party systems can use the ec2/transactionBusAPI request to subscribe to the data stream and read the live notifications in the form of JSON objects. It can be performed over an HTTP or Websocket connection, see the API documentation for more details.
Note: In addition to Event Rule data, most changes made on a Server are also broadcasted over the transaction bus (Server, cameras, layouts settings and status changes, etc), but this article will focus specifically on Event Rule data.
Prerequisite: Configure an Event Rule
In order to start receiving notifications, you will need to create a new Event Rule as follows:
- Launch the Desktop Client and connect to a System.
- Open the Main Menu > System Administration > Event Rules.
- Click Add to create a new Event Rule.
- Select an Event you want to track.
- For the Action, select Show desktop notification to make a Server broadcast the alarms over the transaction bus.
- Apply changes.
How to View and Filter the JSON Data from the Transaction Bus
A filtering option via the ec2/transactionBus API request is not available on 5.0 Systems, so you will need to manually filter out the excess information displayed by the API request.
We created a Python code example to demonstrate how this can be achieved by using asynchronous requests. Asynchronous requests are used so you can continue receiving updates from the Transaction Bus while the program performs other tasks.
import asyncio
import aiohttp
# Define an async function to log in to the API
async def login():
# Start a new aiohttp client session
async with aiohttp.ClientSession() as session:
# Use the session to make a POST request to the login endpoint
async with session.post('https://localhost:7001/web/rest/v1/login/sessions', json={
"username": "admin",
"password": "password123",
"setCookie": True
}, ssl=False) as response:
# Return the JSON response of the request
return await response.json()
# Define an async function to connect to the websocket API
async def get_bus_ws():
# Call the login function and get the token from the response
res = (await login())['token']
# Start a new aiohttp client session
async with aiohttp.ClientSession() as session:
# Use the session to connect to the websocket API
async with session.ws_connect('wss://localhost:7001/web/ec2/transactionBus/websocket',
headers={'X-Runtime-GUID': res}, ssl=False) as ws:
# Loop indefinitely
while True:
# Receive a message from the websocket API
response = (await ws.receive()).json()
# Extract the command and params from the response to filter everything else out
command = response['tran']['command']
params = response['tran']['params']
print(command, params)
# Define a function to run the async function
def main():
# Run the async function using asyncio
asyncio.run(get_bus_ws())
# If this script is run as the main script, call the main
if __name__ == '__main__':
main()
You will receive a constant stream of information from the transaction bus in JSON format containing relevant information (Event Rules and changes to the Server).
Understanding the JSON Data
The transaction bus was initially designed to transfer data internally between different parts of the software, as a result, it provides too much data to be effectively used for 3rd party applications.
We will focus on the general structure of the incoming JSONs and describe only the details essential to processing the Event Alerts. Other parameters and possible values will be omitted.
Incoming JSON transaction example:
{ "tran": { "command": "broadcastAction", "historyAttributes": { "author": "{bc292159-2be9-4e84-a242-bc6122b315e4}" }, "params": { "actionType": "showPopupAction", "aggregationCount": 1, "params": "eyJhY3Rpb25JZCI6Ins2Y2ZhYWJkMi1lOWFkLTQzNzUtODY0Zi04ZDI5YjQ3OTVlYWZ9IiwiYWRkaXRpb25hbFJlc291cmNlcyI6WyJ7MDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMTAwMDAwMDAwMDAwfSIsInswMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0xMDAwMDAwMDAwMDF9Il0sImFsbFVzZXJzIjpmYWxzZSwiYXV0aFR5cGUiOiJhdXRoQmFzaWNBbmREaWdlc3QiLCJkdXJhdGlvbk1zIjo1MDAwLCJmb3JjZWQiOnRydWUsImZwcyI6MTAsIm5lZWRDb25maXJtYXRpb24iOmZhbHNlLCJwbGF5VG9DbGllbnQiOnRydWUsInJlY29yZEFmdGVyIjowLCJyZWNvcmRCZWZvcmVNcyI6MTAwMCwicmVxdWVzdFR5cGUiOiIiLCJzdHJlYW1RdWFsaXR5IjoiaGlnaGVzdCIsInVzZVNvdXJjZSI6ZmFsc2V9", "receivedFromRemoteHost": false, "resourceIds": [], "ruleId": "{b4372abe-a402-46a0-bb70-cfa56112f8ce}", "runtimeParams": "eyJkZXNjcmlwdGlvbiI6Il9iZWxsX29uIiwiZXZlbnRSZXNvdXJjZUlkIjoiezI2YjA3NTExLTI5YzItYmQwOC1kMWM4LWI0NTk5OGE1Y2UyMX0iLCJldmVudFRpbWVzdGFtcFVzZWMiOiIxNjQzNzI4NTU5NzkyMDAwIiwiZXZlbnRUeXBlIjoic29mdHdhcmVUcmlnZ2VyRXZlbnQiLCJpbnB1dFBvcnRJZCI6IjU0YTk1N2Q1LTJiMmUtNGE1NS1iYmVkLTMxNjkyZDM2N2I3OCIsIm1ldGFkYXRhIjp7ImFsbFVzZXJzIjpmYWxzZSwiaW5zdGlnYXRvcnMiOlsiezk5Y2JjNzE1LTUzOWItNGJmZS04NTZmLTc5OWI0NWI2OWIxZX0iXSwibGV2ZWwiOiIwIn0sIm9taXREYkxvZ2dpbmciOmZhbHNlLCJyZWFzb25Db2RlIjoibm9uZSIsInNvdXJjZVNlcnZlcklkIjoiezE4OGI0Mzg5LTY2MjEtODM0MS0yMDVhLTliY2UyMWQwMTI3Nn0ifQ==", "toggleState": "Undefined" }, "peerID": "{188b4389-6621-8341-205a-9bce21d01276}", "persistentInfo": { "dbID": "{00000000-0000-0000-0000-000000000000}", "sequence": 0, "timestamp": { "sequence": "0", "ticks": "0" } }, "transactionType": "Regular" } }
- tran is the validation keyword which states the value data that comes in a form of the nested JSON object is a server transaction
- command is the validation keyword to differentiate between different types of transactions. The value comes as a string.
- All actions that force clients to do something on their side are marked with the broadcastAction value. Alert notifications could also be filtered using this key-value pair.
- The value behind the params upper-level key contains most of the essential data related to the transaction in a form of the nested JSON object. Most of them are command-specific. We will only cover the ones related to the broadcastAction type.
- actionType key has string values. All alerts notifications are passed with the showPopupAction.
- aggregationCountkey has integer values. It represents a number of the same event being triggered during the configured aggregation period.
- paramskey has the value of a base64-encoded string. Upon decoding, it appears to be a nested JSON object with some technical details used by the Client for proper display of the event.
- runtimeParamskey has the value of a base64-encoded string. Upon decoding it appears to be a nested JSON object with the essential details about an event that triggered the alarm, example:
{ "analyticsEngineId": "{687611a2-fd30-94e7-7f4c-8705642b0bcc}", "caption": "Line crossing - impulse event (caption)", "description": "Line crossing - impulse event (description)", "eventResourceId": "{26b07511-29c2-bd08-d1c8-b45998a5ce21}", "eventTimestampUsec": "1643733726062192", "eventType": "analyticsSdkEvent", "inputPortId": "nx.stub.lineCrossing", "metadata": { "allUsers": false, "level": "0" }, "omitDbLogging": false, "reasonCode": "none", "sourceServerId": "{188b4389-6621-8341-205a-9bce21d01276}" }
- analyticsEngineId, if present, has a string value. Within the curly brackets, Server returns the ID of the analytics engine that triggered the alarm. Specific values should be matched against the Server response to the ec2/getAnalyticsEngines information request.
- caption, if present, has a string value - some custom text generated by the analytics plugin or the 3rd party via a Generic Event.
- description, if present, has a string value - some custom text generated by the analytics plugin or the 3rd party via a Generic Event.
- eventResourceId, if present, has a string value. Within the curly brackets, the Server returns the ID of the resource triggering the event.
Different types of the events could be generated by the cameras, Servers or by the user(in this case, the key will be omitted). Specific values should be matched against the Server response to ec2/getMediaServers and ec2/getCamerasEx information requests. - eventTimestampUsechas a string value. A value represents the exact System-wide timestamp of the event in milliseconds since epoch(1970-01-01 00:00, UTC). The time synchronization feature guarantees simultaneity of the event for different Servers merged into one System.
- eventTypehas a string value. This value reflects the event type that triggered the notification.
- sourceServerIdhas a string value. Within the curly brackets, the Server returns the ID of the Server which was first to register this particular alarm. Specific values should be matched against the Server’s response to ec2/getMediaServers.
Comments
0 comments
Article is closed for comments.