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

Community Tip - Need help navigating or using the PTC Community? Contact the community team. X

IoT Tips

Sort by:
  Expedite your application development with new ThingWorx features.   GUIDE CONCEPT   This project will introduce you to a variety of features designed to expedite the IoT application development workflow. In particular, there are several features that make the creation of custom Services quicker and easier when writing and testing your code.   Following the steps in this guide, you will learn how to access features that will help you throughout your software development lifecycle: development, execution, and testing.   We will teach you how to became a faster and more efficient IoT application developer.     YOU'LL LEARN HOW TO   Use Snippets to generate code Execute and test Services Save Service test cases to facilitate QA process Utilize the code auto-completion feature Test code at design time with Lint warnings and errors   NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete ALL parts of this guide is 30 minutes.        Step 1: Completed Example   Download and extract the completed files for this tutorial attached to this article: ToolsTipsTricks.zip file.   The file provided to you contains a completed example of the Entities covered in this guide. Utilize this file to see a finished example and return to it as a reference if you become stuck during this guide and need some extra help or clarification.   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: Templates and Using Code Snippets    Expedite your application development process by utilizing code Snippets provided in ThingWorx. The JavaScript code snippets will give you insight into best practices for performing common development tasks.   Follow the steps below to create a Service that will: Check a list of Things Find Things with a temperature over an input parameter threshold, and Return the captured list of Things   Create a Thing Template   Utilizing a Thing Template expedites your development process because the Things inherit properties from the Template. In the steps below, it can relate to a real-world scenario where Things might represent parts that belong to an assembly line.   In the top left of the Home screen of Composer, click the + button.       In the dropdown list, click Thing Template.       For the Name field, enter LinePartTemplate. Select GenericThing as the Thing Template and select a Project (ie, PTCDefaultProject).       Click Properties and Alerts. Create a number Property named PartTemperature. Create a string Property named PartName.     Click Save. Now that you've saved the Template, you can create Things that inherit the properties PartTemperature and PartName. Create a couple new Things with LinePartTemplate as the Thing Template. For testing purposes, set a different value for the PartTemperature Property of each Thing. NOTE: When you run the Service later, you'll be able to see the different Things with values - some within a temperature threshold based on the conditions we set.   Using Service Call Setup   Code Snippets help shorten time to develop Services, but you are also provided with a way to call Services from an entity plus the default input parameters needed to make the call.   In the top left of the Home screen of Composer, click the + button.       In the dropdown list, click Thing.       For the Name field, enter LineCheckSystem. Select GenericThing as the Thing Template and select a Project (ie, PTCDefaultProject).     Switch to the Services tab. Create a Service called ListHotLineParts. Switch to the Me/Entities tab.   Select the Other entity radio option. Enter LinePartTemplate into the search field and select it when it pops up.   Expand the Services section.  Enter GetImplementingThingsWithData into the search field and select the arrow next to it.   You should now see a Snippet of JavaScript inserted into the Service code window. The GetImplementingThingsWithData Service is used to get all the Things with a specific Thing Template as it's base template. The return of this call will provide you with an InfoTable of all the Things you created on your own in the last section. Refer to LineTemplateThing1 in the completed download for an example.     Using Code Snippets   Lets's update the Snippet inserted in the last section.   Update the variable name from result to partsList. Switch to the Snippets tab of the Service. In the search bar, enter/filter Infotable for loop. Expand the Info Table section and click the arrow next to Infotable for loop.   All places where yourInfotableHere is located, replace it with the name of your list, partsList.   Click Done. Click Save.   At this point, you have created a loop that will iterate through the set of Things created with LinePartTemplate set as the Thing Template.   Since the JavaScript snippets were provided and all you had to do was update the variable names, now you must retrieve the input from the user on what the temperature threshold will be. This will be handled in the next section.     Build Return Value List   You can set the threshold to what is considered a "Hot" part in two different ways. Use a static value in order to keep things standardized OR create an input variable to make things more flexible. In the steps below, we are adding an input variable to finish off our Service.   Go to the Inputs tab of the Service. Add an input parameter called TemperatureThreshold that is a Number. Keep the other settings clear. Go to the Outputs tab, select INFOTABLE in the dropdown.  In the Data Shape search field, use the + New Data Shape sign to create a new DataShape. An example is shown below. I’ve named this Data Shape LinePartDataShape. Switch to the Snippets tab of the Service. In the JavaScript code, put your cursor on a new line before the for loop (ie, line 1). In the search bar, filter for Create Infotable from datashape and select it in the Infotable section by clicking the arrow next to it. Select the newly created LinePartDataShape DataShape when a popup appears and click Insert Code Snippet. You will see the newly inserted snippet that creates an Info Table from our new Data Shape.   Add a check inside of the for loop for the PartTemperature of the current item in the list of parts. if(row.PartTemperature > TemperatureThreshold){ } Move the cursor inside of the condition we just added. In the search bar, filter and select Create infotable entry from datashape in the Info Table section by clicking the arrow next to it. Select the newly created LinePartDataShape Data Shape when a popup appears and click Insert Code Snippet. You will see the newly inserted snippet that creates an entry for the Info Table. Update the inserted code snippet to assign the new entry values to that of a row in the Info Table. After updating the with code below, ensure to keep your cursor inside the conditional on a new line. var newEntry = new Object(); newEntry.PartName = row.PartName; // STRING newEntry.PartTemperature = row.PartTemperature; // NUMBER Your entire code thus far should match the following: var params = { infoTableName : "InfoTable", dataShapeName : "LinePartDataShape" }; // CreateInfoTableFromDataShape(infoTableName:STRING("InfoTable"), dataShapeName:STRING):INFOTABLE(LinePartDataShape) var result = Resources["InfoTableFunctions"].CreateInfoTableFromDataShape(params); // result: INFOTABLE dataShape: "RootEntityList" var partsList = ThingTemplates["LinePartTemplate"].GetImplementingThingsWithData(); var tableLength = partsList.rows.length; for (var x=0; x < tableLength; x++) { var row = partsList.rows[x]; if(row.PartTemperature > TemperatureThreshold){ var newEntry = new Object(); newEntry.PartName = row.PartName; // STRING [Primary Key] newEntry.PartTemperature = row.PartTemperature; // NUMBER } } In the search bar, filter and select AddRow by clicking the blue arrow next to it. Update the inserted code snippet to add the newEntry object to the result Info Table created earlier. result.AddRow(newEntry); Save your work. You now have a fully-functional Service that you were able to create faster because of code snippets and pre-loaded Services. See the below to confirm your code matches up after removing some commented lines. Click here to view Part 2 of this guide.
View full tip
  Step 8: Troubleshooting   Issue                                       Resolution CSS does not seem to be applied to the Mashup. Verify your CSS is included in the runtime TWX CSS. Clear Browser cache if your CSS is not merged to the combined TWX CSS. (under debug mode: Hold refresh button->Clear Cache). TWX fails to import the extension. If the extension is already installed, but you made recent changes, you need to bump the Version number in the metadata.xml. Recent CSS changes are ignored. Clear browser cache if your CSS file has changed recently.     Step 9: Next Steps   Congratulations! You've successfully completed the Add Style to Your UI with CSS guide, and learned how to:   Create custom CSS classes using the integrated CSS editor Bind CSS classes to a Mashup and to individual Widgets Use Media queries to dynamically apply styling   Learn More   We recommend the following resources to continue your learning experience:    Capability     Guide Build Application Development Tips & Tricks Experience ThingWorx Application Development Reference   Additional Resources   If you have questions, issues, or need additional information, refer to:  Resource       Link Community Developer Community Forum Support Help Center
View full tip
    Step 11: Build Extension   You can use either Gradle or Ant to build your ThingWorx Extension Project. Ant is the preferred method.   Build Extension with Gradle   Right click on your project ->Gradle (STS)->Tasks Quick Launcher.     NOTE: This opens up a new window.   Set Project from the drop-down menu to your project name and type Tasks as build. Press Enter   NOTE: This will build the project and any error will be indicated in the console window. Your console window will display BUILD SUCCESSFUL. This means that your extension is created and stored as a zip file in your_project->build->distributions folder.   Build Extension with Ant   Go to the Package explorer -> your_project->. Right click on build-extension.xml->Run As->Ant Build   Your console output will indicate BUILD SUCCESSFUL.   NOTE: This will build your project and create the extension zip in the your_project->build->distributions folder of your project.     Step 12: Import Extension    If you have valuable data on your ThingWorx server, save the current state before importing an untested extension by duplicating and renaming the ThingworxStorage directory. This will save all current entities and a new, empty ThingworxStorage directory will be generated when Tomcat is restarted. To restore your saved state, rename the duplicate directory back to ThingworxStorage. Alternatively, If you do not back up your storage, make sure that any entities you want to save are exported into xml format. This way you will be able to restore your ThingWorx server to its initial state by deleting the storage directory before importing the saved entities.   Import Extension In the lower left corner, click Import/Export, then select Import. NOTE: The build produces a zip file in ProjectName->build->distributions folder. This zip file will be required for importing the extension. For the Import Option option, select Extension. Click Browse and choose the zip file in the distributions folder (located in the Exclipse Project's build directory). Click Import.   Create a Thing   Create a Thing using the ThingWorx Composer with the Thing Template set to the WeatherThingTemplate.     Open the ConfigurationTable tab and add the appid from the OpenWeatherMap.org site.   Open the WeatherAppMashup Mashup by searching for WeatherAppMashup in the Search bar.   Click View Mashup in the WeatherAppMashup Mashup window. Type the name of a city (eg. Boston) and click go.   NOTE: You can now see the current temperature reading and weather description of your city in the Mashup.   Troubleshooting   If your import did not get through with the two green checks, you may want to modify your metadata.xml or java code to fix it depending on the error shown in the logs.   Issue Solution JAR Conflict arises between two similar jars JAR conflicts arise when a similar jar is already present in the Composer database. Try to remove the respective jar resources from the metadata.xml. Add these jars explicitly in twx-lib folder in the project folder inside the workspace directory. Now, build the project and import the extension in ThingWorx Composer once again. JAR is missing Add the respective jar resource in metadata.xml using the ThingWorx->New Jar Resource. Now, build the project and import the extension in ThingWorx Composer once again. Minimum Thingworx Version [ 7.2.1] requirements are not met because current version is: 7.1.3 The version of SDK you have used to build your extension is higher than the version of the ThingWorx Composer you are testing against. You can manually edit the configfiles->metadata.xml file to change the Minimum ThingWorx version to your ThingWorx Composer version.   Step 13: Next Steps    Congratulations! You've successfully completed the Create an Extension tutorial, and learned how to:   Install the Eclipse Plugin and Extension SDK Create and configure an Extension project Create Services, Events and Subscriptions Add Composer entities Build and import an Extension   Learn More We recommend the following resources to continue your learning experience:" Capability Guide Build Application Development Tips & Tricks Additional Resources If you have questions, issues, or need additional information, refer to: Resource Link Community Developer Community Forum Support Extension Development Guide
View full tip
    Step 4: Create Extension Project   In this tutorial, you will create a ThingWorx extension that retrieves weather information using OpenWeatherMap API. Create Account In this part of the lesson, you will create a free account in OpenWeatherMap that creates an AppKey so you can access their REST API. Sign-up for a free account. Log in to your account. Create a new API Key   NOTE: We will use this generated API key as a parameter in the REST calls.   Create New Extension Project   NOTE: Make sure that you are in the ThingWorx Extension Perspective. To verify, you should see a plus icon:   in the menu bar. If you don’t see this, you are probably in the wrong perspective. Go back to the previous step to learn how to set the perspective to ThingWorx Extension in Eclipse.   Go to File->New->Project. Click ThingWorx->ThingWorx Extension Project.  Click Next. NOTE: A New ThingWorx Extension window will appear. Enter the Project Name (for example, MyThingworxWeatherExtension). Select Gradle or Ant as your build framework. Enter the SDK location by browsing to the directory where the Extension SDK is storeed.   NOTE: The Eclipse Plugin accepts the Extension SDK version 6.6 or higher. Enter the Vendor information (for example, ThingWorx Labs). Change the default package version from 1.0.0 to support extension dependency. NOTE: The information from ThingWorx Extension Properties is used to populate the metadata.xml file in your project. The metadata.xml file contains information about the extension and details for the various artifacts within the extension. The information in this file is used in the import process in ThingWorx to create and initialize the entities. Select the JRE version to 1.8. Click Next then click Finish. Your newly created project is added to the Package Explorer tab.   Create New Entity   Select your project and click Add to create a new entity. NOTE: You can also access this from the ThingWorx menu on the menu bar. Create a Thing Template for your MyThingWorxWeatherExtension Project.   NOTE: In this guide, we are using a Template, but in a real-world scenario, you may consider using a Thing Shape to encapsulate extension functionality. By using Thing Shapes you give users of your extension the ability to easily add new functionality to existing Things. It is simple to add a new Thing Shape to an existing Thing Template, while using the properties or services defined by a Thing Template would require recreating all existing assets using the new Template. Since subscriptions cannot be created on Thing Shapes, you might choose to create Thing Templates that implement one or more subscriptions for convenience. In the pop-up window, browse to add the source folder of your project in Source Folder. NOTE: It should default to the src directory of your project. In our case it will be MyThingworxWeatherExtension/src. Browse to add the package where you want to create this new class, or simply give it a name (such as com.thingworx.weather). Enter a name and description to your Thing Template (WeatherThingTemplate).  NOTE: By default, the Base Thing Template is set to GenericThing. Select Next. NOTE: If you want to give other users of this entity permission to edit it in ThingWorx Composer, select the entity as an editable entity. Only non-editable entities can be upgraded in place; editable entities must be deleted and recreated when your extension is updated. If you need to make it possible to customize the extension, consider using a configuration table to save user customizations. Select Finish.   Verify that you have a WeatherThingTemplate class created that extends the Thing class. @ThingworxBaseTemplateDefinition(name = "GenericThing") public class WeatherThingTemplate extends Thing { public WeatherThingTemplate() { // TODO Auto-generated constructor stub } } NOTE: You might see a warning to add a serial version. You can add a default or generated serial value.   Step 5: Add Properties    In this section, you are going to add CurrentCity, Temperature and WeatherDescription properties to the WeatherThingTemplate. These properties are associated with the Thing Template and add the @ThingworxPropertyDefinitions annotation before the class definition in the code.   Right click inside the WeatherThingTemplate class or right click on the WeatherThingTemplate class from the Package Explorer. Select ThingWorx Source-> Add Property. In the popup window, create a property to store the city name. Name = CurrentCity, Base Type = STRING, Description = ‘’ Select the Has Default Value checkbox and enter a city name (eg. Boston). This will be the default value unless a specific value is passed. Select the “Persistent” checkbox. This will maintain the property value if a system restart occurs. NOTE: If you select the Logged checkbox, the property value is logged to a data store. If you select the Read Only checkbox, the data will be static. Select VALUE from the Data Change Type drop down menu       NOTE: This allows any Thing in the system to subscribe to a data change event for this property. Choose to use one of the following Data Change Types:   Data Change Type Description Always Fires the event to subscribers for any property value change Never Does not fire a change event On For most values, any change will trigger this. Off Fires the event if the new value is false Value For numbers, if the new value has changed by more than the threshold value, fire the change event. For non-numbers, this setting behaves the same as Always. Select Finish. Create another property called Temperature with a base type of NUMBER. You can keep the default values for the other parameters. Create another property called WeatherDescription with a base type of STRING. Keep the default values for the other parameters.   Step 6: Create Configuration Table   In this part of the lesson, we will create a configuration table to store the API Id that you generated from the openMapsWeather. Configuration tables are used for Thing Templates to store values similar to properties that do not change often.   Right-click inside the WeatherThingTemplate class and select ThingWorx Source->Add Configuration Table. Create a new configuration table with name OpenWeatherMapConfigurationTable. Click Add in the Data Shape Field Definitions frame. NOTE: Configuration tables require fields (columns) with a defined table structure (DataShape). Enter appid as the name with a base type STRING. Select the Required checkbox. Click OK, then Finish to add the Configuration Table To use the appid in the REST calls, you need to obtain the value from the configuration table and assign it to a field variable in the Java code. We will use the initializeThing method to obtain the appid value at runtime. NOTE: The initializeThing() method acts as an initialization hook for the Thing. Every time a Thing is created or modified, this method is executed and the value of appid is obtained from the configuration table and stored in a global field variable of the class. initializeThing() must call super.initializeThing() to ensure it performs initialization of the Thing. Create the initializeThing() method and field variable _appid with base type STRING anywhere in the WeatherThingTemplate class. private static Logger _logger = LogUtilities.getInstance().getApplicationLogger(WeatherThingTemplate.class); private String _appid; @Override public void initializeThing() throws Exception { super.initializeThing(); _appid = (String) this.getConfigurationSetting("OpenWeatherMapConfigurationTable", "appid"); } NOTE: In the code above we used ThingWorx LogUtilities to get a reference to the ThingWorx logging system, then assigned the reference to the variable _logger. In the steps below we will use this variable to log information. There are multiple kinds of loggers and log levels used in the ThingWorx Platform, but we recommend that you use the application or script loggers for logging anything from inside extension services. If prompted to import the logger, use slf4j.     Click here to view Part 3 of this guide.
View full tip
    Step 9: Create Event and Subscription   In this section, you will create a mechanism to notify the user when inclement weather occurs. For example, whenever the weather indicates storm/snow/rain, an Event should be triggered. This event is then handled by a service called a Subscription.   For this tutorial, while updating weather information inside the service UpdateWeatherInfo,we need to fire an Event: BadWeather when the weather description indicates either storm/snow/rain. This Event is handled by a Subscription: HandleWeather, which is a service that gets called whenever the BadWeather Event is fired. The subscription service HandleWeather updates a property called AlertNotification.   Create Event   In this part of the lesson, we will create an Event: BadWeather that updates weather information inside the service UpdateWeatherInfo when the weather description indicates either storm/snow/rain.   Create a property AlertNotification with a baseType STRING using the Add Property feature of the plugin we discussed before. Right click inside your java file->ThingWorx Source->Add Event.   Set the name to BadWeather and set a name for the Data Shape to Weather. NOTE: This custom Data Shape has to be created in Composer. Importing Datashapes and other custom entities created in Composer into your extension will be discussed later in the tutorial. Our DataShape Weather includes one field called WeatherDescription with a STRING base type.  Click Finish. NOTE: This will create annotation for your EventDefinition.    Create Subscription   In this part of the lesson, we will create a Subscription: HandleWeather, which is a service that gets called whenever the BadWeather Event is fired. The subscription service HandleWeather updates a property called AlertNotification. Right click inside your java file ->ThingWorx Source->Add Subscription   Set the Event Name to BadWeather and Handler Service to HandleWeather. NOTE: This means that whenever the BadWeather event is fired, the HandleWeather service will be executed. Source is left blank if the event belongs to the same template. Click Finish. This creates annotation for subscription service and also creates a new service called HandleWeather.   Modify Service   In this part of the lesson, you'll ensure that when the properties are updated, BadWeather event is triggered if the description indicates rain/snow/thunderstorm. To do this, we will modify the UpdateWeatherInfo service.   After we have called the setPropertyValue method for the properties WeatherDescription and Temperature, we can check if the weather description contains snow/rain/thunderstorm. We will create an InfoTable from the Weather Datashape. InfoTables represent data sets that take the structure of the Datashape. Each row of an InfoTable can be passed as a ValueCollection to hold data within the table. When an event is fired, we need to send data along with it. This data will be passed as an InfoTable and it is then handled by the Subscription handling the Event.We use a ValueCollection to add the weatherDescription to the InfoTable. Then, this InfoTable is set as the Event Data.   Add the code snippet to UpdateWeatherInfo section at the end of the service after setting the properties- Temperature and WeatherDescription. /* fire event BadWeather */ if (description.contains("snow") || description.contains("rain") || description.contains("thunderstorm")) { ValueCollection v = new ValueCollection(); v.put("weatherDescription", new StringPrimitive(description)); InfoTable data = InfoTableInstanceFactory.createInfoTableFromDataShape("Weather"); data.addRow(v); _logger.info("Firing event"); ThingworxEvent event = new ThingworxEvent(); event.setEventName("BadWeather"); event.setEventData(data); this.dispatchEvent(event); } Inside the HandleWeather service, set the property AlertNotification. Ensure that you have created the property AlertNotification using the eclipse plugin. Add the following code snippet to the HandleWeather service. @ThingworxServiceDefinition(name = "HandleWeather", description = "Subscription handler", category = "", isAllowOverride = false, aspects = {"isAsync:false"}) public void HandleWeather( @ThingworxServiceParameter(name = "eventData", description = "", baseType = "INFOTABLE") InfoTable eventData, @ThingworxServiceParameter(name = "eventName", description = "", baseType = "STRING") String eventName, @ThingworxServiceParameter(name = "eventTime", description = "", baseType = "DATETIME") DateTime eventTime, @ThingworxServiceParameter(name = "source", description = "", baseType = "STRING") String source, @ThingworxServiceParameter(name = "sourceProperty", description = "", baseType = "STRING") String sourceProperty) throws Exception { _logger.trace("Entering Service: HandleWeather with: Source: \"\", Event: \"BadWeather\", Property: \"\""); this.setPropertyValue("AlertNotification", new StringPrimitive("Alert:"+eventData.getFirstRow().getStringValue("weatherDescription"))); _logger.trace("Exiting Service: HandleWeather"); } Now we have an event BadWeather fired every time weather description indicates storm/snow/rain and it is handled by HandleWeather service that sets the AlertNotification property to the InfoTable data passed by the event.     Step 10: Add Composer Entities In previous parts of this tutorial, we assumed we had a datashape Weather available with field weatherDescription as the Datashape of our event: BadWeather. In this part of the lesson, we'll create a DataShape. Go to ThingWorx Composer. Click the + button. In the dropdown, select Data Shape. Enter a name, for example: Weather. Add a Field Definition weatherDescription with baseType STRING. Click check mark in the top left, then Save.   Click the More drop-down, then click Export. Export the DataShape entity from Composer, it will download in your system as an xml file. Go back to Eclipse, right-click on your project ->Import..->ThingWorx->Entities. Click Next. Browse to the directory where the xml file was downloaded. Select the xml file and Click Finish.   NOTE: This adds the xml file to the Entities folder in your project. Following the same procedure, import other entities required for this Extension stored in the Entities folder of the download we provided for this training.   NOTE: You can uncheck the box for importing DataShapes_Weather.xml, if you already loaded your Datashape in the previous steps.     Click here to view Part 5 of this guide.
View full tip
  Step 7: Add JAR Resources   You can add external JARs for use by your extension. Every third-party JAR that is not already included in either the ThingWorx Extension SDK or ThingWorx Core needs to be added to your extension project as a JAR Resource. These JAR resources are added to your metadata.xml as a tag and are used to reference the Java classes in the third-party JAR on which the extension depends. You can either use the Add button   or the ThingWorx Menu from the menu bar to add a new JAR resource. By doing so, the JAR is automatically updated in the metadata file and added to the build path. Although ThingWorx allows developers to include jar files for third-party libraries in their code, it is recommended that you avoid adding jar files for common libraries and instead use the jar files that are included with the SDK. Adding jar files to an extension could cause conflicts with jar files already used by the ThingWorx server, either when uploading an extension, or when an extension executes. Even if your extension works today, future updates to ThingWorx may require updates to your extensions. Similarly, packaging a verison of a commonly used library may mean that a customer will not be able to use your extension together with someone else’s extension.   Select the project to which you want to add the jar file to and select New Jar Resource.       Open the directory in which you have stored the training files for this tutorial. Browse to the Jars directory. Select the json-simple-1.1.1.jar file. Add a description and click Finish. NOTE: This will automatically add json-simple-1.1.1.jar to the lib folder and to your project’s build path. Add httpclient-4.5.6.jar, httpcore-4.4.10.jar and commons-logging-1.2.jar directly into the twx-lib folder in the Project folder. NOTE: These JARs are included in the group of JARs used by ThingWorx by default. In order to build your extension locally, without bundling the jars into your extension that are available on the ThingWorx server, add the above JARs to your project's build path by right-clicking on your project in the Package Explorer, right-click Your_Extension_Project (ie, MyThingWorxWeatherExtension) and select Build Path -> Configure Build Path. Verify the jars we added are in the build path. Otherwise, click Add JARs, then browse to the directory containing these JARs (lib) and add them. NOTE: twx-lib folder is a hidden folder and does not appear in the Eclipse package explorer. The twx-lib folder can be found in the WeatherExtension project inside the Eclipse workspace directory.   Step 8: Create Services   Now that you have created properties, configuration tables and added the required jars, you can begin to add services to your WeatherThingTemplate.   In this part of the lesson, we’ll add a service, UpdateWeatherInfo that will take a City parameter and update the properties of this template using the values obtained from the openWeatherMap API.   Right click inside the WeatherThingTemplate and select ThingWorx Source->Add Service. Create a new service with name UpdateWeatherInfo. Click Add in the Input Parameters frame to add City parameter with a base type STRING.   Set the name and base type of the Output Parameter based on the value that you want the service to return. For simplification, assume this service returns nothing. Set the Base Type to NOTHING. Click Finish to create the service. Copy and Paste the code for UpdateWeatherInfo as specified below. @ThingworxServiceDefinition(name = "UpdateWeatherInfo", description = "updates weather description and temperature properties", category = "", isAllowOverride = false, aspects = { "isAsync:false" }) @ThingworxServiceResult(name = "Result", description = "", baseType = "NOTHING") public void UpdateWeatherInfo( @ThingworxServiceParameter(name = "City", description = "city name", baseType = "STRING") String City) throws Exception { _logger.trace("Entering Service: UpdateWeatherInfo"); String cityProp = this.getPropertyValue("CurrentCity").getStringValue(); if (City == null){ City = cityProp; } else { this.setPropertyValue("CurrentCity", new StringPrimitive(City)); } String url = "http://api.openweathermap.org/data/2.5/weather?q=" +URLEncoder.encode(City,"UTF-8") + "&appid="+ _appid+"&units=imperial"; // create a http client HttpClient client = new DefaultHttpClient(); // create a get request with the URL HttpGet getRequest = new HttpGet(url); // add Accept header to accept json format response getRequest.addHeader("Accept", "application/json"); // send the get request and obtain a response HttpResponse response = client.execute(getRequest); // if response is successful the status code will be 200. if (response.getStatusLine().getStatusCode() == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(sb.toString()); JSONArray weather = (JSONArray) json.get("weather"); Iterator<JSONObject> it = weather.iterator(); String description = (String) it.next().get("description"); this.setPropertyValue("WeatherDescription", new StringPrimitive(description)); double temp = (Double) ((JSONObject) json.get("main")).get("temp"); this.setPropertyValue("Temperature", new NumberPrimitive(temp)); /* fire event BadWeather */ _logger.trace("Exiting Service: UpdateWeatherInfo"); } }   Troubleshooting Issue Solution The iterator() is undefined in JSONArray Import only org.json.simple.*. Importing other JSON libraries can give this error. HttpClient/HttpGet could not be resolved to a type. Make sure you have imported the jars: httpclient-4.5.2.jar, httpcore-4.4.5.jar and commons-logging-1.2.jar, json-simple-1.1.1.jar as indicated in the previous chapter. Make sure you have imported the following packages in your template by Eclipse   Your code should be similar to the following:   package com.thingworx.weather; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URLEncoder; import java.util.Iterator; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.slf4j.Logger; import com.thingworx.logging.LogUtilities; import com.thingworx.metadata.annotations.ThingworxBaseTemplateDefinition; import com.thingworx.metadata.annotations.ThingworxConfigurationTableDefinition; import com.thingworx.metadata.annotations.ThingworxConfigurationTableDefinitions; import com.thingworx.metadata.annotations.ThingworxDataShapeDefinition; import com.thingworx.metadata.annotations.ThingworxFieldDefinition; import com.thingworx.metadata.annotations.ThingworxPropertyDefinition; import com.thingworx.metadata.annotations.ThingworxPropertyDefinitions; import com.thingworx.metadata.annotations.ThingworxServiceDefinition; import com.thingworx.metadata.annotations.ThingworxServiceParameter; import com.thingworx.metadata.annotations.ThingworxServiceResult; import com.thingworx.things.Thing; import com.thingworx.types.primitives.NumberPrimitive; import com.thingworx.types.primitives.StringPrimitive; @ThingworxBaseTemplateDefinition(name = "GenericThing") @ThingworxPropertyDefinitions(properties = { @ThingworxPropertyDefinition(name = "CurrentCity", description = "", category = "", baseType = "STRING", isLocalOnly = false, aspects = { "defaultValue:Boston", "isPersistent:true", "isLogged:true", "dataChangeType:VALUE" }), @ThingworxPropertyDefinition(name = "Temperature", description = "", category = "", baseType = "NUMBER", isLocalOnly = false, aspects = { "defaultValue:0", "isPersistent:true", "isLogged:true", "dataChangeType:VALUE" }), @ThingworxPropertyDefinition(name = "WeatherDescription", description = "", category = "", baseType = "STRING", isLocalOnly = false, aspects = { "dataChangeType:VALUE" }) }) @ThingworxConfigurationTableDefinitions(tables = { @ThingworxConfigurationTableDefinition(name = "OpenWeatherMapConfigurationTable", description = "", isMultiRow = false, ordinal = 0, dataShape = @ThingworxDataShapeDefinition(fields = { @ThingworxFieldDefinition(name = "appid", description = "", baseType = "STRING", ordinal = 0, aspects = { "isRequired:true" }) })) }) public class WeatherThingTemplate extends Thing { private static final long serialVersionUID = -5294151832877452442L; public WeatherThingTemplate() {} private static Logger _logger = LogUtilities.getInstance().getApplicationLogger(WeatherThingTemplate.class); private String _appid; @Override public void initializeThing() throws Exception {     super.initializeThing();     _appid = (String) this.getConfigurationSetting("OpenWeatherMapConfigurationTable", "appid"); } @ThingworxServiceDefinition(name = "UpdateWeatherInfo", description = "updates weather description and temperature properties", category = "", isAllowOverride = false, aspects = {     "isAsync:false" }) @ThingworxServiceResult(name = "Result", description = "", baseType = "NOTHING") public void UpdateWeatherInfo(     @ThingworxServiceParameter(name = "City", description = "city name", baseType = "STRING") String City) throws Exception {     _logger.trace("Entering Service: UpdateWeatherInfo");     String cityProp = this.getPropertyValue("CurrentCity").getStringValue();     if (City == null){         City = cityProp;     } else {         this.setPropertyValue("CurrentCity", new StringPrimitive(City));     }     String url = "http://api.openweathermap.org/data/2.5/weather?q=" +URLEncoder.encode(City,"UTF-8") + "&appid="+ _appid+"&units=imperial";     // create a http client     HttpClient client = HttpClientBuilder.create().build();     // create a get request with the URL     HttpGet request = new HttpGet(url);     // add Accept header to accept json format response     request.addHeader("Accept", "application/json");     // send the get request and obtain a response     HttpResponse response = client.execute(request);     // if response is successful the status code will be 200.     if (response.getStatusLine().getStatusCode() == 200) {         BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));         StringBuilder sb = new StringBuilder();         String line = "";         while ((line = br.readLine()) != null) {             sb.append(line);         }         JSONParser parser = new JSONParser();         JSONObject json = (JSONObject) parser.parse(sb.toString());         JSONArray weather = (JSONArray) json.get("weather");         Iterator<JSONObject> it = weather.iterator();         String description = (String) it.next().get("description");         this.setPropertyValue("WeatherDescription", new StringPrimitive(description));         Double temp = (Double) ((JSONObject) json.get("main")).get("temp");         Number number = (Number) temp;         this.setPropertyValue("Temperature", new NumberPrimitive(number));         _logger.trace("Exiting Service: UpdateWeatherInfo");     } } }     Click here to view Part 4 of this guide.
View full tip
    Build extensions quickly and extend your application functionality with the Eclipse Plugin.   GUIDE CONCEPT   Extensions enable you to quickly and easily add new functionality to an IoT solution. Extensions can be service (function/method) libraries, connector templates, functional widgets, and more.   The Eclipse Plugin for ThingWorx Extension Development (Eclipse Plugin) is designed to streamline and enhance the creation of extensions for the ThingWorx Platform. The plugin makes it easier to develop and build extensions by automatically generating source files, annotations, and methods as well as updating the metadata file to ensure the extension can be imported.   These features allow you to focus on developing functionality in your extension, rather than worrying about getting the syntax and format of annotations and the metadata file correct.   YOU'LL LEARN HOW TO   Install the Eclipse Plugin and Extension SDK Create and configure an Extension project Create Services, Events and Subscriptions Add Composer entities Build and import an Extension   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 Example    Download the attached file needed for this tutorial: ExtensionSampleFiles.zip.   The ExtensionSampleFiles.zip file provided to you contains a completed example of the scenario you will be walk through in the following steps. Utilize this file if you would like to see a finished example as a reference or if you become stuck during this guide and need some extra help.     Step 2: Download Plugin and SDK    The ThingWorx Extension SDK provides supported classes and APIs to build Java-based extensions. The APIs included in this SDK allow manipulation of ThingWorx platform objects to create Java based extensions that can extend the capability of the existing ThingWorx platform.   The Eclipse Plugin assists in working with the Extension SDK to create projects, entities, and samples. Download the Eclipse Plugin. Download the Extension SDK.. Make a note of the directory where the plugin and the extension SDK are stored. The path of the directory will be required in upcoming steps. Do not extract the zip files.     Step 3: Install and Configure   Before you install the plugin, ensure that software requirements are met for proper installation of the plugin. Open Eclipse and choose a suitable directory as a workspace. Go to the menu bar of the Eclipse window and select Help->Install New Software… After the Install window opens, click Add to add the Eclipse Plugin repository. Click Archive… and browse to the directory where the Eclipse Plugin zip file is stored and click Open. Enter a name (for example, Eclipse Plugin).     Click OK. NOTE: Do not extract this zip file. Ensure that the Group items by category checkbox is not selected. Select ThingWorx Extension Builder in the items list of the Install window. Click Next and the items to be installed are listed Click Next and review the license agreement. Accept the license agreement and click Finish to complete the installation process.   NOTE: If a warning for unsigned content is displayed, click OK to complete the installation process. Restart Eclipse. When Eclipse starts again, ensure that you are in the ThingWorx Extension perspective. If not, select Window->Perspective->Open Perspective->Other->ThingWorx Extension, then click OK.      NOTE: Opening any item from File->New->Other…->ThingWorx will also change the perspective to ThingWorx Extension.     You are ready to start a ThingWorx Extension Project!     Click here to view Part 2 of this guide.  
View full tip
  Step 8: Call Custom Service   In order to execute a Service of a specific Thing with the REST API, you can use the POST verb.   Required Parameters:   AppKey created by your ThingWorx server Name of the Thing that implements a custom Service Name of the custom Service Names of inputs, if any, required by the Service Request   Construct the URL. To call a custom Service of an existing Thing, make an HTTP POST to this endpoint: <server_ip:port>/Thingworx/Things/<name of Thing>/Services/<name of Service> Substitute <name of Thing> with the actual name of a Thing that exists on the ThingWorx server, and <name of Service> with an existing Service. Send request parameters The names of the inputs along with their values are sent in the body of the POST as a JSON object. For example, the JSON object below will send a parameter named 'firstNumber' with a value of 35 and a parameter named secondNumber with a value of 711. { "firstNumber": "35", "secondNumber": "711" } NOTE: The full request must include a header with the appKey for your specific ThingWorx server.   Response   A successful call to a Service will return a JSON object in the body of the response containing both a DataShape object and an array named rows. Inside the array, an object named result will have the value returned by the custom Service. Here is an example response:   { "dataShape": { "fieldDefinitions": { "result": { "aspects": {}, "baseType": "NUMBER", "description": "", "name": "result", "ordinal": 0 } } }, "rows": [ { "result": 746.0 } ] } WARNING for other HTTP clients: Most HTTP clients do not set a Content-Type header by default, without this header set the server will return an error message. The POST request to the Service endpoint has a JSON body so the header must be set to match the format of the request body.   Step 9: Import and Export Entities   Collections of Entities that perform a function can be grouped then shared by exporting from a server. These entity collections are called Extensions and can be uploaded using the REST API. You can create custom Extensions or download Extensions created by other developers. You can use the REST API to automate the process of uploading an Extension to a ThingWorx server.   Required Parameters   AppKey created by your Foundation server Path to properly formatted zip file containing extension Entities Request   Construct the URL. Upload an Extension by making an HTTP POST to the endpoint: <Server IP:port〉Thingworx/ExtensionPackageUploader Send request parameters. The zip file that contains the extension entities is uploaded as a multi-part POST. The name of the file parameter is upload. Use a library to properly format the multi-part POST request You must also send this header: X-XSRF-TOKEN:TWX-XSRF-TOKEN-VALUE Authenticate the Request. All API requests to the ThingWorx server must be authenticated either with a username and password or with an appKey. For this example we will authenticate by passing the appKey as a URL query string parameter. The parameter appKey is recognized by the ThingWorx server as an authentication credential in requests, it can be passed either as a URL query string parameter .../CreateThing?appKey=64b87... , or as request header appKey: 64b87...   Response   A successful call to upload an Extension will return a description of the Entities that were successfully uploaded in the body of the response.   HTTPie example: http -f POST iotboston.com:8887/Thingworx/ExtensionPackageUploader upload@/home/ec2-user/extension.zip X-XSRF-TOKEN:TWX-XSRF-TOKEN-VALUE appKey:d0a68eff-2cb4-4327-81ea-7e71e26bb645 cURL example: curl -v --header X-XSRF-TOKEN:TWX-XSRF-TOKEN-VALUE --header appKey:d0a68eff-2cb4-4327-81ea-7e71e26bb645 -F upload=@extension.zip iotboston.com:8887/Thingworx/ExtensionPackageUploader?purpose=import&validate=false     Download Things By Name   The REST API can be used to export a file representation of Things on a ThingWorx Foundation server. The downloaded file can be imported to another ThingWorx server making the Thing available for use.   Required Parameters   AppKey created by your Foundation server Name of the Thing Request   Construct the URL. Retrieve the components of a Thing by making an HTTP GET to the endpoint. Substitute <name of Thing> with the actual name of a Thing that exists on the ThingWorx server that wil be downloaded. <Server IP:port>/Thingworx/Exporter/Things/<name of Thing> Send request parameters. No parameters are sent. Authenticate the Request. All API requests to the ThingWorx server must be authenticated either with a username and password or with an appKey. For this example we will authenticate by passing the appKey as a URL query string parameter. The parameter appKey is recognized by the ThingWorx server as an authentication credential in requests, it can be passed either as a URL query string parameter .../CreateThing?appKey=64b87... , or as request header appKey: 64b87...   Response   It is possible for the content to be returned in two different formats by sending an Accept header with the request.   Desired Response Type  Accept Header Values JSON application/json XML text/xml HTML text/html (or omit Accept Header) CSV text/csv   A successful call to download a Thing will return a file in the body of the response suitable for importing into a ThingWorx Foundation server.   HTTPie example:   http -v GET iotboston.com:8081/Thingworx/Exporter/Things/PiThing appKey==d0a68eff-2cb4-4327-81ea-7e71e26bb645 Accept:text/xml     Download Things By Tag   The REST API can be used to export a file representation of Things on a ThingWorx Foundation server. This file can be imported to another ThingWorx server making the Thing available for use.   Required Parameters   AppKey created by your Foundation server Name of the Tag Request   Construct the URL. Retrieve the components of a Thing by making an HTTP GET to the endpoint <Server IP:port〉/Thingworx/Exporter/Things Send request parameters. The Tag name is sent as a request parameter named: searchTags Authenticate the Request. All API requests to the ThingWorx server must be authenticated either with a username and password or with an appKey. For this example we will authenticate by passing the appKey as a URL query string parameter. The parameter appKey is recognized by the ThingWorx server as an authentication credential in requests, it can be passed either as a URL query string parameter .../CreateThing?appKey=64b87... , or as request header appKey: 64b87...   Response   It is possible for the content to be returned in two different formats by sending an Accept header with the request.   Desired Response Type  Accept Header Values JSON application/json XML text/xml HTML text/html (or omit Accept Header) CSV text/csv   A successful call to download a Thing will return a file in the body of the response suitable for importing into a ThingWorx Foundation server   HTTPie example:   http -v GET iotboston.com:8081/Thingworx/Exporter/Things searchTags==Applications:Raspberry_light appKey==d0a68eff-2cb4-4327-81ea-7e71e26bb645 Accept:text/xml     Step 10: Authentication Tags   A Tag is composed of two parts: a Vocabulary, and a specific vocabulary term. A Tag is shown as Vocabulary:VocabularyTerm. Almost every ThingWorx entity can be tagged. Tags can be used to create a relationship between many different ThingWorx Entities.   Create New Tag   You can use the REST API to create a new dynamic Tag vocabulary.   Required Parameters   AppKey created by your Foundation server Name of Tag Vocabulary   Request   Construct the URL. Create a new Tag Vocabulary by making an HTTP PUT to this endpoint: 〈Server IP:port〉/Thingworx/ModelTags Send Request Parameters. The name of the new DataShape and the name of the base DataShape that the new DataShape extends are sent in the body of the POST as a JSON object. For example, the JSON object below will create a new DataShape named SomeTestDataShape using the system template GenericThing. { "name": "SecondTest", "isDynamic": "true" } Authenticate Request. All API requests to the ThingWorx server must be authenticated either with a username and password or with an appKey. For this example we will authenticate by passing the appKey as a URL query string parameter. The parameter appKey is recognized by the ThingWorx server as an authentication credential in requests, it can be passed either as a URL query string parameter .../CreateThing?appKey=64b87... , or as request header appKey: 64b87...   Response   A successful call to the ModelTag Service does not return any content in the body of the response, only an HTTP 200 is returned.   HTTPie example:   http -v -j PUT http://52.201.57.6/Thingworx/ModelTags name=SecondTest isDynamic=true appKey==64b879ae-2455-4d8d-b840-5f5541a799ae     Warning for other HTTP clients: Most HTTP clients do not set a Content-Type header by default, without this header set the server will return an error message. The PUT request to the ModelTags endpoint has a JSON body so the header must be set to match the format of the request body. The Content-Type header does not appear in the sample HTTPie call because HTTPie sets the Accept and Content-type request headers to application/json by default. Below is an example cURL call that explicitly sets the Content-Type header to application/json.   curl -v -H "Content-Type: application/json" -X PUT -d '{"name": "SecondTest", "isDynamic":"true"}' http://52.201.57.6/Thingworx/ModelTags?appKey=d0a68eff-2cb4-4327-81ea-7e71e26bb645   Add Tag to Thing   You can use the REST API to add a Tag to a Thing. There must be a Thing and a Dynamic Tag Vocabulary already created on your Foundation Server before you can add a Tag.   Required Parameters   AppKey created by your Foundation server Name of the Thing to be tagged Name of Dynamic Tag Vocabulary Name of for Tag to be assigned to Thing Request   Construct the URL. Substitute 〈name of Thing〉 with the actual name of a Thing that exists on the ThingWorx server that will have the Tag added. Add a new Tag to an existing Thing by making an HTTP POST to this endpoint: 〈Server IP:port〉/Thingworx/Things/〈name of Thing〉/Services/AddTags Send request parameters. The name of the new field to be added and type of the field are sent in the body of the POST as a JSON object. For example, the JSON object below will create a new field named SomeNumber using the ThingWorx base type NUMBER. Some other commonly used types are STRING, INTEGER, and BOOLEAN. Include a header in the full request with the appKey for your specific ThingWorx server. { "tags" : "SecondlightTest:RaspberryTest", }   Response   A successful call to the AddTags Service does not return any content in the body of the response. Only an HTTP 200 is returned.   HTTPie example:   http -v -j http://52.201.57.6/Thingworx/Things/SomeTestThing/Services/AddTags appKey==64b879ae-2455-4d8d-b840-5f5541a799ae tags=SecondTest:RaspberryTest curl -v -H "Content-Type: application/json" -X POST -d '{"tags": "SecondlightTest:RaspberryTest"}' http://52.201.57.6/Thingworx/Things/PiThing/Services/AddTags?appKey=d0a68eff-2cb4-4327-81ea-7e71e26bb645 Warning for other HTTP clients: Most HTTP clients do not set a Content-Type header by default, without this header set the server will return an error message. The POST request to the AddPropertyDefinition endpoint has a JSON body so the header must be set to match the format of the request body. The Content-Type header does not appear in the sample HTTPie call because HTTPie sets the Accept and Content-type request headers to application/json by default. Below is an example cURL call that explicitly sets the Content-Type header to application/json.   curl -v -H "Content-Type: application/json" -X POST -d '{"tags": "SecondlightTest:RaspberryTest"}' http://52.201.57.6/Thingworx/Things/PiThing/Services/AddTags?appKey=d0a68eff-2cb4-4327-81ea-7e71e26bb645      Click here to view Part 4 of this guide.  
View full tip
    Step 4: Use Collection Widget   At this point, you have created the following Entities:   A Thing with data stored in an Info Table Property (columns defined by a Data Shape)   A base Mashup (containing Gauge, LED Display, and Text Field Widgets) that displays an individual row of data from the table   Now, you need to use the Collection Widget to display this Mashup for every row of data in the table.   On the ThingWorx Composer Browse tab, click Visualization > Mashups, + New              2. Keep the default of Responsive with no Templates chosen, and click OK.        3. In the Name field, enter cwht_collection_mashup              4. If Project is not already set, search for and select PTCDefaultProject.        5, Click Save.        6. Click Design               7.  On the top-left Layout tab, ensure that the default of Positioning > Responsive is selected.  You want the "base" Mashup to generally be Static, while the "collection" Mashup should be Responsive to allow it to grow to an appropriate size.         8. From the top-left Widgets tab, drag-and-drop a Collection Widget onto the central Canvas area.       Access Mashup Data Service   Click the + icon at the top-right to open the Add Data pop-up menu.               2. In the Entity Filter field, search for and select cwht_thing.         3. In the Services Filter field, enter getproperties.         4. Click the right arrow beside GetProperties to add the GetProperties Service to the right-side of the pop-up menu.         5. Click the Execute on Load checkbox             6. Click Done to close the pop-up menu. The GetProperties Service of the cwht_thing is now shown on the right under the Data tab.         7. On the top-right, expand GetProperties.           8. Drag-and-drop GetProperties > infotable_property onto the Collection Widget            9. On the Select Binding Target pop-up, click Data     Configure Properties   In the Collection Widget's Filter Properties field in the bottom-left, enter mashup. This will limit the displayed Properties of the Collection Widget (in the bottom-left section) to only those containing the word "mashup".            2.  For the Mashup Property, search for and select cwht_base_mashup.  Choosing "cwht_base_mashup" lets the Collection Widget know which base Mashup to repeat in every Cell               3. In the MashupHeight field, enter 250 and hit the Tab keyboard key to apply the change. This Property changes the height of each Cell of the Collection Widget. Ensure the height is large enough to fit all of the Widgets.          4. In the MashupWidth field, enter 500 and hit the Tab keyboard key.  This Property changes the width of each Cell of the Collection Widget. Ensure the is large enough to fit all of the Widgets.            5. In the Filter Properties field, enter uidfield.          6. In the UIDField drop-down, select first_number.  The UIDField sets the unique identifier for the Collection Widget.            7. In the Filter Properties field, enter sort.          8. In the SortField drop-down, select first_number.  SortField determines which sub-section of the Infotable to use for sorting purposes.          9. Check the SortAscending checkbox            10. n the Filter Properties field, enter mashupprop           11. Click Add, copy-and-paste the following JSON into the MashupPropertyBinding Property, replacing the existing curly braces {}, then click Done.   The point of this JSON is to relate the columns of the Infotable Property to the Mashup Parameters that we previously defined in the base Mashup. { "first_number" : "first_number", "second_number" : "second_number", "third_number" : "third_number" }                12. Click Save, then View Mashup.     Notice that the base Mashup we previously created has been replicated multiple times, corresponding to each row of the Info Table Property.   As an extension exercise, go back into cwht_thing and add another row of data. Refresh the Collection Widget Mashup to see another instantiation of the base Mashup automatically added to display that new row.   A Mashup utilizing the Collection Widget dynamically expands to accommodate both the user and the available data.   Step 5: Next Steps   Congratulations! You've successfully completed the Organize Your UI guide, and learned how to: Create a Datashape to define columns of a table Create a Thing with an Info Table Property Create a base Mashup to display data Utilize a Collection Widget to display data from multiple rows of a table Learn More   We recommend the following resources to continue your learning experience: Capability Guide Build Application Development Tips & Tricks Experience ThingWorx Application Development Reference   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource  Link Community Developer Community Forum Support Collection Widget Help Center  
View full tip
    Modernize your Mashups with CSS to enhance the presentation of your application.   GUIDE CONCEPT   This project will introduce using CSS to create a customized, consistent look and feel for your IoT application.   Following the steps in this guide, you will create a custom CSS class definitions and bind these classes to Mashup features.   We will teach you how to present a professional-looking user interface and ensure consistency of style treatments within your application by implementing Cascading Style Sheets (CSS) in Mashups.     You'll learn how to   Create custom CSS classes using the integrated CSS editor Bind CSS classes to a Mashup and to individual Widgets Use Media queries to dynamically apply styling     Step 1: Custom CSS Benefits   You now have more flexibility to customize your application’s UI and improve the user experience using industry-standard web techniques. You can implement CSS in ThingWorx to control the visualization of your Mashup.   Feature                   Benefit Text Treatments Optimize text with shadow, color, font, and border Responsive UI Customize layout based on user actions and the data being displayed Media Queries Accommodate many screen sizes with flexboxes and other standard containers Animations Implement standard CSS key frames Customizations Modify application appearance without changing source Mashup Linting Expedite development with code auto-completion and design-time syntax warnings       Step 2: Access Sample Files   We created sample entities you can use to complete the steps in this guide. Download the attached Mashups_CustomCssTutorialMashup.xml From the Home page of Composer, click the Import/Export icon, then choose Import   Keep the default options and click Browse. Locate and select the CustomCssTutorialMashup.xml file you downloaded and extracted, click Open then Import.   Click Close after the Import successful message is displayed. Click the Browse tab in the left navigation panel, then click Mashups.                     6. Select the CustomCssTutorialMashup.                 7. Click View Mashup to view the Mashup.     NOTE: This is a simple Mashup designed to demonstrate how the UI changes when CSS is applied.       Step 3: Create CSS Rule Block   In this step, you will use the built-in editor to create a custom CSS class that will be used in the next step to modify the appearance of three buttons grouped by the Fieldset Widget.   Open the CustomCssTutorialMashup in Edit and Design view.     Click Custom CSS.     Copy the CSS class below and paste it into the Custom CSS editor: .myMashupClass .widget-fieldset .widget-ptcsbutton { box-shadow: 5px 5px 5px #888888; } NOTE: This class will create a shadow around all of the buttons that are in a Fieldset container  only after it is bound to a Mashup,   4. Click Save.     Tips   Press Ctrl -> Space to use the Auto-complete feature and see code snippets, which can expedite your development time.     The Linting feature will warn you if there are errors in your code, so you can fix them at design time.       Step 4: Apply Custom Class to Mashup   In this step we will demonstrate how to modify the look and feel of a Mashup without changing the Mashup itself. The myMashupClass we just created chains two selectors: the widget-fieldset and the widget-button. Only Widgets that are in both selector categories will be modified.   Click Design and select the Explorer tab, then select the top-level Mashup.     In the property panel in the lower left, locate the CustomClass property and type myMashupClass as the value. Press Tab to save the value change.     WARNING: You must press Tab after every property change in order for the new value to be saved.   4. Click Save then View Mashup to see that the buttons in the Field Set have shadow borders.       Step 5: Apply Custom Class to Widget   In addition to the Mashup level, you can apply style treatments directly to a Widget in your Mashup. In ThingWorx, the following Widgets have a CustomClass property you can modify:     For this example, we will make the text on one of the buttons all caps.   In the CustomCssTutorialMashup, click Custom CSS. Add the following css code: .myButtonClass .widget-ptcsbutton { text-transform: uppercase; }     Return to the Design view, and In the Explorer tab, click the button-3.     In the Property panel, enter myMashupClass to the CustomClass field, then press tab     Save then View Mashup the Mashup to see that the button text is now all caps.       Step 6: Bind Custom Class   The UI of a Mashup can be dynamically updated at runtime by binding the value of the CustomClass property to a dynamic data source such as: Services Mashup parameters Widgets (expression widgets for example)   In this portion of the guide, we will demonstrate modifying a Mashup in response to user actions:   Return to the Design view for the CustomCssTutorialMashup. In the Mashup Builder, click the Functions tab in the lower right, then expand Event Routers and expand eventsrouter-6     Click Output property and drag it onto the bottom button of the group of three buttons.     Select the CustomClass property from the pop-up to bind it to Button-4   In Mashup Builder click Custom CSS tab. Add the following css code: .myBoundButtonClass1 .widget-ptcsbutton { text-transform: lowercase; } .myBoundButtonClass2 .widget-ptcsbutton { text-transform: uppercase; }           7. Click Save and then View Mashup.           8. Click on each of the Apply buttons to see the results of a CSS class applied to in response to user actions.     Step 7: Use Media Queries   You can use Media queries to apply styling based on the characteristics of the device being used to access the application. For this example, we will use a CSS Class to hide three elements when the browser’s width is less than 600 pixels wide.   1. Open the CustomCssTutorialMashup in Edit and Design view, then click Custom CSS.     2. Copy the CSS class below and use the Custom CSS editor to add it to the top of the existing  CSS, then click Save. @media screen and (max-width: 1000px) { #root_ptcslabel-10-bounding-box { visibility: hidden; } #root_ptcstextfield-7-bounding-box{ visibility: hidden; } #root_ptcstextfield-12-bounding-box { visibility: hidden; } }   NOTE: The ID selector in your CSS must add root_ to the beginning, and -bounding-box to the end of the element’s ID shown in Mashup Builder.   3. Click View Mashup, then click and drag the edge of the browser window to reduce the width below 600 pixels.     NOTE: The three Widgets selected in the media class added in the last step will disappear as soon as the browser is less than 600 pixels wide.       Click here to view Part 2 of this guide.
View full tip
Timers and Schedulers can also be created and configured programmatically via custom services. The following service, which can be created on any Thing, will create a new Timer using the following Inputs:         // create new Thing var params = { name: ThingName /* STRING */, description: undefined /* STRING */, thingTemplateName: "Timer" /* THINGTEMPLATENAME */, tags: undefined /* TAGS */ }; Resources["EntityServices"].CreateThing(params); // read initial configuration // result: INFOTABLE var configtable = Things[ThingName].GetConfigurationTable({tableName: "Settings"}); // update configuration with service parameters configtable.updateRate = updateRate configtable.runAsUser = user // set new configuration table var params = { configurationTable: configtable /* INFOTABLE */, persistent: true /* BOOLEAN */, tableName: "Settings" /* STRING */ }; Things[ThingName].SetConfigurationTable(params);   This code is an example which could also be used to create a new Scheduler. The configuration table for a Timer has the following attributes: updateRate enabled runAsUser The configuration table for a Scheduler has the following attributes: schedule enabled runAsUser  
View full tip
In this post we will take a look at using an existing JavaScript Library. The library will we will use is agGrid  which provides a very extensive Grid UI component. The objectives are To see how to add the library Use an external source to populate the grid Provide a click action when a user selects a row (Part 2) (see attachments - import AAGridExtensionExample as an extension and import as File PTC-ExternalSources-Entities ) Previous Posts for reference Widget Extensions Introduction Widget Extensions Click Event Widget Extensions Date Picker Widget Extensions Google Bounce We will not worry about CSS - I'm working on a post for that using Thingworx 8.2 CustomClass (CSS) feature. Also I will assume you have worked through the Widget Extensions Introduction The image below image below shows the resulting UI after grid population and a user clicked a row The following provides the high level areas of interest Steps 1. Create a Working Folder for example  AGGrid as in previous posts setup your ui folder and metadata file 2. Think of a name for the Extension - we will use aggrid and add a folder with this name under ui folder 3. create the required files as per previous posts - Note the jslibrary folder is where aagrid resides     Below shows the jslibrary folder the main file we care about is the ag-grid (we could use the min file but initially have the full makes debugging easier) 4. Setup the metadata file 5. Understand some of the agGrid requirements To create a grid we need to use the function agGrid which comes from the ag-grid.js       myGrid = new agGrid.Grid(gridContainer, gridOptions ); The gridContainer is where the grid will be placed in the DOM and the gridOptions is a definition object that holds all the settings for the grid before it is created. Using a init function inside the runtime.js (see previous posts for runtime)  we can get the gridContainer  by using a snippet like this document.getElementById(gridElementId); The gridOptions takes the form of a json object - note there are many options please refer to the agGrid documentation for more info. Our focus will be  columnDefs , rowData to start with. These 2 define the layout and the contents of the grid The columnsDefs takes the form of an Array of JSON basically headerName: and field The image below shows a hard-coded approach I took initially To make this more generic I created a Thingworx datashape and used a service script GetColumndefs to populate and output the columnDefs service script example uses a PTC-ExternalSourcesHelper thing below is the GetColumnsDefs service The next point of focus will be the gridOptions and the rowData (JSON  array of data ) based on the same definition as the columnDefs Both the columnDefs and the GridDataAsJSON (which turns into rowData)  shown below are setup in the ide.js file (see previous posts for ide) Returning back to the services we need to get some Grid data from an external source. For that we will create a GetRSSFeed and use that inside GetRSSAsJSON The GetRSSFeed  looks like this and uses the url input More Top Stories - Google News The GetRSSAsJSON looks like this looking back at the code maybe I should changed to result.rows when returning the GridData  but for now it works. The last thing is getting the data from the services and we use the updateProperty ( previous posts for ide ). Here we check for the property and set and pass the RawData to the drawaggrid function The drawaggrid takes in the rowData and uses the columnDefs to understand the format. Also the last thing the drawaggrid  function is create the actual grid. (Finally!) 5. lat but not least - Wire it all up in a Mashup! The first set is to zip up the Extension and Import  (see previous posts) The next is to create a Mashup and add the PTC-ExternalSourcesHelper entity and wire up the GetColumsDefs and the GetRSSAsJSON to the agGrid widget and then preview and hopefully it all works - I will upload the Extension and Entities shortly See you in Part 2 not yet created! (see attachments - import AAGridExtensionExample as an extension and import as File PTC-ExternalSources-Entities )
View full tip
Previous blogs Widget Extensions Introduction Widget Extensions Click Event This blog we will take a quick look at making a new Date Picker Widget I'm not going to worry about styles just the basics of getting the widget defined and able to place in the Composer canvas. As in previous blogs we have to decide on a name, we will use DatePicker Because we don't want to write all of the logic that has been written many times will use a jquery datepicker https://jqueryui.com/datepicker/ which has a lot options. The simple syntax is $(#myDate).datepicker() which will do most of the work. The $ is the jquery reference an the  #myDate is the id where the datapicker will render and the datepicker is the function worker. Before we get into the renderHtml I realize I need to quickly talk about the widgetProperties function in the ide.js. This where we set what properties can be defined and whether they are dynamic. For example the thought it useful to have a Title , Date and some simple css style configurable options. Inside the widgetProprties we have properties section (json) and the basic  pattern is PropertyName baseType defaultValue isBindingTarget Setting the isBindTarget to true allows for dynamic setting in the composer. Below is the complete definition for the widgetProperties Next we set up the design time (ide)  renderhtml And finally we define the  runtime renderHtml which looks like this Deploy it and you have a basic Data Picker. There is more work to do on this to provide better styling but  its a start!
View full tip
Sometimes it's needed to delete the existing PostgreSQL database, especially if a different major version was installed at first by mistake (for example, 9.6 in place of the supported 9.4). Then it's absolutely necessary to ensure the database is fully deleted and there is no db ghosts. The proper way to uninstall is to go to the postgresql server installation directory and find one uninstall-postgresql file. Double click on the Uninstall-postgresql file to run the un-installer- it will un-install postgresql. In case the uninstall wasn't performed correctly, below are the manual steps to clean it up. One sign of existing "ghost" db, is randomly seeing a second PostgreSQL server in the pgAdmin III or experiencing "error"-less problems when running the ThingWorx installation scripts. To uninstall manually,in this example we will use 9.6 as the version to delete - please replace with your own where needed: Remove the postgresql server installation directory. (rd /s /q "C:\Program Files\PostgreSQL\9.6") Assuming default location. Delete the user 'postgres' (net user postgres /delete) Remove the Registry entries. (HKEY_LOCAL_MACHINE\SOFTWARE\PostgreSQL\Installations\postgresql-9.6) and (HKEY_LOCAL_MACHINE\SOFTWARE\PostgreSQL\Services\postgresql-9.6) Remove the postgresql-9.6 service. (sc delete postgresql-9.6)
View full tip
This example provides the ability to generate a simple entity structure and some historical data for each entity. Historical data is run through a ThingWorx service to generate histogram data for display in a bar chart.  The provided ThingWorx entities and PDF document provide the example as well as documentation.
View full tip
The KEPServerEX installer download is available from the My Kepware web portal: https://my.kepware.com/mykepware/ It will be necessary to create a new My Kepware account if you have not already done so. When you log in to your My Kepware account, you will be at the My Kepware Home page. In the left column, you will see a link to download the latest release. You can access all of the features of KEPServerEX with this installation, including the Thingworx Native Interface. For more information on installation of KEPServerEX, see this guide: https://www.kepware.com/en-us/products/kepserverex/documents/installation-guide.pdf
View full tip
This has been moved to its new home in the Augmented Reality Category in the PTC Community.
View full tip
Performance and memory issues in ThingWorx often appear at the Java Virtual Machine (JVM) level. We can frequently detect these issues by monitoring JVM garbage collection logs and thread dumps. In this first of a multi-part series, let's discuss how to analyze JVM garbage collection (GC) logs to detect memory issues in our application. What are GC logs? When enabled on the Apache server, the logs will show the memory usage over time and any memory allocation issues (See: How to enable GC logging in our KB for details on enabling this logging level).  Garbage Collection logs capture all memory cleanup operations performed by the JVM.  We can determine the proper memory configuration and whether we have memory issues by analyzing GC logs. Where do I find the GC logs? When configured as per our KB article, GC logs will be written to your Apache logs folder. Check both the gc.out and the gc.restart files for issues if present, especially if the server was restarted when experiencing problems. How do I read GC logs? There are a number of free tools for GC log analysis (e.g. http://gceasy.io, GCViewer). But GC logs can also be analyzed manually in a text editor for common issues. Reading GC files: Generally each memory cleanup operation is printed like this: Additional information on specific GC operations you might see are available from Oracle. A GC analysis tool will convert the text representation of the cleanups into a more easily readable graph: Three key scenarios indicating memory issues: Let's look at some common scenarios that might indicate a memory issue.  A case should be opened with Technical Support if any of the following are observed: Extremely long Full GC operations (30 seconds+) Full GCs occurring in a loop Memory leaks Full GCs: Full GCs are undesirable as they are a ‘stop-the-world’ operation. The longer the JVM pause, the more impact end users will see: All other active threads are stopped while the JVM attempts to make more memory available Full GC take considerable time (sometimes minutes) during which the application will appear unresponsive Example – This full GC takes 46 seconds during which time all other user activity would be stopped: 272646.952: [Full GC: 7683158K->4864182K(8482304K) 46.204661 secs] Full GC Loop: Full GCs occurring in quick succession are referred to as a Full GC loop If the JVM is unable to clean up any additional memory, the loop will potentially go on indefinitely ThingWorx will be unavailable to users while the loop continues Example – four consecutive garbage collections take nearly two minutes to resolve: 16121.092: [Full GC: 7341688K->4367406K(8482304K), 38.774491 secs] 16160.11: [Full GC: 4399944K->4350426K(8482304K), 24.273553 secs] 16184.461: [Full GC: 4350427K->4350426K(8482304K), 23.465647 secs] 16207.996: [Full GC: 4350431K->4350427K(8482304K), 21.933158 secs]      Example – the red triangles occurring at the end of the graph are a visual indication that we're in a full GC loop: Memory Leaks: Memory leaks occur in the application when an increasing number of objects are retained in memory and cannot be cleaned up, regardless of the type of garbage collection the JVM performs. When mapping the memory consumption over time, a memory leaks appears as ever-increasing memory usage that’s never reclaimed The server eventually runs out of memory, regardless of the upper bounds set           Example(memory is increasing steadily despite GCs until we'll eventually max out): What should we do if we see these issues occurring? Full GC loops and memory leaks require a heap dump to identify the root cause with high confidence The heap dump needs to be collected when the server is in a bad state Thread dumps should be collected at the same time A case should be opened with support to investigate available gc, stacktrace, or heap dump files
View full tip
A Feature - a piece of information that is potentially useful for prediction. Any attribute could be a feature, as long as it is useful to the model. Feature engineering – Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data. It’s a vaguely agreed space of tasks related to designing feature sets for Machine Learning applications. Components: First, understanding the properties of the task you’re trying to solve and how they might interact with the strengths and limitations of the model you are going to use. Second, experimental work were you test your expectations and find out what actually works and what doesn’t. Feature engineering as a technique, has three sub categories of techniques: Feature selection, Dimension reduction and Feature generation. Feature Selection: Sometimes called feature ranking or feature importance, this is the process of ranking the attributes by their value to predictive ability of a model. Algorithms such as decision trees automatically rank the attributes in the data set. The top few nodes in a decision tree are considered the most important features from a predictive stand point. As a part of a process, feature selection using entropy based methods like decision trees can be employed to filter out less valuable attributes before feeding the reduced dataset to another modeling algorithm. Regression type models usually employ methods such as forward selection or backward elimination to select the final set of attributes for a model. For example: Project Development decision-tree:                                                  Dimension Reduction: This is sometimes called feature extraction. The most classic example of dimension reduction is principle component analysis or PCA. PCA allows us to combine existing attributes into a new data frame consisting of a much reduced number of attributes by utilizing the variance in the data. The attributes which "explain" the highest amount of variance in the data form the first few principal components and we can ignore the rest of the attributes if data dimensionality is a problem from a computational standpoint. Feature Generation or Feature Construction: Quite simply, this is the process of manually constructing new attributes from raw data. It involves intelligently combining or splitting existing raw attributes into new one which have a higher predictive power. For example a date stamp may be used to generate 2 new attributes such as AM and PM which may be useful in discriminating whether day or night has a higher propensity to influence the response variable. Feature construction is essentially a data transformation process. Tips for Better Feature Engineering Tip 1: Think about inputs you can create by rolling up existing data fields to a higher/broader level or category. As an example, a person’s title can be categorized into strategic or tactical. Those with titles of “VP” and above can be coded as strategic. Those with titles “Director” and below become tactical. Strategic contacts are those that make high-level budgeting and strategic decisions for a company. Tactical are those in the trenches doing day-to-day work.  Other roll-up examples include: Collating several industries into a higher-level industry: Collate oil and gas companies with utility companies, for instance, and call it the energy industry, or fold high tech and telecommunications industries into a single area called “technology.” Defining “large” companies as those that make $1 billion or more and “small” companies as those that make less than $1 billion.   Tip 2: Think about ways to drill down into more detail in a single field. As an example, a contact within a company may respond to marketing campaigns, and you may have information about his or her number of responses. Drilling down, we can ask how many of these responses occurred in the past two weeks, one to three months, or more than six months in the past. This creates three additional binary (yes=1/no=0) data fields for a model. Other drill-down examples include: Cadence: Number of days between consecutive marketing responses by a contact: 1–7, 8–14, 15–21, 21+ Multiple responses on same day flag (multiple responses = 1, otherwise =0) Tip 3: Split data into separate categories also called bins. For example, annual revenue for companies in your database may range from $50 million (M) to over $1 billion (B). Split the revenue into sequential bins: $50–$200M, $201–$500M, $501M–$1B, and $1B+. Whenever a company falls with the revenue bin it receives a one; otherwise the value is zero. There are now four new data fields created from the annual revenue field. Other examples are: Number of marketing responses by contact: 1–5, 6–10, 10+ Number of employees in company: 1–100, 101–500, 502–1,000, 1,001–5,000, 5,000+ Tip 4: Think about ways to combine existing data fields into new ones. As an example, you may want to create a flag (0/1) that identifies whether someone is a VP or higher and has more than 10 years of experience. Other examples of combining fields include: Title of director or below and in a company with less than 500 employees Public company and located in the Midwestern United States You can even multiply, divide, add, or subtract one data field by another to create a new input. Tip 5: Don’t reinvent the wheel – use variables that others have already fashioned. Tip 6: Think about the problem at hand and be creative. Don’t worry about creating too many variables at first, just let the brainstorming flow.
View full tip
Hi,   I have just been playing around with the Edge MicroServer on a couple of Raspberry Pi's.  I obviously want them connected to ThingWorx, however they stop when the SSH session closes which isn't ideal.  I thought about doing something really quick and dirty using 'nohup', but this could have lead to many running processes, and wouldn't still not have started automatically when the Pi booted.  So, I did it right instead using init.d daemon configurations.   There are two files; one for the EMS and one for the Lua Script Resource.  You need to put these in /etc/init.d, then make sure they are owned by root.   sudo chown root /etc/init.d/thingworx* sudo chgrp root /etc/init.d/thingworx*   You'll need to modify the paths in the first lines of these files to match where you have your microserver folder.  Then you need to update the init.d daemon configs and enable the services.   sudo update-rc.d thingworx-ems defaults sudo update-rc.d thingworx-ems enable sudo update-rc.d thingworx-lsr defaults sudo update-rc.d thingworx-lsr enable   You can then start (stop, etc.) like this:   sudo service thingworx-ems start sudo service thingworx-lsr start   They should both also start automatically after a reboot.   Regards,   Greg
View full tip
1. Add an Json parameter Example: { ​    "rows":[         {             "email":"example1@ptc.com"         },         {             "name":"Qaqa",             "email":"example2@ptc.com"         }     ] } 2. Create an Infotable with a DataShape usingCreateInfoTableFromDataShape(params) 3. Using a for loop, iterate through each Json object and add it to the Infotable usingInfoTableName.AddRow(YourRowObjectHere) Example: var params = {     infoTableName: "InfoTable",     dataShapeName : "jsontest" }; var infotabletest = Resources["InfoTableFunctions"].CreateInfoTableFromDataShape(params); for(var i=0; i<json.rows.length; i++) {     infotabletest.AddRow({name:json.rows.name,email:json.rows.email}); }
View full tip
Announcements