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

Community Tip - Learn all about the Community Ranking System, a fun gamification element of the PTC Community. X

IoT Tips

Sort by:
    Keys to utilizing the C and Java SDK for ThingWorx application development   GUIDE CONCEPT   This project will introduce to coding examples utilized for SDKs to be used with Java and C. You can also use the Java SDK for Android development.   Following the steps in this guide, you will be better prepared to creating your own application using one of our SDKs.   We will teach you how to handle Properties, Entities, data, make Service calls and creating Remote Services.     YOU'LL LEARN HOW TO   How to create, update, and retrieve Property values Utilize Data Shapes for handling data and triggering Events Construct Info Tables for Services and retrieving data after Service calls Add key features of an edge/remote application   NOTE: The estimated time to complete this guide is 30 minutes.     Step 1: Connection Process   he ThingWorx SDKs follows a three-step process when connecting to the ThingWorx Platform.   NOTE: In this context, Client refers to the application and the SDK running on the device and Server refers to the ThingWorx Platform.   Websocket   The client opens a Websocket to the server using the host and port. With the ThingWorx platform you can connect via HTTP and HTTPS with access to Services, Properties, Events, Entities, and Resources.   Authentication   In order to connect and access information from the server, you must utilize an authorization method. Application Keys provide a secure method for the SDK to log into the platform and perform transactions. The client sends an authentication message to the server containing an Application Key.   Binding   Binding is an optional step in the client connection process. The SDK client allows one or more VirtualThings to be associated with a Websocket connection, using their names or identifiers. Binding a property in your ThingWorx application to that of your source code provides several benefits, including being able to update properties while offline.     Click here to view Part 2 of this guide.
View full tip
    Step 7: Access Data   Now that we have a basic display in-place, we need to access the backend data.   To do so, we'll make use of built-in Mashup Data Services.   At the top-right, ensure that the Data tab is selected.   Click the green + button.   In the Entities Filter field of the Add Data Pop-up, search for and select MDSD_Thing. In the Services Filter field, type getprop. Click the arrow beside GetProperties. Note that the GetProperties() Service has been added to the right section. Check the Execute on Load checkbox.   At the bottom-right of the pop-up, click Done. Note how the GetProperties() Mashup Data Service has been added to the top-right under the Data tab.   Bind Info Table Property   Now that we have access to the Data Service within the Mashup, we'll use it to pull backend data into the Mashup (specifically, the aggregated Info Table Property), and then bind it to the Grid Widget.   Expand the GetProperties Service.   Drag-and-drop MDSD_InfoTable_Property onto the Grid Advanced Widget.   On the Select Binding Target Pop-up, select Data.   Note how the bottom-center Connections Window indicates that the aggregated Info Table Property is now bound to the grid.   Access the Aggregation Service   Because we selected the Execute on Load option for GetProperties(), the Service will grab the information from the aggregated Info Table Property and propagate that into the Grid Advanced Widget on initially opening the Mashup in a web browser.   However, we currently have no way to call our custom aggregation Service besides diving into the backend as we did when we first created it and performed testing.   Instead, we want the Mashup itself to have the ability to call the aggregation Service.   We'll do so via the Button Widget's Clicked Event, but we first need to gain access to our custom Service in the Mashup.   In the top-right Data tab beside Things_MDSD_Thing, click the green </> button. Note that the Add Data Pop-up opens with the MDSD_Thing pre-selected.   On the left of the Add Data Pop-up, expand Select Service Category, and choose **Uncategorized**. Note our custom MDSD_Aggregation_Service.   Beside MDSD_Aggregation_Service, click the right arrow to add it to the Selected Services section. Note that we do NOT want to check "Execute on Load", because don't want the Service called upon initially opening the Mashup in a web browser.   At the bottom-right, click Done. Note the MDSD_Aggregation_Service has been added to the far-right Data tab.   Bind Button to Aggregation Service   Now that we can reference the aggregation Service in the Mashup, we'll bind it to pressing the Button Widget.   Click the Button Widget to select it.   Click the top-left of the Button Widget to reveal the Drop Down Menu.   Drag-and-drop the Clicked Event onto the MDSD_Aggregation_Service under the Data Tab.   On the bottom-right, with the MDSD_Aggregation_Service selected, drag-and-drop the MDSD_Aggregation_Service's ServiceInvokeCompleted Event onto GetProperties in the Data Tab. This causes the completion of the aggregation Service to re-call GetProperties, which updates the grid; as such, a new entry into the Info Table Property created by the custom Service will immediately show up in the Grid Widget. In the top-right, click the GetProperties Service to see all of its interactions in the bottom-center Connections window.   At the top, click Save.       Step 8: Test Application   Our MVP MRI Service Application is now complete.   Let's test it.   At the top, click View Mashup. Note the pre-existing single entry from our Service test which we executed directly from the backend.   Click Retrieve MRI Statistics.   Wait a moment and click Retrieve MRI Statistics again. Note that each click adds another entry to the Grid Widget.   Each time that you press the Button Widget, what you're really doing is calling our custom aggregation Service in the Foundation backend.   This Service then goes out and pulls in information from our various EMS-connected Edge sub-systems.   To add additional sub-systems (maybe a "friction" detection on the patient-bed indicating that it needs additional grease) all you would have to do is repeat the steps in this Learning Path, i.e. connect the additional sub-system with the EMS, add another Field Definition to the Data Shape, and modify the aggregation Service to retrieve that info and store it in the Info Table Property.   In addition, you may wish to improve the GUI. Rather than using a Positioning: Static Mashup, you could utilize a Responsive setup, sub-divide the Canvas into various sections, and then add items such as your company's logo. This would also make the GUI more friendly to different screen resolutions.   You can even add business logic to the Mashup itself. For instance, the Auto Refresh Widget (Legacy) can effectively be used as a "timer". In the same way that the Button Widget's Clicked Event calls the aggregation Service, the Auto Refresh Widget could be used to trigger the Service call at a set interval. Then, as long as the Mashup was open, the Button Widget would only be needed when you wanted an immediate status update.   For more information on implementing additional business logic, refer to the Create Custom Business Logic guide.   Or the Time Selector Widget could be used to restrict the information in the Grid Widget to only the timeframe you wanted to investigate.       Step 9: Next Steps   Congratulations! You've successfully completed the Medical Data Storage and Display guide, and learned how to:   Create a Data Shape and Info Table Property to store Medical Data Create a Service to combine data from multiple Edge devices into a single, logical Thing Create a Mashup to view and retrieve Medical data   This is the last guide in the Medical Device Service learning path.   Learn More   We recommend the following resources to continue your learning experience:    Capability     Guide Build Methods for Data Storage Experience Create Your Application UI   Additional Resources   If you have questions, issues, or need additional information, refer to:    Resource       Link Community Developer Community Forum Support ThingWorx Help Center  
View full tip
  Step 7: Set-up and Run Demo   The ThingWorx Azure IoT Connector download includes a Java application that simulates a device connecting to your Azure IoT Hub. A ThingTemplate is also included and can be imported into ThingWorx.   Import Demo Templates   In ThingWorx Composer, click Import/Export menu, then click From File and browse to ../demo/edgedevice- demo/platform/entities/CPUDemo_AllEntities.xml   Click Import then click Close when the import successful message is displayed. Create a new Thing using the imported template azureDemo1, enter a name for your Thing and click Save. NOTE: You will enter this name in the demo config file in the next step. Configure Demo Application   In the ../demo/edge-device-demo/conf subdirectory, open the edge-device.conf file with a text editor. Edit the deviceId to be the name of the Thing you created in step 3. Edit the iotHubHostName to use the name of your hub plus the domain: azure-devices.net. For example, sample-iot-hub.azuredevices.net. Edit the registryPolicyKey property to use the Primary Key for the registryReadWrite policy in the Azure IoT Hub. Below is an example configuration: azure-edge-device { deviceId = "alstestedgething" iotHubHostname = "alsiot.azure-devices.net" registryPolicyName = "registryReadWrite" registryPolicyKey = "pzXAi2nonYWsr3R7KVX9WuzV/1234567NZVTuScl/Kg=" }   Run Demo Script   Open a shell or Command Prompt, set the EDGE_DEVICE_DEMO_OPTS environment variable to refer to the file you just edited: Linux - export EDGE_DEVICE_DEMO_OPTS="-Dconfig.file=../conf/edge-device.conf" Windows - set EDGE_DEVICE_DEMO_OPTS="-Dconfig.file=../conf/edge-device.conf" Launch the demo from the ../demo/edge-device-demo/bin subdirectory, using the edge-device-demo command. Return to the ThingWorx Composer and open the Properties page of the Azure Thing that you created previously. Click the refresh button to see the properties change every five seconds. Open the azure-iot-demo Mashup and view the Load Average and CPU gauges, and the increases in the values of the Cycle and Uptime fields. NOTE: If the edgedevice-demo is running on Windows, the Load Average does not register.   Step 8: Next Steps   Congratulations! You've successfully completed the Connect Azure IoT Hub to ThingWorx Quickstart. By following the steps in this lesson, you imported a device created in Azure into ThingWorx and saw how data from an Azure device could be used in a ThingWorx Mashup.   Learn More   We recommend the following resources to continue your learning experience:   If you're following the Azure MXChip Development Kit learning path, the next guide is Create a Thing Shape.    Capability     Guide Connect Choose a Connectivity Method Build Design Your Data Model Experience Create Your Application UI   Additional Resources   If you have questions, issues, or need additional information, refer to:  Resource       Link Community Developer Community Forum Support Getting Started with ThingWorx        
View full tip
    Step 8: Tasks   If you are using the built-in Tasker to drive data collection or other types of repetitive or periodic activities, create a function for the task. Task functions are registered with the Tasker and then called at the rate specified after they are registered. The Tasker is a very simple, cooperative multitasker, so these functions should not take long to return and most certainly must not go into an infinite loop.   The signature for a task function is found in [C SDK HOME DIR]/src/utils/twTasker.h. The function is passed a DATETIME value with the current time and a void pointer that is passed into the Tasker when the task is registered. After creating this function, it will need to be registered using the twApi_CreateTask function after the connection is created. Below shows an example of creating this function, registering this function, and how this function can be used.   #define DATA_COLLECTION_RATE_MSEC 2000 void dataCollectionTask(DATETIME now, void * params) { /* TW_LOG(TW_TRACE,"dataCollectionTask: Executing"); */ properties.TotalFlow = rand()/(RAND_MAX/10.0); properties.Pressure = 18 + rand()/(RAND_MAX/5.0); properties.Location.latitude = properties.Location.latitude + ((double)(rand() - RAND_MAX))/RAND_MAX/5; properties.Location.longitude = properties.Location.longitude + ((double)(rand() - RAND_MAX))/RAND_MAX/5; properties.Temperature = 400 + rand()/(RAND_MAX/40); /* Check for a fault. Only do something if we haven't already */ if (properties.Temperature > properties.TemperatureLimit && properties.FaultStatus == FALSE) { twInfoTable * faultData = 0; char msg[140]; properties.FaultStatus = TRUE; properties.InletValve = TRUE; sprintf(msg,"%s Temperature %2f exceeds threshold of %2f", thingName, properties.Temperature, properties.TemperatureLimit); faultData = twInfoTable_CreateFromString("message", msg, TRUE); twApi_FireEvent(TW_THING, thingName, "SteamSensorFault", faultData, -1, TRUE); twInfoTable_Delete(faultData); } /* Update the properties on the server */ sendPropertyUpdate(); } … twApi_CreateTask(DATA_COLLECTION_RATE_MSEC, dataCollectionTask); … while(1) { char in = 0; #ifndef ENABLE_TASKER DATETIME now = twGetSystemTime(TRUE); twApi_TaskerFunction(now, NULL); twMessageHandler_msgHandlerTask(now, NULL); if (twTimeGreaterThan(now, nextDataCollectionTime)) { dataCollectionTask(now, NULL); nextDataCollectionTime = twAddMilliseconds(now, DATA_COLLECTION_RATE_MSEC); } #else in = getch(); if (in == 'q') break; else printf("\n"); #endif twSleepMsec(5); }      Step 9: File Transfer Example    To handle file transfers, a virtual directory is created in the SteamSensor1 entity and in the [C SDK HOME DIR]/examples/FileTransferExample application directory. The source code used for this example is found in [C SDK HOME DIR]/examples/FileTransferExample/src/main.c.   Inside of the [C SDK HOME DIR]/examples/FileTransferExample folder, create the folder structure shown below: /transfer/ /transfer/incoming/ /transfer/outgoing/ Inside of the /transfer/outgoing/ directory, create and open a file with the name outgoing.txt. Once the outgoing.txt document is open, add the following text, save, and close the file: Hello. This is a file coming from the client application. Navigate to the [C SDK HOME DIR]/examples/FileTransferExample/src/main.c code and update the lines below with the appropriate information for your IP, port, and the “admin_key” Application Key’s keyId value in the ThingWorx Composer: /* Server Details */ #define TW_HOST "127.0.0.1" #define TW_PORT 80 #define TW_APP_KEY "ce22e9e4-2834-419c-9656-ef9f844c784c" To support file transfers in your client application, you must use the twFileManager_AddVirtualDir function in order to create the virtual directories in the entity with such a capability. It will also define the directories available for file operations. A virtual directory maps a unique name to an absolute path of a directory in the file system. All subdirectories of the specified directory are exposed to the server. You can define multiple virtual directories. The directories do not need to be contiguous.   Staging Directory   As an optional, but recommended step, you should set the directory that the application should use for staging when performing file transfers. This can be seen in the line below and should be done before initializing the FileManager. The default directory of the FileManager is most likely owned by root and will require a change to either the location of the staging directory and the ownership of the staging directory, or running the application as a User with the correct permissions.   twcfg.file_xfer_staging_dir = "staging"; The example provided uses the TW_SHARE_DIRECTORY macro to create two virtual directories that will act as the root directories in the virtual file system of this application are added. The client is then started as follows with the necessary TW_ADD_FILE_TRANSFER_SHAPE function being called: TW_ADD_FILE_TRANSFER_SHAPE(); TW_SHARE_DIRECTORY("in", "/transfer/incoming/"); TW_SHARE_DIRECTORY("out", "/transfer/outgoing/"); The creations of the payloads used to create the remote directories on the platform have been moved to a helper function below to make the design cleaner: int setupSystemRepo(const char * remoteInPath, const char * remoteOutPath, const char * remoteFile); After our remote directories and files have been setup, it is time to perform the file transfers. Normally, this would mean invoking the Copy service for a Subsystem, but two functions have been created to make this process easier: int twFileManager_GetFile(const char * sourceRepo, const char * sourcePath, const char * sourceFile, const char * targetRepo, const char * targetPath, const char * targetFile, uint32_t timeout, char asynch, char ** tid) int twFileManager_SendFile(const char * sourceRepo, const char * sourcePath, const char * sourceFile, const char * targetRepo, const char * targetPath, const char * targetFile, uint32_t timeout, char asynch, char ** tid) The table below displays an example of the first set of parameters:    Parameter     Example                             Description sourceRepo SystemRepository The name of FileRepository or RemoteThing to transfer the file FROM. sourcePath outgoing The path specifying the location of the source file. sourceFile The name of the source file.   targetRepo SteamSensor1 The name of FileRepository or RemoteThing to transfer the file TO. targetPath incoming The path specifying the destination location of the file. targetFile incoming.txt The name of the file at the target. This name can differ from the sourceName. timeout 15,000 The amount of time (in seconds) to wait for a synchronous transfer to complete before cancelling the transfer. async false If false, the service call will block for timeout seconds or until the transfer completes. tid incoming0123 The unique TID associated with the file.   The C SDK also provides the ability to create a FileCallback function that the FileManager will call that function when any file transfer events occur. You can provide a wildcard filter so that only file transfer Events of files that match the filter call the callback function. In addition, callbacks can be set up as “one-shots” such that the callback is unregistered automatically after it is invoked the first time.   NOTE: An optional file transfer callback is registered in the code and provided. You will see the output from the function as files are sent and received.   After running this application, you will notice a new file in the transfer/incoming folder after refreshing. This is the file that we created in the ThingWorx Composer file system for the SystemRepository Entity and was able to copy from that location to our local project. We have also sent a file to the server’s SystemRepository. The BrowseFileSystem and GetFileListing services can be used to check for the folders and files created.   twFileManager_RegisterFileCallback(fileCallbackFunc, NULL, FALSE, NULL);     Step 10: Support Other Platforms   All Websocket errors indicate some general issue communicating with the ThingWorx platform. If you experience an issue connecting, refer to the table below for a list of websocket errors, their corresponding codes, and an explanation of the issue.    Code     Message                                                                      Troubleshooting 200 TW_UNKNOWN_WEBSOCKET_ERROR An unknown error occurred on the websocket. 201 TW_ERROR_INITIALIZING_WEBSOCKET An error occurred while initializing the websocket. Check your websocket configuration parameters for validity. 202 TW_TIMEOUT_INITIALIZING_WEBSOCKET A timeout occurred while initializing the websocket. Check the status of the connection to ThingWorx. 203 TW_WEBSOCKET_NOT_CONNECTED The websocket is not connected to ThingWorx. The requested operation cannot be performed. 204 TW_ERROR_PARSING_WEBSOCKET_DATA An error occurred while parsing websocket data. The parser could not break down the data from the websocket. 205 TW_ERROR_READING_FROM_WEBSOCKET An error occurred while reading data from the websocket. Retry the read operation. If necessary, resend the data. 206 TW_WEBSOCKET_FRAME_TOO_LARGE The SDK is attempting to send a websocket frame that is too large. The Maximum Frame Size is set when calling twAPI_Initialize and should always be set to the Message Chunk Size (twcfg.message_chunk_size). 207 TW_INVALID_WEBSOCKET_FRAME_TYPE The type of the frame coming in over the websocket is invalid. 208 TW_WEBSOCKET_MSG_TOO_LARGE The application is attempting to send a message that has been broken up in to chunks that are too large to fit in a frame. You should not see this error. 209 TW_ERROR_WRITING_TO_WEBSOCKET An error occurred while writing to the Web socket. 210 TW_INVALID_ACCEPT_KEY The Accept key sent earlier from ThingWorx is not valid.     Step 11: Next Steps   Congratulations! You've successfully completed the Low Level Device Connect Guide, and learned how to utilize the resources provided in the Edge SDK to create your own application.   The next guide in the Utilizing ThingWorx to Secure Your Aerospace and Defense Systems learning path is Tracking Activities and Statistics.    Learn More   We recommend the following resources to continue your learning experience:    Capability      Guide Build Design Your Data Model Build Implement Services, Events, and Subscriptions   Additional Resources   If you have questions, issues, or need additional information, refer to:    Resource       Link Community Developer Community Forum Support C Edge SDK Help Center      
View full tip
  Step 6: Create Event Router   What do you do when a user can perform multiple events in which data is generated, and want those outputs to go through the same exact process? An Events Router Function is your solution. The Events Router Function allows for multiple data sources to be funneled to one location. Let's create a simple example in our MyFunctionsMashup Mashup. In this Mashup, we'll add two Text Field Widgets and a Label Widget. The two Text Field Widgets will take user input and then an Events Router will send the output to the Label. Let's start!   Open the MyFunctionsMashup Mashup to the Design tab. Click on the Widgets tab. Type in the Filter text box for Text Field.   Drag and drop TWO (2) Text Field Widgets to the Mashup Canvas. Type in the Filter text box for Label.   Drag and drop ONE (1) Label Widget to the Mashup Canvas. We now have all the Widgets we need for this example. Let's get started on the Events Router Function. Click the + button in the Functions panel. Select Events Router in the dropdown.   Set the Name to routeUserInput.   Click Next. Set the Inputs field to 2.   Click Done. We have our Events Router setup. Now, we'll bind our new items together. Click the Bind (arrows) button on the routeUserInput Events Router.   Click the down arrow next to Input1. Select Add Source.   In the Widgets tab, scroll to the bottom and select Text Property of the first of the two recent Text Fields we created (it should be third to last).   Click Next. Click the down arrow next to Input2. Select Add Source.   In the Widgets tab, scroll to the bottom and select Text Property of the second of the two recent Text Fields we created (it should be second to last).   Click Next. Click the down arrow next to Output. Select Add Target.   In the Widgets tab, scroll to the bottom and select LabelText Property of the recent Label we created (it should be last).   Click Next. Click Done. Click Save for the Mashup. You have just created an Events Router that will update a Label based on the typed input from two Text Fields. View your Mashup and play around with the bottom two text boxes. For a completed example, download and unzip, then import the attached FunctionsGuide_Entities.zip.     Step 7: Next Steps   Congratulations! You've successfully completed the Explore UI Functions guide, and learned best practices for building a complex Mashup that navigations, multiple data inputs, confirmations, and all working together effectively for an enhanced user experience.   Learn More   We recommend the following resources to continue your learning experience:    Capability    Guide Experience Object-Oriented UI Design Tips   Additional Resources   If you have questions, issues, or need additional information, refer to:    Resource       Link Community Developer Community Forum Support Mashup Builder Support Help Center
View full tip
    Step 8: Learn More About Widgets   For more details on how to use and customize Widgets highlighted in this guide, refer to:    Widget            Link to How-To Layout Customizable and Responsive UI Gauge Display Property Values with a Gauge Style Define Your UI Style Navigation Customizable and Responsive UI Google Map Display Geolocation Data in Your UI     Step 9: Next Steps   Congratulations! You've successfully completed the Design an Effective UI guide, and learned best practices for building a complex Mashup that includes maps, menus, and detail sections all working together effectively for an enhanced user experience.   Learn More   We recommend the following resources to continue your learning experience:     Capability    Guide Experience Object-Oriented UI Design Tips   Additional Resources   If you have questions, issues, or need additional information, refer to:     Resource      Link Community Developer Community Forum Support Mashup Builder Support Help Center
View full tip
  Learn how to create systems to handle logistics and production distribution   GUIDE CONCEPT   This project will introduce complex aspects of the ThingWorx Composer and solution building.   Following the steps in this guide, you will develop your own IoT application or get a jump start in how to utilize ThingWorx for your needs.   We will teach you how to create a focused rules engine or service level logic to be used with the ThingWorx Platform.     YOU'LL LEARN HOW TO   Create automated logistical processes Use Services, Alerts, and Subscriptions to handle processes without human interaction Integrating complex logic with straight forward step by step systems   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: Examples and Strategy   This guide builds on the knowledge gained in Factory Line Automation.   Download FoodIndustry.zip attached to this guide and extract/import the contents.   For the completed example, download the automated_food_industry.zip, also attached here. This download provides three Users and a Security Group. Please watch your count for Users or the import could fail.   In this tutorial we continue with our real-world scenario for the Fizos food company. We already have our factory data, and automated cooking processed for our sausage product lines. Now, let's see how we can use the data model we built before into making a smarter system of deliveries. We will take into consideration the locations of our factories, the vehicles we have available, our customers (stores and individuals), and see how much we can automate.   Setting Up Orders   One important part of being in business is having a product that people or companies want to buy. You'll need a way to track these sales and we're going to start with doing just that. Let's create our order shapes and tables.   In the ThingWorx Composer, click the + New in the top left of the screen.     Select Data Shape in the dropdown.     In the name field, enter Fizos.Orders.DataShape and select a Project (ie, PTCDefaultProject). All of our orders will be based off this Data Shape.     Click Save then Edit to store all changes now. Add the list of properties below: Name Base Type Aspects Description ID Integer 0 minimum, primary key, default 0 Row identifier CustomerId Integer N/A String used as unique identifer across multiple platforms Type String N/A Type of customer (individual or another company) Factors Tag Data Tag This will hold the different type of data points or tags that will help to analyze a customer's order Products Infotable Data Shape: Fizos.DataShapes.Products List of orders TotalPrice Number Minimum 0 Price of the order Status String N/A The current order status (ie, processed, shipped, completed, etc) Completed Boolean N/A Whether the order has been completed   The Properties for the Fizos.Orders.DataShape Data Shape are as follows:   6. In the ThingWorx Composer, click the + New in the top left of the screen.   7. Select Data Table in the dropdown and select Data Table in the prompt.   8. In the name field, enter Fizos.Orders.DataTable. Our differing types of customers will fall under this template. 9. For the Data Shape field, select Fizos.Orders.DataShape and select a Project (ie, PTCDefaultProject).     10. Click Save then Edit to store all changes now. 11. This Entity will be used to house our data and provide assistance with our analytics.   We now have our model of orders ready to be stored. Of course, our orders are simplified. We can add much more to get them rolling, but the most important aspect right now is our Factors field. While we know a ton of information about customers, we can also analyze what kind of products they're buying and their ordering habits.     Step 2: Expanding Customer Models    Let's start with our customers. We created the data shape for customers before when we decided to put them in data tables. This time, we'll add some customers, but also expand on our modeling of what a customer entails. In this step, as with all the steps in this learning path, you can go as granular as you like. If you'd like to make 100 data tags, then it helps with understanding your customer, but it might be too much based on your goals. Remember, more data means more processing of that data.   Creating Customer Data Tags   These data tags will help us decide priority, relationships, and much more.   In the ThingWorx Composer, click the + New in the top left of the screen.     Select Data Tag in the dropdown.     In the name field, enter Fizos.CustomerTags and select a Project (ie, PTCDefaultProject). Check the Dynamic checkbox. This allows for new vocabulary terms to be created during runtime.   Click on the Vocabulary Terms tab, and add the following terms and then add as many more as you see fit: Name  Store  Individual  Office  Company  FirstTime  Repeat  Partner  LongTerm  ShortTerm  Old  MiddleAged  Young  Loyal We just added a number of data tags based on customer type, age, times the customer has bought from us, etc. This will help us with characterizing and modeling our customers. We'll also cheat a bit and use these data tags to help with deliveries. If you're a partment brand, we might work faster to send goods. For example, the code below returns the list of orders that were made by partners. We can add this as a service to our Fizos.Logistics template.   var index; var customerId; var partnerObj = {}; var query = { "filters": { "type": "EQ", "fieldName": "Completed", "value": false } }; var orders = Things["Fizos.Orders.DataTable"].QueryDataTableEntries({ query: query }); var customers = Things["Fizos.Customers.DataTable"].GetDataTableEntries(); var result = Resources["InfoTableFunctions"].CreateInfoTableFromDataShape({ infoTableName : "InfoTable", dataShapeName : "Fizos.Orders.DataShape" }); var partners = Resources["InfoTableFunctions"].TagFilter({ inclusive: true, fieldName: "Factors", t: customers, tags: "Fizos.CustomerTags:Partner" }); for(index = 0; index < partners.rows.length; index++) { customerId = partners.rows[index].ID; partnerObj[customerId] = true; } for(index = 0; index < orders.rows.length; index++) { customerId = orders.rows[index].CustomerId; if(partnerObj[customerId] === true) { var newEntry = new Object(); newEntry.ID = orders.rows[index].ID; newEntry.CustomerId = orders.rows[index].CustomerId; newEntry.Type = orders.rows[index].Type; newEntry.Products = orders.rows[index].Products; newEntry.Factors = orders.rows[index].Factors; newEntry.TotalPrice = orders.rows[index].TotalPrice; result.AddRow(newEntry); } } This code will retrieve all orders that are not in a completed state. It will then figure out which orders are for partners and return those orders. You can see in this simple example how Data Tags can be used.     Click here to view Part 2 of this guide.
View full tip
  Step 4: Simulated Model   Models are primarily used by Analytics Manager (which will be discussed in the next guide), but they can still be used to estimate the accuracy of predictions.   When Models are calculated, they inherently withhold a certain amount of data (~20%). The prediction model is then run against the withheld data. This provides a form of "accuracy measure".   The withheld-data is selected randomly, so you'll actually get a slightly different model and accuracy measure each time that you create a Model versus the same dataset.   On the left, click Analytics Builder > Models.   Click New….   In the Model Name field, enter simulated_model. In the Dataset field, select simulated_dataset.   Click Submit. After ~60 seconds, the Model Status will change to COMPLETED.     Select the model that was created in the previous step, i.e. simulated_model. Click View… to open the Model Information page.   As with Signals and Profiles, our Model is once again "too good". In fact, it's perfect.   The expected "Precision" is 1.0, i.e. 100%. The True vs False Positive rate shown in the graph goes straight up to the top immediately.   While you want a graph that is "high and left", you're very unlikely to ever see real-world scenarios such as shown here.   Still, you've been able to progress the process of using Foundation (and now Analytics) to build an analytical model of MotorCo's prototype engine.   What needs to happen now is to receive real world data from your R&D engineers.     Step 5: Upload Real World Data   In your process of using the EMS Engine Simulator, the idea has always been to get a headstart on the engine developers.   At some point, they would wire sensors into the EMS and start providing real world data.   In our scenario, that has now happened. Real world data is being fed from the EMS to Foundation, Foundation is collecting that data in an Info Table Property, and you've even exported the data as a .csv. file.   This new dataset is over periods of both good and bad grease conditions. The engineers monitoring the process can flip a sensor switch connected to the EMS to log the current grease situation as either good or bad at the same time that the vibration sensors are taking readings.   We will now load this real world dataset into Analytics in the same manner that we did earlier with the simulated dataset.   Download the attached analytics_vibration.zip file to your computer. Unzip the analytics_vibration.zip file to access the vibration_data_and_header.csv and vibration_metadata.json files. On the left, click Analytics Builder > Data. Under Datasets, click New....   In the Dataset Name field, enter vibration_dataset. In the File Containing Dataset Data section, search for and select vibration_data_and_header.csv. In the File Containing Dataset Field Configuration section, search for and select vibration_metadata.json.   Click Submit.     Step 6: Real World Signals and Profiles   Now that the real-world vibration data has been uploaded, we’ll re-run Signals and Profiles just as we did before.   Hopefully, we’ll start seeing some patterns.   On the left, click Analytics Builder > Signals. At the top, click New….   In the Signal Name field, enter vibration_signal. In the Dataset field, select vibration_dataset.   Click Submit. Wait ~30 seconds for Signal State to change to COMPLETED     The results show that the five Frequency Bands for Sensor 1 are the most highly correlated with determining our goal of detecting a low grease condition.   For Sensor 2, only bands one and four seem to be related, while bands two, three, and five are hardly relevant at all.   This is a very different result than our earlier simulated data. Instead, it looks like it’s possible that the vibration-frequencies getting pickup up by our first sensor are explicitly more important.   Profiles   We’ll now re-run Profiles with our real-world dataset. On the left, click Analytics Builder > Profiles. Click New….   In the Profile Name field, enter vibration_profile. In the Dataset field, select vibration_dataset.   Click Submit. After ~30 seconds, the Signal State will change to COMPLETED.     The results show several Profiles (combinations of data) that appear to be statistically significant.   Only the first few Profiles, however, have a significant percentage of the total number of records. The later Profiles can largely be ignored.   Of those first Profiles, both Frequency Bands from Sensor 1 and Sensor 2 appear.   But in combination with the result from Signals (where Sensor 1 was always more important), this could possibly indicate that Sensor 1 is still the most important overall.   In other words, since Sensor 1 is statistically significant both by itself and in combination (but Sensor 2 is only significant in combination  with Sensor 1), then Sensor 2 may not be necessary.     Click here to view Part 3 of this guide.
View full tip
  Step 5: Widget Properties   You can configure Properties to change the style of the map as well as specify a custom image to use for map markers. Other Properties allow two linear paths and polynomial regions to also be displayed on the map Widget with optional tooltip data.   Bindable   Name Type  Default Direction  Description Data Infotable None Input Source for the data that is displayed as discrete markers LocationField MenuName None Input Field that contains Location type data to plot markers MarkerField MenuName None Input Field that contains data of type Image used to plot markers ShowMarkerTooltip Boolean True Input Hovering over map markers will display a tooltip when set to true ToolTipField1 thru 4 MenuName None Input Optional field displayed in tooltip when the user hovers over a map marker ToolTipLabel1 thru 4 String None Input Optional label for tooltip data RouteData Infotable None Input Source for the data that is displayed as a connected route RouteLocationField MenuName None Input Field that contains Location type data to plot connected route line ShowRoute Boolean False Input Show route data on map when set to true PlannedRouteData Infotable None Input Source for the data that is displayed as a second connected route PlannedRouteLocationField MenuName None Input Field that contains Location type data to plot a second connected route line ShowPlannedRoute Boolean False Input Show planned route data on map when set to true RegionData Infotable None Input Source for the data that is displayed as a region RegionLocationData Infotable None Input Region location data source RegionLocationsField MenuName None Input Field which will provide location table information for region RegionLayerField MenuName None Input Field that contains Numeric data used for region layer number ShowRegions Boolean False Input Show region data on map when set to true ShowRegionTooltips Boolean True Input Hovering over region will display a tooltip when set to true RegionToolTipField1 thru 4 MenuName None Input Optional field displayed in tooltip when the user hovers over a region RegionToolTipLael1 thru 4 String None Input Optional label for region tooltip data RegionFillOpacity Number 1 Input Opacity of region fill color from 0 being transparent to 1 being opaque SelectedLocation Location None Input/Output The currently selected location CurrentZoom Number 8 Output The currently displayed zoom level ( 1 - 15 ) Zoom Number 8 Input Number used to set the zoom level ( 1 - 15 ) ShowMarkers Boolean True Input Shows map markers if set to true ShowPathMarkers Boolean True Input Shows map markers if set to true ShowTraffic Boolean False Input Shows traffic data color overlay on map if set to true NEBoundary Location None Output The northeast boundary location NWBoundary Location None Output The northwest boundary location SEBoundary Location None Output The southeast boundary location NWBoundary Location None Output The southwest boundary location Visible Boolean True Input Widget is visible if set to true     Static   Name Type  Default Description DisplayName String None Name used for widget in user facing interactions Description String None Description used for widget in user facing interactions MapType Roads/Satellite/Hybrid/Terrain Roads The type of map content displayed MapSkin Normal/Blue/Grey Normal Options for styling maps monochromatically AutoZoomBehavior Data change/Initial Data only Data Change Controls when map will automatically zoom to show all markers ClusterLocations Boolean False Combines multiple location markers that are near one another into a single marker if true MultiSelect Boolean False Enable multiple marker selection   Widget Events   DoubleClicked- Triggered when user double clicks on the Google Map. Changed- Triggered when the data for this widget is modified. BoundsChanged- Triggered when the bounding box of the displayed map changes.     Step 6: Next Steps   If you have questions, issues, or need additional information, refer to:   Resource     Link Community Developer Community Forum Support Google Map Widget Help Center Free Google Maps Widget Extension IQNOX  
View full tip
This has been moved to its new home in the Augmented Reality Category in the PTC Community.
View full tip
This has been moved to its new home in the Augmented Reality Category in the PTC Community.
View full tip
This has been moved to its new home in the Augmented Reality Category in the PTC Community.
View full tip
    Configure ThingWorx Advisors to remotely monitor your connected assets.   Guide Concept   This project will introduce ThingWorx Advisors.   Following the steps in this guide, you will learn how to add users, create a model to store data, and configure asset Properties.   We will show you how ThingWorx Advisors let you remotely monitor equipment without writing any code.   You'll learn how to   Configure ThingWorx Advsors Connect ThingWorx Advisors to ThingWorx Kepware Server Create assets in ThingWorx and tie them to data items in Kepware Server   NOTE: The estimated time to complete this guide is 60 minutes       Step 1: Configure Connection   This step shows how to open Controls Advisor, and configure the communication with ThingWorx Kepware Server.   Open Controls Advisor   Click on Hosted Server Info to open your ThingWorx Foundation server. In ThingWorx Foundation Composer, click Browse then Visualization > Master then click PTC.Factory.PlantStatus.Master.   Next click View Mashup button.    Click the App Switcher icon in the upper left.    Create Connection   In the top-left, click the app switcher icon. Click Controls Advisor in the app switcher.     click-controls-advisor     3. Click the + icon to add a new Connection.     click-plus-add-connection     4. Enter my-kepware-connection in the Connection Name field. 5. Click the wand icon in the Application Key User Name dropdown and select Administrator. 6. Click the Application Key Expiration Date date picker and select a date a year in the future.     create-connection     7. Click Done to close the date picker, then click OK. 8. Information that you will enter in Kepware is shown, click Print Instructions to save.     connection-summary     NOTE: If no port is shown, use 80 for an HTTP connection or 443 for an HTTPS connection. 9. Click Close to close the connection inforamtion pop-up. 10. The information is always available by selecting the Key icon in Controls Advisor.     new-connection-saved       Configure Communication with Kepware   Open ThingWorx Kepware Server configuration tool using either the desktop shortcut or the task bar icon.   Right click Project and select Properties to configure the connection with ThingWorx.   kepware-properties     3, Select ThingWorx in left panel. Under Connection Settings, update the Host, Port and Application Key to match your ThingWorx server.     /kepware-thingworx-settings     NOTE: All the required information is available in the "print" browser tab from the previous step. If no port number is shown, use 80 for an HTTP connection or 443 for an HTTPS connection.   4. Set Disable Encryption to No and Trust all Certificates to Yes. 5. Enter my-kepware-connection-GW in Thing name. 6. Click Apply, then OK. 7. Check Connected to ThingWorx is shown in Kepware.   NOTE: The message displayed should say: Connected to ThingWorx.    Troubleshooting   If you are unable to make a connection from KEPServerEX®, try the following:   Verify that the information you entered into the KEPServerEX Project Properties is exactly as displayed in the on-screen set-up instructions. If KEPServerEX is on a different machine than ThingWorx® ensure that your firewall is set to allow incoming connections on the port specified.     Step 2: Add User   In this part of the lesson, you'll create a User and modify permissions.   Click the grid icon located in the upper left to switch to a different utility.   Click the Configuration and Setup utility icon.    Click the Users tab, then click the Plus icon to open the Create User pop-up.   Enter a User Name that is at least 3 characters.   Enter the required First Name and Last Name. Although they will not be used in this guide, enter the required Email and Work Phone. Enter Mobile Phone including + and country code, +1 for US mobile phones. Check the SMS Notification Preference.   Enter a Password of at least 14 characters, then re-enter it in the Confirm Password field.   Create a User for yourself as a Controls Engineer. This role gives access to all of the Advisors installed on the system. The other roles are given a subset of the Advisors, depending on the functionality they need to perform their jobs.         Step 3: Create a Model   In this part of the lesson, you will create a Model to store data.   If Configuration and Setup is not already open, click the Utility Selector grid in the upper left, then click the Configuration and Setup utility icon.    Click on the Equipment tab.   Click on the + icon on the top left to add a new asset.   Set the new resource to Asset and name it Asset1. NOTE: You can also enter a description. Create another resource, this time with the Type set to Line. Name it Station A. After both resources have been created, select Asset1 and then click the pencil icon to configure it. On the Asset Configuration Details page, locate the Related Lines table. Click the + icon to relate line to the asset.   Select Station A, then click Add.   Step 4: Configure Asset Properties   From the Administration and Configuration page for Asset1, click Additional Properties located in the left-hand navigation pane.   Click the + icon to add a new property to the asset. Name the Property Temp.   Click the tag picker icon to associate this property in ThingWorx with a data tag from KEPServerEX. In the Resource Type drop-down, choose KEPServerEX. Select your server name (for this exercise, we use KEPServerEX.Local). NOTE: You will see a hierarchical view of all tags available from your KEPServerEX instance. In the left column, scroll down to Ch1 and click the triangle icon to expand it. Click Ch1.Asset1 to see the available Tags in the right column.   Select Temperature, then click OK. Click Save to save this Property. TIP: For additional practice, try to add a few more assets.   Step 5: Next Steps   Congratulations! You've successfully completed the Configure ThingWorx Advisors guide. In this guide, you learned how to configure ThingWorx Advisors to connect to KEPServerEX and connect an asset.   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community ThingWorx Advisors Community Support Kepware Technical Support Asset Advisor for service Home ThingWorx Asset Advisor for service
View full tip
    Step 3: Create A Tree Grid   With our MyFunctionsMashup Mashup open, let's add a Validation. A Validation is similar to an Expression, except you have the added capability of triggering Events based on a True or False outcome of your validation. We will use the Validation to check and confirm the Text Field we created only has the values we added in our Functions. Let's also add two Status Message Functions that will show whether or not a user has added any text outside of what we want.   Open the MyFunctionsMashup Mashup to the Design tab. Click the green + button in the Functions area.    In the New Function modal, select Validator.     Set the Name to isDataClean.     Click Next.  Click Add Parameter. Set the Name to text and ensure the Base Type is STRING.     Add the following code to the Expression are: if(text === "NO") { result = true; } else if(text === "YES") { result = true; } else { let array = text.split("YES").join(""); array = array.split(",").join(""); let count = array.trim().length; if(count) { result = false; } else { result = true; } }   9. Click Done.   We have our Validator in place, now we need our two Status Message Functions. Why two? You can setup one Status Message to perform the task, but for this case, we're keeping things simple.   Click the + button in the Functions area. Select Status Message in the dropdown.    Set the Name to GoodInputProvided.   Click Next. Ensure Message Type is Info. In the Message field, enter Text is all good!.   Click Done. Let's create another Status Message Function. Set the Name to BadnputProvided.   Click Next. Change Message Type to Error. In the Message field, enter Text is BAD!.   Click Done.   We now have two Status Message Functions and a Validator to help with checking our text data. Let's connect everything together. This time, let's use the Bind button.   Expand the Validator section in the Functions tab. Click the Bind (arrows) button on the isDataClean Validator. This window will help us configure connections a bit easier.    Click the down arrow by the True Event. Click Add Trigger Service.   Click Functions. Check the checkbox by GoodInputProvided.   Click Next. Click the down arrow by the False Event. Click Add Trigger Service.   Click Functions. Check the checkbox by BadInputProvided.   Click Next. You should currently have the following setup:    Let's add in our connections to the Text Field and when we'll run this Validation.    Click the down arrow by the text Property.   Click Add Source. With the Widgets tab selected, scroll down and select the Text Property of our Text Field.   Click Next. Click the down arrow by Evaluate Service. Select Add Event Trigger.   With the Widgets tab selected, scroll down and select the Clicked Property of our Button.   Click Next. You should currently have the following setup:   Click Done. Click Save and view your updated Mashup.   Your Validator is complete. You now have a way to tell when a user has inputed their own text into the text box. To try things out, add some crazy characters, hit the button, and see what happens. You might notice that you have your Expressions running at the same time as your Validator. Switch up the bindings to get it to run the way you want it to.     Step 4: Next Steps   Congratulations! You've successfully completed the Explore UI Functions guide, and learned best practices for building a complex Mashup that navigations, multiple data inputs, confirmations, and all working together effectively for an enhanced user experience.   Learn More   We recommend the following resources to continue your learning experience:    Capability     Guide Experience Object-Oriented UI Design Tips   Additional Resources   If you have questions, issues, or need additional information, refer to:    Resource       Link Community Developer Community Forum Support Mashup Builder Support Help Center
View full tip
    Step 5: Properties   In the Delivery Truck application, there are three Delivery Truck Things. Each Thing has a number of Properties based on its location, speed, and its deliveries carried out. In this design, when a delivery is made or the truck is no longer moving, the Property values are updated. The deliveryTruck.c helper C file is based on the DeliveryTruck Entities in the Composer. After calling the construct function, there are a number of steps necessary to get going. For the SimpleThing application, there are a number of methods for creating Properties, Events, Services, and Data Shapes for ease of use.   Properties can be created in the client or just registered and utilized. In the SimpleThingClient application, Properties are created. In the DeliveryTruckClient application, Properties are bound to their ThingWorx Platform counterpart. Two types of structures are used by the C SDK to define Properties when it is seen fit to do so and can be found in [C SDK HOME DIR]/src/api/twProperties.h:    Name                   Structure            Description Property Definitions twPropertyDef Describes the basic information for the Properties that will be available to ThingWorx and can be added to a client application. Property Values twProperty Associates the Property name with a value, timestamp, and quality.   NOTE: The C SDK provides a number of Macros located in [C SDK HOME DIR]/src/api/twMacros.h. This guide will use these Macros while providing input on the use of pure function calls.   The Macro example below can be found in the main source file for the SimpleThingClient application and the accompanying helper file simple_thing.c.   TW_PROPERTY("TempProperty", "Description for TempProperty", TW_NUMBER); TW_ADD_BOOLEAN_ASPECT("TempProperty", TW_ASPECT_ISREADONLY,TRUE); TW_ADD_BOOLEAN_ASPECT("TempProperty", TW_ASPECT_ISLOGGED,TRUE);   NOTE: The list of aspect configurations can be seen in [C SDK HOME DIR]/src/api/twConstants.h. Property values can be set with defaults using the aspects setting. Setting a default value in the client will affect the Property in the ThingWorx platform after binding. It will not set a local value in the client application.   For the DeliveryTruckClient, we registered, read, and update Properties without using the Property definitions. Which method of using Properties is based on the application being built.   NOTE: Updating Properties in the ThingWorx Platform while the application is running, will update the values in the client application. To update the values in the platform to match, end the Property read section of your property handler function with a function to set the platform value.   The createTruckThing function for the deliveryTruck.c source code takes a truck name as a parameter and is used to register the Properties, functions, and handlers for each truck.   The updateTruckThing function for the deliveryTruck.c source code takes a truck name as a parameter and is used to either initialize a struct for DeliveryTruck Properties, or simulate a truck stop Event, update Properties, then fire an Event for the ThingWorx platform.   Connecting properties to be used on the platform is as easy as registering the property and optionally adding aspects. The following shows the properties that correlate to those in the DeliveryTruck entities in the Composer. To do this within the code, you would use the TW_PROPERTY macro as shown in the deliveryTruck.c. This macro must be proceeded by either TW_DECLARE_SHAPE, TW_DECLARE_TEMPLATE or TW_MAKE_THING because these macros declare variables used by the TW_PROPERTY that follow them.   //TW_PROPERTY(propertyName,description,type) TW_PROPERTY(PROPERTY_NAME_DRIVER, NO_DESCRIPTION, TW_STRING); TW_PROPERTY(PROPERTY_NAME_DELIVERIES_LEFT, NO_DESCRIPTION, TW_NUMBER); TW_PROPERTY(PROPERTY_NAME_TOTAL_DELIVERIES, NO_DESCRIPTION, TW_NUMBER); TW_PROPERTY(PROPERTY_NAME_DELIVERIES_MADE, NO_DESCRIPTION, TW_NUMBER); TW_PROPERTY(PROPERTY_NAME_LOCATION, NO_DESCRIPTION, TW_LOCATION); TW_PROPERTY(PROPERTY_NAME_SPEED, NO_DESCRIPTION, "TW_NUMBER);   Read Properties   Reading Properties from a ThingWorx platform Thing or the returned Properties of a Service can be done using the TW_GET_PROPERTY macro. Examples of its use can be seen in all of the provided applications. An example can be seen below:   int flow = TW_GET_PROPERTY(thingName, "TotalFlow").number; int pressue = TW_GET_PROPERTY(thingName, "Pressure").number; twLocation location = TW_GET_PROPERTY(thingName, "Location").location; int temperature = TW_GET_PROPERTY(thingName, "Temperature").number;   Write Properties   Writing Properties to a ThingWorx platform Thing from a variable storing is value uses a similarly named method. Using the TW_SET_PROPERTY macro will be able to send values to the platform. Examples of its use can be seen in all of the provided applications. An example is shown below:   TW_SET_PROPERTY(thingName, "TotalFlow", TW_MAKE_NUMBER(rand() / (RAND_MAX / 10.0))); TW_SET_PROPERTY(thingName, "Pressure", TW_MAKE_NUMBER(18 + rand() / (RAND_MAX / 5.0))); TW_SET_PROPERTY(thingName, "Location", TW_MAKE_LOC(gpsroute[location_step].latitude,gpsroute[location_step].longitude,gpsroute[location_step].elevation));   This macro utilizes the twApi_PushSubscribedProperties function call to push all property updates to the server. This can be seen in the updateTruckThing function in deliveryTruck.c.   Property Change Listeners   Using the Observer pattern, you can take advantage of the Property change listener functionality. With this pattern, you create functions that will be notified when a value of a Property has been changed (whether on the server or locally by your program when the TW_SET_PROPERTY macro is called).   Add a Property Change Listener   In order to add a Property change listener, call the twExt_AddPropertyChangeListener function using the:   Name of the Thing (entityName) Property this listener should watch Function that will be called when the property has changed   void simplePropertyObserver(const char * entityName, const char * thingName,twPrimitive* newValue){ printf("My Value has changed\n"); } void test_simplePropertyChangeListener() { { TW_MAKE_THING("observedThing",TW_THING_TEMPLATE_GENERIC); TW_PROPERTY("TotalFlow", TW_NO_DESCRIPTION, TW_NUMBER); } twExt_AddPropertyChangeListener("observedThing",TW_OBSERVE_ALL_PROPERTIES,simplePropertyObserver); TW_SET_PROPERTY("observedThing","TotalFlow",TW_MAKE_NUMBER(50)); } NOTE: Setting the propertyName parameter to NULL or TW_OBSERVE_ALL_PROPERTIES, the function specified by the propertyChangeListenerFunction parameter will be used for ALL properties.   Remove a Property Change Listener   In order to release the memory for your application when done with utilizing listeners for the Property, call the twExt_RemovePropertyChangeListener function.   void simplePropertyObserver(const char * entityName, const char * thingName,twPrimitive* newValue){ printf("My Value has changed\n"); } twExt_RemovePropertyChangeListener(simplePropertyObserver);       Step 6: Data Shapes   Data Shapes are an important part of creating/firing Events and also invoking Services.   Define With Macros   In order to define a Data Shape using a macro, use TW_MAKE_DATASHAPE.   NOTE: The macros are all defined in the twMacros.h header file.   TW_MAKE_DATASHAPE("SteamSensorReadingShape", TW_DS_ENTRY("ActivationTime", TW_NO_DESCRIPTION ,TW_DATETIME), TW_DS_ENTRY("SensorName", TW_NO_DESCRIPTION ,TW_NUMBER), TW_DS_ENTRY("Temperature", TW_NO_DESCRIPTION ,TW_NUMBER), TW_DS_ENTRY("Pressure", TW_NO_DESCRIPTION ,TW_NUMBER), TW_DS_ENTRY("FaultStatus", TW_NO_DESCRIPTION ,TW_BOOLEAN), TW_DS_ENTRY("InletValve", TW_NO_DESCRIPTION ,TW_BOOLEAN), TW_DS_ENTRY("TemperatureLimit", TW_NO_DESCRIPTION ,TW_NUMBER), TW_DS_ENTRY("TotalFlow", TW_NO_DESCRIPTION ,TW_INTEGER) );   Define Without Macros   In order to define a Data Shape without using a macro, use the twDataShape_CreateFromEntries function. In the example below, we are creating a Data Shape called SteamSensorReadings that has two numbers as Field Definitions.   twDataShape * ds = twDataShape_Create(twDataShapeEntry_Create("a",NULL,TW_NUMBER)); twDataShape_AddEntry(ds, twDataShapeEntry_Create("b",NULL,TW_NUMBER)); /* Name the DataShape for the SteamSensorReadings service output */ twDataShape_SetName(ds, "SteamSensorReadings");     Step 7: Events and Services   Events and Services provide useful functionality. Events are a good way to make a Service be asynchronous. You can call a Service, let it return, then your Entity can subscribe to your Event and not keep the original Service function waiting. Events are also a good way to allow the platform to respond to data when it arrives on the edge device without it having to poll the edge device for updates.   Fire Events   To fire an Event you first need to register the Event and load it with the necessary fields for the Data Shape of that Event using the twApi_RegisterEvent function. Afterwards, you would send a request to the ThingWorx server with the collected values using the twApi_FireEvent function. An example is as follows:   twDataShape * ds = twDataShape_Create(twDataShapeEntry_Create("message", NULL,TW_STRING)); /* Event datashapes require a name */ twDataShape_SetName(ds, "SteamSensorFault"); /* Register the service */ twApi_RegisterEvent(TW_THING, thingName, "SteamSensorFault", "Steam sensor event", ds); …. struct { char FaultStatus; double Temperature; double TemperatureLimit; } properties; …. properties. TemperatureLimit = rand() + RAND_MAX/5.0; properties.Temperature = rand() + RAND_MAX/5.0; properties.FaultStatus = FALSE; if (properties.Temperature > properties.TemperatureLimit && properties.FaultStatus == FALSE) { twInfoTable * faultData = 0; char msg[140]; properties.FaultStatus = TRUE; sprintf(msg,"%s Temperature %2f exceeds threshold of %2f", thingName, properties.Temperature, properties.TemperatureLimit); faultData = twInfoTable_CreateFromString("message", msg, TRUE); twApi_FireEvent(TW_THING, thingName, "SteamSensorFault", faultData, -1, TRUE); twInfoTable_Delete(faultData); }   Invoke Services   In order to invoke a Service, you will use the twApi_InvokeService function. The full documentation for this function can be found in [C SDK HOME DIR]/src/api/twApi.h. Refer to the table below for additional information.    Parameter         Type                  Description entityType Input The type of Entity that the service belongs to. Enumeration values can be found in twDefinitions.h. entityName Input The name of the Entity that the service belongs to. serviceName Input The name of the Service to execute. params Input A pointer to an Info Table containing the parameters to be passed into the Service. The calling function will retain ownership of this pointer and is responsible for cleaning up the memory after the call is complete. result Input/Output A pointer to a twInfoTable pointer. In a successful request, this parameter will end up with a valid pointer to a twInfoTable that is the result of the Service invocation. The caller is responsible for deleting the returned primitive using twInfoTable_Delete. It is possible for the returned pointer to be NULL if an error occurred or no data is returned. timeout Input The time (in milliseconds) to wait for a response from the server. A value of -1 uses the DEFAULT_MESSAGE_TIMEOUT as defined in twDefaultSettings.h. forceConnect Input A Boolean value. If TRUE and the API is in the disconnected state of the duty cycle, the API will force a reconnect to send the request.   See below for an example in which the Copy service from the FileTransferSubsystem is called:   twDataShape * ds = NULL; twInfoTable * it = NULL; twInfoTableRow * row = NULL; twInfoTable * transferInfo = NULL; int res = 0; const char * sourceRepo = "SimpleThing_1"; const char * sourcePath = "tw/hotfolder/"; const char * sourceFile = "source.txt"; const char * targetRepo = "SystemRepository"; const char * targetPath = "/"; const char * targetFile = "source.txt"; uint32_t timeout = 60; char asynch = TRUE; char * tid = 0; /* Create an infotable out of the parameters */ ds = twDataShape_Create(twDataShapeEntry_Create("sourceRepo", NULL, TW_STRING)); res = twDataShape_AddEntry(ds, twDataShapeEntry_Create("sourcePath", NULL, TW_STRING)); res |= twDataShape_AddEntry(ds, twDataShapeEntry_Create("sourceFile", NULL, TW_STRING)); res |= twDataShape_AddEntry(ds, twDataShapeEntry_Create("targetRepo", NULL, TW_STRING)); res |= twDataShape_AddEntry(ds, twDataShapeEntry_Create("targetPath", NULL, TW_STRING)); res |= twDataShape_AddEntry(ds, twDataShapeEntry_Create("targetFile", NULL, TW_STRING)); res |= twDataShape_AddEntry(ds, twDataShapeEntry_Create("async", NULL, TW_BOOLEAN)); res |= twDataShape_AddEntry(ds, twDataShapeEntry_Create("timeout", NULL, TW_INTEGER)); it = twInfoTable_Create(ds); row = twInfoTableRow_Create(twPrimitive_CreateFromString(sourceRepo, TRUE)); res = twInfoTableRow_AddEntry(row, twPrimitive_CreateFromString(sourcePath, TRUE)); res |= twInfoTableRow_AddEntry(row, twPrimitive_CreateFromString(sourceFile, TRUE)); res |= twInfoTableRow_AddEntry(row, twPrimitive_CreateFromString(targetRepo, TRUE)); res |= twInfoTableRow_AddEntry(row, twPrimitive_CreateFromString(targetPath, TRUE)); res |= twInfoTableRow_AddEntry(row, twPrimitive_CreateFromString(targetFile, TRUE)); res |= twInfoTableRow_AddEntry(row, twPrimitive_CreateFromBoolean(asynch)); res |= twInfoTableRow_AddEntry(row, twPrimitive_CreateFromInteger(timeout)); twInfoTable_AddRow(it,row); /* Make the service call */ res = twApi_InvokeService(TW_SUBSYSTEM, "FileTransferSubsystem", "Copy", it, &transferInfo, timeout ? (timeout * 2): -1, FALSE); twInfoTable_Delete(it); /* Grab the tid */ res = twInfoTable_GetString(transferInfo,"transferId",0, &tid);   Bind Event Handling   You may want to track exactly when your edge Entities are successfully bound to or unbound from the server. The reason for this is that only bound items should be interacting with the ThingWorx Platform and the ThingWorx Platform will never send any requests targeted at an Entity that is not bound. A simple example that only logs the bound Thing can be seen below. After creating this function, it will need to be registered using the twApi_RegisterBindEventCallback function before the connection is made.   void BindEventHandler(char * entityName, char isBound, void * userdata) { if (isBound) TW_LOG(TW_FORCE,"BindEventHandler: Entity %s was Bound", entityName); else TW_LOG(TW_FORCE,"BindEventHandler: Entity %s was Unbound", entityName); } …. twApi_RegisterBindEventCallback(thingName, BindEventHandler, NULL);   OnAuthenticated Event Handling   You may also want to know exactly when your Edge device has successfully authenticated and made a connection to the ThingWorx platform. Like the bind Event handling, this function will need to be made and registered. To register this handler, use the twApi_RegisterOnAuthenticatedCallback function before the connection is made. This handler form can also be used to do a delay bind for all Things.   void AuthEventHandler(char * credType, char * credValue, void * userdata) { if (!credType || !credValue) return; TW_LOG(TW_FORCE,"AuthEventHandler: Authenticated using %s = %s. Userdata = 0x%x", credType, credValue, userdata); /* Could do a delayed bind here */ /* twApi_BindThing(thingName); */ } … twApi_RegisterOnAuthenticatedCallback(AuthEventHandler, NULL);     Click here to view Part 3 of this guide.
View full tip
This has been moved to its new home in the Augmented Reality Category in the PTC Community.
View full tip
This has been moved to its new home in the Augmented Reality Category in the PTC Community.
View full tip
This has been moved to its new home in the Augmented Reality Category in the PTC Community.
View full tip
  Step 5: Additional Services   The Trend, Range, and Threshold Services are some of the Services the Statistical Monitoring ThingShape offers. Below is a table of additional included Services.   Links to guides for using services like these to build complete IoT applications are found in the next step.   Calculation Service Name Description Consecutive Points Based On a Range GetNumberOfConsecutivePointsBasedOnARange Calculate the number of points in the largest group of consecutive points meeting the range criteria. Consecutive Points Based On a Threshold GetNumberOfConsecutivePointsBeyondAThreshold Calculate the number of points in the largest group of consecutive points meeting the threshold criteria. Number of Points with Percentage Change Out of Range GetNumberOfPointsWithChangeRateOutOfRange Monitor for how many pairs of consecutive points in a series have a numerical percentage change outside the defined range. If the first value in a pair is 0, the pair is not considered.       Step 6: Next Steps   Congratulations!   In this guide, you've learned how to:   Create a Value Stream Create a Thing with the Statistical Monitoring Thing Shape Modify a Property to record values to the Value Stream Test built-in Services used in Statistical Monitoring   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Build Get Started with ThingWorx for IoT Build Build a Predictive Analytics Model Build Operationalize an Analytics Model   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support Descriptive Analytics Help Center    
View full tip
  Display project burn up/down via a convenient Mashup Widget.   GUIDE CONCEPT   Long term projects need to be managed. As a project is scoped, requirements get defined and delivery-timeframes are estimated. As work is done, requirements are completed.   One way to track this project progress is with a Waterfall Chart.   This guide will show you how to utilize a Waterfall Chart Widget to easily display the project workflow.        YOU'LL LEARN HOW TO   Create a Data Shape Create a Thing Create an Info Table Property Populate an Info Table with appropriate data for a Waterfall Chart Create a Mashup Utilize a Waterfall Chart to display project progress   NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete this guide is 30 minutes     Step 1: Create Data Shape   In this scenario, we'll store the Waterfall Chart's data in a Property type called an Info Table.   An Info Table is a spreadsheet-like Property, but in order to define the columns of the table, we first have to define a Data Shape. We'll do that in this step.   In the left-side navigation, click Browse > Modeling > Data Shapes.   At the top, click + New.   In the Name field, type TPWC_DataShape. If Project is not already set, search for and select PTCDefaultProject .   At the top, click Field Definitions.   At the top-left, click + Add.   On the right-side slide-out, in the Name field, type month. Note that you want to leave "Base Type" as the default of "STRING". Check Is Primary Key.   Click the "check with a plus" button for Done and Add.   In the Name field, type amount. Change Base Type, to NUMBER.   Click the "check" button for Done.   At the top, click Save .     Step 2: Create Thing   Now that we have our Data Shape, we can create a Thing to document the project progress over time.   As already mentioned, we'll use an Info Table Property, formatted by the previously-created Data Shape, to do so.   Click Browse > Modeling > Things.   Click + New.   In the Name field, type TPWC_Thing. If Project is not already set, search for and select PTCDefaultProject. In the Base Thing Template field, search for and select GenericThing. At the top, click Save.   Add Info Table Property Now that we have our Thing instantiated, we want to add an Info Table Property. At the top, click Properties and Alerts.   Click + Add.   On the right-side slide-out, in the Name field, type InfoTable_Property. Change Base Type to INFOTABLE. In the Data Shape field, search for and select TPWC_DataShape. Note that the Data Shape field will not appear until you set Base Type to INFOTABLE. Check Persistent.   At the top-right, click the "check" button for Done. At the top, click Save.   Set Value of Property Now that we have a place in which to store spreadsheet-like values, we'll do so manually for testing.  On the InfoTable_Property row, under the Value column, click the "pencil" icon for Set value of property.   On the pop-up, click + Add.   Enter the following values in each field as per the table below: Field Name Value month January amount 380   Click Add.   Repeat Steps 2-4 multiples times until all of the below values have been entered. Note that amount should be left blank for both Mid-Term and Total. Note that you may enter fewer than all the values listed below if so desired, though your final Waterfall Chart will not match the following screenshots. month amount February 85 March 50 April 1000 May -300 June 0 Mid-Term   July 30 August -655 September -100 October -250 November 350 December -100 Total     On the pop-up, click Save.   At the top, click Save.   Step 3: Create Mashup   Now that we have our data in-place for testing (and could be connected to automated systems after we finish testing), we need to visualize the data.   As mentioned, we'll use a Waterfall Chart Widget, but first, we need to create a Mashup into which we can place the Widget.   Click Browse > Visualization > Mashups.   Click + New.   Leave the defaults and click OK.   In the Name field, type TPWC_Mashup. If Project is not already set, search for and select PTCDefaultProject. At the top, click Save.   At the top, click Design.   At the top-left, click the Widgets tab.   Drag-and-drop a Waterfall Chart Widget onto the central Canvas.   At the top, click Save.     Click here to view Part 2 of this guide.
View full tip
  Use ThingWorx Advisors to view trends and monitor Alerts. Step 2: Create and Configure Alert   Click the grid icon.   Select Configuration and Setup, then select the Alert tab. NOTE: If you are using the Demo Factory Simulator, you will see that several alerts have already been configured. To create a new alert, click the Alert tab, then click the + icon. Select the following properties in the Select Tag or Property box: Under Equipment Type, select Asset. Under Equipment, select 1-3_CNCMill. In Properties, click Temperature. Click OK. Set up the following in the Create New Alert pop-up: In the Alert Name text box, type HighTemp. In the Alert Type drop-down, choose Above. In the Value text box, type 34. In the Alert Description text box, type Temperature close to failure.   NOTE: An Alert will now be triggered whenever the temperature of Asset1 is more than 34.   Step 3: Monitor Alert   Click the grid icon. Select Alert Monitoring. NOTE: You can see the temperature alert message that you created earlier, and the amount of time that it’s been in that state. Select the HighTemp alert. Confirm that the Acknowledged field is recorded as false in the lower left-hand corner beneath the Details.   Select the HighTemp alert, then click the check mark icon to acknowledge the alert.   In the Acknowledge Alerts dialog, provide explanation. Click OK.   Note the updates to the Alert Monitoring page.   NOTE: Anyone viewing the Alerts will now be able to clearly see the green check mark, which indicates that the Alert has been acknowledged.   Step 4: Next Steps  Next Steps   Congratulations! You've successfully completed the Configure ThingWorx Advisors for Trending and Alerts guide. You have learned how to create and monitor trends and alerts based on assets connected with Kepware.   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community ThingWorx Manufacturing Community Support Kepware Technical Support Manufacturing Home ThingWorx Manufacturing    
View full tip