cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - You can subscribe to a forum, label or individual post and receive email notifications when someone posts a new topic or reply. Learn more! X

Low Level Device Connection Part 1

No ratings

 

Utilize the C SDK to build an app that creates a secure connection to ThingWorx with low level device access.

 

Guide Concept

 

This project will cover using the ThingWorx C SDK to develop applications for the purpose of secure and low level development.

 

Following the steps in this this guide, you will be ready to develop your own IoT application with the ThingWorx C SDK.

 

We will teach you how to use the C programming language to connect and build IoT applications to be used with the ThingWorx Platform.

 

 

 

You'll learn how to

 

  • Establish and manage a secure connection with a ThingWorx server, including SSL negotiation and connection maintenance.
  • Enable easy programmatic interaction with the Properties, Services, and Events that are exposed by Entities running on a ThingWorx server.
  • Basic concepts of the C Edge SDK
  • How to create an application that can communicate with other devices

 

NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete ALL parts of this guide is 60 minutes

 

 

 

Step 1: Completed Examples

 

Download the completed files attached to this tutorial: C_SDK.zip.

 

This tutorial will guide you through working with the C SDK on differing levels. Utilize this file to see a finished example and return to it as a reference if you become stuck creating your own fully flushed out application. With the C SDK, you can connect to whatever device you have at a level most programming languages wouldn't be able to. Now think of your secure system, your fighter jet, or even you communication devices. All these systems and levels need to have a way to secure transfer data and the C SDK is how we do it.

 

Keep in mind, this download uses the exact names for entities used in this tutorial. If you would like to import this example and also create entities on your own, change the names of the entities you create.

 

 

Step 2: Environment Setup

 

In order to compile C code, download the attached C compiler: C-SDK-2-2-12-1052.zip.

 

 Operating System          Notes
WindowsYou will need a 3rd party compiler such as MinGW GCC, Cygwin GCC or you can follow these Microsoft instructions to download and use the Microsoft Visual C++ Build Tool.
MacDownload the Apple Developer Tools.
Linux/UbuntuA compiler is included by default.

 

NOTE: You can use CMake, version 2.6.1 or later to build projects or make files, which then are used to build the applications that you develop with the C SDK.

Before you can begin developing with the ThingWorx C SDK, you need to generate an Application Key and modify the source code file. You can use the Create an Application Key as a reference.

 

Modify Source File

 

    1. Extract the files from the C SDK samples zip file. At the top level of the extracted files, you will see a folder called examples, which provides examples of how to utilize the C SDK.
    2. Open a terminal, go to your workspace, and create a new project.
    3. After you've created this project in your workspace, import the entire C SDK downloaded from the PTC Support site for ease of use (mainly the src folder and the CMakeList.txt file).
    4. You can start creating your connection code or open the main.c source file in the examples\SteamSensor\src directory for an example.

 

 Operating System        Code
Linux/Ubuntugedit main.c OR vi main.c
Macopen –e main.c
Windowsstart main.c

 

5. Modify the Server Details section at the top with the IP address for your ThingWorx Platform instance and the application key you would like to use.

  • Change the TW_HOST definition accordingly.
  • Change the TW_PORT definition accordingly.
  • Change the TW_APP_KEY definition to the keyId value saved from the last step.

/* Server Details */
#define TW_HOST "https://pp-XXXXXXXXX.devportal.ptc.i"
#define TW_PORT 80
#define TW_APP_KEY "e1d78abf-cfd2-47a6-92b7-37dc6dd34618"

NOTE: Using the Application Key for the default Administrator is not recommended. If administrative access is absolutely necessary, create a user and place the user as a member of Admins.

 

Compile and Run Code

 

To test your connection, you will only need to update the main.c in the SteamSensor example folder.

 

CMake can generate visual studio projects, make build files or even target IDEs such as Eclipse, or XCode. CMake generates a general description into a build for your specific toolchain or IDE.

 

  1. If you have not downloaded and installed CMake, do it now at the CMake website.

    NOTE: CMake comes as a command line and a GUI application. The steps in this guide use the command line version only.

  2. Inside the specific example folder you would like to run, ie SteamSensor.
  3. Create a directory to build in, for this example call it cmake.
mkdir cmake
cd cmake

4. Run the CMake command listed below. This assumes CMake is already on your PATH.

cmake -G "Visual Studio 15 2012" ..

5. CMake has now produced a set of project files which should be compatible with your development environment.

 Operating System    Command                                        Notes
Unixcommand-> makeA set of make files
Windows**msbuild tw-c-sdk.sln /t:build**A visual studio solution


NOTE
: CMake does its best to determine what version of Visual Studio you have but you may wish to specify which version to use if you have more than one installed on your computer. Below is an example of forcing CMake to use a specific version of Visual Studio: cmake -G "Visual Studio 15 2017" .. If your version of Visual Studio or other IDE is unknown, use cmake -G to see a list of supported IDEs.

 

You also have the alternative of opening the tw-c-sdk.sln from within Visual Studio and building in this IDE.

 

NOTE: By default, CMake will generate a build for the creation of a release binary. If you want to generate a debug build, use the command-> cmake -DBUILD_DEBUG=ON.

 

6. Once your build completes you will find the build products in the cmake directory. From here, open the project in your IDE of choice.

NOTE: You should receive messages confirming successful binding, authentication, and connection after the main.c file edits have been made.

 

 

 

Step 3: Run Sample Code

 

The C code in the sample download is configured to run and connect to the Entities provided in the ThingWorxEntitiesExport.xml file. Make note of the IP address of your ThingWorx Composer instance. The top level of the exported zip file will be referred to as [C SDK HOME DIR].

  1. Navigate to the [C SDK HOME DIR]/examples/ExampleClient/src directory.
  2. Open the main.c source file.

     Operating System      Command
    Linux/Ubuntugedit main.c OR vi main.c
    Macopen –e main.c
    Windowsstart main.c

 

3. Modify the Server Details section at the top with the IP address for your ThingWorx Platform instance and the Application Key you would like to use. Change the TW_HOST definition accordingly.

NOTE: By default, TW_APP_KEY has been set to the Application Key from the admin_key in the import step completed earlier. Using the Application Key for the default Administrator is not recommended. If administrative access is absolutely necessary, create a user and place the user as a member of the Admins security group.

/* Server Details */
#define TW_HOST "127.0.0.1"
#define TW_APP_KEY "ce22e9e4-2834-419c-9656-e98f9f844c784c"

 

4. If you are working on a port other than 80, you will need to update the conditional statement within the main.c source file. Search for and edit the first line within the main function. Based on your settings, set the int16_t port to the ThingWorx platform port.

5. Click Save and close the file.

6. Create a directory to build in, for this example call it bin.

 Operating System            Command

Linux/Ubuntumkdir bin
Macmkdir bin
Windowsmkdir bin

 

7. Change to the newly created bin directory.

 Operating System              Command

Linux/Ubuntucd bin
Maccd bin
Windowscd bin

 

8. Run the CMake command using your specific IDE of choice.

NOTE: Include the two periods at the end of the code as shown below. Use cmake -G to see a list of supported IDEs.

cmake ..

 

9. Once your build completes, you will find the build products in the bin directory, and you can open the project in your IDE of choice.

NOTE: You should receive messages confirming successful binding, authentication, and connection after building and running the application.

10. You should be able to see a Thing in your ThingWorx Composer called SimpleThing_1 with updated lastConnection and isConnected properties. SimpleThing_1 is bound for the duration of the application run time.

 

The below instructions will help to verify the connection.

 

  1. Click Monitoring.
  2. Click Remote Things from the list to see the connection status.

    RemoteMonitoring.png

You will now be able to see and select the Entity within the list.

 

 

 

Step 4: ExampleClient Connection

 

The C code provided in the main.c source file is preconfigured to initialize the ThingWorx C Edge SDK API with a connection to the ThingWorx platform and register handlers. In order to set up the connection, a number of parameters must be defined. This can be seen in the code below.

 

#define TW_HOST "127.0.0.1"
#define TW_APP_KEY "ce22e9e4-2834-419c-9656-ef9f844c784c

#if defined NO_TLS
    #define TW_PORT = 80;
#else
    #define TW_PORT = 443;
#endif

 

The first step of connecting to the platform: Establish Physical Websocket, we call the twApi_Initialize function with the information needed to point to the websocket of the ThingWorx Composer. This function:

 

  • Registers messaging handlers
  • Allocates space for the API structures
  • Creates a secure websocket

err = twApi_Initialize(hostname, port, TW_URI, appKey, NULL, MESSAGE_CHUNK_SIZE, MESSAGE_CHUNK_SIZE, TRUE);

if (TW_OK != err) {
    TW_LOG(TW_ERROR, "Error initializing the API");
    exit(err);
}

 

If you are not using SSL/TLS, use the following line to test against a server with a self-signed certificate:

twApi_SetSelfSignedOk();

 

In order to disable HTTPS support and use HTTP only, call the twApi_DisableEncryption function. This is needed when using ports such as 80 or 8080. A call can be seen below:

 

twApi_DisableEncryption();

 

The following event handlers are all optional. The twApi_RegisterBindEventCallback function registers a function that will be called on the event of a Thing being bound or unbound to the ThingWorx platform. The twApi_RegisterOnAuthenticatedCallback function registered a function that will be called on the event the SDK has been authenticated by the ThingWorx Platform. The twApi_RegisterSynchronizeStateEventCallback function registers a function that will be called after binding and used to notify your application about fields that have been bound to the Thingworx Platform.

 

twApi_RegisterOnAuthenticatedCallback(authEventHandler, TW_NO_USER_DATA);
twApi_RegisterBindEventCallback(NULL, bindEventHandler, TW_NO_USER_DATA);
twApi_RegisterSynchronizeStateEventCallback(NULL, synchronizeStateHandler, TW_NO_USER_DATA);

 

NOTE: Binding a Thing within the ThingWorx platform is not mandatory, but there are a number of advantages, including updating Properties while offline.

  

You can then start the client, which will establish the AlwaysOn protocol with the ThingWorx Composer. This protocol provides bi-directional communication between the ThingWorx Composer and the running client application. To start this connection, use the line below:

 

err = twApi_Connect(CONNECT_TIMEOUT, RETRY_COUNT);
    
if(TW_OK != err){
    exit(-1);
}

 

Click here to view Part 2 of this guide.

 

 

 

Version history
Last update:
‎Mar 07, 2023 02:53 PM
Updated by:
Labels (2)
Attachments
Contributors