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

Community Tip - Have a PTC product question you need answered fast? Chances are someone has asked it before. Learn about the community search. X

IoT Tips

Sort by:
    Step 8: Verify Connectivity   The EMS is now attempting to talk to ThingWorx Foundation.   However, ThingWorx does not have detailed information about the Edge device that is attempting to connect to it, so it will show up in the Unbound category of Remote Things.   Open ThingWorx Composer.     On the left, click Monitoring.   Click Status -> Remote Things.     Click Unbound.     Confirm that you see the PiThing listed in the Unbound section. NOTE: The name PiThing comes from the config.lua script. PiThing is simply the name that is in that script, hence the name that you see in ThingWorx. To change the name of the device, you could stop both wsems and luaScriptResource, edit config.lua to use a different Thing name other than PiThing, and then restart both of the EMS programs. At that point, the Thing showing up in Remote Things -> Unbound would be whatever name you changed to in config.lua.   Create a Remote Thing   Now that the EMS is communicating with ThingWorx Foundation, let's create a Remote Thing to which Foundation can tie said connection.   In ThingWorx Composer, click Browse > Modeling > Things.     At the top-left, click + New.       In the Name field, enter PiThing. Note that the name must match the spelling and capitalization of the Thing's name that you entered in the EMS's config.lua for it to auto-connect.   If Project is not already set, search for and select PTCDefaultProject. In the Base Thing Template field, search for remotethingwith.     Select RemoteThingWithTunnelsAndFileTransfer. At the top, Click Save. Note the status-indication pop-up indicating that PiThing is now connected.       Use Services to Explore EMS Files   Now that your Remote Thing is Saved and Connected, we can use some of the built-in Services to explore the EMS folders and files which we previously created for testing purposes.   At the top of PiThing, click Services.   Under the Execute column, click the Play Symbol for BrowseDirectory.   In the top-left path field, type / and click the bottom-right Execute button. Note the other and tw folders which we previously created for testing.   In the top-left path field, type /tw and click the bottom-right Execute button. Note the tw_test_01.txt file which we previously created for testing.     As the tw_test_01.txt file (and its parent folder) were items which we custom-created for this guide, you should now be 100% convinced that connectivity between Foundation and the EMS is dynamically working.   If so desired, you could explore into other folders (or even add additional files to these folders), run the BrowseDirectory Service again, and confirm that Foundation is now aware of the EMS and actively communicating.     Step 9: Next Steps   Congratulations! You've successfully completed the Setup a Raspberry Pi as an IoT Device guide, and learned how to:   Set up Raspberry Pi Install, configure, and launch the EMS Connect a remote device to ThingWorx   The next guide in the Medical Device Service learning path is Medical Data Storage and Display.    Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Manage Data Model Introduction Connect Connect Industrial Devices and Systems   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support ThingWorx Edge MicroServer (EMS) Help Center External Raspberry Pi Documentation
View full tip
    Step 5: Limiting Composer Access   If you would like to limit a User even more, there are a few things you can do. Go back to the Administrator account and open one of the accounts we created, such as User.OtherAgencies, you will notice the Enabled and Locked checkboxes. Enabled allows you to set whether an account can be used in ThingWorx during runtime. Locked dictates whether an account can be logged into at all.     Suppose we would like for the user to only see emptiness when they try to access the Composer. Follow the below steps to limit ThingWorx Composer access even more.   1. Open one of the Users we created earlier, ie User.OtherAgencies and click on the User Profile tab.  The user profile configuration allows an administrator to control which categories and entities should be displayed for an individual User.     2. You will see various sections and checkboxes. Uncheck all of them to stop access to importing, exporting, creating new Entities, being able to see existing Entities, and much more.     3. Click Save.   Now if you attempt to log into the ThingWorx Composer, you will notice a very difference experience without the ability to see current Entities. Perform this update for all the Users we created, except for User.IT and User.AgencySuperUser.     Step 6: Creating Clearance Levels   ThingWorx does not include default security clearance levels for you. What it does include are Thing Groups. Thing Groups are a reference-able entity type in ThingWorx that allow for Things and Thing Groups as its members. They also provide ThingWorx administrators the ability to manage at scale exposure of Things to only those that require access.   Before we create out first Thing Group, let us create some Entities that will house resources. The first will be an image that is top secret (shown below). In ThingWorx, this would be of type Media. After, we will create a file repository that will contain super-secret documents, a repository for job applications, and another repository for documents that are publicly accessible.   Our Top Secret Image:     Create the Media Entity    Let us store our image in ThingWorx. This image will need extra credentials to access it. This authentication can be performed with a basic username/password setup or SSO utilizing your own configurations.   1.  In the ThingWorx Composer, click the + New button in the top left.    2. In the dropdown list, click Media.   3. In the Name field, use TopSecretImage.   4. Set the Project field to an existing Project (ie, PTCDefaultProject) and click Save. 5. Click Change and add an image or use the image above.     6. Click on the Configuration tab.     7. For the Authentication Type field, select basic. You can select other types based on your Single Sign On and server level configurations, but we will keep this scenario simple.     8. Set a Username and Password that would be used to access our top secret Media.     9. Click Save.   Create the File Repositories   Let us create the setup for our repositories.   1.  In the ThingWorx Composer, click the + New button in the top left.    2. In the dropdown list, click Thing.     3. In the Name field, use TopSecretDocuments and FileRepository as the Base Thing Template.     4. Click Save.  5. Repeat steps 1-4 to create two File Repositories titled JobApplications and PublicDocuments.     Security Levels and Resource Lockdown    We now have our several resources and areas for differing levels of access. We will create 3 Thing Groups to mimic security levels. Our top-secret image will exist independently on ThingWorx, but also inside of a file repository for some level of redundancy. That file repository will belong to one Thing Group, while the other two file repositories will have their own separate Thing Groups.   1. Open the TopSecretDocuments File Repository Thing.  2. Click on the Services tab.     3. Scroll down to the SaveImage and click the play button.      4. Enter a path (such as /SecretImage.png) for the image to reside on the server and click Change to add an image.     5. Click the Execute button.    You now have your image in a File Repository. Let us add this Entity to a Thing Group, then configure the permissions at the Thing Group level.   1.  In the ThingWorx Composer, click the + New button in the top left.      2. In the dropdown list, click Thing Group.     3. In the Name field enter Clearance.Top.     4. Set the Project field to an existing Project (ie, PTCDefaultProject) and click Save. 5. Click the Services tab and click the play button to execute the AddMembers Service.     6. Click on the members Input Info Table and click the + Add button.      7. Enter TopSecretDocuments as the name of the member and Thing as the type. 8. Click Add and Save. Set the Project field to an existing Project (ie, PTCDefaultProject).      9. With you members set, click Execute. 10. Repeat steps 1-9 to create two more Thing Groups and add the other File Repository Entities that we created earlier. Name these Thing Groups Clearance.Public and Clearance.HumanResources. If we wanted to, we could create a Thing Group to add here as a member of another Thing Groups’ hierarchy.   Thing Group Permissions    Time to set the permissions. With the Clearance.Top Thing Group selected, follow the below instructions. As mentioned before, in a production system, you would have more Users and User Groups to completely setup this scenario.   1. Click Permissions. 2. For Visibility, enter PTCDefenseDepartment into the filter.  3. Expand the Organization and select the Agents unit and click Save. 4. Click the Run Time tab. 5. Set the permissions for the Agency.Agents User Group to have full access as shown below:  6. Click Save.  7. Repeat steps 1-6 for our other security clearance Thing Groups. Set the permissions to a department and User Group that you see fit.     Step 7: Next Steps   Congratulations! You've successfully completed the Securing Resources and Private Data guide. In this guide, you learned how to:   Securing data and private information Use Services, Alerts, and Subscriptions to handle processes without human interaction Handling group and organization permissions   The next guide in the Utilizing ThingWorx to Secure Your Aerospace and Defense Systems learning path is Connecting External Databases and Model.    Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Build ThingWorx Solutions in Food Industry Build Design Your Data Model Build Implement Services, Events, and Subscriptions   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum
View full tip
    Step 4: Scheduling Automated Processes   There are many processed that are handled by a corporation. With something as important as food, there is a lot of red tape and regulation.   We will further our Fizos application to monitor food temperatures, expiration dates, product state, and other issues that are factors into the condition of the product. To reduce waste and increase the safety of the food being produced, our application will create entities to model our products after and create a high-level rules engine for the usage and handling of these products.   Let's start with implementing the task of factory inspections. To implement this, we'll use a scheduler to kickstart our daily process and start filling in some of the necessary data.   Schedulers are a great way to execute routine processed. The execute using a configuration similar to that of a cron job on the Linux operating system. In the next guide, schedules will be used to start our deliveries and help execute certain functions of our business logic.   Creating Factories   Before we begin, we'll be using Data Tags. These tags will help organize, filter, search, and analyze what is happening throughout our applications.   In the ThingWorx Composer, click the + New in the top left of the screen.   Select Data Tag in the dropdown.   Set the name as Fizos.FactoryTags. Set the Project (ie, PTCDefaultProject). Add new terms now or you can add them later. We'll be adding them later. You can utilize tags with almost anything in this scenario. The more data, the better.   Now let's begin creating the factory data.   Open the Fizos.Factories.DataTable Data Table and go to the services tab.   Open the AddDataTableEntries service to be executed. This service will allow us to create some general data to work with. You can create as many as you like for this test. Click the values parameter to start creating entries. After clicking + Add, you'll see our Features property. This is where we can find the factory tags we just created, and create as many terms as we like. For simplicity, click New Term create two tags, Sausage and Atlanta. These options will provide us with the purpose of the factory and a location.   4. Save your entry and create a second entry with any location and tags you like. We aren't adding vehicles as of yet, but we will in the next section. 5. After saving, don't forget to execute the service with the two entries saved. If you did it correctly, the values parameter of the service, should show at least a 2 inside of the parentheses. You can also add data to the other parameters if you like. See below:     You now have two factories. We need to inspect these factories daily. What does an inspection entail exactly? You can create custom factories based on the type of products manufactured or have a generic system. Nevertheless, we will log and store these reports in a data table. Let's go. 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.FactoryInspections.DataShape. All of our factory inspections will be based off this Data Shape. Set the Project (ie, PTCDefaultProject) and click Save to store all changes now.   Add the list of properties below: Name                      Base Type     Aspects            Description GUID String primary key Report identifier FactoryID Integer 0 minimum Factory identifier DateRequest DateTime N/A Date the inspection was requested DateCompleted DateTime N/A Date the inspection was completed Report JSON N/A This will hold the inspection report data   The fields for the Fizos.FactoryInspections.DataShape Data Shape are as follows: In the ThingWorx Composer, click the + New in the top left of the screen.   Select Data Table in the dropdown.   In the name field, enter Fizos.FactoryInspections.DataTable. Our Data Table will hold all of our records on factory inspections. For the Data Shape field, select Fizos.FactoryInspections.DataShape. Set the Project (ie, PTCDefaultProject) and click Save to store all changes now.   This entity will be used to house our data and provide assistance with our analytics. For this scenario, we will create the scheduler that starts a generic process process. In the ThingWorx Composer, click the + New in the top left of the screen.   Select Schedulers in the dropdown.   Select Scheduler in the pop-up.   4. Name the new Schedule Fizos.Factory.Schedule. 5. For the Run As User field, select the Fizos.Factory.User that was provided in the download. 6. Set the Project (ie, PTCDefaultProject). 7. Click Save and your entity should match the below configuration.   8. For the Schedule field, set it to 0 0 7 * * ?. This will run the process every day at 7 AM.      9. Switch to the Subscriptions tab and add a new subscription. 10. Name this new subscription PerformDailyInspections and select ScheduledEvent as the event input.     11. Add the following code to the source section: var factories = Things["Fizos.Factories.DataTable"].GetDataTableEntries({}); var tableLength = factories.rows.length; for (var x=0; x < tableLength; x++) { var row = yourInfotableHere.rows[x]; Things["Fizos.ProductsBusinessLogic"].InspectFactory({ FactoryID: row.ID }); }   This code will execute the inspection request service. Now let's expand on the Fizos.ProductsBusinessLogic to produce and handle the result of a request. Open Fizos.ProductsBusinessLogic in Edit mode and go to the Services tab. Open the InspectFactory Service and add the below code. This code will create an inspection request in the data table and you can add code to simulate sending out this request to a user's device or have users query the data table for open requests. var table = Things["Fizos.Factories.DataTable"].GetDataTableEntryByKey({ key: factoryID }); var factory = table.rows[0]; var guid = generateGUID(); // Fizos.FactoryInspections.DataShape entry object var newEntry = new Object(); newEntry.GUID = guid; newEntry.FactoryID = factoryID; newEntry.DateRequest = new Date(); newEntry.DateCompleted = undefined; newEntry.Report = undefined; var values = Resources["InfoTableFunctions"].CreateInfoTableFromDataShape({ infoTableName : "InfoTable", dataShapeName : "Fizos.FactoryInspections.DataShape" }); values.AddRow(newEntry); Things["Fizos.FactoryInspections.DataTable"].AddDataTableEntry({ sourceType: "Source Code", values: values, source: "InspectFactory", }); // Use guid for tracking report request // Create inspection request in ThingWorx attached to guid. This could be stored in a data table or a property field // Send out employee to factory 3. Open the ReceiveInspection Service and add the below code. This code can be accessed via a REST request to the system. This code can be modified to include error handling and conditions to support new requests coming in. var table = Things["Fizos.FactoryInspections.DataTable"].GetDataTableEntryByKey({ key: guid }); var data = table.rows[0]; var update = {}; update.GUID = guid; update.FactoryID = data.FactoryID; update.DateRequest = data.DateRequest; update.DateCompleted = new Date(); update.Report = report; var values = Resources["InfoTableFunctions"].CreateInfoTableFromDataShape({ infoTableName : "InfoTable", dataShapeName : "Fizos.FactoryInspections.DataShape" }); values.AddRow(update); Things["Fizos.FactoryInspections.DataTable"].AddOrUpdateDataTableEntry({ sourceType: "Service Code", values: values, source: "ReceiveInspection" }); // Have employee log data using guid // Track everything inside of logs or data table   You now have a system that will run every day creating requests, storing those requests, and updating those requests with the final reports.     Step 5: Next Steps   Congratulations! You've successfully completed the ThingWorx Solutions in Food Industry guide. In this guide, you learned how to:   Create automated processing, data, and endpoints that can handle that data without manual interaction Use services, alerts, and subscriptions to increase performance Begin making your data model and cornerstone entities to understand how a complex business logic is built   The next guide in the Complex and Automatic Food and Beverage Systems learning path is Factory Line Automation.    Learn More   We recommend the following resources to continue your learning experience:    Capability     Guide Build Design Your Data Model Build Implement Services, Events, and Subscriptions   Additional Resources If you have questions, issues, or need additional information, refer to:  Resource       Link Community Developer Community Forum  
View full tip
    Step 4: Create Thing   Now that we have a Data Shape to format the combination of data coming from the various sub-systems, we can now instantiate a Thing with an Info Table Property to hold all of said data.   Click Browse > Modeling > Things.   Click + New. In the Name field, type MDSD_Thing. If Project is not already set, search for and select PTCDefaultProject. In the Base Thing Template field, search for and select Generic Thing.   At the top, click Save.   Add Info Table Property   We now have a Thing to aggregate the MRI sub-system information, but we still need a Property to perform the actual storage.   We'll use an Info Table Property for this, with the columns of the Info Table formatted by the Data Shape we created in the previous step.   At the top, click Properties and Alerts.   Click + Add.   On the right in the Name field, type MDSD_InfoTable_Property. Change the Base Type to INFOTABLE. In the Data Shape field, search for and select MDSD_DataShape.   Check the box for Persistent.   At the top-right, click the "Check" button for Done. At the top, click Save.     Step 5: Create Service   Now that we have a Thing with an Info Table Property to store our aggregated data from multiple MRI sub-systems, we need to develop a Service which will grab said data and propagate that information into the Info Table Property.   At the top of MDSD_Thing, click Services.   Click + Add.   Under Service Info in the Name field, type MDSD_Aggregation_Service.     Access to MRI Sub-systems   We now need to access the various sub-systems of the MRI that are already talking to ThingWorx Foundation.   Once again, we'll only be doing so for two sub-systems in this MVP example. But the general premise will extend to as many remote devices as is necessary.   You will simply add more references as additional sub-systems are needed.   In the Javascript code window, copy-and-paste in var embedded_properties = Things["MDSD_Embedded_Thing"].GetPropertyValues(); This provides a reference to the embedded microcontroller's Properties. All Things are accessible in Foundation via the "Things" array, and you simply need to provide the Thing-name to index into the array; this functions similarly to a "global" variable, so that any Thing can reference any other Thing. The built-in GetPropertyValues Service simply returns the values of all Properties of the Thing being referenced. In the Javascript code window, copy-and-paste in var pc_properties = Things["MDSD_PC_Thing"].GetPropertyValues(); This provides a reference to the PC's Properties.     Add Values to Info Table   Now that we have references to the sub-systems, we'll add their individual Property values to each field of the Info Table Property.   We'll do this via the built-in AddRow() Service.   To begin an AddRow Service call, copy-and-paste me.MDSD_InfoTable_Property.AddRow({ The me reference is MDSD_Thing, since we're inside said Entity. The MDSD_InfoTable_Property is the Property we added in this guide's previous step. The built-in AddRow Service will add each following Property value to a field of the Info Table formatted by the previously-created Data Shape.   Copy-and-paste Coolant_Percent:embedded_properties.Coolant_Percent, This stores the embedded microcontroller's "Coolant Percent" in the first field of a row of the aggregated Info Table.   Copy-and-paste Field_Strength:embedded_properties.Field_Strength, Likewise, this references the second Property of the embedded microcontroller to store in the second field of the Info Table.   Copy-and-paste Magnet_Temperature:embedded_properties.Magnet_Temperature,   Now that we have all the embedded microcontroller's values, copy-and-paste the following lines for the PC's values: Number_of_Scans:pc_properties.Number_of_Scans,SSD_Space_Open:pc_properties.SSD_Space_Open, Unused_RAM:pc_properties.Unused_RAM,   We also want to record the Timestamp (via the built-in Date Service) when these entries were added; copy-and-paste Timestamp:Date.now()   Finally, close off the AddRow Service with some braces, i.e. copy-and-paste });   Review the entire Service in Foundation and ensure that it matches the Javascript code below. var embedded_properties = Things["MDSD_Embedded_Thing"].GetPropertyValues(); var pc_properties = Things["MDSD_PC_Thing"].GetPropertyValues();me.MDSD_InfoTable_Property.AddRow({ Coolant_Percent:embedded_properties.Coolant_Percent, Field_Strength:embedded_properties.Field_Strength, Magnet_Temperature:embedded_properties.Magnet_Temperature, Number_of_Scans:pc_properties.Number_of_Scans, SSD_Space_Open:pc_properties.SSD_Space_Open, Unused_RAM:pc_properties.Unused_RAM, Timestamp:Date.now() }); For the MDSD_Aggregation_Service, click Done. Click Save.   Test Service   Before going further, we should test the Service to ensure that it is correctly adding entries to the aggregate Info Table Property.   On the MDSD_Aggregation_Service row, under the Execute column, click the Play icon.   At the bottom-right of the Execute Service pop-up, click Execute.   Click Done, and return to Properties and Alerts. Notice under the Value column that the Info Table Property now has an entry.   Under the Value column, click the Pencil icon for Edit.   Review the values and confirm that every field has a valid entry. Note that your values will differ from those in the picture due to the random nature of the simulator. On the pop-up, click Cancel. At the top, click Save.     Step 6: Create Mashup   Now that we have a Thing that has logically aggregated the infomation into a single Info Table Property (and a Service to carry out said aggregation), we can start to visualize the data with a Mashup.   For more information on Mashups, reference the Create Your Application UI guide.   Click Browse > Visualization > Mashups.   Click + New.   On the New Mashup Pop-up, leave the defaults, and click OK. In the Name field, type MDSD_Mashup.   If Project is not already set, search for and select PTCDefaultProject. At the top, click Save.   At the top, click Design.   At the top-left, click the Layout tab.   For Positioning, select the Static radio-button.   At the top-left, click the Widgets tab. At the top, click Save.   Widgets   We now have a "Static Positioning" Mashup, which will let us drag-and-drop Widgets without them auto-expanding to fill the entire space. This will alow us to have multiple Widgets without worrying about sub-dividing the Mashup.   In particular, we're interested in the Grid Widget to display our aggregated data, as well as a Button Widget to call the Service to perform the aggregation.   On the left in the Filter Widgets field, type grid.   Drag-and-drop a Grid Advanced Widget onto the central Canvas area.   In the Filter Widgets field, type button.   Drag-and-drop a Button Widget onto the central Canvas area.   Re-size (by clicking-and-stretching) and move the two Widgets such that they look roughly like the picture below.   Click the Button Widget to select it. In the Filter Properties field of the bottom-left Properties section, type label.   In the Label field, type Retrieve MRI Statistics, and then hit the Tab keyboard key to lock in the change.   At the top, click Save.     Click here to view Part 3 of this guide.
View full tip
  Create an Engine Failure Prediction GUI to warn about customer issues.   GUIDE CONCEPT   This guide will use ThingWorx Foundation's Mashup Builder to create a Graphical User Interface (GUI) to display results from Analytics Manager comparisons of your analytical model to real-time data.   Following the steps in this guide, you will learn how to utilize Widgets and backend data to quickly visualize customer failure conditions.     YOU'LL LEARN HOW TO   Create a Mashup Add Widgets to represent different data Bring Backend Data into the Mashup Tie data to Widgets View Analytical Results in a convenient GUI   NOTE:  The estimated time to complete all parts of this guide is 30 minutes.     Step 1: Scenario   In this guide, we're finishing up with the MotorCo scenario where an engine can fail catastrophically in a low-grease condition.   In previous guides, you've gathered and exported engine vibration-data from an Edge MicroServer (EMS) and used it to build an engine analytics model. You've even put that analytical model into service to give near-immediate results from current engine-vibration readings.   The goal of this guide is to create a GUI to visualize those predicted "low grease" conditions to facilitate customer warnings.     GUI-creation to visualize analytical model deployment can be extremely helpful for the automative segment in particular. For instance, each car that comes off the factory line could have an EMS constantly sending data from which an analytical model could automatically detect engine trouble.   This could enable your company to offer an engine monitoring subscription service to your customers.   This guide will show you how to visualize the results of an engine analytic model for a "smart, connected products" play.     Step 2: Create Mashup   Mashups are ThingWorx Foundation's method of creating Graphical User Interfaces (GUIs).   Mashups are created through the Mashup Builder interface.   Before you can use this drag-and-drop interface, you must first create a new Mashup.      1. In ThingWorx Foundation Composer, click Browse > Visualization > Mashups.      2. Click + New.        3. Leave the defaults and click OK.        4. In the Name field, type EFPG_Mashup.      5. If Project is not already set, search for and select PTCDefaultProject.        6. At the top, click Save.        7. At the top, click Design. You are now in the Mashup Builder interface, where you can drag-and-drop graphical elements (Widgets) to create your GUI.      8. At the top-left, click the Layout tab.        9. Change Positioning to Static. This removes any auto-positioning or dynamic-sizing from our Mashup, so that we can place and size Widgets manually.      10. At the top, click Save again.       Step 3: Add Widgets   We now want to add several Widgets to our Mashup by dragging-and-dropping them into the central Canvas area.   Return to the Widgets tab in the top-left.       2. In the Filter Widgets field, type label.        3. Drag-and-drop five (5) Label Widgets onto the central Canvas area.      4. Select the Label Widgets, go to the Properties in the bottom-left, and change the Label's LabelText to s1_fb1 through s1_fb5.         5. Filter Widgets for text field, and then drag-and-drop five (5) Text Field Widgets onto the central Canvas area.        6. Drag-and-drop two (2) more Label Widgets onto the central Canvas area.      7. Change their LabelText Properties to Result_low_grease and Result_low_grease_mo.        8. Drag-and-drop two (2) more Text Field Widgets onto the central Canvas area.        9. In the top-left Widget's tab, change Category to Legacy.      10. Drag-and-drop an Auto Refresh Widget onto the Canvas.        11. At the top, click Save.         Step 4: Add Data   Now that we have a rough set of Widgets in place to display Data in our Mashup, we need to bring in backend Data from Composer.      1. In the top-right, ensure the Data tab is active.      2. Click the green + button.        3. In the Entity Filter field, search for and select EdgeThing.      4. In the Services Filter field, type getprop.      5. Click the right-arrow beside GetProperties.      6. On the right, check Execute on Load.        7. In the bottom-right, click Done.      8. On the right, expand GetProperties.        9. At the top, click Save.       Step 5: Bind Data   Now that backend Data is accessible inside Mashup Builder, we need to bind it to the various Widgets.   Drag-and-drop Data > Things_EdgeThing > GetProperties > s1_fb1 to the top-left Text Field under the s1_fb1 Label Widget.           2. On the Select Binding Target pop-up, click Text.         3. Repeat for s1_fb2 through s1_fb5 on the 2nd-5th Text Field Widgets.       4. Drag-and-drop Data > Things_EdgeThing > GetProperties > Result_low_grease to the top-right Text Field under the Result_low_grease Label Widget, and select Text on the Binding pop-up.       5. Repeat for Result_low_grease_mo on the Text Field just below.       6. Click the Auto Refresh Widget to select it.       7. In the bottom-left Properties, set RefreshInterval to 1.         8. With the Auto Refresh Widget still selected, click the top-left corner to reveal a drop-down.       9. Drag-and-drop the Refresh Event onto Things_EdgeThing > GetProperties.       10. On the right, click the GetProperties Mashup Data Service to reveal all of its interactions in the bottom-center Connections window.              11. At the top, click Save.       Step 6: View Mashup   In the last guide, we disabled the Analysis Event after confirming that appropriate analytical jobs were being created and completed whenever new data from our EMS Engine Simulator entered Foundation.   We now need to re-enable that Event so that we can see the results in our Mashup.       1. Return to Analytics > Analytics Manager > Analysis Events.       2. Select the Event, and click Enable.   View Analytical Results   With the Analysis Event enabled, we can now view our Mashup to watch engine-failure-predictions be displayed in real time.       1. Return to EFPG_Mashup.       2. At the top, click View Mashup.       3. Wait and notice how the refresh occurs every second, including both true and false analytics results for the "low grease" condition.      4. When you are satisfied that you have observed enough true/false results, return to Analytics > Analytics Manager > Analysis Events and Disable the event.   Through this Learning Path, you have done all of the following:   Connect a remote device to Foundation using the Edge MicroServer (EMS) Fed relevant product-data to the Foundation backend Formatted and exported that data in a manner which Analytics could understand Imported that data and used it to build an Analytics Model of your remote device Started feeding real-time remote data into the model to achieve immediate failure-prediction results Create a GUI to easily visualize those results   You now have a completed Minimum Viable Product (MVP) for a Service Play with MotorCo's new engines.   These new engines may have a known-failure condition, but (because you've instrumented those engines to provide constant data) you can monitor them and predict failures before they actually happen.   This could easily be an up-sell scenario for MotorCo's customers. They could simply purchase the engine. Or they could both purchase the engine and enroll in a service contract where you notified them of impending issues.   What was originally a single-point source of income is now ongoing        Step 7: Next Steps   Congratulations. You've completed the Engine Failure-Prediction GUI guide. In this guide you learned how to:   Create a Mashup Add Widgets to represent different data Bring Backend Data into the Mashup Tie data to Widgets View Analytical Results in a convenient GUI   The next guide in the Vehicle Predictive Pre-Failure Detection with ThingWorx Platform learning path is Enhanced Engine Failure Visualization.   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Build Implement Services, Events, and Subscriptions Guide   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support Analytics Manager Help Center
View full tip
  Use Subsystems to retrieve User/Thing-count and License-expiration information   Guide Concept   In this guide, you'll learn how a Foundation Administrator can access important license-accounting Subsystems.    In particular, we'll look at the User Management and Licensing Subsystems, and how you can use them to ensure that you're not getting close to running out of Users, Things, or your time-to-expiration.    We'll also explore how you can import a new license_capability_response.bin file when your original license is running low on time.      You'll learn how to   Access the Foundation Subsystems Execute built-in Services to retrieve: User counts Thing counts License expiration count Create a "License Dashboard" Mashup Update to a new License   NOTE: The estimated time to complete ALL parts of this guide is 30 minutes     Step 1: Introduction   ThingWorx Foundation uses a licensing system based around a file named license_capability_response.bin.  However, if you're using the downloadable installer, then it's possible that you've never even touched this part of the system before.   Besides doing the initial install, you'll also have to check to see that your license has enough Users, Things, and time left before expiration. You need to ensure that a new license is acquired and properly replaced beforehand... or else your Foundation installation may become unusable.    Therefore, this guide will run you through how to access that information, as well as how to update to a new license_capability_response.bin file when the time is right.      Step 2: Get User Count   The first item we'll investigate is checking on our number of Foundation Users.    When first developing an IoT application, low User counts are typically the norm. Only your team really needs access to Foundation itself, so having only a few Users more than your R&D-team-size is possibly going to be sufficient.    And, if your application is something along the lines of factory-monitoring, then it's possible that your User counts, even when deployed, are going to continue to stay relatively low.    However, many IoT applications involve a tremendous number of Users, as your end-customers will generate a Foundation User whenever they sign up for your application. Think something along the lines of a ride-sharing app, or even a Smart Cities play... either of those can result in thousands (if not tens-of-thousands) of Users.    As such, a Foundation system administrator will need to keep a tight track on the User counts to ensure, whenever you're approaching your upper threshold, that enough warning is given to provide time to receive and install a new license_capability_response.bin with a larger User count.    Navigate to Foundation Composer's Browse > All.   On the left-side Navigation, scroll down until you see the System section. Note that you will likely be unable to even see the System section unless you are an Administration-level User.   Click Subsystems.   Click UserManagementSubsystem.   At the top, click Services.   Scroll down and find the built-in GetUserCount Service.   On the line for GetUserCount, click the "play" icon for Execute Service.   At the bottom-right of the pop-up, click Execute.   Click Done to close the pop-up. The return value from GetUserCount is one way to reveal how many current Users are provisioned for your Foundation system.    Moving forward, we'll explore yet another way, while also looking into our Thing counts.    In particular, you might find that the GetUserCount value doesn't completely match due to some internal system accounts. These system accounts are not counted against your license, however, and may need to be accounted for when using the GetUserCount Service.        Step 3: Get Current License Info   While GetUserCounts can be helpful for getting the current amount of provisioned Users, it does nothing to compare that count to the total allowed by the license.    Instead, we'll make use of a different Subsystem, i.e. the LicensingSubsystem.    Return to Browse > System > Subsystems.   Click LicensingSubsystem.   At the top, click Services.   Scroll down until you find GetCurrentLicenseInfo.   On the GetCurrentLicenseInfo line, click the "play" icon for Execute Service.   On the bottom-right of the pop-up, click Execute.   When you're done analyzing the counts, click Done to close the pop-up.   The first thing to notice is that the InUseFeatureCount for twx_named_user possibly does not match the return of GetUserCount. As already mentioned, this is because of system accounts that are not counted against your license.    For example, for a fresh installation, the GetUserCount may return 4, while InUseFeatureCount returns 2. The 2-count is more accurate, as it is used versus your total license-amount. However, GetCurrentLicenseInfo is less useful for doing a simple comparison between a stored "last user amount" vs "current user amount".    The solution is simple. Compare the return of GetUserCount versus the return of GetCurrentLicenseInfo to determine the true total. In this case, the number of system accounts is 2, so some "GetUserCount - 2" custom-Service could be very helpful.   In addition, GetCurrentLicenseInfo returns the very important twx_things value, i.e. how many Thing Entities have been created in the system. This is typically another hard limit in your license, and needs to be watched over.    Finally, the DaysRemaining column shows how long you have before your license becomes inactive. This is something which needs to be constantly monitored to ensure that your Foundation system as a whole is still running!   Next, we'll explore making a Mashup to reference these built-in Services in a more comfortable environment which auto-updates and can be used as, effectively, a Foundation system dashboard.     Step 4: Create Dashboard Mashup   While the User Management and Licensing Subsystems can be used as previously described to determine relevant admin information, traversing through the Foundation backend can be tedious.    To make User, Thing, and License Expiration Date counts easier to monitor, we'll now create a "dashboard" which automatically pulls this information into a convenient Mashup.    Navigate to Browse > Visualization > Mashups.   Click + New.    Leave the defaults and click OK.   In the Name field, type Licensing_Mashup.   If Project is not set, search for and select PTCDefaultProject. Click Save. Click Design.   Set Layout   Now that we have a new Mashup, we'll start adding the items we'll need to display information from the Subsystems.    First, we'll change the Layout.   In the top-left, ensure that the Layout tab is active.   Click Add Top.   Ensure the new top section is selected, and set Positioning to Static.   Scroll down in the Layout tab, and set Container Size to Fixed Size.   In the new Height field, type 100, and then hit your keyboard's Tab key to lock-in your change. Note that the px will be automatically added after hitting the Tab key.   At the top, click Save.   Add Widgets   Now that we have the Layout we want, we can add Widgets to display data coming from the backend.   In the top-left, click the Widgets tab.   Drag-and-drop a Label Widget onto the top section.   With the Label still selected, in the bottom-left Properties section, change LabelText to User Count, and hit Tab.   Drag-and-drop a Text Field Widget, also in the top section, and below the Label.   In the top-left Widgets tab, change Category to Legacy. Drag-and-drop an Auto Refresh Widget in the top section as well.    In the top-left Widgets tab, change Category back to Standard. Drag-and-drop a Grid Advanced Widget onto the Bottom section.   At the top, click Save.   Click here to view Part 2 of this guide.
View full tip
    Step 3: Creating Customer Data   Now let’s begin creating the customer data. Just enough examples for us to understand what is happening at each step. Let’s create at least 4 customers by following the steps below:   Open the Fizos.Customers.DataTable Data Table and go to the services tab. Open the AddDataTableEntries service to be executed. This service will allow us to create some general data to work with. You can create as many as you like for this test. Click the values parameter to start creating entries. After clicking + Add, and enter data for customers. Try to add at least 1 Factor data tag for each customer.     Save your entry and create a second entry with any location and tags you like. We aren’t adding vehicles as of yet, but we will in the next section. After saving, don’t forget to execute the service with the two entries saved. If you did it correctly, the values parameter of the service, should show at least 1 inside of the parentheses. See below for an example:     We just added customers manually. While convenient for our test, what we truly want is a system that is hands off. What we need is, a way to add customers programatically. Whether a customer is ordering on a website you created for them or they are checking out as a guest (we still want to track this). Below, you’ll see a quick service to add a new user. This service can be created inside of the Fizos.Customers.DataTable data table.   var customer = Resources["InfoTableFunctions"].CreateInfoTableFromDataShape({ infoTableName : "InfoTable", dataShapeName : "Fizos.Customers.DataShape" }); var count = me.GetDataTableEntryCount(); var newEntry = {}; newEntry.ID = count + 1; newEntry.UUID = generateGUID(); newEntry.Type = Type; newEntry.Factors = "Fizos.CustomerTags:FirstTime"; newEntry.Name = Name; newEntry.Email = Email; newEntry.Address = Address; newEntry.Phone = Phone; customer.AddRow(); me.AddDataTableEntry({ sourceType: "Service", values: customer, source: "AddNewCustomer" }); We can adapt these for the customers that would rather not have accounts and be considered guests. Instead of the FirstTime data tag, you might want to add a Guest tag. For name, you could have it empty. The other fields, you’ll still want to likely have. This can give you insight into who these customers are that rather the guest checkout/ordering.     Step 4: Expanding Logistics Models   Let's do a quick review of what we have before we jump forward. In this Learning Path, we've setup scheduled factory inspections, machine automation, created customers, and setup order creation. What we're missing is the handling of deliveries.   In this learning path, we have talked about how to handle design aspects that could be held in a data table or have entities created to model each one. While there are many pros and cons to each method, we will do a mixture of both. Having the logistics data in data tables provide us with an easy form of querying data. Having entities match up with vehicles/transportation allows us to have greater tracking and live updates.   Let's create the vehicle/transportation data model, come up with logic on how to do deliveries from the factories we created earlier in this learning path, then setup a schedule or timer to kickstart the process.   Vehicles Data Model We already have our Data Table of vehicles. Let's create the templates and entities that will be a 1 to 1 between Thing and vehicle.   In the ThingWorx Composer, click the + New in the top left of the screen.   Select Thing Shape in the dropdown.   In the name field, enter Fizos.Vehicles.ThingShape and select a Project (ie, PTCDefaultProject). This Entity will have Services implemented by all types of vehicles. Save your changes and create three Thing Templates which implement this Thing Shape. See below for examples:   Fizos.Vans.ThingTemplate: These are smaller vehicles used to make short or last step deliveries.     Fizos.Trucks.ThingTemplate: These are trucks of different types making larger deliveries.     Fizos.Planes.ThingTemplate: These are planes used to deliver products to long distance locations.     Handling Shipping and Deliveries The cost of shipping and delivering goods is often the last thing people want to think about. Sometimes the cost of shipping goods is more expensive than the goods themselves. So how can we make this one of our strongest factors? By continuing trying to make our design simpler and less costly. We all know that it won't be an easy feat. The best way to do this is to have a system where we can have analytics and continuously improve on.   Let's start with the beginner steps of creating our straight-forward delivery service. Then, we will add Value Streams and tracking to see where we can make improvements. Finally, the solutions get better as we repeat these steps. No one solution is perfect, and no logic will be without holes or issues. Nevertheless, you continuously work on it, so that you can save cost and improve customer experience.   Open Fizos.Vehicles.ThingShape and go to the Properties tab. Create the following list of Properties. These properties are the generic concepts for a vehicle that can deliver a package. Name Base Type Aspects Details FuelCapacity Number 0 minimum, unit: liters logged, persistent AverageFuelConsumption Number 0 minimum, unit: liters logged, persistent MaxMass Number 0 minimum, unit: kilograms logged, persistent MaxVolume Number 0 minimum, unit: cubic meters logged, persistent CurrentLocation Location N/A logged, persistent CurrentOrders InfoTable(Fizos.Orders.DataShape) N/A logged, persistent Your properties should look like the following: Inside the Fizos.Vehicles.ThingShape entity, go to the Services tab. Create the following list of Services. These services are also generic in nature and are based on the concept of a vehicle going to a pick up location, goods being loaded onto the vehicle, the vehicle traveling to a destination, then delivering goods. Name Input Return Type Override Async Description PickUpGoods PickUpLocation: Location Nothing Yes Yes Go to a pickup location (factory or otherwise), and pick up goods. LoadGoods Orders: InfoTable (Fizos.Orders.DataShape) Nothing Yes Yes Perform the task of loading goods onto a vehicle (adding rows to the CurrentOrders property) Travel Destination: Location Nothing Yes Yes Travel for destination A to destination B DeliverGoods Orders: InfoTable (Fizos.Orders.DataShape) Nothing Yes Yes Perform the task of unloading goods at a current location As you can see, the goods are orders. In a real world environment, we would create a separate Data Shape and Data Table for packages to hold a number of orders. We are doing this without the packages Data Table for simplicity in this example. One reason why our products have mass and volume properties is to help with the idea of loading a vehicle and the type of boxes or packaging to use. This could be another way to cut cost. Your Services should look like the following: The same way we were able to create a system that was automated, we will create events that will notify subscribers of certain tasks being complete. This way, the next level of service can be performed instantly by our robot army. Inside the Fizos.Vehicles.ThingShape entity, go to the Events tab. Create the following list of events. These Events will connect to a task being completed. For example, when the vehicle has arrived to a location, an Event will be triggered and thus the next task can begin. For a bit more automation, add an Event you might think is needed, like when fuel is needed in the vehicle.   Name Data Shape Description DestinationReached AlertEvent This alert is fired when the vehicle has reached a location (whether for delivery or pickup). OrdersLoaded AlertEvent This alert is fired when all orders have been loaded onto a vehicle. DeliveryCompleted AlertEvent This alert is fired when the vehicle has completed a delivery. This delivery might have been the last order delivery and vehicle needs to head back for more orders to be picked up. Your Services should look like the following: Let's take a quick break to go over how this will work. A Service in the Fizos.Logistics Entity will search for all Things that implement the Fizos.Vehicles.ThingShape Entity. Each list of these Entities will have it's PickUpGoods Service called with the desired pickup location. When the destination is reached inside of the PickUpGoods Service, the DestinationReached Alert will be triggered. A Subscription waiting for this Event at the Thing level, will call the LoadGoods Service based on the condition of no orders being in the vehicle CurrentOrders Property. This LoadGoods Service will finish and trigger a OrdersLoaded Event. A subscription waiting for this Event at the Thing level, will call the Travel service. The Service will be called with the customer location as the destination OR the location of another site to perform other tasks. When the destination is reached inside of the Travel Service, the DestinationReached Alert will be triggered. A Subscription waiting for this Event at the Thing level, will call the DeliverGoods Service based on the condition of orders being left in the CurrentOrders Property. When the delivery is complete, the DeliveryCompleted Alert will be triggered. A Subscription waiting for this Event at the Thing level, will decide whether to go to a factory or pickup location to restart the process or wait for more instructions. You may have noticed a few things here. For starters, we are starting this from the Fizos.Logistics entity instead of a scheduler. For this process, you can start it with a scheduler, but being a 24 hour company, we don't have a schedule to start deliveries. That being said, the click of a button would do the job.   You can also see that we haven't given you the service code for some of these services. For some of these functions, they're almost duplicates of prior services. What will be more challenging and fun is the logic for which orders go to which delivery method. This is a mixture of vehicle properties, order properties, customer type, and customer location.     Step 5: Next Steps   Congratulations! You've successfully completed the Automated Distribution and Logistics guide.   In this guide, you learned 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   The next guide in the Complex and Automatic Food and Beverage Systems learning path is Securing Industry Data.    Learn More We recommend the following resources to continue your learning experience:   Capability            Guide Build ThingWorx Solutions in Food Industry Build Design Your Data Model Build Implement Services, Events, and Subscriptions   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support Help Center
View full tip
Using the Solution Central API Pitfalls to Avoid by Victoria Firewind, IoT EDC   Introduction The Solution Central API provides a new process for publishing ThingWorx solutions that are developed or modified outside of the ThingWorx Platform. For those building extensions, using third party libraries, or who just are more comfortable developing in an IDE external to ThingWorx, the SC API makes it simple to still utilize Solution Central for all solution management and deployment needs, according to ThingWorx dev ops best practices. This article hones in one some pitfalls that may arise while setting up the infrastructure to use the SC API and assumes that there is already AD integration and an oauth token fetcher application configured for these requests.   CURL One of the easiest ways to interface with the SC API is via cURL. In this way, publishing solutions to Solution Central really involves a series of cURL requests which can be scripted and automated as part of a mature dev ops process. In previous posts, the process of acquiring an oauth token is demonstrated. This oauth token is good for a few moments, for any number of requests, so the easiest thing to do is to request a token once before each step of the process.   1. GET info about a solution (shown) or all solutions (by leaving off everything after "solutions" in the URL)     $RESULT=$(curl -s -o test.zip --location --request GET "https://<your_sc_url>/sc/api/solutions/org.ptc:somethingoriginal12345:1.0.0/files/SampleTwxExtension.zip" ` --header "Authorization: Bearer $ACCESS_TOKEN" ` --header 'Content-Type: application/json' ` )     Shown here in the URL, is the GAV ID (Group:Artifact_ID:Version). This is shown throughout the Swagger UI (found under Help within your Solution Central portal) as {ID}, and it includes the colons. To query for solutions, see the different parameter options available in the Swagger UI found under Help in the SC Portal (cURL syntax for providing such parameters is shown in the next example).   Potential Pitfall: if your solution is not published yet, then you can get the information about it, where it exists in the SC repo, and what files it contains, but none of the files will be downloadable until it is published. Any attempt to retrieve unpublished files will result in a 404.   2. Create a new solution using POST     $RESULT=$(curl -s --location --request POST "https://<your_sc_url>/sc/api/solutions" ` --header "Authorization: Bearer $ACCESS_TOKEN" ` --header 'Content-Type: application/json' ` -d '"{\"groupId\": \"org.ptc\", \"artifactId\": \"somethingelseoriginal12345\", \"version\": \"1.0.0\", \"displayName\": \"SampleExtProject\", \"packageType\": \"thingworx-extension\", \"packageMetadata\": {}, \"targetPlatform\": \"ThingWorx\", \"targetPlatformMinVersion\": \"9.3.1\", \"description\": \"\", \"createdBy\": \"vfirewind\"}"' )     It will depend on your Powershell or Bash settings whether or not the escape characters are needed for the double quotes, and exact syntax may vary. If you get a 201 response, this was successful.   Potential Pitfalls: the group ID and artifact ID syntax are very particular, and despite other sources, the artifact ID often cannot contain capital letters. The artifact ID has to be unique to previously published solutions, unless those solutions are first deleted in the SC portal. The created by field does not need to be a valid ThingWorx username, and most of the parameters given here are required fields.   3.  PUT the files into the project     $RESULT=$(curl -L -v --location --request PUT "<your_sc_url>/sc/api/solutions/org.ptc:somethingelseoriginal12345:1.0.0/files" ` --header "Authorization: Bearer $ACCESS_TOKEN" ` --header 'Accept: application/json' ` --header 'x-sc-primary-file:true' ` --header 'Content-MD5:08a0e49172859144cb61c57f0d844c93' ` --header 'x-sc-filename:SampleTwxExtension.zip' ` -d "@SampleTwxExtension.zip" ) $RESULT=$(curl -L --location --request PUT "https://<your_sc_url>/sc/api/solutions/org.ptc:somethingelseoriginal12345:1.0.0/files" ` --header "Authorization: Bearer $ACCESS_TOKEN" ` --header 'Accept: application/json' ` --header 'Content-MD5:fa1269ea0d8c8723b5734305e48f7d46' ` --header 'x-sc-filename:SampleTwxExtension.sha' ` -d "@SampleTwxExtension.sha" )     This is really TWO requests, because both the archive of source files and its hash have to be sent to Solution Central for verifying authenticity. In addition to the hash file being sent separately, the MD5 checksum on both the source file archive and the hash has to be provided, as shown here with the header parameter "Content-MD5". This will be a unique hex string that represents the contents of the file, and it will be calculated by Azure as well to ensure the file contains what it should.   There are a few ways to calculate the MD5 checksums and the hash: scripts can be created which use built-in Windows tools like certutil to run a few commands and manually save the hash string to a file:      certutil -hashfile SampleTwxExtension.zip MD5 certutil -hashfile SampleTwxExtension.zip SHA256 # By some means, save this SHA value to a file named SampleTwxExtension.sha certutil -hashfile SampleTwxExtension.sha MD5       Another way is to use Java to generate the SHA file and calculate the MD5 values:      public class Main { private static String pathToProject = "C:\\Users\\vfirewind\\eclipse-workspace\\SampleTwxExtension\\build\\distributions"; private static String fileName = "SampleTwxExtension"; public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException { String zip_filename = pathToProject + "\\" + fileName + ".zip"; String sha_filename = pathToProject + "\\" + fileName + ".sha"; File zip_file = new File(zip_filename); FileInputStream zip_is = new FileInputStream(zip_file); try { // Calculate the MD5 of the zip file String md5_zip = DigestUtils.md5Hex(zip_is); System.out.println("------------------------------------"); System.out.println("Zip file MD5: " + md5_zip); System.out.println("------------------------------------"); } catch(IOException e) { System.out.println("[ERROR] Could not calculate MD5 on zip file named: " + zip_filename + "; " + e.getMessage()); e.printStackTrace(); } try { // Calculate the hash of the zip and write it to a file String sha = DigestUtils.sha256Hex(zip_is); File sha_output = new File(sha_filename); FileWriter fout = new FileWriter(sha_output); fout.write(sha); fout.close(); System.out.println("[INFO] SHA: " + sha + "; written to file: " + fileName + ".sha"); // Now calculate MD5 on the hash file FileInputStream sha_is = new FileInputStream(sha_output); String md5_sha = DigestUtils.md5Hex(sha_is); System.out.println("------------------------------------"); System.out.println("Zip file MD5: " + md5_sha); System.out.println("------------------------------------"); } catch (IOException e) { System.out.println("[ERROR] Could not calculate MD5 on file name: " + sha_filename + "; " + e.getMessage()); e.printStackTrace(); } }     This method requires the use of a third party library called the commons codec. Be sure to add this not just to the class path for the Java project, but if building as a part of a ThingWorx extension, then to the build.gradle file as well:     repositories { mavenCentral() } dependencies { compile fileTree(dir:'twx-lib', include:'*.jar') compile fileTree(dir:'lib', include:'*.jar') compile 'commons-codec:commons-codec:1.15' }       Potential Pitfalls: Solution Central will only accept MD5 values provided in hex, and not base64. The file paths are not shown here, as the archive file and associated hash file shown here were in the same folder as the cURL scripts. The @ syntax in Powershell is very particular, and refers to reading the contents of the file, in this case, or uploading it to SC (and not just the string value that is the name of the file). Every time the source files are rebuilt, the MD5 and SHA values need to be recalculated, which is why scripting this process is recommended.   4. Do another PUT request to publish the project      $RESULT=$(curl -L --location --request PUT "https://<your_sc_url>/sc/api/solutions/org.ptc:somethingelseoriginal12345:1.0.0/publish" ` --header "Authorization: Bearer $ACCESS_TOKEN" ` --header 'Accept: application/json' ` --header 'Content-Type: application/json' ` -d '"{\"publishedBy\": \"vfirewind\"}"' )     The published by parameter is necessary here, but it does not have to be a valid ThingWorx user for the request to work. If this request is successful, then the solution will show up as published in the SC Portal:    Other Pitfalls Remember that for this process to work, the extensions within the source file archive must contain certain identifiers. The group ID, artifact ID, and version have to be consistent across a couple of files in each extension: the metadata.xml file for the extension and the project.xml file which specifies which projects the extensions belong to within ThingWorx. If any of this information is incorrect, the final PUT to publish the solution will fail.   Example Metadata File:     <?xml version="1.0" encoding="UTF-8"?> <Entities> <ExtensionPackages> <ExtensionPackage artifactId="somethingoriginal12345" dependsOn="" description="" groupId="org.ptc" haCompatible="false" minimumThingWorxVersion="9.3.0" name="SampleTwxExtension" packageVersion="1.0.0" vendor=""> <JarResources> <FileResource description="" file="sampletwxextension.jar" type="JAR"></FileResource> </JarResources> </ExtensionPackage> </ExtensionPackages> <ThingPackages> <ThingPackage className="SampleTT" description="" name="SampleTTPackage"></ThingPackage> </ThingPackages> <ThingTemplates> <ThingTemplate aspect.isEditableExtensionObject="false" description="" name="SampleTT" thingPackage="SampleTTPackage"></ThingTemplate> </ThingTemplates> </Entities>       Example Projects XML File:     <?xml version="1.0" encoding="UTF-8"?> <Entities> <Projects> <Project artifactId="somethingoriginal12345" dependsOn="{&quot;extensions&quot;:&quot;&quot;,&quot;projects&quot;:&quot;&quot;}" description="" documentationContent="" groupId="org.ptc" homeMashup="" minPlatformVersion="" name="SampleExtProject" packageVersion="1.0.0" projectName="SampleExtProject" publishResult="" state="DRAFT" tags=""> </Project> </Projects> </Entities>       Another large issue that may come up is that requests often fail with a 500 error and without any message. There are often more details in the server logs, which can be reviewed internally by PTC if a support case is opened. Common causes of 500 errors include missing parameter values that are required, including invalid characters in the parameter strings, and using an API URL which is not the correct endpoint for the type of request. Another large cause of 500 errors is providing MD5 or hash values that are not valid (a mismatch will show differently).    Another common error is the 400 error, which happens if any of the code that SC uses to parse the request breaks. A 400 error will also occur if the files are not being opened or uploaded correctly due to some issue with the @ syntax (mentioned above).  Another common 400 error is a mismatch between the provided MD5 value for the zip or SHA file, and the one calculated by Azure ("message: Md5Mismatch"), which can indicate that there has been some corruption in the content of the upload, or simply that the MD5 values aren't being calculated correctly. The files will often say they have 100% uploaded, even if they aren't complete, errors appear in the console, or the size of the file is smaller than it should be if it were a complete upload (an issue with cURL).   Conclusion Debugging with cURL can be a challenge. Note that adding "-v" to a cURL command provides additional information, such as the number of bytes in each request and a reprint of the parameters to ensure they were read correctly. Even still, it isn't always possible for SC to indicate what the real cause of an issue is. There are many things that can go wrong in this process, but when it goes right, it goes very right. The SC API can be entirely scripted and automated, allowing for seamless inclusion of externally-developed tools into a mature dev ops process.
View full tip
  Use the C SDK to build an app that connects to ThingWorx with persistent bi-directional communication.     GUIDE CONCEPT   This project will introduce more complex aspects of the ThingWorx C SDK and help you to get started with development.   Following the steps in this this guide, you will be ready to develop your own IoT application with the ThingWorx C SDK.   We will teach you how to use the C programming language to connect and build IoT applications to be used with the ThingWorx Platform.   YOU'LL LEARN HOW TO   Establish and manage a secure connection with a ThingWorx server, including SSL negotiation and connection maintenance Enable easy programmatic interaction with the Properties, Services, and Events that are exposed by Entities running on a ThingWorx server Create applications that can be directly used with your device running the C programming language Basic concepts of the C Edge SDK How to use the C Edge API to build a real-world application How to utilize resources provided in the Edge SDK to help create your own application    Note: The estimated time to complete ALL 4 parts of this guide is 60 minutes.      Step 1: Completed Examples   Download the completed files for this tutorial: ThingWorx C Edge SDK Sample Files.zip.   This tutorial will guide you through working with the C SDK on differing levels. Utilize this file to see a finished example and return to it as a reference if you become stuck creating your own fully fleshed 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: Environment Setup   In order to compile C code, you need a C compiler and the ThingWorx C Edge SDK. It will be helpful to have CMake installed on your system. CMake is a build tool that will generate make or project files for many different platforms and IDEs.   Operating System Notes Windows You will need a 3rd party compiler such as MinGW GCC, Cygwin GCC or you can follow these Microsoft instructions to download and use the Microsoft Visual C++ Build Tool. Mac Download the Apple Developer Tools. Linux/Ubuntu A compiler is included by default.   NOTE: You can use CMake, version 2.6.1 or later to build projects or make files, which then are used to build the applications that you develop with the C SDK.   Before you can begin developing with the ThingWorx C SDK, you need to generate an Application Key and modify the source code file. You can use the Create an Application Key guide as a reference.   Modify Source File   Extract the files from the C SDK samples zip file. At the top level of the extracted files, you will see a folder called examples. This directory provides examples of how to utilize the C SDK. Open a terminal, go to your workspace, and create a new directory. You can also just switch to the unzipped directory in your system. After you've created this directory in your workspace, copy the downloaded files and folders into your new directory. You can start creating your connection code or open the main.c source file in the examples\SteamSensor\src directory for an example.   Operating System Code Linux/Ubuntu gedit main.c OR vi main.c Mac open –e main.c Windows start main.c        5. Modify the Server Details section at the top with the IP address for your ThingWorx Platform instance and the Application Key you would like to use.   Change the TW_HOST definition accordingly. Change the TW_PORT definition accordingly. Change the TW_APP_KEY definition to the keyId value saved from the last step.   /* Server Details */ #define TW_HOST "https://pp-XXXXXXXXX.devportal.ptc.i" #define TW_PORT 80 #define TW_APP_KEY "e1d78abf-cfd2-47a6-92b7-37ddc6dd34618" NOTE: Using the Application Key for the default Administrator is not recommended. If administrative access is absolutely necessary, create a User and place the user as a member of Admins.   Compile and Run Code   To test your connection, you will only need to update the main.c in the SteamSensor example folder. CMake can generate Visual Studio projects, make build files or even target IDEs such as Eclipse, or XCode. CMake generates a general description into a build for your specific toolchain or IDE.   Inside the specific example folder you would like to run, ie SteamSensor. Create a directory to build in, for this example call it bin. mkdir bin  cd bin      5. Run the CMake command listed below. This assumes CMake is already on your PATH. cmake ..      6. CMake has now produced a set of project files which should be compatible with your development environment.   Operating System Command Note Unix make A set of make files Windows msbuild tw-c-sdk.sln /t:build A visual studio solution   NOTE: CMake does its best to determine what version of Visual Studio you have but you may wish to specify which version to use if you have more than one installed on your computer. Below is an example of forcing CMake to use a specific version of Visual Studio: cmake -G "Visual Studio 15 2017" .. If your version of Visual Studio or other IDE is unknown, use cmake -G to see a list of supported IDEs.   You also have the alternative of opening the tw-c-sdk.sln from within Visual Studio and building in this IDE.   NOTE: By default, CMake will generate a build for the creation of a release binary. If you want to generate a debug build, use the command-> cmake -DBUILD_DEBUG=ON ..       7. Once your build completes you will find the build products in the CMake directory (see example below). From here, open the project in your IDE of choice.   NOTE: You should receive messages confirming successful binding, authentication, and connection after the main.c file edits have been made.   Operating System Files Description Unix ./bin/src/libtwCSdk_static.a  Static Library Unix ./bin/src/libtwCSdk.so  Shared Library Unix ./bin/examples/SteamSensor/SteamSensor   Sample Application Windows .\bin\src\<Debug/Release>\twCSdk_static.lib  Static Library Windows .\bin\src\<Debug/Release>\twCSdk.dll  Shared Library Windows .\bin\examples\<Debug/Release>\SteamSensor\SteamSensor.exe  Sample Application     Step 3: Run Sample Code   The C code in the sample download is configured to run and connect to the Entities provided in the ThingWorxEntitiesExport.xml file. Make note of the IP address of your ThingWorx Composer instance. The top level of the exported zip file will be referred to as [C SDK HOME DIR].   Navigate to the [C SDK HOME DIR]/examples/ExampleClient/src directory. Open the main.c source file.   Operating System Command Linux/Ubuntu gedit main.c OR vi main.c Mac open –e main.c Windows start main.c   Modify the Server Details section at the top with the IP address for your ThingWorx Platform instance and the Application Key you would like to use. Change the TW_HOST definition accordingly.   NOTE: By default, TW_APP_KEY has been set to the Application Key from the admin_key in the import step completed earlier. Using the Application Key for the default Administrator is not recommended. If administrative access is absolutely necessary, create a user and place the user as a member of the Admins security group.   /* Server Details */ #define TW_HOST "127.0.0.1" #define TW_APP_KEY "ce22e9e4-2834-419c-9656-e98f9f844c784c"   If you are working on a port other than 80, you will need to update the conditional statement within the main.c source file. Search for and edit the first line within the main function. Based on your settings, set the int16_t port to the ThingWorx platform port. Click Save and close the file. Create a directory to build in, for this example call it bin.   Operating System Command Linux/Ubuntu mkdir bin Mac mkdir bin Windows mkdir bin   Change to the newly created bin directory.   Operating System Command Linux/Ubuntu cd bin Mac cd bin Windows cd bin   Run the CMake command using your specific IDE of choice.    NOTE: Include the two periods at the end of the code as shown below. Use cmake -G to see a list of supported IDEs.   cmake ..   Once your build completes, you will find the build products in the bin directory, and you can open the project in your IDE of choice. NOTE: You should receive messages confirming successful binding, authentication, and connection after building and running the application    10. You should be able to see a Thing in your ThingWorx Composer called SimpleThing_1 with updated last Connection and isConnected properties. SimpleThing_1 is bound for the duration of the application run time                                                                                                                                                                                The below instructions will help to verify the connection.   Click Monitoring. Click Remote Things from the list to see the connection status.   You will now be able to see and select the Entity within the list.   Step 4: ExampleClient Connection   The C code provided in the main.c source file is preconfigured to initialize the ThingWorx C Edge SDK API with a connection to the ThingWorx platform and register handlers. In order to set up the connection, a number of parameters must be defined. This can be seen in the code below.   #define TW_HOST "127.0.0.1" #define TW_APP_KEY "ce22e9e4-2834-419c-9656-ef9f844c784c #if defined NO_TLS #define TW_PORT = 80; #else #define TW_PORT = 443; #endif The first step of connecting to the platform: Establish Physical Websocket, we call the   twApi_Initialize function with the information needed to point to the websocket of the ThingWorx Composer. This function:   Registers messaging handlers Allocates space for the API structures Creates a secure websocket   err = twApi_Initialize(hostname, port, TW_URI, appKey, NULL, MESSAGE_CHUNK_SIZE, MESSAGE_CHUNK_SIZE, TRUE); if (TW_OK != err) { TW_LOG(TW_ERROR, "Error initializing the API"); exit(err); }   If you are not using SSL/TLS, use the following line to test against a server with a self-signed certificate:   twApi_SetSelfSignedOk();   In order to disable HTTPS support and use HTTP only, call the twApi_DisableEncryption function. This is needed when using ports such as 80 or 8080. A call can be seen below:   twApi_DisableEncryption();   The following event handlers are all optional. The twApi_RegisterBindEventCallback function registers a function that will be called on the event of a Thing being bound or unbound to the ThingWorx platform. The twApi_RegisterOnAuthenticatedCallback function registered a function that will be called on the event the SDK has been authenticated by the ThingWorx Platform.  The twApi_RegisterSynchronizeStateEventCallback function registers a function that will be called after binding and used to notify your application about fields that have been bound to the Thingworx Platform.   twApi_RegisterOnAuthenticatedCallback(authEventHandler, TW_NO_USER_DATA); twApi_RegisterBindEventCallback(NULL, bindEventHandler, TW_NO_USER_DATA); twApi_RegisterSynchronizeStateEventCallback(NULL, synchronizeStateHandler, TW_NO_USER_DATA);   NOTE: Binding a Thing within the ThingWorx platform is not mandatory, but there are a number of advantages, including updating Properties while offline.   You can then start the client, which will establish the AlwaysOn protocol with the ThingWorx Composer. This protocol provides bi-directional communication between the ThingWorx Composer and the running client application. To start this connection, use the line below:   err = twApi_Connect(CONNECT_TIMEOUT, RETRY_COUNT); if(TW_OK != err){ exit(-1); }     Click here to view Part 2 of this guide
View full tip
  Send voice and text messages with Twilio.   GUIDE CONCEPT   This project will demonstrate how you can create applications that provide information to users, even when they are away from their computer. Users who are on the go can benefit from your application by receiving text and voice messages.   Following the steps in this guide, you will learn how to configure and use the Twilio Widget and explore it’s ability to send messages.   We will teach you how data can be used to send pertinent information to any cell phone.   YOU'LL LEARN HOW TO   Download and import the Twilio Widget extension Create a Thing using the Twilio Thing Template Configure the Twilio Thing to use your Twilio account Send text messages using a Service   NOTE:  The estimated time to complete this guide is 30 minutes.     Step 1: Install Twilio Extension   Download the Twilio Extension from IQNOX.com. Note:  IQNOX is a PTC Partner and will be maintaining and supporting specific extensions going forward.  It will be necessary to create an account on the IQNOX website, but the ThingWorx extensions are free. In the lower-left side of Composer, click Import/Export, then Import.   In the Import From File pop-up, under Import Option select Extension from the drop-down, then click Browse. Navigate to the .zip file you downloaded.   Click Import in the Import From File pop-up, then click Close after file is successfully imported.     Step 2: Create Twilio Thing   In this step, you will create a Thing that represents a connection with the Twilio service.   Start on the Browse, folder icon tab on the far left of ThingWorx Composer.  Under the Modeling tab, hover over Things then click the + button. Type twilio-connector in the Name field.   NOTE: This name, with matching capitalization, is required for the example code which will be entered in a later step. If Project is not already set, click the + in the Project text box and select the PTCDefaultProject. In the Base Thing Template text box, click the + and select Twilio.     Click Save.     Step 3: Configure Twilio Thing   Now that we have created a Thing to represent the Twilio connection, we will configure it with your Twilio account credentials.   When the Twilio Extension is installed, it does not include the Twilio account credentials required to send messages.   You will need Twilio account credentials to complete this step. If you do not already have a Twilio account, you can click on this link to create a Twilio account.   Open the twilio-connection Thing if it is not already open. Click on the Configuration tab. Click the pencil icon next to the authToken field.   Copy your AUTH TOKEN from your Twilio account dashboard.   Paste your AUTH TOKEN into the New Password and Confirm Password fields under authToken.   Click the pencil icon next to the accountSID field. Copy your ACCOUNT SID from your Twilio account dashboard, and paste it into the New Password and Confirm Password fields under accountSID. Follow the steps in your Twilio account dashboard to get a trial phone number.   Copy your PHONE NUMBER from your Twilio account dashboard, and paste it into the callerID field.   Click Save.     Step 4: Test Twilio Thing   Now that we have created a Thing to represent the Twilio connection and configured it with Twilio account credentials, we will confirm that everything is working.   Click the Services tab at the top of the twilio-connector Thing.     Click the link to the SendSMSMessage Service in the Services Name column. Enter a phone number in the to field. Enter a test message in the text field.   Click the Execute button to send the SMS message. The service should execute without any errors within a couple of seconds and the phone number will receive your message. Click Close to end testing the service.     Step 5: Sample Alerting App   At this point, you have created and tested a Thing that can send text messages. This step will demonstrate sending a message when a Property Value is out of the desired range.   Import Simulated Freezer Thing   Download and unzip the attached sample Things_freezer.zip. In Composer, click the Import/Export icon at the lower-left of the page.   Click Import. Leave all default values and click Browse to select the Things_freezer.twx file that you just downloaded. Click Open, then Import. When you see the success message, click Close.   Explore Imported Entities   Navigate to the freezer Thing by using the search bar at the top of the screen. Click the Subscriptions tab.   Click reportFreezer under Name. Open the Subscription Info tab. Select the Enabled checkbox.   Click Done then Save to save any changes.   Verify Data Simulation   Open the freezer Thing and click Properties and Alerts tab. Click the Set value in the alertedPhone Property row, in the Value column.   Enter a phone number to receive the SMS alert, then click the Check icon above where you entered the phone number. Click the pencil icon in the temp Property row, in the Value column. Enter a value for the temp property that is greater than 30, and click the Check icon. In a couple seconds, the phone number you entered will receive an alert that includes the value you entered.      Step 6: Next Steps   Congratulations!   In this guide, you learned how to:   Create a Thing using the Twilio Thing Template Configure the Twilio Thing to use your Twilio account Send text messages using a Service   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support Twilio Extension Help Center
View full tip
This has been moved to its new home in the Augmented Reality Category in the PTC Community.
View full tip
U Term Definition user An account that can be used to access ThingWorx (design time and/or run time). user group A collection of users to provide a common level of security-access. Allows you to categorize users of the ThingWorx system. User groups can contain users and groups. All permission settings and overrides are cumulative. The ThingWorx default security policy is restrictive. When you create a new group or user, the account will not have any rights in ThingWorx until you assign them. user management subsystem Subsystem that manages session and password hash settings. See Subsystem.   V Term Definition value stream processing subsystem Subsystem that manages value stream storage and retrieval. See Subsystem. value stream A storage table for time-series information about a Thing's property values. Querying a Value Stream returns the value of the specified property. virtual Thing A modeled Thing defined in Edge that is represented as a remote Thing in the ThingWorx Platform. visibility A simple form of access control. If an entity is visible to members of an organizational unit, those members have access to the entity, and the underlying granular security model determines what interaction members of that organization unit have with a specific asset. Visibility can be set at the collection level, the individual entity level, or at the visibility level of the Thing Template instance. vocabulary A collection of terms used to create tags.   W Term Definition WebSocket-based Edge MicroServer (WS EMS) Allows edge devices or data stores to connect to the ThingWorx Platform through the internet or a firewall using the AlwaysOn™ binary protocol. WebSocket communications subsystem Subsystem that handles core WebSocket communications. See Subsystem. WebSocket execution processing subsystem Subsystem that handles WebSocket execution processing. See Subsystem. widget The components placed on a Mashup such as grids, charts, text boxes, buttons, and navigation links. Anything that is visible or clickable is a widget. wiki A type of Widget that mimics the functionality of a 'collaborative website', and allows collaborative editing of its content and structure by its users. Wikis may have posts added by both human users and the system itself.
View full tip
This video continues Module 3: Data Profiling of the ThingWorx Analytics Training videos. It describes metadata, and how it is used to ensure that your data is handled appropriately when running Signals, Profiles, Training, Scoring, and other jobs inside ThingWorx Analytics.
View full tip
    Step 5: Create InfoTable   Now that we have connected values coming from our EMS engine simulator, we want a method of permanent storage whenever we feel it's appropriate to take a sample.   From repeated sampling, we'll be able to build up a historical record usable for both manual inspection, as well as automatic analysis via ThingWorx Analytics (though ThingWorx Analytics is beyond the scope of this guide).   To hold these records, we'll use an Info Table Property.   But any time that you create an Info Table, you first need a Data Shape to format the columns.   Click Browse > MODELING > Data Shapes.     At the top-left, click + New.   In the Name field, type esimDataShape.     If Project is not already set, search for and select PTCDefaultProject. At the top, click Field Definitions.     We now want to add a separate Field Definition for each entry of our engine simulator data, i.e. low_grease, s1_fb1 through s1_fb5, and s2_fb1 through s2_fb5.   In addition, we'll add an additional field named identifier which simply keeps a rolling count of the current log entry number.   Click + Add.     In the Name field on the right slide-out, type identifier Change the Base Type to NUMBER. Check Is Primary Key   At the top-right, click the "Check with a +" button for Done and Add.     Repeatedly add additional definitions as per the chart below: Note that you will NOT check the "Is Primary Key" box, as you only need one, i.e. identifier. Name Base type low_grease NUMBER s1_fb1 NUMBER s1_fb2 NUMBER s1_fb3 NUMBER s1_fb4 NUMBER s1_fb5 NUMBER s2_fb1 NUMBER s2_fb2 NUMBER s2_fb3 NUMBER s2_fb4 NUMBER Create one additional entry for s2_fb5 and NUMBER, but click the "Check" button for DONE. At the top, click Save.     Create Info Table   Now that we have a Data Shape we can add an Info Table Property to EdgeThing. Return to the Properties and Alerts tab of EdgeThing.   At the top-left, click + Add.   In the Name field of the slide-out on the right, type infoTableProperty.   Change the Base Type to INFOTABLE.   In the new Data Shape field, search for and select esimDataShape.   Check the Persistent checkbox.   At the top-right, click the "Check" button for Done. At the top, click Save.     Click here for Part 4 of this guide.
View full tip
  Enhance your Engine Failure-Prediction GUI.     GUIDE CONCEPT   This guide will use ThingWorx Foundation’s Mashup Builder to create a more advanced Graphical User Interface (GUI) than the one we originally created to display results from Analytics Manager’s engine-failure predictions.   Following the steps in this guide, you will learn how to utilize Widgets and backend data to more completely visualize customer failure conditions.       YOU'LL LEARN HOW TO   Create a Mashup with a Header Divide your Mashup into Sub-sections Use a Contained Mashup to reuse development Store historical data in a Value Steam Display historical data in a Time Series Chart Show spreadsheet data via a Grid Widget Tie Mashup controls into the ThingWorx backend   NOTE: The estimated time to complete all parts of this guide is 60 minutes.     Step 1: Scenario   In this guide, we’re taking our previous MotorCo Minimum Viable Product (MVP) Mashup and expanding it.   Our original Mashup showed the results from ThingWorx Analytics as it determined whether or not a low-grease condition was currently present.   The goal of this guide is to create an Enhanced GUI to visualize those predicted “low grease” conditions in a more complete manner.     GUI-creation to visualize analytical model deployment can be extremely helpful for the automative segment in particular. For instance, each car that comes off the factory line could have an EMS constantly sending data from which an analytical model could automatically detect engine trouble.   This could enable your company to offer an engine monitoring subscription service to your customers.   This guide will show you how to visualize the results of an engine analytic model for a smart, connected products play.     Step 2: Create Mashup   Just like in the last guide, we're now going to create a Mashup to visualize ThingWorx Analytics results.   This one is simply going to be more complicated to include additional functionality.   But before we can start designing our GUI, we must first instantiate a Mashup onto which we can place our Widgets.       1. In ThingWorx Foundation, click Browse > Visualization > Mashups.         2. Click + New.       3. On the New Mashup pop-up under Responsive Templates, click Header Only.       4. Click OK.       5. In the Name field, type EEFV_Mashup.       6. If Project is not already set, search for and select PTCDefaultProject.       7. At the top, click Save.       8. At the top, click Design.         Step 3: Set Layout   Now that we’re in Mashup Builder, you can see the separate top-section of the central Canvas area created by our selection of “Header Only” on the New Mashup pop-up.   Unlike the original Mashup where we used Static Positioning, most of this Mashup will continue to use Responsive so that it can grow and shrink as resolution changes on various viewing devices.   To add multiple Responsive Widgets to a Responsive Positioning Mashup, though, you need to create some additional sub-sections. We’ll do so now.       1. In the top-left of Mashup Builder, click the Layout tab.       2. Click the main, bottom section of the Canvas, i.e. the non-header section, to select it.       3. On the Layout tab, click Add Top.       4. With the top-half of the original bottom section still selected, click Add Left.       5. Click in the bottom section to select the bottom-half of the original container.       6. Click Add Left.       7. At the top, click Save.      You now have a Responsive Positioning Mashup with five (5) sub-sections, i.e. :   Header Top-left Top-Right Bottom-left Bottom-right       Step 4: Adjust Header    In this step, we'll outfit the Header sub-section with a company name and logo.       1. Select the top Header section and ensure that you're still on the Layout tab in the top-left.         2. Change the Positioning to Static.       3. In the top-left, select the Widgets tab.       4. Drag-and-drop an Image Widget onto the Header section.       5. Expand the size of the Image Widget by dragging the corners.       6. Drag-and-drop a Label Widget onto the Header section.       7. Expand the size of the Label Widget.       8. With the Label Widget still selected, change the LabelText Property (in the bottom-left) to MotorCo, and hit the keyboard Tab key to lock-in your modification.         9. In the bottom-left, change to the Style Properties tab.       10. Expand Base > Label, and change font-size to 72px.       11. At the top, click Save.   Upload Media Image   We want to set the earlier Image Widget to the company logo.   To do so, we need to upload it to Foundation by creating a Media Entity.       1. Click Browse > Visualization > Media.       2. Click + New.       3. In the Name field, type EEFV_Logo.       4. If Project is not already set, search for and select PTCDefaultProject.       5. Right-click and "Save as" to download motorco-logo.jpg.       6. Under Image, click Change.       7. Navigate to and select the motorco-logo.jpg file you just downloaded.       8. Click Open.       9. At the top, click Save.   Change Image to Logo   Now that we have the company logo stored within ThingWorx, we can update the Image Widget to reference it.       1. Return to EEFV_Mashup.       2. Click the Image Widget to select it, and ensure that the bottom-left Properties tab is active.         3. Scroll down in the Properties until you find SourceURL.         4. In the Search Media field, type eefv.         5. Select EEFV_Logo.         6. Click Save.     Change Background Color   Finally, we want to change the background color of the Header.       1. In the top-left, select the Explorer tab. Note that the Explorer tab may be in the top-left drop-down if you're using a lower-resolution screen.         2. Select the Header itself.         3. In the bottom-left, select the Style Properties tab and expand Base > Container.         4. Beside background, click the white square to open a color-selector.       5. Select a color you desire.         6. Click Select.         7. Click Save.     Click here to view Part 2 of this guide.
View full tip
    Step 2: Java Properties (cont.)   Annotation @ThingworxPropertyDefinitions(properties = { @ThingworxPropertyDefinition(name = "Temperature", description = "Current Temperature", baseType = "NUMBER", category = "Status", aspects = { "isReadOnly:true" }), @ThingworxPropertyDefinition(name = "Pressure", description = "Current Pressure", baseType = "NUMBER", category = "Status", aspects = { "isReadOnly:true" }), @ThingworxPropertyDefinition(name = "FaultStatus", description = "Fault status", baseType = "BOOLEAN", category = "Faults", aspects = { "isReadOnly:true" }), @ThingworxPropertyDefinition(name = "InletValve", description = "Inlet valve state", baseType = "BOOLEAN", category = "Status", aspects = { "isReadOnly:true" }), @ThingworxPropertyDefinition(name = "TemperatureLimit", description = "Temperature fault limit", baseType = "NUMBER", category = "Faults", aspects = { "isReadOnly:false" }), @ThingworxPropertyDefinition(name = "TotalFlow", description = "Total flow", baseType = "NUMBER", category = "Aggregates", aspects = { "isReadOnly:true" }), })   NOTE: The call to VirtualThing.initializeFromAnnotations is necessary if there are properties, services, and events that are annotated.   Code //Create the property definition with name, description, and baseType PropertyDefinition property1 = new PropertyDefinition(property, "Description for Property1", BaseTypes.BOOLEAN); //Create an aspect collection to hold all of the different aspects AspectCollection aspects = new AspectCollection(); //Add the dataChangeType aspect aspects.put(Aspects.ASPECT_DATACHANGETYPE, new StringPrimitive(DataChangeType.NEVER.name())); //Add the dataChangeThreshold aspect aspects.put(Aspects.ASPECT_DATACHANGETHRESHOLD, new NumberPrimitive(0.0)); //Add the cacheTime aspect aspects.put(Aspects.ASPECT_CACHETIME, new IntegerPrimitive(0)); //Add the isPersistent aspect aspects.put(Aspects.ASPECT_ISPERSISTENT, new BooleanPrimitive(false)); //Add the isReadOnly aspect aspects.put(Aspects.ASPECT_ISREADONLY, new BooleanPrimitive(false)); //Add the pushType aspect aspects.put("pushType", new StringPrimitive(DataChangeType.NEVER.name())); //Add the defaultValue aspect aspects.put(Aspects.ASPECT_DEFAULTVALUE, new BooleanPrimitive(true)); //Set the aspects of the property definition property1.setAspects(aspects); //Add the property definition to the Virtual Thing this.defineProperty(property1);   Update Properties   Property values can be updated using the provided Macros or using the API directly.   The VirtualThing.setPropertyVTQ and VirtualThing.setProperty methods are used to update properties connected to the ThingWorx Platform. It is often easiest to use the setProperty method because it allows the usage of values outside of IPrimitiveType. Using these methods will fire a property changed event and also look to add the update to the pending list of changes to the Platform based on your DataChangeType aspect used for the property. An example of how to use VirtualThing.setProperty can be seen below: double temperature = 400 + 40 * Math.random(); super.setProperty("Temperature", temperature);   NOTE: setPropertyVTQ and setProperty are both methods inside of the VirtualThing class. All objects you would like to have represented in the ThingWorx Platform as an Entity, must extend the VirtualThing class.   When finished with updating all property values, use the VirtualThing.updateSubscribedProperties method to send the queue of changes to the Platform. Property value updates will NOT be sent to the platform if this method is not called. An example can be seen below:   super.updateSubscribedProperties(15000);   Retrieve Properties   Property values can be retrieved using the provided Macros or using the API directly.   The VirtualThing.getProperty and VirtualThing.getCurrentPropertyValue methods are used to retrieve properties connected to the ThingWorx Platform. The VirtualThing.getProperties returns a PropertyCollection which provides a collection type behavior for all properties initialized within your implementation. An example of how to use VirtualThing.getProperty can be seen below:   double temperatureLimit = (Double) getProperty("TemperatureLimit").getValue().getValue();   NOTE: getProperty and getCurrentPropertyValue are both methods inside of the VirtualThing class. All objects you would like to have represented in the ThingWorx Platform as an Entity, must extend the VirtualThing class.   Synchronize Updates   The VirtualThing.synchronizeState method is called when a connect or reconnect occurs. If property values are not synced with the ThingWorx Platform on a regular basis, this method should be overridden with a call to sync properties. An example of this is shown below: public void synchronizeState() { super.synchronizeState(); super.syncProperties(); }   Scan Cycles The VirtualThing.processScanRequest method should be overridden and used to perform the tasks that should occur during a scan cycle. A scan cycle could be considered a reoccurring period in which a task is performed. This should be called and performed after a connection is made and while the application is still connected to the ThingWorx Platform. An example is as follows: while (!client.isShutdown()) { if (client.isConnected()) { for (VirtualThing thing : client.getThings().values()) { try { thing.processScanRequest(); } catch (Exception exception) { System.out.println("Error Processing Scan Request for [" + thing.getName() + "] : " + exception.getMessage()); } } } Thread.sleep(1000); }       Step 3: Java - Data Shapes   DataShapes are used for Events, Services, and InfoTables. In order to create a DataShape, you will use the FieldDefinitionCollection class with a FieldDefinition object to set each aspect and field type for the DataShape. The VirtualThing.defineDataShapeDefinition method adds the recently created definition to the Entities list of DataShapes. If the DataShape is located on the ThingWorx Platform, utilize the ConnectedThingClient.getDataShapeDefinition method in order to retrieve it. An example is shown below of how to create a DataShape and store it to the list of available DataShapes: // Data Shape definition that is used by the delivery stop event // The event only has one field, the message FieldDefinitionCollection fields = new FieldDefinitionCollection(); fields.addFieldDefinition(new FieldDefinition(ACTIV_TIME_FIELD, BaseTypes.DATETIME)); fields.addFieldDefinition(new FieldDefinition(DRIVER_NAME_FIELD, BaseTypes.STRING)); fields.addFieldDefinition(new FieldDefinition(TRUCK_NAME_FIELD, BaseTypes.BOOLEAN)); fields.addFieldDefinition(new FieldDefinition(TOTAL_DELIVERIES_FIELD, BaseTypes.NUMBER)); fields.addFieldDefinition(new FieldDefinition(REMAIN_DELIVERIES_FIELD, BaseTypes.NUMBER)); fields.addFieldDefinition(new FieldDefinition(LOCATION_FIELD, BaseTypes.LOCATION)); defineDataShapeDefinition("DeliveryTruckShape", fields);       Step 4: Java - Info Tables   Infotables are used for storing and retrieving data from service calls.   The provided InfoTable object uses a DataShapeDefinition object to describe the name, base type, and additional information about each field within the table.   The InfoTable class is a collection of ValueCollection entries for each row based on the DataShapeDefinition. When reading values from an InfoTable or loading an InfoTable with data, you will need to use the ValueCollection class.   Create and Load   The code below shows how to utilize these classes in order to create and add data to an InfoTable: DataShapeDefinition dsd = (DataShapeDefinition) this.getDataShapeDefinitions().get("SteamSensorReadings"); InfoTable table = new InfoTable(dsd); ValueCollection entry = new ValueCollection(); DateTime now = DateTime.now(); try { // entry 1 entry.clear(); entry.SetStringValue(SENSOR_NAME_FIELD, "Sensor Alpha"); entry.SetDateTimeValue(ACTIV_TIME_FIELD, now.plusDays(1)); entry.SetNumberValue(TEMPERATURE_FIELD, 50); entry.SetNumberValue(PRESSURE_FIELD, 15); entry.SetBooleanValue(FAULT_STATUS_FIELD, false); entry.SetBooleanValue(INLET_VALVE_FIELD, true); entry.SetNumberValue(TEMPERATURE_LIMIT_FIELD, 150); entry.SetNumberValue(TOTAL_FLOW_FIELD, 87); table.addRow(entry.clone()); // entry 2 entry.clear(); entry.SetStringValue(SENSOR_NAME_FIELD, "Sensor Beta"); entry.SetDateTimeValue(ACTIV_TIME_FIELD, now.plusDays(2)); entry.SetNumberValue(TEMPERATURE_FIELD, 60); entry.SetNumberValue(PRESSURE_FIELD, 25); entry.SetBooleanValue(FAULT_STATUS_FIELD, true); entry.SetBooleanValue(INLET_VALVE_FIELD, true); entry.SetNumberValue(TEMPERATURE_LIMIT_FIELD, 150); entry.SetNumberValue(TOTAL_FLOW_FIELD, 77); table.addRow(entry.clone()); } catch (Exception e) { e.printStackTrace(); }   Read   This code shows how to read a value from an InfoTable. InfoTable result = client.readProperty(ThingworxEntityTypes.Things, "SteamSensor", "name", 10000); String name = result.getFirstRow().getStringValue("name");   The example highlighted below showcases one way to get a property reading from a Thing in the ThingWorx Platform. InfoTable result = client.readProperty(ThingworxEntityTypes.Things, "SteamSensor", "name", 10000); ValueCollection entry = result.getFirstRow(); String name = entry.getStringValue("name");     Click here to view Part 4 of this guide.  
View full tip
  Step 5: Format Timed Values   At the top, click the Services section of scts_thing.   In the Ihnerited Services section, you will see the built-in services of the Statistical Calculation Thing Shape. These services can perform a variety of analytical calculations.   Timed Values Service   The Statistical Calculation Thing Shape can only perform analytics operations on time-series datasets. However, accessing a time-series Value Stream can have a performance hit on the system.   Instead, a Property with an Info Table using a timestamp/value Data Shape is used as the universal input to each built-in service of the Statistical Calculation Thing Shape.   For efficiency, we only reference the Value Stream once to create a formatted timedValues that is used as an input to all other service calls.   At the top, click Services.   Click + Add.   In the Name field, enter timed_values_service. In the Javascript field, copy and past the following code: me.timed_values = me.QueryTimedValuesForProperty({ propertyName: "numbers", maxItems: 10, startTime: me.start_time, endTime: me.end_time });   At the bottom, click Save and Execute.   Click Done, and return to Properties and Alerts. On the timed_values property row, click the pencil icon for Set value of property.   In the pop-up, note that there are now seven entries - each with the 1, 5, 9, 5, 9, 1, and 9 values and the timestamps when you entered them.   In the pop-up, click Cancel. If needed, in the top-right, click the icon to close the slide-out.   Step 6: Calculation Services   Now that the numbers, start_time, end_time, and timed_values service inputs have been set, you can use the built-in Services of the Statistical Calculation Thing Shape to perform a variety of analytics calculations.   Mean Service   First, you will utilize the built-in CalculateMeanValue service.   The dataset is the following: 1, 5, 9, 5, 9, 1, 9.   As such, the mean should be (1+5+9+5+9+1+9)/7 = 39/7 = 5.571...   Return to the Services section. At the top, click + Add. In the Name field, enter mean_service. In the Javascript code section, copy and paste the following: me.mean_result = me.CalculateMeanValue({ timedValues: me.timed_values }); At the top, click Save and Continue.   At the bottom, click Execute. Click Done, then return to the Properties and Alerts section. Note that the mean_result property now has the value 5.571....     Median Service   Next, you will utilize the built-in CalculateMedianValue service.   With our dataset having 5 as the middle value, that should be the result.   Return to the Services section. At the top, click + Add. In the Name field, enter median_service. In the Javascript code section, copy and paste the following: me.median_result = me.CalculateMedianValue({ timedValues: me.timed_values }); At the top, click Save and Continue. At the bottom, click Execute. Click Done, and return to the Properties and Alerts section. Note that the median_result Property now has the value 5.     Mode Service   You will now utilize the built-in CalculateModeValue service.   With the dataset having 9 as the most common value, that should be the result.   Return to the Services section. At the top, click + Add. In the Name field, enter mode_service. In the Javascript code section, copy and paste the following: me.mode_result = me.CalculateModeValue({ timedValues: me.timed_values }); At the top, click Save and Continue.   At the bottom, click Execute. Click Done, and return to the Properties and Alerts section. On the mode_result row and under the Value column, click the "pencil" icon for Set value of property.   In the popup, note that the mode_result Property now has the value 9.   Click Cancel to close the popup. If necessary, at the top-right, click the button to close the slide-out.   Standard Deviation Service   Lastly, you will utilize the built-in CalculateStandardDeviationValue service.   There are multiple free Standard Deviation calculators to check the answer.   Accordingly, the Standard Deviation should be 3.59894...   Return to the Service section. At the top, click + Add. In the Name field, enter standarddev_service. In the Javascript code section, copy and paste the following: me.standarddev_result = me.CalculateStandardDeviationValue({ timedValues: me.timed_values }); At the top, click Save and Continue.   At the bottom, click Execute. Click Done, and return to the Properties and Alerts section. Note that the standarddev_result property now has the value 3.59894...       Step 7: Other Options   The Mean, Median, Mode, and Standard Deviation services you have completed are just a sampling of what the Statistical Calculation Thing Shape offers.   Below is a table of additional built-in services:   Calculation Service Name Description Binned Data Distribution for Bin Size CalculateBinnedDataDistributionForBinSize Calculate the binned distribution of data points based on the desired bin size. Binned Data Distribution for Number of Bins CalculateBinnedDataDistributionForNumberOfBins Calculate the binned distribution of data points based on the desired number of bins. Confidence Interval Values CalculateConfidenceIntervalValues Confidence Interval Values Based on a specified confidence interval percentage, calculate the minimum, median, and maximum interval values. Five Number Property Values CalculateFiveNumberPropertyValues Calculate the five number values: minimum, lower quartile, median, upper quartile, and maximum. Fourier Transform CalculateFourierTransform Calculate the results of running the fast Fourier transform on the specified values. Maximum Value CalculateMaximumValue Calculate the maximum property value in the provided infotable. Minimum Value CalculateMinimumValue Calculate the minimum property value in the provided infotable. Sampling Frequency Values CalculateSamplingFrequencyValues Calculate the sampling frequency values: minimum, median, and maximum.     Step 8: Next Steps   Congratulations!   In this guide, you have learned how to:   Create a Value Stream and Data Shape Create a Thing with the Statistical Calculation Thing Shape Modify a property to record values to the Value Stream Utilize various built-in services for analytical calculations   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide 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 3: Create A Tree Grid   With our MyFunctionsMashup Mashup open, let's add a Validation. A Validation is similar to an Expression, except you have the added capability of triggering Events based on a True or False outcome of your validation. We will use the Validation to check and confirm the Text Field we created only has the values we added in our Functions. Let's also add two Status Message Functions that will show whether or not a user has added any text outside of what we want.   Open the MyFunctionsMashup Mashup to the Design tab. Click the green + button in the Functions area.    In the New Function modal, select Validator.     Set the Name to isDataClean.     Click Next.  Click Add Parameter. Set the Name to text and ensure the Base Type is STRING.     Add the following code to the Expression are: if(text === "NO") { result = true; } else if(text === "YES") { result = true; } else { let array = text.split("YES").join(""); array = array.split(",").join(""); let count = array.trim().length; if(count) { result = false; } else { result = true; } }   9. Click Done.   We have our Validator in place, now we need our two Status Message Functions. Why two? You can setup one Status Message to perform the task, but for this case, we're keeping things simple.   Click the + button in the Functions area. Select Status Message in the dropdown.    Set the Name to GoodInputProvided.   Click Next. Ensure Message Type is Info. In the Message field, enter Text is all good!.   Click Done. Let's create another Status Message Function. Set the Name to BadnputProvided.   Click Next. Change Message Type to Error. In the Message field, enter Text is BAD!.   Click Done.   We now have two Status Message Functions and a Validator to help with checking our text data. Let's connect everything together. This time, let's use the Bind button.   Expand the Validator section in the Functions tab. Click the Bind (arrows) button on the isDataClean Validator. This window will help us configure connections a bit easier.    Click the down arrow by the True Event. Click Add Trigger Service.   Click Functions. Check the checkbox by GoodInputProvided.   Click Next. Click the down arrow by the False Event. Click Add Trigger Service.   Click Functions. Check the checkbox by BadInputProvided.   Click Next. You should currently have the following setup:    Let's add in our connections to the Text Field and when we'll run this Validation.    Click the down arrow by the text Property.   Click Add Source. With the Widgets tab selected, scroll down and select the Text Property of our Text Field.   Click Next. Click the down arrow by Evaluate Service. Select Add Event Trigger.   With the Widgets tab selected, scroll down and select the Clicked Property of our Button.   Click Next. You should currently have the following setup:   Click Done. Click Save and view your updated Mashup.   Your Validator is complete. You now have a way to tell when a user has inputed their own text into the text box. To try things out, add some crazy characters, hit the button, and see what happens. You might notice that you have your Expressions running at the same time as your Validator. Switch up the bindings to get it to run the way you want it to.     Step 4: Next Steps   Congratulations! You've successfully completed the Explore UI Functions guide, and learned best practices for building a complex Mashup that navigations, multiple data inputs, confirmations, and all working together effectively for an enhanced user experience.   Learn More   We recommend the following resources to continue your learning experience:    Capability     Guide Experience Object-Oriented UI Design Tips   Additional Resources   If you have questions, issues, or need additional information, refer to:    Resource       Link Community Developer Community Forum Support Mashup Builder Support Help Center
View full tip
  Step 7: Real World Model   We’ll now rerun model creation with the Real World data.   Even though Signals and Profiles are possibly telling us that only Sensor 1 is needed, the first Model you’ll create will contain all the data, while the second Model will exclude Sensor 2. We’ll then compare the Models to see which one is going to work the best for predicting engine failures.   On the left, click Analytics Builder > Models. Click New….   In the Model Name field, enter vibration_model. In the Dataset field, select vibration_dataset.   Click Submit. After ~60 seconds, the Model Status will change to COMPLETED. Select the model that was created in the previous step, i.e. vibration_model. Click View… to open the Model Information page. Note that your model may differ slightly from the picture below, as the automatically-withheld "test" data is randomly chosen.       Unlike our simulated dataset, this real-world data is not perfect. However, it’s still pretty good, and is much more representative of what a real-world scenario would indicate.   The True Positive Rate shown on the Receiver Operating Characteristic (ROC) chart are much higher than the False Positives.   The curve is relatively high and to the left, which indicates a high accuracy level.   You may also click on the Confusion Matrix tab in the top-left, which will show you the number of True Positive and True Negatives in comparison to False Positives and False Negatives.     NOTE: The number of correct predictions is much higher than the number of incorrect predictions.   As such, we now know that our Sensors have a relatively good chance at predicting an impending failure by detecting low grease conditions before they cause catastrophic engine failure.   Refined Model   We can now compare this first Model that includes both Sensors to a Model using only Sensor 1, since we suspect that Sensor 2 may not be necessary to achieve our goal. On the left, click Analytics Builder > Models. Click New…. In the Model Name field, enter vibration_model_s1_only. In the Dataset field, select vibration_dataset.   On the right beside Excluded Fields from Model, click the Excluded Fields button.   Select s2_fb1 through s2_fb5.   While all the s2 values are selected, click the green "right-arrow", i.e. > button, in the middle.   At the bottom-left, click Save.   Click Submit. After ~60 seconds, the Model State will change to COMPLETED. With vibration_model_s1_only selected, click View….     The ROC chart is comparable to the original model (including Sensor 2).   Likewise, the Confusion Matrix (on the other tab) indicates a good ratio of correct predictions versus incorrect predictions.     NOTE: These Models may vary slightly from your own final scores, as what data is used for the prediction versus for evaluation is random.   ThingWorx Analytics’s Models have indicated that you are likely to receive roughly the same accuracy of predicting a low-grease condition whether you use one sensor or two!   If we can get an accurate early-warning of the low grease condition with just one sensor, it then becomes a business decision as to whether the extra cost of Sensor 2 is necessary.     Step 8: Next Steps   Congratulations! You've successfully completed the Build an Engine Analytical Model guide, and learned how to:   Load an IoT dataset Generate machine learning predictions Evaluate the analytics output to gain insight   The next guide in the Vehicle Predictive Pre-Failure Detection with ThingWorx Platform learning path is Manage an Engine Analytical Model.   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Analyze Operationalize an Analytics Model Build Implement Services, Events, and Subscriptions Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support Analytics Builder Help Center
View full tip
    Step 4: Implement New Features   The SMT Assembly Line Data Model was built around a sample manufacturing facility that tracks critical data points, including diagnostic information for:   motherboards assembly machines assembly line performance   To make informed decisions based on the diagnostic and performance data, you can add features that will increase analytics capabilities.   In this optional step, we'll add a Line Chart to see the performance of any given assembly machine. Once completed, we can create Services that will be used to make calculations on the data we have generated from the assembly line.   For a final challenge, you can create a service that will compare data points to identify what works best in an assembly machine, a larger internal queue, or more placement heads.   Setup New Mashup   Create a Mashup that is Responsive and name it SMTTimeSeriesMashup. Click the Layout tab and add a column to the canvas. Drag and drop a List Widget onto the left column of the layout. Drag-and-drop a Line Chart Widget onto the other column of the layout.   Configure List Widget   Add the GetImplementingThingsWithData Service of the AssemblyMachineTemplate Thing Template as a data source in the Mashup. Ensure the checkbox for Execute on Load is checked. Drag-and-drop GetImplementingThingsWithData > Returned Data > All Data to the List Widget. On the Select Binding Target pop-up, select Data.   With the List widget selected, for the DisplayField property dropdown, select name. In the ValueField property dropdown, select name.   Configure Time Series Data Add the Dynamic QueryPropertyHistory Service of the AssemblyMachineTemplate Thing Template as a data source in the Mashup. Ensure the checkbox for Execute on Load is checked. Drag-and-drop QueryPropertyHistory > Returned Data > All Data to the Time Series Chart Widget. On the Select Binding Target pop-up, select Data. For the XAxisField property dropdown, select timestamp. For the DataField1 property dropdown, select IdleTime OR MotherboardsCompleted.   Connect Widgets   Drag-and-drop the GetImplementingThingsWithData > Returned Data > Selected Row(s) > name property to the EntityName parameter for the Dynamic AssemblyMachineTemplate data source. Select the GetImplementingThingsWithData service, then drag-and-drop the SelectedRowChanged event onto QueryPropertyHistory.   Click Save. After the save is complete, click View Mashup.   You are now able to see what the idle time is for each assemble machine over the span of its use.   Create Service   You can add JavaScript code to calculate the average completion time for the motherboard assembly.   Open the MotherboardTemplate ThingTemplate in Composer. Create a new Service titled CompletionTime. For the Output type, select Number. Enter the following code into the JavaScript window and save: var diff = 1; if(me.EndTime != null && me.StartTime != null){ diff = Math.abs(me.EndTime - me.StartTime); } //Seconds var result = Math.round(diff/1000); //Minutes //var result = Math.round((diff/1000)/60);   You can now calculate the time it takes for an individual motherboard to be completed. Create a service to be used with the GetCompletedMotherboards service (returns a list of all completed Raspberry Pi motherboards) with the SMTAssemblyLineTemplate ThingTemplate to calculate the average time for your assembly line to complete a motherboard. Finish this Service and add configure it to work with your new Mashup.       Step 5: Next Steps   Congratulations! You've successfully completed the ThingWorx Monitor an SMT Assembly Line Guide, learning how to use ThingWorx to create an application that provides real-time insight into connected assets.   Learn More   We recommend the following resources to continue your learning experience:    Capability      Guide Build Design Your Data Model Build Implement Services, Events, and Subscriptions Connect Java SDK Tutorial   Additional Resources   If you have questions, issues, or need additional information, refer to:    Resource       Link Community Developer Community Forum Support Java Edge SDK Help Center
View full tip
Announcements