Now it's time to build an application that determines the segment ID (SID) of your target SmartServer IoT. The SID is required as an element of the topic path in all IAP/MQ API topics. In general, your application publishes to topics to accomplish a task, and subscribes to specific feed back channel topics to see the results, or monitor parts of the system. This basic code will exist in all applications you write.
Follow these steps:
- In VS code, Select
File > Open Folderand create a new folder called
mySidat a desired location.
File > New File, and follow with
File > Saveto save this file as
sid.jsin the mySid directory.
- If not open already, select
View > Intergrated Terminalto access the command shell.
- From the directory mySid, type
npm initand respond to the prompts as shown in the following screenshot. The only essential input is the entry point sid.js.
This command creates the package.json file.
- In the terminal window type
npm install mqtt --saveto pull in mqtt in as a dependency.
This command creates the node_modules directory and its contents.
- Select the Debug icon
Edit your launch.json file to match the code sample shown below. Verify that program (line 11) includes your program file \\sid.js, and add the environment variable DEV_TARGET (line 12), and replace the Xs with your SmartServer's IP address.
The following code needs to be added to the file sid.js.
Lets walk through the code in chunks:
• Line 1 declares the mqtt object that will be the centerpiece of functionality.
• Lines 11-21 create the mqtt client object that connects either:
- to an external broker relative to the application execution (if the environment
variable DEV_TARGET is defined), or
- to a broker running on the same machine, by using the loopback address 127.0.0.1
as would occur when the application is installed and running on the SmartServer,
where the environment variable DEV_TARGET is not defined.
• At Line 26, the application subscribes to the topic
glp/0/././SID. Notice that the subscribe method is called before the connection has been established.
• Two mqtt client events connect and message will fire in order when the client connection to the broker is established, and the SID topic is updated.
- Run this application using the VS Code debugger.
You will see the following output In the debug console (the SID reported in your case will be different):
Congratulations, you have made your first call to the IAP/MQ API. This code is adapted in the next example that will do slightly more interesting things.
Now that you have successfully created an application that interacts with the IAP/MQ API to determine the segment ID of the SmartServer IoT, we will use this application to create one that interacts with devices managed by the SmartServer IoT. Continue with Interacting with Devices Using IAP/MQ.