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

Community Tip - Help us improve the PTC Community by taking this short Community Survey! X

IoT Tips

Sort by:
Dive back into the mashup builder and learn about advanced widgets and layout options.   For full-sized viewing, click on the YouTube link in the player controls.   Visit the Online Success Guide to access our Expert Session videos at any time as well as additional information about ThingWorx training and services.
View full tip
This video will provide you with a brief introduction to the New Composer interface, which has been made available in the 7.4 and later releases of the ThingWorx Platform.  For complete details on what functionality is available within this next generation composer interface, and to also see what lies ahead on our road map, please refer to the following post in the ThingWorx Community: NG Composer feature availability
View full tip
Best Practices in Data Preparation for ThingWorx Analytics Data Preparation is an important phase in the process of Data Analysis when using ThingWorx Analytics. Basically, it is getting your Data from being Raw Data that you might have gathered through your Operational system or from your Data warehouse to the kind of Data ready to be analyzed. In this Document we will be using “Talend Data Preparation Free Desktop” as a Tool to illustrate some examples of the Data Preparations process. This tool could be downloaded under the following Link: https://www.talend.com/products/data-preparation (You could also choose to use another tool) We would also use the Beanpro Dataset in our Examples and illustrations. Checking data formats The analysis starts with a raw data file. The user needs to make sure that the data files can be read. Raw data files come in many different shapes and sizes. For example, spreadsheet data is formatted differently than web data or Sensors collected data and so forth. In ThingWorx Analytics the Data Format acceptable are CSV. So the Data retrieved needs to be inputted into that format before it could be uploaded to TWA Data Example (BeanPro dataset used): After that is done the user needs to actually look at what each field contains. For example, a field is listed as a character field could actually contains none character data. Verify data types Verifying the data types for each feature or field in the Dataset used.  All data falls into one of four categories that affect what sort of analytics that could be applied to it: Nominal data is essentially just a name or an identifier. Ordinal data puts records into order from lowest to highest. Interval data represents values where the differences between them are comparable. Ratio data is like interval data except that it also allows for a value of 0. It's important to understand which categories your data falls into before you feed it into ThingWorx Analytics. For example when doing Predictive Analytics TWA would not accept a Nominal Data Field as Goal. The Goal feature data would have to be of a numerical non nominal type so this needs to be confirmed in an early stage.                 Creating a Data Dictionary A data dictionary is a metadata description of the features included in the Dataset when displayed it consists of a table with 3 columns: - The first column represents a label: that is, the name of a feature, or a combination of multiple (up to 3) features which are fields in the used Dataset. It points to “fieldname” in the configuration json file. - The second column is the Datatype value attached to the label. (Integer, String, Datetime…). It points to “dataType” in the configuration json file. - The third column is a description of the Feature related to the label used in the first column. It points to “description” in the configuration json file. In the context of TWA this Metadata is represented by a Data configuration “json” file that would be uploaded before even uploading the Dataset itself. Sample of BeanPro dataset configuration file below: Verify data accuracy Once it is confirmed that the data is formatted the way that is acceptable by TWA, the user still need to make sure it's accurate and that it makes sense. This step requires some knowledge of the subject area that the Dataset is related to. There isn't really a cut-and-dried approach to verifying data accuracy. The basic idea is to formulate some properties that you think the data should exhibit and test the data to see if those properties hold. Are stock prices always positive? Do all the product codes match the list of valid ones? Essentially, you're trying to figure out whether the data really is what you've been told it is. Identifying outliers Outliers are data points that are distant from the rest of the distribution. They are either very large or very small values compared with the rest of the dataset. Outliers are problematic because they can seriously compromise the Training Models that TWA generates. A single outlier can have a huge impact on the value of the mean. Because the mean is supposed to represent the center of the data, in a sense, this one outlier renders the mean useless. When faced with outliers, the most common strategy is to delete them. Example of the effect of an Outlier in the Feature “AVG Technician Tenure” in BeanPro Dataset:   Dataset with No Outlier: Dataset with Outlier: Deal with missing values Missing values are one of the most common (and annoying) data problems you will encounter. In TWA dealing with the Null values is done by one of the below methods: - Dropping records with missing values from your Dataset. The problem with this is that missing values are frequently not just random little data glitches so this would consider as the last option. - Replacing the NULL values with average values of the responses from the other records of the same field to fill in the missing value Transforming the Dataset - Selecting only certain columns to load which would be relevant to records where salary is not present (salary = null). - Translating coded values: (e.g., if the source system codes male as "1" and female as "2", but the warehouse codes male as "M" and female as "F") - Deriving a new calculated value: (e.g., sale_amount = qty * unit_price) - Transposing or pivoting (turning multiple columns into multiple rows or vice versa) - Splitting a column into multiple columns (e.g., converting a comma-separated list, specified as a string in one column, into individual values in different columns) Please note that: Issue with Talend should be reported to the Talend Team Data preparation is outside the scope of PTC Technical Support so please use this article as an advisable Best Practices document
View full tip
    Build a remote monitoring application with our developer toolkit for real-time insight into a simulated SMT assembly line.   Guide Concept   This project will introduce methods to creating your IoT application with the ability to analyze real time information as the goal. Following the steps in this guide, you will create an IoT application with the ThingWorx Java SDK that is based on the functionality of an SMT assembly line. We will teach you how to use the ThingWorx Java SDK, ThingWorx Composer, and the ThingWorx Mashup Builder to connect and build a fully functional IoT application running numerous queues and "moving parts".   You'll learn how to   Use ThingWorx Composer to build an application that uses simulated data Track diagnostics and performance in real-time   NOTE: The estimated time to complete this guide is 60 minutes       Step 1: Completed Example   Download the completed files for this tutorial attached here: ManagementApplication.zip.   In this tutorial, we walk through a real-world scenario for a Raspberry Pi assembly line. The ManagementApplication.zip file provided to you contains a completed example of an SMT application. 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. The download contains the following Java classes that support this scenario:    Name                          Description Motherboard Abstract representation of a Thing inheriting from a MotherboardTemplate AssemblyLine Abstract representation of a Thing inheriting from a SMTAssemblyLineTemplate AssemblyMachine Abstract representation of a Thing inheriting from a AssemblyMachineTemplate   Once you complete the Java environment setup by installing a Java JDK, import the Entities/ThingWorxEntities.xml file into ThingWorx Composer. This file contains various Data Shapes, Mashups, Value Streams, Things, and Thing Templates necessary to support the application. The more important Entities are as follows:    Feature                                                 Entity Type          Description RaspberryPi 1 - 6 Thing Things that inherit from the motherboard template SolderPasteAssemblyMachine Thing A Thing that inherits from the assembly machine template PickPlaceAssemblyMachine Thing A Thing that inherits from the assembly machine template ReflowSolderAssemblyMachine Thing A Thing that inherits from the assembly machine template InspectionAssemblyMachine Thing A Thing that inherits from the assembly machine template RaspberryPiSMTAssemblyLine Thing A Thing that inherits from the assembly line template MotherboardTemplate ThingTemplate A template used for building motherboard devices AssemblyMachineTemplate ThingTemplate A template used to create the various types of SMT assembly machines SMTAssemblyLineTemplate ThingTemplate A template used to represent the entire assembly line and all devices in it Advisor User User created to be used with the Java SDK examples   NOTE: An Application Key is NOT included in the zip file you downloaded. You will need to create your Application Key and assign it to the Advisor user provided in the ThingWorxEntities.xml file, the Administrator (which is not recommended for production applications), or any user you've created. If you do not know how to create one or just need a refresher, visit the Create An Application Key guide, then come back to this guide.       Step 2: Run Application   The Java code provided in the download is pre-configured to run and connect to the entities in the ThingWorxEntities.xml file. Open the Executable/Script in a text editor, and edit the script with your host and port.  Operating System   File Name Mac/Linux Script.sh Windows Script.bat Update the <HOST> and <PORT> arguments to that of your ThingWorx Composer and update the Application Key argument to the one you have created. Use the examples in the file for assistance. NOTE: If you are using the hosted trial server, follow the HTTPS example and use 443 as the port. After updating the script that pertains to your operating system, double-click or run Script.sh (Linux, Mac) or Script.bat (Windows) to run the Java program. In your browser, proceed to the following URL (replace the host field with your ThingWorx Composer host) in order to see the application work:   <host>/Thingworx/Runtime/index.html#master=AssemblyLineMaster&mashup=RaspberryPiAssemblyLine   You can also open the RaspberryPiAssemblyLine Mashup in the Composer and click View Mashup.   You should be able to see rows of assembly machines with buttons. Click the Start button to start the assembly line. Click the Add Board button to add Raspberry Pi motherboards.   NOTE: The screen will not update and properties cannot be changed until the Java backend starts running. Ensure the connection is made before attempting to start the assembly line.   Functional Breakdown   At runtime, the Mashup executes the following functions:                Mashup Component        Function 1  Assembly Machines Selecting an assembly machine will provide you with information on the diagnostic status of that assembly machine and access to charts highlighting its performance. 2  Start Button Start up the assembly line and all assembly machines. 3  Shutdown Button Stop the assembly line and shutdown all assembly machines. Queues will not be purged. 4  Motherboard Add Dropdown A dropdown that shows the available motherboards that can be added to the assembly line. 5  Add Boards Button If a MotherboardTemplate Entity is selected in the Motherboard Add dropdown, that Raspberry Pi will be added to the assembly line. If no Motherboard is selected, this will add a new Raspberry Pi Thing to the assembly line. 6  Motherboard Image Show all motherboards currently inside the assembly line queue of Raspberry Pi. 7  Motherboard Pick Up Dropdown A dropdown that shows the motherboards in the assembly line that are not in a Complete Stage. 8  Add Pick Up Button If a MotherboardTemplate entity is selected in the Motherboard Pick Up dropdown, that Raspberry Pi will be removed from the assembly line and no longer be available. This can be done if a Raspberry Pi is slowing down the other queues. 9  Box Image Show all motherboards currently in the Complete Stage.         Step 3: Services and Java Implementation   JavaScript using ThingWorx Services   To support and run the application quickly, ThingWorx Services are utilized as much as possible. This ensures the speed and quality of the application are maintained while also ensuring code changes can be made quickly.   Opening and Starting Up   Open the RaspberryPiAssemblyLine Mashup by going to the URL provided in the last section. The machines will all be in a shut-down (RED) state. This is ensured by a call to the Shutdown service within the SMTAssemblyLineTemplate ThingTemplate. This method begins the process of resetting the Motherboards to their default states and AssemblyMachines to a shutdown state.   Click the Start button to call the StartUp Service. This call will notify the Java Code to turn the simulated machines on and begin waiting for any motherboards to be added to the queue.   INFO: The StartUp and Shutdown services call other services, some of which can be overrided. If you would like to make a change to the implementation, make the change in an implementation of the SMTAssemblyLineTemplate ThingTemplate. You can use RaspberryPiSMTAssemblyLine as an example.   New Raspberry Pi Names   The CommonServices Entity provides services that can be reused by other entities easily. The GenerateRandomThingName service is utilized to create a psuedo-random name for a new Motherboard. You can use this service to create names - names may start with “Raspberry,” but not necessarily - they are based on how you set the parameters.   Creating and Adding Boards   Select the Add Board button to make a call to the AddBoard service of the SMTAssemblyLineTemplate ThingTemplate. This service will call the CommonServices Thing to create a new name for the Motherboard, then begin the process of creating, enabling, and adding that Motherboard to the simulated devices in the Java code.   Pickup Boards   Select the Pickup Board button to make a call to the PickUpMotherboard service of the SMTAssemblyLineTemplate ThingTemplate. This service will remove a Motherboard from the assembly line, update the status to having been picked up, and ensure the simulated devices are updated with this new information.   Queue Processing   Add a Motherboard to the available queue of a machine when the Motherboard is ready to be worked on that machine. A machine will NOT know information about a Motherboard until that motherboard is ready for that stage of processing.   The Motherboard is then added to the internal queue of the machine based on the size of the internal queue of that machine. Being in the internal queue of a machine does not mean it is being worked on. The Motherboard is ONLY being worked on when the machine has added the Motherboard to it’s working queue. The size of the working queue is based on the machine’s placement heads. You can play with these values to increase or descrease queue performance.   INFO: The heads, speeds, and queue sizes of the machines are created in the RaspberryPiSMTAssemblyLine Thing. To change these configurations, update the AddStartingMachines service with new values or new machines.   Java Implementation using ThingWorx Java SDK   The Java code we created for the Assembly Line scenario creates a connection to the ThingWorx Composer as any ThingWorx SDK utility would. This code is used to allow extended functionality for the application, and mimics the behavior of devices or machines connected to the ThingWorx Composer.   Motherboard Class   The Motherboard Class contains several methods to ensure the location of the motherboard is known at all times. It also updates the status level from 0 to 100 as the motherboard is being assembled.   AssemblyMachine Class   The fields in the AssemblyMachine class ensure that the queues handled by the machine are working correctly. When an AssemblyMachine is created, it will load both the available queue and the internal queue if the machine will be the first stage in the assembly line (Soldering). If not a solder machine, the queues will be empty, as no device is pending its task. If the machine is on, it will continue to work based on its current status of the motherboards in its queue. When a machine is turned on or the current task is complete, the AssemblyMachine will re-evaluate the queues to optimize timing and decrease idle time.   Challenge: Find a way to improve the timing of the queue and reduce the idle time even more. Think of a problem an assembly line might have when machines are waiting on a prior machine to complete a task.   SMTAssemblyLine Class   The SMTAssemblyLine class handles the overall process and controls how motherboards are handled when entering and exiting the assembly line. There are also listeners to start up the assembly machines.   When a board is added to the queue of the assembly line, it will instantly be added to the available queue for a solder machine to begin processing. This is the only machine that will have immediate access to the motherboard. When a board is picked up from the assembly line queue, the status of the board is set to “PICKED UP”. That motherboard will be available later for processing by the assembly line.     Click here to view Part 2 of this guide.  
View full tip
This expert session goes over some basic backup and recovery principles, and provides details on how these principles can be applied to backing up a ThingWorx Server. Backup methods for the ThingWorx PostgreSQL, Neo4J and H2 releases are discussed.     For full-sized viewing, click on the YouTube link in the player controls.   Visit the Online Success Guide to access our Expert Session videos at any time as well as additional information about ThingWorx training and services.
View full tip
Video Author:                     Stefan Taka Original Post Date:            July 14, 2017 Applicable Releases:        ThingWorx 7.4   Description: This video will provide you with a brief introduction to the New Composer Interface, which has been made available in the 7.4 and later releases of the ThingWorx Platform.  For complete details on what functionality is available within this next generation composer interface, and to also see what lies ahead on our road map, please refer to the following post in the Community.   NG Composer feature availability  
View full tip
A Feature - a piece of information that is potentially useful for prediction. Any attribute could be a feature, as long as it is useful to the model. Feature engineering – Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data. It’s a vaguely agreed space of tasks related to designing feature sets for Machine Learning applications. Components: First, understanding the properties of the task you’re trying to solve and how they might interact with the strengths and limitations of the model you are going to use. Second, experimental work were you test your expectations and find out what actually works and what doesn’t. Feature engineering as a technique, has three sub categories of techniques: Feature selection, Dimension reduction and Feature generation. Feature Selection: Sometimes called feature ranking or feature importance, this is the process of ranking the attributes by their value to predictive ability of a model. Algorithms such as decision trees automatically rank the attributes in the data set. The top few nodes in a decision tree are considered the most important features from a predictive stand point. As a part of a process, feature selection using entropy based methods like decision trees can be employed to filter out less valuable attributes before feeding the reduced dataset to another modeling algorithm. Regression type models usually employ methods such as forward selection or backward elimination to select the final set of attributes for a model. For example: Project Development decision-tree:                                                  Dimension Reduction: This is sometimes called feature extraction. The most classic example of dimension reduction is principle component analysis or PCA. PCA allows us to combine existing attributes into a new data frame consisting of a much reduced number of attributes by utilizing the variance in the data. The attributes which "explain" the highest amount of variance in the data form the first few principal components and we can ignore the rest of the attributes if data dimensionality is a problem from a computational standpoint. Feature Generation or Feature Construction: Quite simply, this is the process of manually constructing new attributes from raw data. It involves intelligently combining or splitting existing raw attributes into new one which have a higher predictive power. For example a date stamp may be used to generate 2 new attributes such as AM and PM which may be useful in discriminating whether day or night has a higher propensity to influence the response variable. Feature construction is essentially a data transformation process. Tips for Better Feature Engineering Tip 1: Think about inputs you can create by rolling up existing data fields to a higher/broader level or category. As an example, a person’s title can be categorized into strategic or tactical. Those with titles of “VP” and above can be coded as strategic. Those with titles “Director” and below become tactical. Strategic contacts are those that make high-level budgeting and strategic decisions for a company. Tactical are those in the trenches doing day-to-day work.  Other roll-up examples include: Collating several industries into a higher-level industry: Collate oil and gas companies with utility companies, for instance, and call it the energy industry, or fold high tech and telecommunications industries into a single area called “technology.” Defining “large” companies as those that make $1 billion or more and “small” companies as those that make less than $1 billion.   Tip 2: Think about ways to drill down into more detail in a single field. As an example, a contact within a company may respond to marketing campaigns, and you may have information about his or her number of responses. Drilling down, we can ask how many of these responses occurred in the past two weeks, one to three months, or more than six months in the past. This creates three additional binary (yes=1/no=0) data fields for a model. Other drill-down examples include: Cadence: Number of days between consecutive marketing responses by a contact: 1–7, 8–14, 15–21, 21+ Multiple responses on same day flag (multiple responses = 1, otherwise =0) Tip 3: Split data into separate categories also called bins. For example, annual revenue for companies in your database may range from $50 million (M) to over $1 billion (B). Split the revenue into sequential bins: $50–$200M, $201–$500M, $501M–$1B, and $1B+. Whenever a company falls with the revenue bin it receives a one; otherwise the value is zero. There are now four new data fields created from the annual revenue field. Other examples are: Number of marketing responses by contact: 1–5, 6–10, 10+ Number of employees in company: 1–100, 101–500, 502–1,000, 1,001–5,000, 5,000+ Tip 4: Think about ways to combine existing data fields into new ones. As an example, you may want to create a flag (0/1) that identifies whether someone is a VP or higher and has more than 10 years of experience. Other examples of combining fields include: Title of director or below and in a company with less than 500 employees Public company and located in the Midwestern United States You can even multiply, divide, add, or subtract one data field by another to create a new input. Tip 5: Don’t reinvent the wheel – use variables that others have already fashioned. Tip 6: Think about the problem at hand and be creative. Don’t worry about creating too many variables at first, just let the brainstorming flow.
View full tip
Validator widgets provide an easy way to evaluate simple expressions and allow users to see different outcomes in a Mashup. Using a validator is fairly intuitive for simple expressions, such as is my field blank? But if we need to evaluate a more complex scenario based on multiple parameters, then we can user our validator with a backing service that will perform more complex analytics. To show how services can work in conjunction with a validator widget, let’s consider a slightly more complicated scenario such as: A web form needs to validate that the zip or postal code entered by the user is consistent with the country the user selected. Let’s go through the steps of validating our form: Create a service with two input parameters. Our service will use regex to validate a postal code based on the user’s country.  Here’s some sample code we could use on an example Thing: //Input parameters: Country and PostalCode (strings) //Country-based regular expressions: var reCAD = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/; var reUS = /^\d{5}(-\d{4})?$/; var reUK = /^[A-Za-z]{1,2}[\d]{1,2}([A-Za-z])?\s?[\d][A-Za-z]{2}$/; var search = ""; //Validate based on Country: if (Country==="CAD")                search = reCAD.exec(PostalCode); else if (Country==="US")                search = reUS.exec(PostalCode); else if (Country==="UK")                search = reUK.exec(PostalCode); (search == null) ? result = false: result = true; Set up a simple mashup to collect the parameters and pass them into our service Add a validator widget Configure the validator widget to parse the output of the service. ServiceInvokeComplete on the service should trigger the evaluation and pass the result of the service into a new parameter on the widget called ServiceResult (Boolean). The expression for the evaluator would then be: ServiceResult? true:false Based on the output of the validator, provide a message confirming the postal code is valid or invalid Add a button to activate the service and the validator evaluation Of course, in addition to providing a message we can also use the results of the validator to activate additional services (such as writing the results of the form to the database). For an example you can import into your ThingWorx environment, please see the attached .zip file which contains a sample mashup and a test thing with a validator service.
View full tip
Introduction to Digital Performance Management (DPM) Written by: Tori Firewind, IoT EDC   “Digital Performance Management (DPM) is a closed-loop, problem solving solution that helps manufacturers identify, prioritize, and solve their biggest loss challenges, resulting in reduced cost, increased revenue, and improved service levels.” – DPM Help Center What is DPM? Digital Performance Manager (DPM) is an application which improves factory efficiency across a variety of different areas, namely “the four P’s” of Digital Transformation: products, processes, places, and people. Each performance issue in a factory can be mapped to at least one of these improvement categories in a new strategy for Continuous Improvement (CI) founded by PTC.   Figure 1 – Each performance issue in a factory can be mapped to at least one of 4 fundamental improvement categories: products, processes, places, and people. PTC’s new, industry-leading strategy for continuous improvement (CI) in factories is a “best practice” approach, taking the collective knowledge of many customers to form a focused, prescriptive path for success. 11 Closing the Loop Across Products, Processes, People, and Places, Manufacturing Leadership Journal   At PTC, CI in factories is driven by a “best practice”  approach, with years of experience in manufacturing solutions combining with the collective knowledge of the many diverse use cases PTC has encountered, to generate a focused, prescriptive path for improvement in any individual factory. Figure 2 – DPM is a closed loop for continuous improvement, a strategy built around industry standard best practices and years of experience.  PTC is also defining new industry standards for OEE analysis by using time as a currency within DPM. This standardization technique improves intuitive impact assessment and allows for direct comparison of metrics (see the Help Center for details on how each metric is calculated).   DPM creates a closed loop for CI, from the monitoring phase performed both automatically and through manual operator input, to the prioritization and analyzation phases performed by plant managers. DPM helps plant managers by tracking metrics of factory performance that often go overlooked by other systems. With Analytics, DPM can also do much of the analysis automatically, finding the root causes much more rapidly. Figure 3 – All levels of the company are involved in solving the same problems effectively and efficiently with DPM. Instead of 100 people working on 100 different problems, some of which might not significantly improve OEE anyway, these same 100 people can tackle the top few problems one at a time, knocking out barriers to continuous improvement together. Production supervisors who manage the entire production line then know which less-than-effective components on the line need help. They can quickly design and redesign solutions for specific production issues. Task management within DPM helps both the production manager and the maintenance engineer to complete the improvement process. Using other PTC tools like Creo and Vuforia make the path to improvement even faster and easier, requiring less expert knowledge from the front-line workers and empowering every level of participation in the digital transformation process to make a direct, measurable impact on physical production.       How Does DPM Work? DPM as an IoT application sits on top of the ThingWorx Foundation server, a platform for IoT development that is extensible and customizable. Manufacturers therefore find they rarely have to rip and replace existing systems and assets to reap the benefits of DPM, which gathers, aggregates, and stores production data (both automatically and through manual input on the Production Dashboard), so that it can be analyzed using time as a currency. DPM also manages the process of implementing improvements (using the Action Tracker) based on the collected data, and provides an easy way to confirm that the improvements make a real difference in the overall OEE (through the Performance Analysis Dashboard). Because the analysis occurs before and after the steps to improve are taken, manufacturers can rest assured that any resources invested on the improvements aren’t done so in vain; DPM is a predictive and prescriptive analysis process.   DPM makes use of an external SQL Server to run queries against collected data and perform aggregation and analysis tasks in the background, on a separate server location than the thing model and ingestion database. This ensures that use cases involving real-time alerts and events, high-capacity ingestion, or others are still possible on the ThingWorx Foundation server.   The IoT EDC is focusing in on DPM alone for a series of  technical briefs which provide insight and expert level recommendations regarding DPM usage and configuration.  Stay tuned into the PTC Community for more updates to come.
View full tip
Scripto provides a RESTful endpoint for Groovy Custom Objects on the Axeda Platform.  Custom Objects exposed via Scripto can be accessed via a GET or a POST, and the script will have access to request parameters or body contents. Any Custom Object of the "Action" type will automatically be exposed via Scripto. The URL for a Scripto service is currently defined by the name of the Custom Object: GET: http://{{YourHostName}}/services/v1/rest/Scripto/execute/<customObjectName> Scripto enables the creation of "Domain Specific Services". This allows implementers to take the Axeda Domain Objects (Assets, Models, DataItems, Alarms) and expose them via a service that models the real-world domain directly (trucks, ATMs, MRI Machines, sensor readings). This is especially useful when creating a domain-specific UI, or when integrating with another application that will push or pull data. Authentication There are several ways to test your Scripto scripts, as well as several different authentication methods. The following authentication methods can be used: Request Parameter credentials: ?username=<yourUserName>&password=<yourPassword> Request Parameter sessionId (retrieved from the Auth service): ?sessionid=<sessionId> Basic Authentication (challenge): From a browser or CURL, simply browse to the URL to receive an HTTP Basic challenge. Request Parameters You can access the parameters to the Groovy script via two Objects, Call and Request. Request is actually just a sub-class of Call, so the values will always be the same regardless of which Object you use.  Although parameters may be accessed off of either object, Call is preferable when Chaining Custom Objects (TODO LINK) together.  Call also includes a reference to the logger which can be used to log debug messages. GET:  http://{{YourHostName}}/services/v1/rest/Scripto/execute/<Your Script Name>?sessionid=<Session Id>&serial_number=mySerialNumber Accessing Parameters through the Request Object import com.axeda.drm.sdk.scripto.Request // Request.parameters is a map of strings def serial_number = Request.parameters.serial_number assert serial_number == "mySerialNumber"       Accessing Parameters through the Call Object import com.axeda.drm.sdk.customobject.Call // Call.parameters is a map of strings def serial_number = Call.parameters.serial_number assert serial_number == "mySerialNumber"       Accessing the POST Body through the Request Object The content from a POST request to Scripto is accessible as a string via the body field in the Request object.  Use Slurpers for XML or JSON to parse it into an object. POST:  http://{{YourHostName}}/services/v1/rest/Scripto/execute/<Your Script Name>?sessionid=<Session Id> Response: { "serial_number":"mySerialNumber"} import com.axeda.drm.sdk.scripto.Request def body = Request.body def slurper = new JsonSlurper() def result = slurper.parseText(body) assert result.serial_number == "mySerialNumber"       Returning Plain Text Groovy custom objects must return some content.  The format of that content is flexible and can be returned as plain text, JSON, XML, or even binary files. The follow example simply returns plain text. GET:  http://{{YourHostName}}/services/v1/rest/Scripto/execute/<Your Script Name> // Outputs:  hello return ["Content-Type":"text/plain","Content":"hello"]       Returning JSON We use the JSONObject Class to format our Map-based content into a JSON structure. The eliminates the need for any concern around formatting, you just build up Maps of Maps and it will be properly formatted by the fromObject() utility method. GET:  http://{{YourHostName}}/services/v1/rest/Scripto/execute/<Your Script Name> import net.sf.json.JSONObject root = [   items:[    num_1: “one”,    num_2: “two”            ] ] /** Outputs {   "items": {  "num_1": "one", "num_2": "two"  } } **/ return ['Content-Type': 'application/json', 'Content': JSONObject.fromObject(root).toString(2)]       Link to JSONObject documentation Returning XML To return XML, we use the MarkupBuilder to build the XML response. This allows us to create code that follows the format of the XML that is being generated. GET:  http://{{YourHostName}}/services/v1/rest/Scripto/execute/<Your Script Name>?sessionid=<Session Id> import groovy.xml.MarkupBuilder def writer = new StringWriter() def xml = new MarkupBuilder(writer) xml.root(){     items(){         num_1("one")         num_2("two")     } } /** Outputs <root>   <items>     <num_1>one</num_1>     <num_2>two</num_2>   </items> </root> **/ return ['Content-Type': 'text/xml', 'Content': writer.toString()]       Link to Groovy MarkupBuilder documentation Returning Binary Content To return binary content, you typically will use the fileStore API to upload a file that you can then download using Scripto.  See the fileInfo section to learn more. In this example we connect the InputStream which is associated with the getFileData() method directly to the output of the Scripto script. This will cause the bytes available in the stream to be directly forwarded to the client as the body of the response. GET:  http://{{Your Host Name}}/services/v1/rest/Scripto/execute/{{Your Script Name}}?sessionid={{Session Id}}&fileId=123 import static com.axeda.sdk.v2.dsl.Bridges.* import com.axeda.services.v2.* import com.axeda.sdk.v2.exception.* def contentType = parameters.type ?: 'image/jpg' return ['Content':fileInfoBridge.getFileData(parameters.fileId), 'Content-Type':contentType]   The Auth Service - Authentication via AJAX Groovy scripts are accessible to AJAX-powered HTML apps with Axeda instance credentials.  To obtain a session from an Axeda server, you should make a GET call to the Authentication service. The service is located at the following example URL: https://{{YourHostName}}/services/v1/rest/Auth/login This service accepts a valid username/password combination in the incoming Request parameters and returns a SessionID. The parameter names it expects to see are as follows: Property Name Description principal.username The username for the valid Axeda credential. password The password for the supplied credential. A sample request to the Auth Service: GET: https://{{YourHostName}}/services/v1/rest/Auth/login?principal.username=YOURUSER&password=YOURPASS Would yield this response (at this time the response is always in XML): <ns1:WSSessionInfo xsi:type="ns1:WSSessionInfo" xmlns:ns1="http://type.v1.webservices.sl.axeda.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">   <ns1:created>2013-08-12T13:19:37 +0000</ns1:created>   <ns1:expired>false</ns1:expired>   <ns1:sessionId>19c33190-dded-4655-b2c0-921528f7b873</ns1:sessionId> <ns1:sessionTimeout> 1800 </ns1:sessionTimeout> </ns1:WSSessionInfo>       The response fields are as follows: Field Name Description created The timestamp for the date the session was created expired A boolean indicating whether or not this session is expired (should be false) sessionId The ID of the session which you will use in subsequent requests sessionTimeout The time (in seconds) that this session will remain active for The Auth Service is frequently invoked from JavaScript as part of Custom Applications. The following code demonstrates this style of invocation. function authenticate(host, username, password) {             try {                 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");             } catch (e) {                 // must be IE             }             var xmlHttpReq = false;             var self = this;             // Mozilla/Safari             if (window.XMLHttpRequest) {                 self.xmlHttpReq = new XMLHttpRequest();             }             // IE             else if (window.ActiveXObject) {                 self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");             }             var SERVICES_PATH = "/services/v1/rest/"             var url = host + SERVICES_PATH + "Auth/login?principal.username=" + username + "&password=" + password;             self.xmlHttpReq.open('GET', url, true);             self.xmlHttpReq.onreadystatechange = function() {                 if (self.xmlHttpReq.readyState == 4) {                     getSessionId(self.xmlHttpReq.responseXML);                 }             }             self.xmlHttpReq.send() } function getSessionId(xml) {             var value             if (window.ActiveXObject) {                 // xml traversing with IE                 var objXML = new ActiveXObject("MSXML2.DOMDocument.6.0");                 objXML.async = false;                 var xmldoc = objXML.loadXML(xml);                 objXML.setProperty("SelectionNamespaces", "xmlns:ns1='http://type.v1.webservices.sl.axeda.com'");                 objXML.setProperty("SelectionLanguage","XPath");                 value =  objXML.selectSingleNode("//ns1:sessionId").childNodes[0].nodeValue;             } else {                 // xml traversing in non-IE browsers                 var node = xml.getElementsByTagNameNS("*", "sessionId")                 value = node[0].textContent             }             return value } authenticate ("http://mydomain.axeda.com", "myUsername", "myPassword")       Calling Scripto via AJAX Once you have obtained a session id through authentication via AJAX, you can use that session id in Scripto calls. The following is a utility function which is frequently used to wrap Scripto invocations from a UI. function callScripto(host, scriptName, sessionId, parameter) {             try {                 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");             } catch (e) {                 // must be IE             }             var xmlHttpReq = false;             var self = this;             // Mozilla/Safari             if (window.XMLHttpRequest) {                 self.xmlHttpReq = new XMLHttpRequest();             }             // IE             else if (window.ActiveXObject) {                 self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");             }             var url = host + SERVICES_PATH + "Scripto/execute/" + scriptName + "?sessionid=" + sessionId;             self.xmlHttpReq.open('GET', url, true);             self.xmlHttpReq.onreadystatechange = function() {                 if (self.xmlHttpReq.readyState == 4) {                     updatepage(div, self.xmlHttpReq.responseText);                 }             }             self.xmlHttpReq.send(parameter); } function updatepage(div, str) {             document.getElementById(div).innerHTML = str; } callScripto("http://mydomain.axeda.com", "myGroovyScriptName", "mySessionId", "myparameter=foo")       A more modern jQuery-based example might look like the following: function callScripto(host, scriptName, sessionId, parameter) {     var url = host + '/services/v1/rest/Scripto/execute/' + scriptName + '?sessionid=' + sessionId     if ( parameter != null ) url += '&' + parameter     $.ajax({url: url,               success:  function(response) {  updatepage(div, response); }           }); } function updatepage(div, str) {     $("#" + div).innerHTML = str } callScripto("http://mydomain.axeda.com", "myGroovyScriptName", "mySessionId", "myparameter=foo") In Conclusion As shown above, Scripto offers a number of ways to interact with the platform.  On each version of the Axeda Platform, all supported v1 and v2 APIs are available for Scripto to interact with the Axeda domain objects and implement business logic to solve real-world customer problems. Bibliography ​(PTC.net account required)     Axeda v2 API/Services Developer's Reference Version 6.8.3 August 2015     Axeda® v1 API Developer’s Reference Guide Version 6.8 August 2014     Documentation Map for Axeda® 6.8.2 January 2015
View full tip
Just like the perfect sandwich, we know that you have specific preferences and requirements for your ThingWorx deployment. Whether you like to keep things simple with a classic grilled cheese or you like to spice things up with a more elaborate chipotle mayo BLT, we’ve got you covered. Our ThingWorx Deployment Architecture Guide explains what you’ll need to deploy ThingWorx in three different scenarios: production, enterprise and high-availability (pictured below).   Deployment Architecture for ThingWorx on Azure in High-Availability We’ve recently published Version 1.1 of the ThingWorx Deployment Architecture Guide. In it, you can find updated deployment architecture diagrams to more distinctly show the data and application layers within a ThingWorx environment. Our team has also added a new section on what you’ll need to deploy ThingWorx on Microsoft Azure, PTC’s preferred cloud platform.   Check it out here or in the attachment section on the right.   Stay connected, Kaya
View full tip
Based on Google's Spanner DB; CockroachDB is a distributed SQL DB scaling horizontally; surviving disk, machine, rack & even datacenter failures. It is built to automatically replicate, rebalance & recover with minimal configuration  See What is CockroachDB? for more.   Useful in use cases requiring: Distributed or replicated OLTP Multi-datacenter deployments Multi-region deployments Cloud migrations Cloud-native infrastructure initiatives Note: CockroachDB in current state isn't suitable for heavy analytics / OLAP.   Feature that makes it really attractive As mentioned above, scaling horizontally it requires minimal configuration out of the box allowing quick setup starting from local laptop/machine as shown below it can scale easily to single dedicated server, development/public cloud cluster. Due to easy setup, adding new nodes is as simple as starting the cockroach utility.See CockroachDB FAQ for more. To top it off, it uses PostgreSQL Wire protocol and PostgreSQL's dialect further reducing configuration and special JDBC driver requirements when a ThingWorx is configured with PostgreSQL as persistence provider.   Setting up cockroach DB cluster Download required binary or docker version from Install CockroachDB available for Mac, Linux & Windows   PS :Following setup uses Window's binary on a VM with Win10 64 bit, 6G RAM.     Starting Cluster node Open command prompt and navigate to the directory where cockroach.exe is unzipped, and launching the node with following command prompt     cockroach.exe start --insecure --host=10.128.13.183 --http-port=8082     This will start a node on defined host in insecure mode with its web based DB administration console on port 8082 and DB listening on default port 26257. Note it will log a security warning since node is started in insecure mode due to the tag --insecure, like so     * * WARNING: RUNNING IN INSECURE MODE! * * - Your cluster is open for any client that can access 10.128.13.183. * - Any user, even root, can log in without providing a password. * - Any user, connecting as root, can read or write any data in your cluster. * - There is no network encryption nor authentication, and thus no confidentiality. * * Check out how to secure your cluster: https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html * CockroachDB node starting at 2018-03-16 11:52:57.164925 +0000 UTC (took 2.1s) build: CCL v1.1.6 @ 2018/03/12 18:04:35 (go1.8.3) admin: http://10.128.13.183:8082 sql: postgresql://root@10.128.13.183:26257?application_name=cockroach&sslmode=disable logs: C:\CockroachDb\cockroach116\cockroach-data\cockroach-data\logs store[0]: path=C:\CockroachDb\cockroach116\cockroach-data\cockroach-data status: restarted pre-existing node clusterID: 012d011e-acef-47e2-b280-3efc39f2c6e7 nodeID: 1     Ensure that the secure mode is used when deploying in production.   Starting 2 additional nodes   Starting node2 cockroach.exe start --insecure --store=node2 --host=10.128.13.183 --port=28258 --http-port=8083 --join=10.128.13.183:26257   Starting node 3   cockroach.exe start --insecure --store=node2 --host=10.128.13.183 --port=28259 --http-port=8084 --join=10.128.13.183:26257     Note: Both of these 2 nodes are joining the cluster via 10.128.13.183:26257 (port for the node 1)   Verifying the live cluster and nodes via the web based CockroachDB admin console Open a web browser with any of the above node's http-port e.g. http://10.128.13.183:8084 Click on the View nodes list on the right panel   This will open the nodes list page   Connecting to ThingWorx as external datastore Good news, if your ThingWorx is running with PostgreSQL persistence provider, then no additional JDBC driver needed as CockroachDB uses the PostgreSQL wire protocol additionally, the SQL dialect is that of PostgreSQL For any other persistence provider download and install the PostgreSQL Relational Database Connector from ThingWorx Marketplace.   Creating a database in the cluster Start SQL client connecting to any of the running node, open a command prompt navigate to the directory containing cockroach.exe use following command:   cockroach sql --insecure --port=26257 This will change the prompt to root@<serverName/IP>:26257> Since above command logs in insecure mode no password is needed, default admin username is root in CockroachDb, use following to create a database   create database thingworx; show databases; root@10.128.13.183:26257/> SHOW databases; +--------------------+ | Database | +--------------------+ | crdb_internal | | information_schema | | pg_catalog | | system | | thingworx | | thingworxdatastore | +--------------------+ (6 rows)   This confirms thingworx database is created Creating a user to access that database CREATE USER cockroach WITH PASSWORD 'admin'; This will grant all rights to "cockroach" user on the database thingworx database   grant all on database thingworx to cockroach; Creating a Thing & connecting to CockroachDB via ThingWorx Composer For below example ThingWorx is using PostgreSQL as persistence provider. Create a Thing based of Database Thing Template Use following connection settings:   JDBC Driver Class Name : org.postgresql.Driver JDBC Connection String : jdbc:postgresql://<serverIp/name>:26257/thingworx?sslmode=disable Database User Name : cockroach Database password : <password>   Navigate to the Properties to verify the connectivity   Creating table(s) Now that the Thing is connected to the database, there are following ways DB objects can be created Via Thing based SQL Command Via SQL CockroachDB's SQL client Following command will create a small demo table CREATE TABLE demo ( id INT, demovalue STRING) Use SQLCommand as JavaScript handler when using above statement to create table directly from ThingWorx's Database Thing Verifying the Database & a table created within that DB via the web admin console of CockroachDb Under the left panel click on the Databases from the home page of one of the node's web admin consloe e.g. http://localhost:8084     Apart from other useful information about the database e.g. the database size and total number of tables, etc., clicking on the table name will also show the sql used to create it (including the defaults).   Creating couple of Database Thing services to perform bulk insert into the table from ThingWorx Composer Insert Service created as SQL Command with code snippet, service takes 2 inputs of type int and string   insert into demo values ([[id]], [[demoValue]]) JavaScript service executing bulk demo data insert by wrapping the SQL service created above   for (i=0; i<2000; i++) { var params = { id: i /* INTEGER */, demoValue: 'Insert from node 0 while node 3 is down' /* STRING */ }; // result: NUMBER var result = me.InsertDemo(params); }   At this point different users in ThingWorx with sufficient access rights can create their DB Things in ThingWorx Composer and can use any of the node address to read/write the data to the CockroachDB cluster. For the purpose of demo one node was stopped while other 2 were running and data was written to the clsuter via the test service created above. Once the 3rd node was restarted we can see the automatic replication happening between the nodes; this can be seen live via the web based admin console of any of the running node's web console.   As highlighted above at certain point in time after i.e 1500hrs all nodes were synced with the data, including the node3 ,which as mentioned above was down while data was being inserted to the cluster. All of the above replication process was done using default configuration.  
View full tip
ThingWorx Manufacturing Tips & Tricks Webinar is a weekly opportunity to hear PTC Subject Matter Experts present on various topics related to the manufacturing space and applications.   Agenda for this week's recorded session - - Manufacturing Apps Overview - Christine Bahmer - Insight CM Integration - Aron Semle - 3rd Party Systems Integration - Varathan Ranganathan - Q&A  
View full tip
  Connect   Connect Your Data to ThingWorx In the world of IoT application development, connectivity refers to the infrastructure and protocols which connect devices to the cloud or network. Edge devices handle the interface between the physical world and the cloud. ThingWorx provides you with several different tools for connecting to the ThingWorx platform. Your decision on which connectivity method to pick will be dependent on your individual use case.   Learning Paths Connect and Configure Industrial Devices and Systems   Featured Guides Install ThingWorx Kepware Server Connect to an Azure OPC UA Server   REST API Use the REST API to Connect Low-Capability Devices to ThingWorx   Using the ThingWorx REST API is an easy way for low-capability devices to connect with the ThingWorx platform and push data to the platform. Any edge device that can make an HTTP POST can read and update properties or execute services on the ThingWorx platform.   Choose a Connectivity Method Use REST API to Access ThingWorx Connect an Arduino Developer Board   Edge SDKs Connect natively to ThingWorx using an AlwaysOn protocol SDK.  Secure, embeddable, and easily deployable communications designed for connecting sensors, devices and equipment across any network topology and any communication scenario.   SDKs are available for Java, C, .net and allow you to connect your devices to ThingWorx with the AlwaysOn protocol. Using the Edge SDKs will give you all the flexibility you need to meet your application's requirements and build robust, secure, full-featured edge integrations and gateways for any platform.   ThingWorx Edge SDKs SDK Reference C SDK Tutorial Java SDK Tutorial   Edge Microserver The Edge Microserver proxies connections via AlwaysOn   Connect your devices to the ThingWorx platform with the Edge MicroServer, a pre-built application that enables devices incapable of making TLS connections to securely interact with the platform.   Connect Raspberry Pi to ThingWorx Choose a Connectivity Method   Kepware Server Access data from industrial machine controllers   ThingWorx Kepware Server with 150+ industrial protocol drivers allows you to easily connect to different types of industrial equipment. The interface provides real-time, bi-directional industrial controls data to the ThingWorx Platform via the AlwaysOn protocol.   Install ThingWorx Kepware Server   Device Cloud Connectors Connect devices with the adapter of your choice and integrate with ThingWorx to build scalable IoT applications.   Connect Azure IoT Devices     Analyze   Analyze and Visualize IoT Data The AI and Machine Learning technologies used in ThingWorx Analytics automate much of the complex analytical processes involved in creating data-driven insights for your IIoT application. Simulate behavior of physical products in the digital world, use predictive analytic algorithms to find patterns in your business data and generate a prediction model, or build a real-time anomaly detection model by monitoring for data points that fall outside of an expected range.   Learning Paths Monitor Factory Supplies and Consumables Design and Implement Data Models to Enable Predictive Analytics   Featured Guides Operationalize an Analytics Model Build a Predictive Analytics Model   Perform Analytical Calculations Embed analytics capabilities into your industrial IoT applications in order to monitor real-time data, predict future events and conditions, and optimize performance of devices and organizations.   Operationalize an Analytics Model Build a Predictive Analytics Model Monitor an SMT Assembly Line Statistical Monitoring with Descriptive Analytics Perform Statistical Calculations with Descriptive Analytics     Build   Rapid, Model-based Application Development Build your industrial IoT application using ThingWorx’s drag-and-drop GUI development environment, model-based development platform. Using the ThingModel to describe assets, processes, and organizational elements and how they relate to each other. Define the functional behavior, add business logic, and extend your application with pre-built plugins. With a properly-constructed framework, your application will be scalable, flexible and more secure.   Learning Paths Medical Device Service Design and Implement Data Models to Enable Predictive Analytics   Featured Guides Get Started with ThingWorx for IoT Data Model Introduction   Build the Data Model Define the properties, services, and events of Things you want to expose to your application developers. The ThingWorx Data Model is a logical representation of the physical devices, systems, and people that interact with your application.   Data Model Introduction Monitor an SMT Assembly Line Data Model Implementation Design Your Data Model   Leverage the Data Model Leverage your data model using events subscriptions, and custom business logic.   Monitor an SMT Assembly Line Methods for Data Storage Bind Data to Widgets Implement Services, Events, and Subscriptions Create Custom Business Logic Application Development Tips & Tricks Create Session Parameters   Extend the Platform Capabilities Take advantage of extensions from partners and third-parties to add new functionality into your system in a seamless manner. Extensions can be service (function/method) libraries, connector templates, widgets, and more.   Create An Extension Create A Mashup Widget Extension Create An Authentication Extension     Manage   ThingWorx Platform Management Efficiently manage your assets with visibility and control over your IoT solution. Install, configure and troubleshoot your application, while monitoring performance and communication with devices. Offering a comprehensive set of tools and features, ThingWorx enables remote access, file transfers, software upgrades, logging, debugging, and more.   Learning Paths Getting Started on the ThingWorx Platform Using an Allen-Bradley PLC with ThingWorx   Featured Guides Deploy an Application   Manage Your Platform Compare Persistence Providers   Manage Your Applications Operationalize application updates, OS upgrades, patches and documentation.   Deploy an Application Compare Persistence Providers     Experience   Design Engaging Experiences Use the industry’s first purpose built IoT application development environment to design engaging experiences for web and mobile applications. Designed to reduce the time, cost, and risk required to build new innovative IoT applications, this layer has two distinct functions: build-time and run-time. Build-time encompasses the technology to create the things in your Industrial IoT solution while Run-time includes the operational permissions to execute and manage those things.   Learning Paths Getting Started on the ThingWorx Platform Customize UI and Display Options to Deploy Applications   Features Guides Create Your Application UI   Application Layout (UI)  Utilize the ThingWorx Mashup Builder tools to design and create engaging IoT applications.   Define Your UI Style Add Style to Your UI with CSS Effective UI Implementation   Charts & Graphs Bring your IoT data to life with dynamic charts and graphs.   How to Display Data in Charts   Reusable Components Leverage the ThingWorx widget library to create a robust user experience and enhance your application capabilities.   Object-Oriented UI Design Tips Display Geolocation Data Using Google Maps Organize Your UI with the Collection Widget     Secure   Securely Collect and Process Data ThingWorx is secure by design and offers multiple authentication options to increase the security of your IoT application. From TLS-encrypted communication and role-based access controls to the distribution of security patches, ThingWorx integrates a range of security features that you can leverage in your development process.   Learning Paths Getting Started on the ThingWorx Platform   Featured Guides Configure Permissions   IoT Application Security Authenticate devices on our platform. ThingWorx handles data transformation, data persistence, and business logic so you can focus on developing your application.   Configure Permissions Enabling LDAP Authentication in ThingWorx Create An Authentication Extension Create An Application Key
View full tip
One of the recurring patterns on the Axeda Platform is making requests from custom objects to other services, to be called either via Scripto, or through Expression Rules that help integrate Axeda data with your custom systems or third parties such as Salesforce.com.  Java developers would normally use a URLConnection to do this, but due to security requirements, access to the URLConnection API is sandboxed, and the HTTPBuilder API is provided instead. Below is a short example of GETting a payload from http://www.mocky.io/v2/57d02c05100000c201208cb5 to your custom object.  One of the requirements of many services is being able to pass in API keys as part of the header request.  While in this example the API key is embedded in the code, the recommended way of storing API keys on the Axeda Platform is to use the External Credential lockbox API.  This allows you to change the API keys securely without needing to change code. import groovyx.net.http.HTTPBuilder import static groovyx.net.http.ContentType.* import static groovyx.net.http.Method.* def http = new HTTPBuilder('https://www.mocky.io') http.request( GET, JSON ) {     uri.path = '/v2/57d02c05100000c201208cb5'     uri.headers.'appKey' = '7661392f-2372-4cba-a921-f1263c938090'     response.success = { resp ->         println "POST response status: ${resp.statusLine}"         logger.info "POST RESPONSE status: ${resp.statusLine}"         assert resp.statusLine.statusCode == 201     } } An example for Salesforce might look like so: import groovyx.net.http.HTTPBuilder import static groovyx.net.http.ContentType.* import static groovyx.net.http.Method.* def xml_body = """<?xml version="1.0" encoding="utf-8" ?> <env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">   <env:Body>     <n1:login xmlns:n1="urn:partner.soap.sforce.com">       <n1:username>johndoe@example.com</n1:username>       <n1:password>Password+SECRETKEY</n1:password>     </n1:login>   </env:Body> </env:Envelope> """ def http = new HTTPBuilder('https://login.salesforce.com/') http.request( POST ) {     uri.path = '/services/Soap/u/35.0 '     body = xml_body     response.success = { resp ->         println "POST response status: ${resp.statusLine         logger.info "POST RESPONSE status: ${resp.statusLine}"         assert resp.statusLine.statusCode == 201     } } This request will give you a security token you can use in future calls to Salesforce APIs; you would use Groovy's native XmlSlurper/XmlParser to parse the response and get the session id to use in future requests.  You would then use this session id like in the following example to get the available REST resources: import groovyx.net.http.HTTPBuilder import static groovyx.net.http.ContentType.* import static groovyx.net.http.Method.* def http = new HTTPBuilder('https://na1.salesforce.com/') http.request( POST ) {     uri.path = '/services/data/v29.0'     uri.headers.'Authorization' = 'Bearer SESSIONID'     response.success = { resp ->         println "POST response status: ${resp.statusLine}"         logger.info "POST RESPONSE status: ${resp.statusLine}"         assert resp.statusLine.statusCode == 201     } } Further reading: HttpBuilder Wiki - https://github.com/jgritman/httpbuilder/wiki Groovy Xml Processing - http://groovy-lang.org/processing-xml.html
View full tip
Hi all,   ThingWorx contains lots of useful functionality for your services (last count is 339 Snippets in ThingWorx 8.5.2). These snippets are an important part of the platform application building capabilities, and most of them are simple enough to understand based on their name and the description that appears when hovering on them.   I have witnessed that however, in some cases, the platform users are not aware of their full capabilities. With this in mind, I started creating some time ago a Snippet Guide for my personal use that I'm sharing now with the community. It contains additional explanations, documentation links and sample source code tested by me.   Please bear in mind that it was done for an earlier ThingWorx version and I did not have enough time to update it for 8.5.x, but it should work the same here as well.   This enhanced documentation is not supported by PTC, so please 1. do not open a Tech Support ticket based on the content of this document and, instead 2. Comment on this thread if there are things I can improve on it.   Happy New Year!
View full tip
ThingWorx Foundation Flow Enable customers using Azure to take advantage of Azure services Access hundreds of Azure system connectors by invoking Azure Logic Apps from within ThingWorx Flow Execute Azure functions to leverage Azure dynamic, serverless scaling and pay just for processing power needed Access Azure Cognitive AI services for image recognition, text to voice/voice to text, OCR and more Easily integrate with homegrown and commercial solutions based on SQL databases where explicit APIs or REST services are not exposed Automatically trigger business process flows by subscribing to Windchill object class and instance events Provide visibility to mature PLM content (such as when a part is released) to downstream manufacturing and supply chain roles and systems Easily add new actions by extending functionality from existing connectors to create new actions to facilitate common tasks Inherit or copy functionality from existing actions and change only what is necessary to support new custom action Azure Connector SQL Database Connector Windchill Event Trigger Custom Action Improvements Platform Composer: Horizontal tab navigation is back!  Also new Scheduler editor. Security: TLS 1.2 support by default, new services for handling expired device connections New support for InFlux 1.7 and MSSQL 2017 * New* Solution Central Package, publish and upload your app with version info and metadata to your tenancy of Solution Central in the PTC cloud Identify missing dependencies via automatic dependency management to ensure your application is packaged with everything required for it to run on the target environments Garner enterprise-wide visibility of your ThingWorx apps deployed across the enterprise via a cloud portal showcasing your company’s available apps, their versions and target environments to foster a holistic view of your entire IIoT footprint across all of your servers, sites and use cases Solution Central is a brand-new cloud-based service to help enterprises package, store, deploy and manage their ThingWorx apps Accelerate your application deployment Initially targeted at developers and admins in its first release, Solution Central enables you to: Mashup Builder 9 new widgets, 5 new functions. Theme Editor with swappable Mashup Preview Responsive Layout enhancements including new settings for fixed and range sizes New Builder for custom screen sizes, new Widget and Style editors, Canvas Zoom Migration utility available for legacy applications to help move to latest features Security 3 new built-in services for WebSocket Communications Subsystem: QueryEndpointSessions, GetBoundThingsForEndpoint, and CloseEndpointSessions Provide greater awareness of Things bound to the platform Allow for mass termination of connections, if necessary Can be configured to automatically disconnect devices with expired authentication methods Encrypting data-in-motion (using TLS 1.2) is a best practice for securely using ThingWorx For previous versions, the installer defaulted to not configuring TLS; ThingWorx 8.5 and later installers will default to configuring TLS ThingWorx will still allow customers to decline to do so, if desired Device connection monitoring & security TLS by default when using installer   ThingWorx Analytics Confidence Model Training and Scoring (ThingWorx Analytics APIs) Deepens functionality by enabling training and scoring of confidence models to provide information about the uncertainty in a prediction to facilitate human and automated decision making Range Property Transform and Descriptive Service Improves ease of implementation of data transformations required for common statistical process control visualizations Architecture Simplification Improves cost of ownership by reducing the number of microservices required by Analytics Server to reduce deployment complexity Simplified installation process enables system administrators to integrate ThingWorx Analytics Server with either (or both) ThingWorx Foundation 8.5 and FactoryTalk Analytics DataFlowML 3.0.   ThingWorx Manufacturing and Service Apps & Operator Advisor Manufacturing common layer extension - now bundling all apps as one extension (Operator Advisor, Asset Advisor, Production KPIs, Controls Advisor) Operator Advisor user interface for work instruction delivery Shift and Crew data model & user interface Enhancements to Operator Advisor MPMLink connector Flexible KPI calculations Multiple context support for assets   ThingWorx Navigate New Change Management App, first in the Contribute series, allows a user to participate in change request reviews delivered through a task list called “My Tasks” BETA Release of intelligent, reusable components that will dramatically increase the speed of custom App development Improvements to existing View Apps Updated, re-usable 3D viewing component (ThingView widget) Support for Windchill Distributed Vaults Display of Security Labels & Values   ThingWorx Azure IOT Hub Connector Seamless compatibility of Azure devices with ThingWorx accelerators like Asset Advisor and custom applications developed using Mashup Builder. Ability to update software and firmware remotely using ready-built Software Content Management via “ThingWorx Azure Software Content Management” Module on Azure IoT Edge. Quick installation and configuration of ThingWorx Azure IoT Hub Connector, Azure IoT Hub and Azure IoT Edge SCM module.   Documentation ThingWorx Platform ThingWorx Platform 8.5 Release Notes ThingWorx Platform Help Center ThingWorx 8.5 Platform Reference Documents ThingWorx Connection Services Help Center   ThingWorx Azure IoT Hub Connector ThingWorx Azure IoT Hub Connector Help Center   ThingWorx Analytics ThingWorx Platform Analytics 8.5.0 Release Notes Analytics Server 8.5.1 Release Notes ThingWorx Analytics Help Center   ThingWorx Manufacturing & Service Apps and ThingWorx Operator Advisor ThingWorx Apps Help Center ThingWorx Operator Advisor Help Center   ThingWorx Navigate ThingWorx Navigate 8.5 Release Notes Installing ThingWorx Navigate 8.5 Upgrading to ThingWorx Navigate 8.5 ThingWorx Navigate 8.5 Tasks and Tailoring Customizing ThingWorx Navigate 8.5 PTC Windchill Extension Guide 1.12.x ThingWorx Navigate 8.5 Product Compatibility Matrix ThingWorx Navigate 8.5 Upgrade Support Matrix ThingWorx Navigate Help Center     Additional Information Helpcenter ThingWorx eSupport Portal ThingWorx Developer Portal PTC Marketplace The National Instruments Connector can be found on PTC Marketplace  
View full tip
Introduction to the mashup builder, mashup types, widget and how to add services to a mashup as well as connecting data from the services to widgets and how to use events in mashups.   For full-sized viewing, click on the YouTube link in the player controls.   Visit the Online Success Guide to access our Expert Session videos at any time as well as additional information about ThingWorx training and services.
View full tip
In this blog I will be covering the initial setup of ThingWorx Android SDK with a sample app (supplied with the Android SDK) and set it up with a web based revision control system like Bitbucket's (free account plan). I'll also be covering quick information on how to enable the HTTPS connection for the ThingWorx server on Windows platform. This will allow for secured connection to the ThingWorx server from the Android application. Do note this is only a reference guide for setting it up with revision control system, you’re free to choose to setup the Android Studio without Bitbucket or with any other revision control system. It’ll be just fine to have a local Git/SVN/Perforce etc. to manage the code repository, setting Android Studio with Bitbucket is officially not supported. Pre-requisite: 1. Download and unzip the ThingWorx Android SDK from https://support.ptc.com 2. An account with Bitbucket is required 3. Download and install Android Studio Project Setup 1. Unzip the downloaded Android SDK on a local drive 2. Start the Android Studio > Import project > navigate to the sample applications location provided with the ThingWorx Android SDK e.g. Thingworx-Android-SDK-X.x.x\samples 3. Select one of the sample application e.g. androidShell, with ThingWorx Android SDK X.x.x there are 3 sample applications currently available when the Android SDK is downloaded: a. Android File Brwoser b. Android Shell c. Android Steam Thing 4. For this blog I'll be setting up the androidShell Android Application 5. Do note that all the sample projects are built using Gradle, so while importing if required select Gradle as the build system for the sample application 6. Once imported successfully in Android Studio you should be able to see the Android project and its file structure like so 7. We'll need an account with Bitbucket, create one if you don't have already 8. Logon to Bitbucket and create a team and new repository under that team 9. Navigate to the repository created in Bitbucket 10. Create a local GIT code repo if you don't already have one, and copy over all the contents from the Android SDK x.x.x.zip to that location 11. On your local machine open a command prompt and navigate to the drive where the local GIT's code repository resides, i.e. the folder where you unzipped the android SDK and execute the commands as mentioned: a. git remote add origin https://<accountName@bitbucket.org>/<teamName>/<projectName>.git b. git push -u origin master Note: This will add the contents of your local GIT repository to the empty code repository you’ve created under the team on Bitbucket. 12. You can also use SourceTree UI application on windows for creating, GIT and Mercury based code repository and connect it to your Bitbucket account 13. On successful commit following will be logged in the command prompt Enabling HTTPS on Tomcat and connecting to Android Application Securing Tomcat on Windows You can skip this section if you already have Tomcat running ThingWorx configured for HTTPS connection. 1. Execute the command in a command prompt C:\>"%JAVA_HOME%\bin\keytool" -genkey -alias tomcat -keyalg RSA -keystore C:\KeystoreTomcat\tomcat.keystore Note: Executing above step will require you to add additional information to the keystore like, Org name, full name location, etc. 2. Edit the <tomcatInstallation>\conf\server.xml file   <Connector   port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"               maxThreads="200" SSLEnabled="true" scheme="https" secure="true" keystoreFile="C:\KeystoreTomcat\tomcat.keystore" keystorePass="<giveYourPasswordHere>" clientAuth="false" sslProtocol="TLS">       <!-- <SSLHostConfig>             <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"                         type="RSA" />         </SSLHostConfig>-->     </Connector> 3. Restart the tomcat service Note: For detailed information on securing the Tomcat on Windows refer to SSL/TLS Configuration How-TO . Note HTTPS setup is only for the Tomcat where ThingWorx is deployed and does not involve certificate setup on the Android Application side Finally,to test if the HTTPS setup was successful or not navigate to https://<serverName/IP>:8443/Thingworx in a web browser. Port 8443 is the default HTTPS port. Starting and connecting Android Application to ThingWorx Now that we have a working secured Tomcat and Android Studio setup with the sample Android Application, androidShell. Let's build and run the application using an emulated Android device in Android Studio 1. Navigate to https://localhost:8443/Thingworx > Import/Export > Import from file and import the Thing entity which will connect to the SampleThing when you’ll run the Android application, for e.g. I imported the Thingworx-Android-SDK-X.X.X\samples\android-shell\entity\Things_AndroidSampleThing.xml because I will be running the androidShell application 2. Attempting to run the Android application without the entity created in ThingWorx first, Thing will show as unbound in RemoteThing. 3. Create an AppKey in ThingWorx > Security > Application Keys with sufficient rights 4. Go to the Android Studio's toolbar and click on AVD Manager icon 5. This will open the Android Virtual Device Manager and lets you create a virtual Android device 6. You can of course use your own actual device to connect over USB and install and test the application on actual hardware 7. If you already have a Virtual or actual device connected to the system, click on Make Project icon in the toolbar 8. Once the Make finishes run the sample application, in my case androidShell application with the Run icon, like so 9. You may now be prompted with the options to select a device virtual or actual 10. Select as desired and click OK 11. This will now launch the application on the selected device, I have selected to launch on the virtual device which will start and emulated Android Device 12. When initiating/running the application for the first time you will be directed to the Settings screen allowing you to enter the connection URI and the Application Key to connect to the ThingWorx server 13. You have to follow one of the following two URI schemes while attempting to connect to a ThingWorx Server a. For HTTP connection use : ws://<machineIP/Name>:8080/Thingworx/WS b. For HTTPS connection use : wss://<machineIP/Name>:8443/Thingworx/WS Note: Ports may differ as these are the default ports, if you are running ThingWorx on different port enhance the URI accordingly 14. Since my ThingWorx is reachable on HTTPS connection i'll use the HTTPS connectino URI scheme and the application key that I have already created in the ThingWorx, which is bound to Administrator user 15. Once done press the back button on the screen to initiate the connection attempt 16. If all's set as it should be you will be able to see the Connected to Server option checked and the Property count for the Serial Number Property being updated every second For more detail on ThingWorx Android SDK refer to the ThingWorx Edge SDKs and WebScocket based Edge MicroServer (WS EMS) Help Center
View full tip
This project is developed out of curiosity of how ThingWorx communicates with sensors and vice versa. Immediately a Smart Parking system idea struck to our mind and I started working on it. While heading from home to office I always worry about car parking space in office especially in rainy season. This project will help user in getting parking space. This project has 4 sections as follows, 1) Smart Parking system: A system application developed in ThingWorx guides user to find empty car parking space. Sensors placed at each car parking slot senses the presence of car. A program running on Raspberry Pi board collects sensor information and sends that information to the Smart Car Parking System application in ThingWorx. The data received through sensor is displayed on ThingWorx dashboard/mashup. 2) Live Traffic: This inherits a Google Map and shows the traffic around user's current location. 3) Traffic Blog: If user is visiting a place and have questions regarding parking, traffic condition etc., then user can post their questions here and people around that area can answer it. Questions are not restricted for parking related questions but like best places to visit in areas, restaurant, shops etc. 4) Automobile Wiki: This page provides an documented help regarding anything related to automobile e.g. how to change car tyres?, how to change car wipers? etc.
View full tip
This might be a well-known topic for some, but I recently had a need that Event Routers fit into perfectly and wanted to share. If you have some neat applications for Event Routers on mashups, feel free to reply!   What? Event Routers are a function on Mashups that let you connect multiple inputs to a single output. For my use case, this was extremely helpful to let me have two different Service Outputs go to the same Widget. They are a really simple tool that can save a lot of headache.   How? Event Routers work by funneling the latest data through to a single output. This is particularly useful for  user-activated actions with the output tied to a widget or another service. The Event Router automatically activates when any one of the Inputs changes.   Example I have two services that generate HTML from different sources, but I want to display just the latest one that the user had activated in a single HTML Text Area widget. The two different services are activated with two different buttons. But how do I show these two outputs in a single widget? Create an Event Router with two HTML inputs!         Now I just tie each service output to the Inputs and tie the Output to the HTML Text Area Text (note: the icon for Input2 is incorrect—it should be HTML as well; this system is running 8.5.1, perhaps it's an issue in that release).         Now when the user clicks on either button, the correct service’s HTML is sent to the HTML Text Area. Ta-da!   P.S. I noticed in some older posts that Event Routers used to be a widget or extension that came and went. Now (8.5+) it is baked into the Functions on the far right side of Mashup Builder.
View full tip
Announcements