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

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

IoT Tips

Sort by:
  Step 5: Widget Properties   You can configure Properties to change the style of the map as well as specify a custom image to use for map markers. Other Properties allow two linear paths and polynomial regions to also be displayed on the map Widget with optional tooltip data.   Bindable   Name Type  Default Direction  Description Data Infotable None Input Source for the data that is displayed as discrete markers LocationField MenuName None Input Field that contains Location type data to plot markers MarkerField MenuName None Input Field that contains data of type Image used to plot markers ShowMarkerTooltip Boolean True Input Hovering over map markers will display a tooltip when set to true ToolTipField1 thru 4 MenuName None Input Optional field displayed in tooltip when the user hovers over a map marker ToolTipLabel1 thru 4 String None Input Optional label for tooltip data RouteData Infotable None Input Source for the data that is displayed as a connected route RouteLocationField MenuName None Input Field that contains Location type data to plot connected route line ShowRoute Boolean False Input Show route data on map when set to true PlannedRouteData Infotable None Input Source for the data that is displayed as a second connected route PlannedRouteLocationField MenuName None Input Field that contains Location type data to plot a second connected route line ShowPlannedRoute Boolean False Input Show planned route data on map when set to true RegionData Infotable None Input Source for the data that is displayed as a region RegionLocationData Infotable None Input Region location data source RegionLocationsField MenuName None Input Field which will provide location table information for region RegionLayerField MenuName None Input Field that contains Numeric data used for region layer number ShowRegions Boolean False Input Show region data on map when set to true ShowRegionTooltips Boolean True Input Hovering over region will display a tooltip when set to true RegionToolTipField1 thru 4 MenuName None Input Optional field displayed in tooltip when the user hovers over a region RegionToolTipLael1 thru 4 String None Input Optional label for region tooltip data RegionFillOpacity Number 1 Input Opacity of region fill color from 0 being transparent to 1 being opaque SelectedLocation Location None Input/Output The currently selected location CurrentZoom Number 8 Output The currently displayed zoom level ( 1 - 15 ) Zoom Number 8 Input Number used to set the zoom level ( 1 - 15 ) ShowMarkers Boolean True Input Shows map markers if set to true ShowPathMarkers Boolean True Input Shows map markers if set to true ShowTraffic Boolean False Input Shows traffic data color overlay on map if set to true NEBoundary Location None Output The northeast boundary location NWBoundary Location None Output The northwest boundary location SEBoundary Location None Output The southeast boundary location NWBoundary Location None Output The southwest boundary location Visible Boolean True Input Widget is visible if set to true     Static   Name Type  Default Description DisplayName String None Name used for widget in user facing interactions Description String None Description used for widget in user facing interactions MapType Roads/Satellite/Hybrid/Terrain Roads The type of map content displayed MapSkin Normal/Blue/Grey Normal Options for styling maps monochromatically AutoZoomBehavior Data change/Initial Data only Data Change Controls when map will automatically zoom to show all markers ClusterLocations Boolean False Combines multiple location markers that are near one another into a single marker if true MultiSelect Boolean False Enable multiple marker selection   Widget Events   DoubleClicked- Triggered when user double clicks on the Google Map. Changed- Triggered when the data for this widget is modified. BoundsChanged- Triggered when the bounding box of the displayed map changes.     Step 6: Next Steps   If you have questions, issues, or need additional information, refer to:   Resource     Link Community Developer Community Forum Support Google Map Widget Help Center Free Google Maps Widget Extension IQNOX  
View full tip
  Create Your Application Guide UI Part 3    Step 5: Add Widgets to Mashup    At this point, you should have an understanding of how the Widgets in your Mashup relate to the data from devices you've connected via the ThingWorx platform.   Scenario   Now, let's try to imagine a real-world scenario. For this example, assume that you are in a company developing an IoT application utilizing ThingWorx Foundation.   Developer Role Responsibility Edge Developers Utilize the Edge MicroServer, Software Development Kits, or ThingWorx Kepware Server to connect devices and bring data into the platform. Backend Developers Created Things, Thing Templates, and Thing Shapes to store and manipulate the data within ThingWorx Foundation. Frontend Developer Tasked with taking the IoT data and creating an interface with which your users can interact to gain insight from the data. In this scenario, you are the Frontend Developer. The Thing you imported previously represents those Edge and Backend Developers’ work. The data is all there. Specifically, let's assume that this Data Model represents a factory inventory system. You want to quickly build a GUI that is a Minimum Viable Product (MVP) to display the current counts of various products in your warehouse, while also allowing you to manually edit those counts if you receive a report that an IoT scanner in the warehouse has malfunctioned. Since this is a real factory, inventory is constantly increasing and decreasing as manufactured parts are completed or shipping orders are fulfilled. In this lesson, we'll simulate these changes by a 10-second-timer which will increment the counts until a shipping order has been fulfilled (100 total parts), at which point the current inventory count for that part will be reset.   Create the Mashup   Follow the subsequent steps to create an MVP GUI for the example scenario: Click Browse > VISUALIZATION > Mashups > + New. Keep the default of Responsive (with NO Responsive Templates chosen), and click OK in the pop-up window. In the Name field, enter MBQSMashup.   If the Project field is not already set, search for and select PTCDefaultProject.  At the top, click Save. At the top, click Design. On the left, click the Left Arrow to slide-back the navigation pane, leaving more room for the Mashup Builder. At the topleft on the Layout tab, for Positioning, check the radio-button for Static.   Add Labels   Follow the subsequent steps to add Labels that clarify GUI sections of the application. Select the Widgets tab, then drag-and-drop three Label Widgets onto the central Canvas.   With the top Label Widget selected (by clicking on it), change the DisplayName to label-gears-count and hit the Tab key on your keyboard to lock in the modification. NOTE: You can find the DisplayName and all other Widget Properties in the bottom-left of the Mashup Builder. Changing the Widget DisplayNames to recognizable values is highly recommended, as it assists with your logic inspection in the bottom-center Connections window.        3. With the newly-named label-gears-count still selected, type Gears Count in the LabelText field and hit the Tab key.       4. Click on the middle Label; then, in the bottom-left Widget Properties panel, change the DisplayName to label-pistons-count and LabelText to Pistons Count.       5. Similarly, change the bottom Label's DisplayName to label-wheels-count and LabelText to Wheels Count.       6. Click Save.   Add TextBoxes   Follow the subsequent steps to display some information on the various part-counts in our inventory. Drag-and-drop three Text Field Widgets onto the central Canvas.   With the top Text Field Widget selected, change the DisplayName to textfield-gears-count and hit the Tab key.   Change the middle Text Field's DisplayName to textfield-pistons-count, and hit the Tab key. Change the bottom Text Field's DisplayName to textfield-wheels-count, and hit the Tab key. Click Save.   Add Checkboxes   We want to display that inventory counts have been manually set when something went wrong, rather than have someone assume that the information is current and coming from an IoT sensor. This also allows us to flag any sensors that are experiencing issues. Follow the subsequent steps to create checkboxes. Drag-and-drop three Checkbox Widgets onto the central Canvas.   With the top Checkbox Widget selected, change the DisplayName to checkbox-gears-manual and the Label property to Gears Manually Set. Change the middle Checkbox's DisplayName to checkbox-pistons-manual and Label to Pistons Manually Set. Change the bottom Checkbox's DisplayName to checkbox-wheels-manual and Label to Wheels Manually Set.   Click Save.   Add Buttons   After our manual count has been entered, we need to trigger storing it in the backend. We can do this with a Button Widget. In addition, it would be helpful to be able to update the changing counts in the Textboxes without having to reload the entire Mashup. Follow the subsequent steps to add Buttons. Drag-and-drop two Button Widgets onto the central Canvas.   With the top Button Widget selected, change the DisplayName to button-manual-set, the Label to Manually Set Counts, and click-and-drag the right-side of the Button to expand its size.   With the bottom Button Widget selected, change the DisplayName to button-manual-retrieve, the Label to Manually Retrieve Counts, and click-and-drag the right-side of the Button to expand its size.   Click Save.   Resize the Mashup   Follow the subsequent steps to enable the Mashup to fit on a smartphone screen. Click-and-drag your Widgets around the Mashup such that they look roughly like the pictures shown above. Click-and-drag the right-side of the Mashup, pulling it to the left to reduce the horizontal size. Click-and-drag the bottom of the Mashup, pulling it up to reduce the vertical size.   Click Save.         Click here to view Part 4 of this guide.   
View full tip
Create Your Application Guide UI Part 2    Step 4: Bind Data to Widgets   Mashup Data Services allow you to access IoT data so you can push data to the platform's backend as well as pull data into the Mashup itself. In the table below, we describe some common Mashup Data Services that enable that functionality: Service Name Description GetProperties Pulls in a particular Thing's Properties, as well as the associated current values contained within those Properties. GetProperties has an option to automatically update the Mashup whenever a Property value changes. GetPropertyValues Pulls in a particular Thing's Properties and their associated current values. However, it does so in an All Data grouping, opening the possibility of assigning all Properties to the same Widget. This can be helpful with some Widgets, such as the List Widget. SetProperties Pushes a value from some Widget (Checkbox, TextBox, etc.) into the Property of a Thing. NOTE: Using a combination of a "Get" and "Set" Mashup Service establishes a bidirectional communication between the Mashup and the backend IoT data storage.   Import an Entity   In order to focus on the Mashup Builder in this lesson, we have created a Thing for you to download and import. This Thing has predefined Properties and associated Values which will simplify the demonstration of binding data to Widgets in subsequent steps. Download and unzip the attached MBQS_Entities.zip file. In the bottom-left, click the "up/down arrows" for Import/Export, then Import.   In the Import pop-up window, click Browse.   In the OS's pop-up, navigate-to, select, and open the MBQS_Entities.twx file you downloaded earlier.   Click Import.   Click Close.   Retrieve Data   You now have a Thing called MBQSThing from which you can retrieve data. To demonstrate this, we'll use the GetPropertyValues Service. At the top-right of Mashup Builder, click the Data tab.   Click the + symbol.   In the Add Data pop-up window's Entity filter field, type mbqs.   Select the MBQSThing.   In the Services Filter field, type getprop.   Click the right arrow to select GetPropertyValues. The GetPropertyValues Service for MBQSThing has now been added to the Selected Services section on the right side of the Add Data pop-up window. Check the box for Execute on Load under Selected Services. Checking this box causes the GetPropertyValues Service to execute as soon as the Mashup is loaded. 8. Click Done.        9. At the top, click Save. Note how the GetPropertyValues Service now appears in the top-right under the Data tab.   View Data Connections   In the top-left of the Mashup Builder, click the Explorer tab, select the Mashup itself, and you can see the connections between the Mashup and the Data sources.   Mashup Builder Section Description Data Previously empty, now has a reference to the GetPropertyValues Service of the MBQSThing. GetPropertyValues On the Data tab, click GetPropertyValues. The Connections window in the bottom-center will update. Bindings Shows the logical flow of the Mashup. In this instance, it shows how GetPropertyValues is called from the Event triggered by the Mashup being Loaded in a web browser. This means that all Properties of the MBQSThing will be available to the Mashup as soon as your UI is opened.   Bind Widget to Property   Follow the steps below to place a Widget in the Mashup and bind the Property named Gauge_Value (of MBQSThing) to it. On the left-side of the Mashup Builder, select the Widgets tab. In the Filter Widgets search box, type gauge. Drag-and-drop a Gauge Widget onto the central Canvas area.   On the right-side, expand GetPropertyValues > Returned Data > All Data. There is a clear left arrow pointing away from the Gauge_Value Property. This indicates that this Property is to be used to set the value on something else. If the arrow had been pointing towards the Gauge_Value Property, that would indicate that it was ready to accept an external value. The clear status of the arrow indicates that it has not yet been tied to anything.        5. Drag-and-drop MBQSThing > GetPropertyValues > Returned Data > All Data > Gauge_Value onto the Gauge Widget in the central Canvas area.          6. On the Select Binding Target pop-up, select Data.       7. At the top, click Save.       8. Click View Mashup. You must enable pop-ups in order to view the Mashup in a new tab.   In your new Mashup, notice that the Gauge has been set to the Gauge_Value default value of 25. In a real-world scenario, you would likely utilize an IoT sensor that would report back to the Thing storing the value. When the Mashup loads, that value would be set to the real-world sensor data value. In the next few steps, you will build a GUI using several different Widgets and Services.   Click here to view Part 3 of this guide.  
View full tip
  Maintain cookies and security information by implementing session parameters in your application.   Guide Concept   This project will introduce creating and accessing session data from a User logged into your application. Session data is global session-specific parameters that can be used on the Client and Server side.   Following the steps in this guide, you will be able to access the logged in User's information and their set values.   We will teach you how to access session data, that can later be used to provide Users with unique experiences and a more robust application.   You'll learn how to   Create Session Data Access Stored Session Data   NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete this guide is 30 minutes     Step 1: Completed Example   Download the completed files for this tutorial:  Sessions.xml.   The Sessions.xml file contains a completed example of session parameters. Utilize this file to see a finished example and return to it as a reference if you become stuck during this guide. 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.     In the bottom-left of Composer, click Import/Export.     Click IMPORT.     In the Import pop-up, keep the default values and click Browse. Navigate to the Sessions.xml file you downloaded. Select it and click Open. Click Import in the Import pop-up. Click Close to close the pop-up.       Step 2: Create Session Parameters  Click the Browse folder on the left-hand side. Under System, select Subsystems.     Filter for UserManagementSubsystem and open it in Edit mode.     Select Services. Filter for the AddSessionShape Service.     Click the Play button to open the Execute window. Enter UserLogin (the provided ThingShape) as the name input field. Click Execute.     Click Done.   You've just created your first Session Parameter. These values are used for content held in a cookie for a website or information that might be static for the User or session.   Best Practice: For information that will be static for the entire application and not based on the session, use a database option or a stored value in a Thing.       Step 3: Access Session Parameters   Click the Browse folder on the left-hand side. Under System, select Resources.   Filter for CurrentSessionInfo and open it.   Select Services. Filter for the GetGlobalSessionValues Service.   Click the Play button to open the Execute window. Click Execute. You will notice the result is a list of the properties in the UserLogin ThingShape. Your result might differ from mine.   Click Done.   NOTE: There is a difference between Session parameters and Mashup parameters. Mashups can have input values that will be used for services or content of that Mashup ONLY. Session parameters are based on the user using the application in a session. This data will be accessible throughout the application and last until they have completed their usage. This guide shows how to create Session parameters that are considered global session parameters.     Step 4: Next Steps   Congratulations! You've successfully completed the Create Session Parameters guide, and learned how to: Access a logged-in user's information and their set values Use session data to provide users with unique experiences and a more robust application   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Build Create Custom Business Logic Build Data Model Introduction   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource  Link Community Developer Community Forum Support Session Parameter Help Center  
View full tip
  Step 5: Additional Services   The Trend, Range, and Threshold Services are some of the Services the Statistical Monitoring ThingShape offers. Below is a table of additional included Services.   Links to guides for using services like these to build complete IoT applications are found in the next step.   Calculation Service Name Description Consecutive Points Based On a Range GetNumberOfConsecutivePointsBasedOnARange Calculate the number of points in the largest group of consecutive points meeting the range criteria. Consecutive Points Based On a Threshold GetNumberOfConsecutivePointsBeyondAThreshold Calculate the number of points in the largest group of consecutive points meeting the threshold criteria. Number of Points with Percentage Change Out of Range GetNumberOfPointsWithChangeRateOutOfRange Monitor for how many pairs of consecutive points in a series have a numerical percentage change outside the defined range. If the first value in a pair is 0, the pair is not considered.       Step 6: Next Steps   Congratulations!   In this guide, you've learned how to:   Create a Value Stream Create a Thing with the Statistical Monitoring Thing Shape Modify a Property to record values to the Value Stream Test built-in Services used in Statistical Monitoring   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Build Get Started with ThingWorx for IoT Build Build a Predictive Analytics Model Build Operationalize an Analytics Model   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support Descriptive Analytics Help Center    
View full tip
    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
Announcements