Tutorial: Tutorial 4: Use Subscription

Tutorial 4: Use Subscription

This tutorial will demonstrate how to use Subscription to monitor changes in device data.

Project Design

Includes:

  • Five Numeric objects (Addresses: LW-100 to LW-104, Type: Uint16)
  • A JS object that uses Subscription to monitor changes in data from LW-100 to LW-104 and outputs the latest results to JS console.

Numeric Object Settings

  1. In the [General] settings page, set the Read/Write addresses of the five Numeric objects to LW-100 through LW-104, respectively.
  2. In the [Format] settings page, set the Device data format of all five Numeric objects to 16-bit Unsigned.

JS Object Settings

  1. In the [Config] settings page, add a subscription named "numericSub", pointing to address LW-100, with the data type set to 16-bit Unsigned and a length of 5.
  • Right-click on config in the table and select [New Value...].

  • Expected software display after completing the steps:

Source Code

// Set the Response callback function for the Subscription
this.config.numericSub.onResponse((err, data) => {
  if (err) {
    console.log('Error:', err.message);
  } else {
    console.log('values:', data.values);
  }
});

Execution Result

  1. Change the values of LW-100 to LW-104 using any of the Numeric objects.

  2. Open cMT Diagnoser. Whenever any value is modified, the JS console will immediately display the updated values.

Explanation

  • Subscription (object)
    • Used to monitor data changes at one or more consecutive device addresses.
    • When data changes, the system notifies through a callback function registered in Subscription.onResponse (function).
    • Suitable for scenarios that require monitoring one or more device addresses and responding immediately to changes in their data.
  • Subscription has 3 read-only properties:
    • address: The first device address monitored by this Subscription.
    • latestData: The most recent data received by this Subscription.
    • length: The number/length of addresses monitored by this Subscription.
  • Comparison between Address and Subscription:
    • Address is suitable for on-demand, occasional data read or write scenarios.
    • Subscription is suitable for continuous monitoring of device addresses where an immediate reaction to changes is needed.
    • Subscription is more resource-intensive than Address and should be used only when necessary.

Reference