# Events

The MQTT device supports several scripts to handle various events and allows your application to perform a custom action when any of the events has been triggered.

To create event scripts, right-click the appropriate MQTT Device and choose which event to handle:

Note: Be aware that event scripts will only be triggered while Designer is running (in either test mode or when the project is deployed).

Event | Description
--- | ---
OnMessageReceived | This event triggers when Designer receives data from the broker with a Topic that matches a Topic that has been Subscribed to. Access data related to the event using event arguments. For example, "OnMessageReceived(MqttMessage message)". Note: To work with this message in a Designer script, you may need to add a reference to Cognex.Designer.MQTTDevice. MqttMessage uses the following structure: string ContentType: identifies the kind of UTF-8 encoded payload. Must be a UTF-8 encoded string. ushort PacketIdentifier: the identifier of the MQTT Packet. byte[] PayloadBytes: returns the Payload as a byte array. ArraySegment<byte> PayloadSegment: an ArrraySegment style of payload. string PayloadString: returns the Payload as a UTF8 string. string ResponseTopic: provides a MQTT5 feature to allow request/response pattern. Indicates the Topic to reply on. bool Retain: flag set by Publisher that indicates message should be retained by broker. string Topic MQTT Topic that the message was published on.
OnConnectingFailed | This event triggers when MQTT Device has attempted to connect to the broker but has failed to connect. Within the event, the Exception raised causing the failure can be accessed. For example, "OnConnectingFailed(Exception exception)" The following example uses this script to write to the Designer log file:
    $System.Log.Write(string.Format("MQTT Device Connection failed. Error: {0}", exception.Message));
OnDisconnected | This event triggers when MQTT Device has disconnected from the broker
OnConnected | This event triggers when MQTT Device has successfully connected to the broker