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

Community Tip - Did you get an answer that solved your problem? Please mark it as an Accepted Solution so others with the same problem can find the answer easily. X

IoT Tips

Sort by:
    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
Create Custom Business Logic    Overview   This project will introduce you to creating your first ThingWorx Business Rules Engine.   Following the steps in this guide, you will know how to create your business rules engine and have an idea of how you might want to develop your own. We will teach you how to use your data model with Services, Events, and Subscriptions to establish a rules engine within the ThingWorx platform.   NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete this guide is 60 minutes.    Step 1: Completed Example   Download the attached, completed files for this tutorial: BusinessLogicEntities.xml.   The BusinessLogicEntities.xml file contains a completed example of a Business Rules Engine. 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: Rules Engine Introduction   Before implementing a business rule engine from scratch, there are a number of questions that should first be answered. There are times in which a business rule engine is necessary, and times when the work can be down all within regular application coding.   When to Create a Rules Engine: When there are logic changes that will often occur within the application. This can be decisions on how to do billing based on the state or how machines in factories should operate based on a release. When business analysts are directly involved in the development or utilization of the application. In general, these roles are often non-technical, but being involved with the application directly will mean the need for a way to make changes. When a problem is highly complex and no obvious algorithm can be created for the solution. This often covered scenarios in which an algorithm might not be the best option, but a set of conditions will suffice.   Advantages of a Rules Engine The key reward is having an outlet to express solutions to difficult problems than can be easily verifiable. A consolidated knowledge base for how a part of a system works and a possible source of documentation. This source of information provides people with varying levels of technical skill to all have insight into a business model.   Business Logic with ThingWorx Core Platform: A centralized location for development, data management, versioning, tagging, and utilization of third party applications. The ability to create the rules engine within the ThingWorx platform and outside of ThingWorx platform. Being that the rules engine can be created outside of the ThingWorx platform, third party rules engines can be used. The ThingWorx platform provides customizable security and provided services that can decrease the time in development.     Step 3: Establish Rules   In order to design a business rules engine and establish rules before starting the development phase, you must capture requirements and designate rule characteristics.   Capture Requirements The first step to building a business rules engine is to understand the needs of the system and capture the rules necessary for success.   Brainstorm and discuss the conditions that will be covered within the rules engine Construct a precise list Identify exact rules and tie them to specific business requirements.   Each business rule and set of conditions within the business rule will need to be independent of other business rules. When there are several scenarios involved, it is best to create multiple rules – one handling each. When business rules are related to similar scenarios, the best methodology is to group the rules into categories.   Category Description Decision Rules Set of conditions regarding business choices Validation Rules Set of conditions regarding data verifications Generation Rules Set of conditions used for data object creation in the system Calculation Rules Set of conditions that handle data input utilized for computing values or assessments   Designate Rule Characteristics Characteristics for the rules include, but are not limited to: Naming conventions/identifiers Rule grouping Rule definition/description Priority Actions that take place in each rule.   After this is completed, you will be ready to tie business requirements to business rules, and those directly to creating your business rules engine within the platform.   Rules Translation to ThingWorx There are different methods for how the one to one connections can be made between rules and ThingWorx. The simplified method below shows one way that all of this can be done within the ThingWorx platform:   Characteristic  ThingWorx Aspect Rule name/identifier Service Name Ruleset  Thing/ThingTemplate Rule definition  Service Implementation Rule conditions Service Implementation Rule actions Service Implementation Data management DataTables/Streams   Much of the rule implementation is handled by ThingWorx Services using JavaScript. This allows for direct access to data, other provided Services, and a central location for all information pertaining to a set of rules. The design provided above also allows for easier testing and security management.   Step 4: Scenario Business Rule Engine    An important aspect to think about before implementing your business rules engine, is how the Service implementation will flow.   Will you have a singular entry path for the entire rules engine? Or will you have several entries based on what is being requested of it? Will you have create only Services to handle each path? Or will you create Events and Subscriptions (Triggers and Listeners) in addition to Services to split the workload?   Based on how you answer those questions, dictates how you will need to break up your implementation. The business rules for the delivery truck scenario are below. Think about how you would break down this implementation.   High Level Flow 1 Customer makes an order with a Company (Merchant). 1.A Customer to Merchant order information is created. 2 The Merchant creates an order with our delivery company, PTCDelivers. 2.A Merchant order information is populated. 2.B Merchant sets delivery speed requested. 2.C Merchant sets customer information for the delivery. 3 The package is added to a vehicle owned by PTCDelivers. 4 The vehicle makes the delivery to the merchant's customer.   Lower Level: Vehicles 1 Package is loaded onto vehicle 1.i Based on the speed selected, add to a truck or plane. 1.ii Ground speed option is a truck. 1.iii Air and Expedited speed options are based on planes usage and trucks when needed. 2 Delivery system handles the deliveries of packages 3 Delivery system finds the best vehicle option for delivery 4 An airplane or truck can be fitted with a limited number of packages.   Lower Level: Delivery 1 Delivery speed is set by the customer and passed on to PTCDelivers. 2 Delivery pricing is set based on a simple formula of (Speed Multiplier * Weight) + $1 (Flat Fee). 2.i Ground arrives in 7 days. The ground speed multiplier is $2. 2.ii Air arrives in 4 days. The air speed multiplier is $8. 2.iii Expedited arrives in 1 day. The expedited speed multiplier is $16. 3 Deliveries can be prioritized based on a number of outside variables. 4 Deliveries can be prioritized based on a number of outside variables. 5 Bulk rate pricing can be implemented.   How would you implement this logic and add in your own business logic for added profits? Logic such as finding the appropriate vehicle to make a delivery can be handled by regular Services. Bulk rates, prioritizing merchants and packages, delivery pricing, and how orders are handled would fall under Business Logic. The MerchantThingTemplate Thing contains a DataChange Subscription for it's list of orders. This Subscription triggers an Event in the PTCDelivers Thing.   The PTCDelivers Thing contains an Event for new orders coming in and a Subscription for adding orders and merchants to their respective DataTables. This Subscription can be seen as the entry point for this scenario. Nevertheless, you can create a follow-up Service to handle your business logic. We have created the PTCDeliversBusinessLogic to house your business rules engine.   Step 5: Scenario Data Model Breakdown   This guide will not go into detail of the data model of the application, but here is a high level view of the roles played within the application.   Thing Shapes ClientThingShape Shape used to represent the various types of clients the business faces (merchants/customers). VehicleThingShape Shape used to represent different forms of transportation throughout the system.   Templates PlaneThingTemplate Template used to construct all representations of a delivery plane. TruckThingTemplate Template used to construct all representations of a delivery truck. MerchantThingTemplate Template used to construct all representations of a merchant where goods are purchased from. CustomerThingTemplate Template used to construct all representations of a customer who purchases goods.   Things/Systems PTCDeliversBusinessLogic This Thing will hold a majority of the business rule implementation and convenience services. PTCDelivers A Thing that will provide helper functions in the application.   DataShapes PackageDeliveryDataShape DataShape used with the package delivery event. Will provide necessary information about deliveries. PackageDataShape DataShape used for processing a package. OrderDataShape DataShape used for processing customer orders. MerchantOrderDataShape DataShape used for processing merchant orders. MerchantDataShape DataShape used for tracking merchants.   DataTables OrdersDatabase DataTable used to store all orders made with customers. MerchantDatabase DataTable used to store all information for merchants.     Step 6: Next Steps   Congratulations! You've successfully completed the Create Custom Business Logic guide, and learned how to: Create business logic for IoT with resources provided in the ThingWorx platform Utilize the ThingWorx Edge SDK platforms with a pre-established business rule engine   We hope you found this guide useful.    The next guide in the Design and Implement Data Models to Enable Predictive Analytics learning path is Implement Services, Events, and Subscriptions.     
View full tip
    Automate business processes with Services, Events and Subscriptions.   Guide Concept   This project will introduce Services, Events, and Subscriptions inside of the ThingWorx platform. Following the steps in this guide, you will be able to expand your data model using Services, Events, and Subscriptions.   We will teach you how to make a more robust and enjoyable experience for users simply by using the resources inside of the ThingWorx Composer.   You'll learn how to   Create Events, Services and Subscriptions in Composer Utilize the ThingWorx Edge SDK platforms with Services, Subscriptions, and Events   NOTE:  The estimated time to complete this guide is 60 minutes     Step 1: Completed Example   This guide references the attached EventsServicesSubscription.zip. The sample application is based on a company needing to make deliveries. The rules engine will handle much of the work outside of the transportation workflow.   Unzip and 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.   What's Inside    Name                                            Type PTCDelivers Thing PTCDeliversBusinessLogic Thing PackageStream Stream OrdersDatabase Database DeliveryDataTable Database PackageDataTable Database MerchantDatabase Database PlaneThingTemplate ThingTemplate MerchantThingTemplate ThingTemplate TruckThingTemplate ThiingTemplate ClientThingShape ThingShape VehicleDeliveryShape ThingShape PackageDataShape DataShape CustomerDataShape DataShape OrderDataShape DataShape PackageDeliveryDataShape DataShape MerchantOrderDataShape DataShape MerchantDataShape DataShape default_user User TestDashboardMashup1 Mashup TestGadget Mashup     Step 2: Functionality   You can combine Services, Subscriptions, and Events to automate business processes or trigger notifications. See the definitions and examples before to gain a better understanding as to the role each plays.    Name                 Function Services Methods and functions to be used within a ThingWorx application. There are Services provided by the system, but custom services need to be made to create the application's functional requirements. All services in the ThingWorx Composer can be accessed by a user with the appropriate permissions. Remote services can be created with the use of the ThingWorx SDKs. Events An Event represent a change in state of a property or changes in a running application. Changes can be handled in different ways based on the method used to fire or queue them. They are a great resource for property value changes and alerts. Subscriptions The implementation for a subscription is the same as that of a service. Subscriptions are activated when the Event they are listened for is triggered.       Step 3: Create Events   Events are used to mark situations that can occur within an application. They can be used for scenarios ranging from a dangerous situation that is imminent and needs to be checked by personnel to just a system notification. Each Event is based on a DataShape that will hold the necessary information about the Event.   For example, it wouldn’t be enough to just know that a rain Event has occurred. It might be helpful to also know the location, the time the rain started and expectations of the amount of rain to fall.   Follow the steps below to create an Event for the TruckThingTemplate Entity.   Open the TruckThingTemplate Entity and click the Events tab. Click Add.   Enter an Event name, such as PackageDelivered. For the DataShape, in the Search Data Shape field, filter and select PackageDataShape.   Events can be queued or fired based on updates done in Composer, property changes of a running application, or programmatically. Triggering or firing an Event can be done in Services utilizing JavaScript.       Step 4: Services Interface   To create Services within ThingWorx, go to the Services tab of the Entity that will house the Service. Our PTCDeliversBusinessLogic Thing will contain several Services for us.   Within the Services tab under the Entity Information section of a Thing, you will see built in functionality for all the ThingTemplates and ThingShapes the Thing inherits from. You will also see the section that allows you to create new Services.   Service Info Tab   This tab is for the general information of the Service. This is where you will add the Service name, description, category, whether the service is asynchronous, and whether the Service can be overridden.     Inputs Tab   This tab is for the parameters for the Service. For input parameters, a parameter can be required and default values are allowed.     Outputs Tab   This tab is for the return type of the Service. The resulting output of the Service can stretch from being nothing to user defined Entities.     Snippets Tab   This tab allows users to pick from reusable JavaScript code that is specific to ThingWorx. These snippets are grouped by resources used, functionality, and type. You are also provided a search bar to look for keywords or titles.   When a snippet is found, click the arrow. This will insert the JavaScript code into the Script section wherever the cursor is located. From here, edit the inserted snippet to work with the rest of your code. This section is often helpful in getting to know how to perform service calls and code for the ThingWorx environment.     Me/Entities Tab   A listing of all Properties, Events, and Services belonging to custom and provided Entities in ThingWorx. As with the Snippets section, clicking the blue and white arrow will insert the reusable code to wherever the cursor is located. After the code is inserted, update the code to your liking. This is often a great resource for buildiung up payload for Service calls.       Click here to view Part 2 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 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 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 12: Connect to Temperature Sensor   This step is optional. Additional instructions are provided for developers who are interested in interfacing with sensors.   The DHT11 and DHT22 digital temperature and humidity sensors are inexpensive and available from several sources: Adafruit Sparkfun SeeedStudio The Raspberry Pi does not come with any built-in analog to digital conversion capability and because these sensors are digital they can be interfaced easily with a Raspberry Pi. We will be using a Python library developed by Adafruit that simplifies interfacing with these sensors.   Install Adafruit Python Library for Sensors   We will use Git to download the Adafruit DHT11 Python from GitHub. Check if Git is already installed by opening a command window and typing the command: git If you see a "command not found" error message use this command to install Git: sudo apt-get install git-core If you get an error installing Git, run the command: sudo apt-get update then try to install Git again. Change into the EMS directory: cd microserver Download the Adafruit library with this command: git clone https://github.com/adafruit/Adafruit_Python_DHT.git Change into the directory that was just downloaded: cd Adafruit_Python_DHT Install Python build libraries: sudo apt-get install build-essential python-dev Build and install the library with this command: sudo python setup.py install   Connect Sensor to Raspberry Pi Power down the Raspberry Pi before making any wire connections. To prevent any flash memory corruption, enter the command shutdown -h now then wait a few seconds for it to complete before disconnecting the power supply. Use female-to-female jumper wires to connect the sensor as shown below. The black wire is connected to ground, the red wire is 5v or VCC, and the yellow wire carries is the digital signal. WARNING: Double check your connections before applying power. Mistakes can destroy the sensor and the Raspberry Pi!   3. Apply power and boot the Raspberry Pi. 4. Change into the EMS directory:   cd microserver 5. Test the sensor with this commmand:   ./Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4   In a few a seconds the current temperature and humidity will be displayed. Change the 11 parameter to 22 if you are using the DHT22 sensor. The 4 parameter is the GPIO pin number of the Raspberry Pi that is conneCted to the sensor's signal pin. This command is the same command the luaScriptResource will use to get temperature and humidity readings.   Modify Lua template file A dozen lines need to be added to the file PiTemplate.lua file in the /microserver/etc/custom/templates directory.   After the line: properties.cpu_volt = { baseType="NUMBER", pushType="ALWAYS", value=0 } Add the two lines: properties.temp = { baseType="NUMBER", pushType="ALWAYS", value=0 } properties.humidity = { baseType="NUMBER", pushType="ALWAYS", value=0 } After the line: local voltCmd = io.popen("vcgencmd measure_volts core") Add the line: local sensorCmd = io.popen("./Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4") After the line: properties.cpu_volt.value = s Add these 9 lines: -- set property temp and humidity local sensor = sensorCmd:read("*a") log.debug("[PiTemplate]",string.format("raw sensor %s", sensor)) s = string.match(sensor,"Temp=(%d+\.%d+)"); log.debug("[PiTemplate]",string.format("scaled temp %.1f", s)) properties.temp.value = s s = string.match(sensor,"Humidity=(%d+\.%d+)"); log.debug("[PiTemplate]",string.format("scaled humidity %.1f", s)) properties.humidity.value = s Stop and then restart luaScriptResource by using the following commands. ps -efl Will list all running processes, note the number in the PID column for ./lusScriptResource kill -9 PID# Replace PID# with number noted above and the process will be ended. Run LuaScriptResource by executing the following command: sudo ./luaScriptResource   Update Properties of PiThing   Log onto ThingWorx Foundation server. Click on the Home icon in Composer then broswse to Things > PiThing > Properties and click Manage Bindings button.   Click on the Remote tab, then drag and drop the temp and humidity Properties one at a time to the green plus sign next to Create new Properties. Click Done to close the binding window, then click Save. NOTE: The temp and humidity Properties will be updated every 30 seconds.     Step 13: Next Steps   Congratulations! You've successfully completed the Connect Raspberry Pi to ThingWorx guide, and learned how to:   Set up Raspberry Pi Install, configure and launch the EMS Connect a remote device to ThingWorx   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Manage Data Model Introduction Build Get Started with ThingWorx for IoT   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support Edge SDKs and WebSocket-based Edge MicroServer (WS EMS) Help Center External Raspberry Pi Documentation  
View full tip
Connect and Monitor Industrial Plant Equipment Learning Path   Learn how to connect and monitor equipment that is used at a processing plant or on a factory floor.   NOTE: Complete the following guides in sequential order. The estimated time to complete this learning path is 180 minutes.   Create An Application Key  Install ThingWorx Kepware Server Connect Kepware Server to ThingWorx Foundation Part 1 Part 2 Create Industrial Equipment Model Build an Equipment Dashboard Part 1 Part 2
View full tip
  Step 5: Bind Industrial Tag   Now that you've established a connection, you can use ThingWorx Foundation to inspect all available information on ThingWorx Kepware Server.   ThingWorx Kepware Server includes some information by default to assist you with verifying a valid connection with ThingWorx Foundation.   Create New Thing   In ThingWorx Foundation, click Browse > Modeling > Industrial Connections.   Click IndConn_Server. At the top, click Discover. The Discover option is exclusive to Things inheriting the IndustrialGateway Thing Template and displays information coming from ThingWorx Kepware Server.   Expand Channel1. Click Device1. On the right, you’ll see Tag1 and Tag2, which are pre-defined Tags to assist with connectivity testing.   Click the checkbox next to Tag1. Click Bind to New Entity.   In the Choose Template pop-up, select RemoteThing and click OK.   Finalize New RemoteThing   You’ll now be in an interface to create a new Thing with a predefined Property based on ThingWorx Kepware Server Tag1.   Type IndConn_Tag1 in the Name field. In the Description field, enter an appropriate description, such as Thing with a property fed from an Kepware Server Tag. The Base Thing Template has been automatically set to RemoteThing. The Implemented Shapes has been automatically set to IndustrialThingShape.   If Project is not already set, search for and select PTCDefaultProject.   Click Save.   Test Connection   The IndConn_Tag1 Thing you created now has a Property with a value that will change with each update from ThingWorx Kepware Server.   The Tag1 we utilized is a 'ramp' and therefore, the value will increase at regular intervals.   At the top, click Properties and Alerts. Under Inherited Properties, you will see entries for both RemoteThing and IndustrialThingShape. The Property isConnected is checked, indicating a connection from Foundation to ThingWorx Kepware Server. The Property IndustrialThing has been automatically set to IndConn_Server. Notice the predefined Property named Channel1_Device1_Tag1.   Click Refresh repeatedly. You’ll see the value increase with each Refresh. This represents data being simulated in ThingWorx Kepware Server.   Step 6: Log to Value Stream   Now that you have explored the Properties of IndConn_Tag1, you’ve seen how ThingWorx Kepware Server feeds information to ThingWorx Foundation.   To get an even better indication of changes and confirm continued connectivity, we will log the changes to a Value Stream in order to record the values with a TimeStamp.   Create Value Stream   In ThingWorx Foundation, click Browse > Data Storage > Value Streams.   Click + New.   In the Choose Template pop-up, select ValueStream. Click OK. Type IndConn_ValueStream in the Name field. In the Description field, enter an appropriate description, such as Value Stream to record changes from ThingWorx Kepware Server. If Project is not already set, search for and select PTCDefaultProject. Click Save.   Bind Value Stream   Return to the IndConn_Tag1 Thing. At the top, select General Information. In the Value Stream field, search for and select IndConn_ValueStream.   At the top, select Properties and Alerts.   Click Channel1_Device1_Tag1. A new set of options will expand from the right.   Check the box for Persistent. Check the box for Logged.   In the top-right, click the Check button to close the expanded options. Click Save.   All changes to the Tag1 Property fed from ThingWorx Kepware Server are now stored and TimeStamped to the IndConn_ValueStream.     Step 7: Visualize the Data   We'll now create a Mashup to visualize the record of information from ThingWorx Kepware Server.   In ThingWorx Foundation, click Browse > Visualization > Mashups.   Click +New.   In the New Mashup pop-up, leave the default selections and click OK.   In the Name field, type IndConn_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, ensure the Widgets tab is selected.   In the Filter Widgets field at the top-left, type line. Drag-and-drop a Line Chart onto the central canvas area.     Add Data   At the top-right, ensure the Data tab is active.   Click the + button.   In the Entity Filter field, search for and select IndConn_Tag1. In the Services Filter field, type queryprop. Click the right-arrow button beside QueryPropertyHistory. The QueryPropertyHistory Service of the IndConn_Tag1 Thing will appear on the right in the Selected Services field. Check the box under Execute on Load in the Selected Services field.   Click Done. Note that the QueryPropertyHistory Service now appears on the right side Data tab. On the top-right Data tab, expand Things_IndConn_Tag1 > QueryPropertyHistory > Returned Data.   Drag-and-drop All Data from the QueryPropertyHistory Service from the right onto the Line Chart in the center.   In the Select Binding Target pop-up, select Data.   Configure Chart Properties   Click the Line Chart to select it. In the bottom-left Properties, type xaxisfield in the filter. Expand the drop-down for XAxisField.   Select timestamp. At the top, click Save. Click View Mashup. (You may have to enable pop-ups in your browser.)   The IndConn_Mashup will show you the recorded history of Property changes that came from ThingWorx Kepware Server.   Because the Tag1 Example is a ramp, you’ll notice a slowly-increasing value in the Line Chart.   Reload the Mashup's browser-tab to see the value increase even further.   NOTE: If the Mashup visualization is blank, confirm your connection to ThingWorx Kepware Server. Return to the Test Connection section of the "Bind Industrial Tag" step.     Step 8: Next Steps   Congratulations! You've successfully completed the Connect Industrial Devices and Systems guide.   You've learned how to:   Connect ThingWorx Kepware Server to ThingWorx Foundation Secure the connection with an Application Key Create an IndustrialGateway Thing Map ThingWorx Kepware Server Tags to ThingWorx Foundation Thing Properties Visualize Data from connected digital assets   Learn More   Capability Resource Connect Connect to an Allen-Bradley PLC   Additional Resources   For additional information on ThingWorx Kepware Server:   Resource Link Documentation Kepware documentation Support Kepware Support site
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
    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
Configure Permissions Guide Part 1   Overview   This project will introduce you to permissions inside of the ThingWorx platform. Permissions are used to control usage during development, runtime, and experience. Following the steps in this guide, you will be able to create Users, User Groups, Application Keys, and Organizations and tie them together. We will teach you how to create functional permission schemes in the ThingWorx platform to create a secure application and development environment.   NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete ALL 2 parts of this guide is 30 minutes.    Step 1: Completed Example   Download and unzip the completed files attached to this tutorial: PermissionsEntities.zip.   In this tutorial, we walk through security concepts within ThingWorx. Utilize this file to see a finished example and return to it as a reference if you become stuck creating your own fully flushed out application.   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: Common Terms   It is important to understand the terminology before creating Users, Groups, and Permissions: Term Definition Entity Generic name for any of the customizable building blocks inside the ThingWorx Platform User An Entity dedicated to identifying a person or device accessing the platform User Group An Entity that defines role-based permissions for Users in bulk Tags and Projects Mechanisms used to group Entities together by marking them as similar or related Composer The ThingWorx GUI tool for building your solution Resource A collection of Services which are not stateful (i.e. they do not have Properties, Events, etc.); they can be found in Composer under the System category Organization Hierarchical structures that allow you to assign visibility to Entities in the ThingWorx Model     Step 3: Users   Users represent an individual person or connected system. They contain information such as a username, email, and password (Standard Credentials) as well as peripheral information such as Name of the actual person/system/device it was created for. Users can be created, updated, and deleted just like every other Entity.   Create User   In the ThingWorx Composer, click the + New at the top of the screen. Select User in the dropdown. Name the User default_user and add a password. Set the Project field (ie, PTCDefaultProject) and click Save. User-Related Services   There are a few Services available through a resource called EntityServices, that allow you to interact with user entities programmatically.   Once a user has been created, you can interact with it through some built-in Services:     Default Users   There are two key users built into every instance of ThingWorx when initially created.   Administrator: When setting up your platform, you'll use the Administrator user first, because it is the user that will allow you to set up new users and assign them to Administrator or other roles.   NOTE: It is extremely important to reset the Administrator password after your first login. Leaving the default password could allow the system to be compromised in the future.   System User: The System User is created to allow service chaining on a given Thing when a user may not have direct permissions for every part of the chain. It exists so that access to given Services can be granted based on some previous logic instead of direct overarching permissions. For example: if the user is within the building, then trigger a Service, otherwise do not trigger the Service.     Step 4: User Groups   In many IoT solutions there will be a large scale of Users using the system. Because of this it doesn’t make sense to manually set the permissions of every User added to the system. This is why we created User Groups. User Groups provide a role-based approach to permissions and exist to give similar Users the same permissions across multiple Entities on the platform. User groups set permissions exactly the same way as Users do (see next section), but you can simply add a User to a User Group in order to set permissions at scale. For example: Creating a User group such as "Solution Architects" would allow you to do something like set all permissions for design time but limit permissions for run time. Similarly you could create a user group called "Solution Users" who have no design time permissions and specific run time permissions.   Create Group and Add Users   In the ThingWorx Composer, click the + New at the top of the screen. Select User Group in the dropdown. Name your group ExampleGroup. Set the Project field (ie, PTCDefaultProject) and click Save. Click Members to view current members in the group. Filter and select the user you want to add in the Available Members section. Click the arrow on their row or drag the User to the Members section. Click Save. NOTE: Individual user permissions will override group user permissions. In other words, if you initially add a user to a group so they inherit the permissions of the group, you will still be able to customize permissions for an individual user in that group as needed.   User Group Services   There are a few Services available through a resource called EntityServices, that allow you to interact with user group entities programmatically. Service Name Description CreateGroup Creates a new User Group DeleteGroup Deletes a user Group   Once a group has been created you can interact with it through built-in services to add or remove a User. Service Name Description AddMember Adds a User or User Group to this group AssignMembers Adds a list of Users or User Groups to this group DeleteMember Removes a User or User Group from the members of this group     Default User Groups   The platform has a few User Groups included in the platform by default. These are used to set up common roles that are often associated with using the platform and have built in permissions.   Click here to view Part 2 of this guide. 
View full tip
Build a Predictive Analytics Model Guide Part 1   Overview   This project will introduce ThingWorx Analytics Builder. Following the steps in this guide, you will create an analytical model, and then refine it based on further information from the Analytics platform. We will teach you how to determine whether or not a model is accurate and how you can optimize both your data inputs and the model itself.   NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete ALL 2 parts of this guide is 60 minutes.      Step 1: Scenario   MotorCo manufactures, sells, and services commercial motors. Recently, MotorCo has been developing a new motor, and they already have a working prototype. However, they've noticed that the motor has a chance to FAIL CATASTROPHICALLY if it's not properly serviced to replace lost grease on a key moving part. In order to prevent this type of failure in the field, MotorCo has decided to instrument their motors with sensors which record vibration. The hope is that these sensors can detect certain vibrations which indicate required maintenance before a failure occurs. MotorCo has decided to utilize ThingWorx Analytics to scan their prototype data for any insights they can gain to address this issue. Challenges: There is a known failure mode of a prototype, but it is not currently possible to predict when the failure might happen Until this failure mode is mitigated, the prototype cannot move into full production While connected data is being monitored, what to do with that data is not currently known The additional sensors are adding to the overall cost of the product   Step 2: Settings   If you manually installed the Analytics extension, then you need to complete the steps below to finalize the connection.  On the ThingWorx Composer Analytics tab, click ANALYTICS BUILDER > Settings. In the Analytics Server field, search for and select your Server Thing Entity, such as AnalyticsServer_Thing or localhost-AnalyticsServer. Click Verify Configuration.   Click Save. WARNING: You MUST CLICK SAVE or the configurations will be lost when you move to Data in the next step.   Step 3: Upload Data   We will now load the data that ThingWorx Analytics will use to generate a model. Download the attached analytics_vibration.zip 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.... The New Dataset pop-up will open.         5. In the Dataset Name field, enter vibration_dataset. 6. In the File Containing Dataset Data section, search for and select vibration_data_and_header.csv. 7. In the File Containing Dataset Field Configuration section, search for and select vibration_metadata.json.   8. Click Submit. Note that it will take a variable amount of time for the data-upload to complete, based on the size of your dataset.              Step 4: Signals   The Signals section of ThingWorx Analytics looks for the most statistically correlated single field in the dataset which relates to your selected goal. This doesn't necessarily indicate that it is the cause of your goal, whether maximizing or minimizing. It just means that the dataset indicates that this single field happens to correlate with the goal that you desire. On the left, click ANALYTICS BUILDER > Signals.   At the top, click New…. A New Signals pop up will open.   3. In the Signal Name field, enter vibration_signal. 4. In the Dataset field, select vibration_dataset. 5. Leave the Goal field set to the default of low_grease. 6. Leave the Filter field set to the default of all_data. 7. Leave the Excluded Fields from Signal field set to the default of empty. 8. Click Submit. 9. Wait ~30 seconds for Signal State to change to COMPLETED The results will be displayed at the bottom.             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 at all related, and bands two, three, and five are hardly related at all.   Click here to view Part 2 of this guide. 
View full tip
    Step 3: Test Services and Save Test Cases   In the previous step, you created an Entity with a customized Service. You can easily test and update the Service within the same editing window. This allows you to quickly modify a Service and confirm that its new behavior is functioning as expected. Test Execution   To execute a Service, you can do it while still developing and after you have created it.   During Development   Open the LineCheckSystem Thing. Select the Services tab. Click the ListHotLineParts link.   If you scroll to the bottom of the page, you will see the Execute window. Enter a value for the TemperatureThreshold and click Execute.     After Development   Open the LineCheckSystem Thing. Select the Services tab. Click the ListHotLineParts Execute play button.   Enter a value for the TemperatureThreshold and click Execute.       Saving Test Cases   Store input parameters makes testing during development and after development much faster. Whether you are testing base cases, specific scenarios, or throwing everything you possibly can at your Service, this tab will allow you to store and name test cases for later usage. During Development   Open the LineCheckSystem Thing. Select the Services tab. Click the ListHotLineParts link   If you scroll to the bottom of the page, you will see the Execute window. Enter a value for the TemperatureThreshold and click Save Input Set. When prompted, enter a name for this test case and click Save Input Set.   After Development   Open the LineCheckSystem Thing. Select the Services tab. Click the ListHotLineParts Execute play button.   Enter a value for the TemperatureThreshold and click Save Input Set.   When prompted, enter a name for this test case and click Save Input Set.   While this example is pretty simple and straightforward, it is also possible to store other values and other data types! You will be provided with a dropdown of your stored test cases. Just select a case and click Execute.     Step 4: Utilize Code Auto-Complete Feature   If it is not open already, open the ListHotLineParts Service or create a new one. On a new line, enter ThingTemplates["LinePartTemplate"]. Add a period . after the closing bracket to gain access to the Services and Properties of the Thing Template we created earlier.     You will now see the Services and Properties that were created inside of the LinePartTemplate or passed down in its object-oriented model.     Step 5: Test Code at Design Time with Linting   Linting is a process by which your development environment warns you of possible issues even before any attempt to run or test the code. Instead, an in-editor warning pops up that alerts you to the issue as you’re writing your code. Linting is yet another feature which many IDEs provide outside of the IoT realm.   Select the Lint checkbox at the top of the Service-editing section.   Type any statement that would cause a Lint warning or error to pop up. In this case, it is best programming practice to use a semi-colons at the end of JavaScript code.   Debugging   Services within the composer are based on the Rhino JavaScript engine, which is built using Java.   It is currently unavailable to see the JavaScript code running within the browser, but you are able to still log what is occurring at each step of development and runtime. ThingWorx provides logging that will go to the ScriptLog under the Monitor section on the left. The logger uses different log levels that will appear differently in the ScriptLog screen.   Level Syntax Example info logger.info logger.info("X + 1 = " + 5); trace logger.trace logger.trace("Print this InfoTable - " + table.toJSON()); warning logger.warn logger.warn("Print random JSON data - " + JSON.stringify(data)); debug logger.debug logger.debug("Adding debug information here."); error logger.error logger.error("What kind of error took place? " + err.message); Testing Tips   From the Lint website, here are some common mistakes that JavaScript Lint looks for: Missing semicolons at the end of a line. Curly braces without an if, for, while, etc. Code that is never run because of a return, throw, continue, or break. Case statements in a switch that do not have a break statement. Leading and trailing decimal points on a number. A leading zero that turns a number into octal (base 8). Comments within comments. Ambiguity whether two adjacent lines are part of the same statement. Statements that don't do anything. JavaScript Lint also looks for the following less common mistakes: Regular expressions that are not preceded by a left parenthesis, assignment, colon, or comma. Statements that are separated by commas instead of semicolons. Use of increment (++) and decrement (--) except for simple statements such as "i++;" or "--i;". Use of the void type. Successive plus (e.g. x+++y) or minus (e.g. x---y) signs. Use of labeled for and while loops. if, for, while, etc. without curly braces. (This check is disabled by default.)     Step 6: Next Steps    Congratulations! You've successfully completed the Application Development Tools, Tips & Tricks, and learned 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   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Build Create Custom Business Logic Guide 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 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 13: C - Support Other Platforms   If you are using a platform that is different than the options provided in the CMake configurations or in the C SDK configurations, you can add your own computer type.   CMake has its own custom toolchain support that enables you to add your computer to the CMake configurations.   Go to the CMake Toolchain. NOTE: The C SDK provides a CMakeList.txt file that contains the setup instructions for the C SDK. Make changes only if you have verified the configurations and compiler information. Create a CMakeList.txt file based on your OS inside the folder in which you would like to setup your application. Modify the Platform Configuration section of the CMakeList.txt file to add your personal computer architecture if it is not already listed. Ensure your configurations are in your application's CMakeList.txt file.   An example of the Platform Configuration section is shown below. if (PLATFORM) if (${PLATFORM} MATCHES "linux-arm") set(OS "linux") set(ARCHITECTURE "arm") set(CMAKE_C_COMPILER ${CMAKE_CURRENT_SOURCE_DIR}/../TOOLS/gcc-linux-arm-cross/bin/arm-angstrom-linux-gnueabi-gcc) set(CMAKE_FIND_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../TOOLS/gcc-linux-arm-cross ${CMAKE_CURRENT_SOURCE_DIR}/../TOOLS/gcc-linux-arm-cross/arm-angstrom-linux-gnueabi) # Set LD_LIBRARY_PATH set(Env{LD_LIBRARY_PATH} "${CMAKE_FIND_ROOT_PATH}/lib/gcc") else () if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") set(OS "linux") if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "x86_64" OR ${CMAKE_SYSTEM_PROCESSOR} MATCHES "AMD64") set(ARCHITECTURE "x86_64") set(PLATFORM "linux-x86-64") elseif (${CMAKE_SYSTEM_PROCESSOR} MATCHES "x86_32" OR ${CMAKE_SYSTEM_PROCESSOR} MATCHES "i[36]86") set(ARCHITECTURE "x86_32") set(PLATFORM "linux-x86-32") elseif (${CMAKE_SYSTEM_PROCESSOR} MATCHES "armv5tejl") set(ARCHITECTURE "arm") set(PLATFORM "linux-arm") elseif (${CMAKE_SYSTEM_PROCESSOR} MATCHES "armv[67]l") set(ARCHITECTURE "arm-hwfpu") set(PLATFORM "linux-arm-hwfpu") else () # default to linux-x86_64 set(ARCHITECTURE "x86_64") set(PLATFORM "linux-x86-64") endif() endif ()   An example of how to work with your OS in your application's CMakeList.txt file is shown below: add_executable (SteamSensor src/main.c src/SteamThing.c) target_link_libraries (SteamSensor LINK_PUBLIC twCSdk) if (${OS} MATCHES "windows") add_custom_command(TARGET SteamSensor POST_BUILD COMMAND cmake -E copy_if_different "${CMAKE_BINARY_DIR}/$<CONFIGURATION>/twCSdk.dll" "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>/twCSdk.dll" COMMENT "Copying C SDK dll to example directory.") if (${TLS_LIB} MATCHES "openssl") # Copy over openssl dll files add_custom_command(TARGET SteamSensor POST_BUILD COMMAND cmake -E copy_if_different "${OPENSSL_SSLEAY_BIN_PATH}" "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>/ssleay32.dll" COMMENT "Copying ssleay dll to example directory.") add_custom_command(TARGET SteamSensor POST_BUILD COMMAND cmake -E copy_if_different "${OPENSSL_LIBEAY_BIN_PATH}" "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>/libeay32.dll" COMMENT "Copying ssleay dll to example directory.") endif () endif () if (${OS} MATCHES "linux") if (${TLS_LIB} MATCHES "openssl") # Copy over openssl libraries. add_custom_command(TARGET SteamSensor POST_BUILD COMMAND cmake -E copy_if_different "${OPENSSL_LIB_DIR}/libcrypto.so.1.0.0" "${CMAKE_CURRENT_BINARY_DIR}" COMMAND cmake -E copy_if_different "${OPENSSL_LIB_DIR}/libssl.so.1.0.0" "${CMAKE_CURRENT_BINARY_DIR}" COMMENT "Copying openssl to test directory.") endif () endif () if (${OS} MATCHES "macos") if (${TLS_LIB} MATCHES "openssl") # Copy over openssl libraries. add_custom_command(TARGET SteamSensor POST_BUILD COMMAND cmake -E copy_if_different "${OPENSSL_LIB_DIR}/libcrypto.1.0.0.dylib" "${CMAKE_CURRENT_BINARY_DIR}" COMMAND cmake -E copy_if_different "${OPENSSL_LIB_DIR}/libssl.1.0.0.dylib" "${CMAKE_CURRENT_BINARY_DIR}" COMMENT "Copying openssl to test directory.") endif () endif()     Step 14: Next Steps   Congratulations! You've successfully completed the SDK Reference Guide.   This guide is designed to be used as a reference when developing your application with one of the ThingWorx SDKs.   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Build Design Your Data Model   Additional Resources   If you have questions, issues, or need additional information, refer to: Resource Link   Community Developer Community Forum   Support C SDK Help Center Java SDK Help Center
View full tip
Learn how to create a web application to monitor and control an Allen-Bradley PLC.   GUIDE CONCEPT   This guide will create a ThingWorx Foundation Mashup GUI to monitor and control an Allen-Bradley PLC connected via ThingWorx Kepware Server.   YOU'LL LEARN HOW TO   Create a Mashup Add Widgets Access backend data via Mashup Data Services Tie data to Widgets Create a simple web application that monitors and controls a PLC   NOTE:  The estimated time to complete all parts of this guide is 30 minutes.     Step 1: Learning Path Overview   Assuming you are using this guide as part of the Rockwell Automation Learning Path, then you have now completed each of the following installations:   Connected Components Workbench ThingWorx Kepware Server ThingWorx Foundation (for Windows)   You've also connected an Allen-Bradely PLC to Connected Components Workbench and then to ThingWorx Kepware Server.   You have propagated that information further from ThingWorx Kepware Server into Foundation.   In this final step, we'll create a simple Mashup to visualize the interface from Foundation to ThingWorx Kepware Server to the PLC.   NOTE: Both Rockwell Automation's Connected Components Workbench and ThingWorx Kepware Server are time-limited trials. If significant time has passed while persuing this Learning Path, you may need to reinitialize them. Consult the Troubleshooting step of this guide for more information.       Step 2: New Mashup   A Mashup is a Graphical User Interface (GUI) to interact with your application.   In this step, you will create a new, blank Mashup. You will later populate it with Widgets (graphical elements) and tie those elements to data.   In the top-left of ThingWorx Composer, click the Browse folder icon. Click VISUALIZATION > Mashups.   Click + New.   Select Responsive, then click OK. A new Mashup tab will open.     In the Name field, enter RWLP_Mashup. If Project is not already set, click the + in the Project text box and select the PTCDefaultProject. At the top, click Save.     Step 3: Add Widgets   Widgets are drag-and-drop, stand-alone, graphical elements which you can add to your Mashup to represent certain pieces of backend data.   In this step, you will add a pair of Checkboxes to represent the PLC functionality.   At the top of the RWLP_Mashup tab, click Design. It may take a few moments for the Mashup Builder interface to load.     Click The Widgets tab, then In the Filter field on the left, enter check. Drag-and-drop a Checkbox widget onto the central Canvas area.   Drag-and-drop a second Checkbox onto the Canvas.   At the top, click Save.     Step 4: Add Data    To have the Checkbox Widgets actually interact with the PLC, you need to bind them to the backend data.   To do so, you will make use of a Mashup Data Service from the previously-created PLCcoils Thing. At the top-right, click the Data tab, then click the + symbol.   In the Add Data pop-up window, enter plc in the Entity Filter search box.   Select the PLCcoils Thing. In the Services Filter search box, search for getprop.   Click the right arrow to select GetProperties. Check the box for Execute on Load under Selected Services. This causes the Service to be automatically executed upon the Mashup being loaded. In the Services Filter search box, search for setprop. Click the right arrow to select SetProperties. Note that you should keep Execute on Load un-checked for this Service, as we do NOT want it to automatically execute on Mashup load.     Click Done, then click the > to expand both GetProperties and SetProperties.   At the top, click Save.     Click here to view Part 2 of this guide.
View full tip
    Step 4: Connect Peripherals and Initial Configuration   Connect Peripherals   Now that we have a working microsdhc flash card with the Raspbian OS, we want to insert it into the Pi, as well as connect our other peripherals and power.   Remove the microsdhc card from the adapter.       With the power supply NOT connected, insert the microsdhc card into the Pi. Note that it may help to turn the Pi over.     With the power supply NOT connected to a wall-socket, connect the power, monitor, USB keyboard, and USB mouse.       Plug-in the power-supply to a wall-socket and wait for the Pi to boot.     Pi Initial Configuration   The Raspbian OS needs some initial configuration to set things such as your location and to connect to a WiFi network.   Click Next on the initial Raspbian start pop-up. Set your Country, Language, TimeZone, Use English language (if applicable), and Use US keyboard (if applicable), then click Next.       Enter and Confirm a new password, then click Next. If applicable, check the This screen shows a black border around the desktop checkbox, and click Next.     Select an appropriate WiFi network, and click Next.   Enter the WiFi password, and click Next.     On the Update Software screen, it is recommended to click Skip. If you have a microsdhc card with 16GB or more, then you may click Next to peform an OS update. Note that this process may be time-intensive... 30+ minutes.     If you performed an OS update, and it has completed with a System is up to date pop-up, click OK.     When the Setup is complete, click Restart. After the reboot, you will be automatically re-logged into Raspbian.       Step 5: Install EMS   Now that the Pi is fully setup, you want to download the Edge MicroServer (EMS) onto the Pi. On the Raspberry Pi, open a web browser and navigate to this guide, then download MED-61060-CD-054_SP10_Microserver-Linux-arm-hwfpu-openssl-5-4-10-1509.zip.   Click the download's options drop-down, and select Show in folder.       Right-click on the .zip file and select Extract Here.       Navigate into the newly-extracted /microserver folder.     The primary executables which enable the EMS functionality are the following: File Name Description wsems An executable file that runs the Edge MicroServer. luascriptresource The Lua utility that is used to run Lua scripts, configure remote things, and integrate with the host system.     Create Additional Directories   New folders may be added to the /microserver directory for various purposes. Some of these will be utilized within this guide, while others may be utilized in future guides using the EMS.   In the /microserver folder, create a /logs directory. Create a /other directory. Create a /staging directory. Create a /tw directory. Create a /updates directory.   Create Test Files   It can also be helpful during testing to have some small files in these folders to further demonstrate connectivity.   As these files were custom-created for the guide, seeing them within ThingWorx Foundation ensures that the connection between Foundation and the EMS is real and current.   In the /tw directory, create a text file named tw_test_01.txt. In the /other directory, create a text file named other_test_01.txt.     Click here to view Part 3 of this guide.
View full tip
    Step 4: Launch IoT Hub Connector   Open a shell or a command prompt window. On a Windows machine, open the command prompt as Administrator. The AZURE_IOT_OPTS environment variable must be set before starting the Azure IoT Hub Connector. Below are sample commands using the default installation directory. On Windows: set AZURE_IOT_OPTS=-Dconfig.file=C:\ThingWorx-Azure-IoT-Connector-<version>\azure-iot-<version>-application\conf\azure-iot.conf -Dlogback.configurationFile=C:\ThingWorx-Azure-IoT-Connector-<version>\azure-iot-<version>-application\conf\logback.xml On Linux: export AZURE_IOT_OPTS="-Dconfig.file=/var/opt/ThingWorx-Azure-IoT-Connector-<version>/azure-iot-<version>-application/conf/azure-iot.conf -Dlogback.configurationFile=/var/opt/ThingWorx-Azure-IoT-Connector-<version>/azure-iot-<version>-application/conf/logback.xml" NOTE: You must run the export command each time you open a shell or command prompt window. Change directories to the bin subdirectory of the Azure IoT Hub Connector installation. Start the Azure IoT Hub Connector with the appropriate command for your operating system. On Windows: azure-iot.bat On Linux: /azureiot   NOTE: On Windows you may have to shorten the installation directory name or move the bin directory closer to the root directory of your system to prevent exceeding the Windows limit on the classpath length. The Connection Server should start with no errors or stack traces displayed. If the program ends, check the following: Java version is 1.8.0, update 92 or greater and is Java(TM) not OpenJDK Open azure-iot.conf and confirm ThingWorx Foundation is set to the correct URL and port. Confirm the platform scheme is ws if http is used to access ThingWorx. Confirm all Azure credentials are correct for your Azure account. In ThingWorx Foundation click the Monitoring tab then click Connection Servers. You should see a server named azure-iot-cxserver-{server-uuid}, where {server-uuid} is a unique identifier that is assigned automatically to the server.     Step 5: Import Device from Azure   With the ThingWorx Azure IoT Connector, you can import into ThingWorx any existing devices that are currently provisioned to the Azure IoT Hub.   Add Device Azure IoT Hub If you have not provisioned any devices to your Azure IoT Hub you can learn more about Azure IoT Hub device identity before following the steps below to create a test device. In your Azure Portal, click All Resources, then select the name of your IoT Hub. Under Explorers click IoT devices, then click + Add. Enter a name for your device, then click Save When the device name appears in the list it is ready to us     Import Device into ThingWorx We will manually execute a service in ThingWorx that will import Azure IoT Hub devices into ThingWorx. In ThingWorx Composer, navigate to the ConnectionServicesHub Thing. Click Services tab and scroll to the ImportAzureIotDevices service and click the execute Arrow.   NOTE: The * in the pattern field will act as a wildcard and import all devices, you can enter a string to match that will only import a subset of all available devices.     Click Execute to import the devices then click Done. Click Things in the left column to see the Things that were created.     Step 6: 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 Demo configuration azure-edge-device { // Name of the remote thing on the ThingWorx platform, which should match the Azure Device ID deviceId = "alstestedgething" // Name of the hub host in Azure iotHubHostname = "alsiot.azure-devices.net" // Policy name used by this thing (could require services as well in future) registryPolicyName = "registryReadWrite" // The Key related to the policy above 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 7: 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: 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 4: Add Data   We've added a Waterfall Chart Widget to the Mashup, but we still need to bring in backend data.   Ensure the top-right Data tab is active.   Click the green + button.   In the Entity field, search for and select TPWC_Thing. In the Services field, type getprop. Click the right arrow beside GetProperties. On the right, check Execute on Load.   In the bottom-right of the pop-up, click Done.   Under the Data tab on the right, expand GetProperties.   Drag-and-drop Things_TPWC_Thing > GetProperties > InfoTable_Property onto the Waterfall Chart.   On the Select Binding Target pop-up, click Data.     Widget Properties   With the Waterfall Chart bound to data, we now just need to configure a few of the chart's Properties. With the Waterfall Chart selected in the central Canvas area, ensure the Properties tab is active in the bottom-left.   In the Filter field, type xaxis.   In the XAxisField, search for and select month.   In the Filter field, clear the xaxis search and then start a new filter with usetrend.   Check the UseTrendColors box.   At the top, click Save.     Step 5: View Mashup   Up to this point, we've created a Data Shape to format the columns of an Info Table Property. You then created a Thing, as well as an Info Table Property formatted by the Data Shape. As a test, you added some manually-entered data to the Info Table. After creating a Mashup, you added a Waterfall Chart Widget and tied it to that backend data.   The only thing left to do is to visualize your GUI.    Ensure that you're on the Design tab of the TPWC_Mashup.   At the top, click View Mashup. The end result is a visualization of burn up/down as the project is first defined and then implemented.     Step 6: Next Steps   Congratulations! You've successfully completed the Track Progress with Waterfall Chart guide, and learned 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  Learn More   We recommend the following resources to continue your learning experience: Capability Guide Manage How to Display Data in Charts Additional Resources   If you have questions, issues, or need additional information, refer to: Resource Link Community Developer Community Forum Support Waterfall Chart Help  
View full tip
Announcements