Building Agents

Overview

To get started with developing a new Agent, create a new C# library project in Visual Studio and import the XMPro.IoT.Framework NuGet package. When writing the code for an Agent, you will have to implement a number of interfaces. Which interfaces to implement depends on the category under which your Agent will fall:

Listeners

Listeners are created by implementing IAgent and IPollingAgent interfaces. To push the events to the next receiver, the OnPublish event should be invoked and the events should be passed as arguments.

Action Agents/ Functions

Action Agents are created by implementing the IAgent and IReceivingAgent interfaces. The Receive method will be called every time events are received by this Agent. To publish these events again, the same logic as per the Listener Agent can be used.

Context Providers

Context Providers are created by implementing the IAgent, IPollingAgent interfaces. They are very similar to Listeners; however, Context Providers publish all available records/events when polled instead of only publishing the newer/changed ones.

Transformations

Transformations are implemented in a similar way as Action Agents, except that all Transformations should have the Require Input Map flag set to false and must not implement the GetInputAttributes method, hence it should be:
1
public IEnumerable<XMIoT.Framework.Attribute> GetIntputAttributes(string endpoint, IDictionary<string, string> parameters)
2
{
3
4
throw new NotImplementedException();
5
6
}
Copied!
The interfaces that can be implemented are as follows:
The matrix below shows which interface needs to be implemented for which category Agent:
Agent Category
IAgent
IPollingAgent
IReceivingAgent
IPublishesError
Listener
Required
Required
Optional
Optional
Context Provider
Required
Required
Optional
Optional
Transformation
Required
Optional
Required
Optional
Action Agent/ Function
Required
Optional
Required
Optional
AI & Machine Learning
Required
Optional
Required
Optional

IAgent

IAgent is the primary interface that has to be implemented by all Agents as it provides the structure for the workings of the Agent. After implementing this interface, there are several methods you have to add to your project that forms part of this predefined structure.

Settings/Configurations

Some Agents need to be provided with configurations by the user, for example, for a CSV listener Agent to be able to get records from a CSV file, it needs the following:
  • Polling interval (in seconds)
  • CSV file
  • CSV Definition
Each of these settings needs to be referenced in the code and needs to correspond to the settings template that should be created when packaging your Agent.
A template is a JSON representation of all the controls and their layout that will be used to capture the settings from a user.
An example of the settings template (generated using the XMPro Package Manager) after it has been rendered in Data Stream Designer is shown in the image below. The settings in this example consist of the following controls:
  • Group (Data)
  • File Upload
  • Group (Payload)
  • Grid
Each control needs to have a Key field defined in the template. This key uniquely identifies it in the template and allows the Agent code to access its value at any time. To get the value contained in a setting, use the following code:
1
string mySetting = parameters[“myUniqueKey”];
Copied!
Before a template is rendered on the screen, or if a postback occurs on any control in the template, the method below would be called to allow the Agent an opportunity to make any necessary runtime changes to the template, for example, verifying user credentials, displaying all tables of a selected database in a drop-down list, etc. In this example, no changes are being made to the template but, if needed, they can be added to the todo section.
For a postback to occur after a user navigates out of a setting field, the Postback property needs to be set to true when packaging the Agent.
1
public string GetConfigurationTemplate(string template, IDictionary<string, string> parameters)
2
{
3
4
//parse settings JSON into Settings object
5
var settings = Settings.Parse(template);
6
//populate the settings/configuration controls with the user selected values
7
new Populator(parameters).Populate(settings);
8
// ToDo: update the controls, values or the data sources here
9
//return the updated settings xml
10
return settings.ToString();
11
12
}
Copied!

Validate

If a user tries to run an Integrity Check on a Data Stream in Data Stream Designer, all Agents will be requested to validate the configurations they have been provided. An Agent has to use this opportunity to inform the user about any configurations that are incorrect, for example, credentials that have expired, required values that are missing, etc.
To validate the configurations/ settings in an Agent, the Validate method needs to be implemented. This method returns an array of errors that occurred. If validation was successful, an empty array would be returned.
The example code below verifies if a user has specified a broker address, topic, and payload definition for an MQTT Agent:
1
public string[] Validate(IDictionary<string, string> parameters)
2
{
3
4
int i = 1;
5
var errors = new List<string>();
6
this.config = new Configuration() { Parameters = parameters };
7
8
if (String.IsNullOrWhiteSpace(this.Broker))
9
errors.Add($”Error {i++}: Broker is not specified.);
10
11
if (String.IsNullOrWhiteSpace(this.Topic))
12
errors.Add($”Error {i++}: Topic is not specified.);
13
14
var grid = new Grid();
15
grid.Value = this.config[“PayloadDefinition”];
16
if (grid.Rows.Any() == false)
17
errors.Add($”Error {i++}: Payload Definition is not specified.);
18
return errors.ToArray();
19
20
}
Copied!

Output Payload

Each Agent has the responsibility to inform the Engine about the structure of the payload that will be produced by the Agent. To do this, implement the following method:
1
IEnumerable<Attribute> GetOutputAttributes(string endpoint, IDictionary<string, string> parameters)
Copied!
This method returns a collection that has an Attribute type, which is a type that represents the name and type of a given attribute in the outgoing payload. As from XMPro.IOT.Framework version 3.0.2, comparison/ equality operations are also supported in Attribute, for example:
1
new XMIoT.Framework.Attribute(“Name1”, Types.DateTime).Equals(new XMIoT.Framework.Attribute(“Name2”, Types.String));
Copied!

Create

Each Agent needs to implement a method called Create, which will be invoked when your Agent is being hosted. User-defined configuration is passed as a parameter to this method and should be stored in a class variable as far as possible for later use. This is a good point to provide any resources needed for the working of your Agent.
1
void Create(Configuration configuration)
2
{
3
4
this.config = configuration;
5
// ToDo: Provision any resources or write Startup logic.
6
7
}
Copied!

Start

The Start method needs to be implemented by all Agents. This method will be invoked when your Agent is hosted and starts to work.
1
void Start()
Copied!

Destroy

Each Agent needs to implement a Destroy method, which will be invoked when a data stream is being unpublished. Use this method to release any resources or memory that your Agent may have acquired during its lifetime.
1
void Destroy()
Copied!

Publishing Events

To push the events to the next Agent, your Agent should invoke the OnPublish event with the events passed as arguments:
1
this.OnPublish?.Invoke(this, new OnPublishArgs(new JArray(), “EndpointName”));
Copied!
Events are represented as JSON Objects and have to be pushed as a collection, i.e. JArray.
Please note that OnPublishArgs(Array rtr) is obsolete from XMPro.IOT.Framework 3.0.2 onwards. You are now required to specify the endpoint name on which you would like to publish (i.e. OnPublishArgs(Array rtr, string Endpoint))

Decrypting Values

If an Agent’s configuration contains a Secure/Password Textbox, its value will automatically be encrypted. To decrypt the value, use the following set of instructions:
1
var request = new OnDecryptRequestArgs(value);
2
this.OnDecryptRequestArgs?.Invoke(this, request);
3
var decryptedVal = request.DecryptedValue;
Copied!

Custom Events

While building your agent, you may need to use external libraries or third-party event subscriptions to handle custom events. If these are used, you will need to catch any exceptions from the event handlers yourself, to prevent uncaught exceptions that could possibly crash the Data Stream if they get through.

IPolling Agent

The IPollingAgent interface allows time-based operations. Implementing this interface will automatically add a PollingInterval setting to the configuration template of your Agent, which can be used by the user to specify the time for polling. The following method will be invoked every time the poll interval expires:
1
void Poll()
Copied!
This method can be used to listen to a third-party system for changes every x seconds.

IReceivingAgent

If your Agent is required to receive inputs from other Agents, you should implement the IReceivingAgent interface.

Input Payload

Each Agent is responsible to inform the Engine about the structure of the payload it consumes. To achieve this in your Agent, implement the following method:
1
IEnumerable<Attribute> GetInputAttributes(string endpoint, IDictionary<string, string> parameters)
Copied!
This method returns a collection consisting of Attribute, which is a type that represents the name and type of a given attribute in the incoming payload.

Input Mapping

In most cases, if an incoming payload structure is supposed to be different from what the parent is sending, i.e. the Input Payload has been specified above, the user will have to map parent outputs to the current Agent’s inputs. To enable this, mark the Require Input Map flag as true in the Stream Integration Manager when packaging the Agent.

Endpoint

Each Agent can have a number of input and output endpoints. Endpoints are the points where incoming or outgoings arrows are connected. Each endpoint consists of a Name<String> attribute. You will be passed an endpoint name when queried for an Input payload definition. Be sure to specify the endpoint name when querying the parent’s output payload definition.

Parent Outputs

All receiving Agents can query the structure of parent Agent outputs connected at a given endpoint by invoking an event, as demonstrated in the example below:
1
var args = new OnRequestParentOutputAttributesArgs(this.UniqueId, “Input”);
2
this.OnRequestParentOutputAttributes.Invoke(this, args);
3
var pOuts = args.ParentOutputs;
Copied!

Receiving Events

Events published to a receiving Agent can be received by implementing the following method:
1
void Receive(string endpointName, JArray events)
Copied!
The endpointName parameter will identify which endpoint the events have been received at.
It is not guaranteed that the Start method will be invoked before the Receive method. Use the Create method to execute any logic that needs to be executed before the Receive method is called.

IPublishError

An Agent can publish messages to an error endpoint by implementing the IPublishesError interface. An unhandled error in an Agent will be captured and error information will be published to the error endpoint.
Implement the interface member:
1
public event EventHandler<OnErrorArgs> OnPublishError;
Copied!
To push the error to the next Agent, the OnPublishError event should be invoked, and the error information should be passed as arguments:
1
this.OnPublishError?.Invoke(this, new OnErrorArgs(AgentId, Timestamp, Source, Error, DetailedError, Data));
Copied!
Error endpoints should be enabled in XMPro Stream Integration Manager when packaging the Agent. This can be done by selecting the “Add On Error Endpoint?” checkbox. See the image on the right for an example.

Example

The code below is an example of a basic MQTT Listener Agent. Take note of how the interfaces and methods have been implemented.
Please note that this example uses the M2MqttDotnetCore 1.0.7 NuGet package.
1
using Newtonsoft.Json.Linq;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Text;
6
using uPLibrary.Networking.M2Mqtt;
7
using uPLibrary.Networking.M2Mqtt.Messages;
8
using XMIoT.Framework;
9
using XMIoT.Framework.Settings;
10
using XMIoT.Framework.Settings.Enums;namespace XMPro.MQTTAgents
11
{
12
public class Listener : IAgent
13
{
14
15
private Configuration config;
16
private MqttClient client;
17
private string Broker => this.config[“Broker”];
18
private string Topic => this.config[“Topic”];
19
20
public long UniqueId { get; set; }
21
public event EventHandler<OnPublishArgs> OnPublish;
22
public event EventHandler<OnDecryptRequestArgs> OnDecryptRequest;
23
24
public void Create(Configuration configuration)
25
{
26
this.config = configuration;
27
this.client = new MqttClient(this.Broker);
28
this.client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
29
}
30
31
public void Start()
32
{
33
if (this.client.IsConnected == false)
34
{
35
this.client.Connect(Guid.NewGuid().ToString());
36
this.client.Subscribe(new string[] { this.Topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
37
}
38
}
39
40
private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
41
{
42
try
43
{
44
var message = Encoding.UTF8.GetString(e.Message);
45
this.OnPublish?.Invoke(this, new OnPublishArgs(JArray.Parse(message), “Output”));
46
}
47
catch (Exception ex)
48
{
49
Console.WriteLine($”{DateTime.UtcNow}|ERROR|XMPro.MQTTAgents.Listener|{ex.ToString()});
50
}
51
}
52
53
public void Destroy()
54
{
55
if (this.client?.IsConnected == true)
56
this.client.Disconnect();
57
}
58
59
public string GetConfigurationTemplate(string template, IDictionary<string, string> parameters)
60
{
61
var settings = Settings.Parse(template);
62
new Populator(parameters).Populate(settings);
63
return settings.ToString();
64
}
65
66
public string[] Validate(IDictionary<string, string> parameters)
67
{
68
int i = 1;
69
var errors = new List<string>();
70
this.config = new Configuration() { Parameters = parameters };
71
72
if (String.IsNullOrWhiteSpace(this.Broker))
73
errors.Add($”Error {i++}: Broker is not specified.);
74
75
if (String.IsNullOrWhiteSpace(this.Topic))
76
errors.Add($”Error {i++}: Topic is not specified.);
77
78
var grid = new Grid();
79
grid.Value = this.config[“PayloadDefinition”];
80
81
if (grid.Rows.Any() == false)
82
errors.Add($”Error {i++}: Payload Definition is not specified.);
83
84
return errors.ToArray();
85
}
86
87
public IEnumerable<XMIoT.Framework.Attribute> GetOutputAttributes(string endpoint, IDictionary<string, string> parameters)
88
{
89
var grid = new Grid();
90
grid.Value = parameters[“PayloadDefinition”];
91
foreach (var row in grid.Rows)
92
{
93
yield return new XMIoT.Framework.Attribute(row[“Name”].ToString(), (Types)Enum.Parse(typeof(Types), row[“Type”].ToString()));
94
}
95
}
96
}
97
}
Copied!

Further Reading