TF6701 TC3 IoT Communication (MQTT)

IotMqttSampleMathworksThingspeak

Communication with the MathWorks ThingSpeak Cloud is illustrated in this sample. Since this sample is essentially based on the sample IotMqttSampleUsingQueue, only the parts that are relevant for establishing a connection with the ThingSpeak Cloud are explained in this section.

Download: IotMqttSampleMathworksThingspeak.zip

Parameters for establishing a connection

The following code snippet illustrates the parameters that are necessary for establishing a connection with the MathWorks ThingSpeak Cloud. The parameters are essentially static parameters. These can also be specified in the declaration part during instantiation of the MQTT client.

 
IF bSetParameter THEN
  bSetParameter := FALSE;
  fbMqttClient.sHostName:= 'mqtt.thingspeak.com';
  fbMqttClient.nHostPort:= 1883;
  fbMqttClient.sClientId:= 'myTwinCATSystem';
END_IF
 

ThingSpeak also supports protection of the communication connection via TLS. The CA certificate must be downloaded from ThingSpeak and referenced in the function block via the TLS structure. Authentication via a password that corresponds to the MQTT API key of the ThingSpeak account can also be set at the function block via the corresponding input parameter. The user name has no purpose and can be assigned any value. For more information about the ThingSpeak CA certificate and the MQTT API key we recommend referring to the Mathworks ThingSpeak documentation.

 
IF bSetParameter THEN
  bSetParameter := FALSE;
  fbMqttClient.sHostName:= 'mqtt.thingspeak.com';
  fbMqttClient.nHostPort:= 8883;
  fbMqttClient.sClientId:= 'myTwinCATSystem';
  fbMqttClient.sUsername:= 'myUser';
  fbMqttClient.sUserPassword:= 'myUserPassword';
  
  stMqttTls.sVersion:= 'tlsv1.2';
  stMqttTls.sCA:= 'C:\TwinCAT\3.1\Config\Certificates\thingSpeakCa.cer';
  fbMqttClient.stTLS := stMqttTls;
END_IF
 

Publish

When publishing data to the MathWorks ThingSpeak Cloud, the topic must be specified in the following form:

channels / <channelID> / publish / <apiKey>

<channelID> corresponds here to the ID of the channel that was designated and configured for data reception in the MathWorks ThingSpeak portal.

<apiKey> corresponds to the access key for the channel.

Subscribe

When subscribing to data, the topic must be specified in the following form:

channels / <channelID> / subscribe / fields / <fieldKey>

<channelID> corresponds here to the ID of the channel that was designated and configured for data reception in the MathWorks ThingSpeak portal.

<fieldKey> corresponds to the name of the field from which a value is to be received.

Data format

The MathWorks ThingSpeak Cloud currently uses its own string-based data format. This data format is generated in the function F_Mqtt_ThingSpeak_CreatePayloadStr().

 

Requirements

Development environment
Target platform
PLC libraries to include
TwinCAT v3.1.4022.0
IPC or CX (x86, x64, ARM)
Tc3_IotBase,
Tc2_Utilities (>= v3.3.19.0)