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

Community Tip - Need to share some code when posting a question or reply? Make sure to use the "Insert code sample" menu option. Learn more! X

IoT Tips

Sort by:
  Implement reusable Mashup Templates and Shapes in your IoT application.     Guide Concept   This guide will introduce you to creating your own advanced responsive ThingWorx user interface templace. You’ll learn some best practices and tips for creating a UI for your IoT application. With Mashup templates, you’re able to quickly and easily build pages that will look alike and have some of the same functionality already programmed.   Following the steps in this guide, you will create reusable content and develop scalable user interfaces.   We will teach you how to make UI development easier and more efficient for all of your IoT application needs.     You'll learn how to   Utilize ThingWorx using best practices for UI design Create Entities to make development faster and scalable    NOTE: The estimated time to complete this guide is 30 minutes     Step 1: Completed Example Files   Download and import GiftedReusability.xml attached to this case. Within the file you imported, you will find Entities referenced in this lesson, including a finished application. Import and utilize this file to see a finished example and return to it as a reference if you become stuck during this guide and need some extra help or clarification. Keep in mind, this download uses the exact names for entities used in this tutorial. If you would like to import this example and also create entities on your own, change the names of the entities you create.     Step 2: Create Reusable Mashup   A reusable Mashup can be embedded in another Mashup in order to enable common components. Follow the steps below to create a reusable Mashup.   In the ThingWorx Composer, click the + New at the top of the screen.   Select Mashup Template in the dropdown.   Select Responsive for the layout option. Click Ok.   Enter a name for the Mashup Template, such as MashupTemplateExample. Set the Project field (ie, PTCDefaultProject). Click Save then click Design to get to the Mashup canvas.   You've now created a Mashup template that can be utilized to create other Mashups faster and easier. After saving, you will have the regular Mashup design window as shown below.     Play around and have some fun with this new Mashup. With the Workspace view in the Default option, you can see how simple it is to add sections and layout configurations within the page. You can also see that there is functionality for adding Widgets and data to the template. Let's add containers.   Let's add some containers to our UI. This will allow for easier grouping of UI components or to allow users an easy comparison of charts and graphs.   Select the Main layout and click Add Left. Do this a second time. Select the left most container and select Add Bottom. Select the right most container and select Add Top. Select the top section that was just added and click Add Right.   You should have something like the image above. Now that you have formulated these sections, you can use the standard methods to add Widgets, styles, and data. In the Nested Container section, you can decide on how these containers should be sized as your add new sections to your page.   If you make any changes to this Mashup Template, you are then able to create new Mashups based off of this Mashup after select Responsive as the layout option. We will be making some of these changes in the next steps.       Step 3: Configure Mashup   There are two Thing Templates provided. AirHandler is a top level template with several direct implementations (FanA, FanB, FanC, etc.). There is also a HeatHandler Thing Template. This template inherits from the AirHandler Thing Template and has 2 direct implementations.   The AirHandlerTemplate Mashup can be used with either direct AirHandler implementations, or indirect implementations such as implementations of the HeatHandler Thing Template. This Mashup can also be reused further with implementations of another Thing Template.   Open the AirHandlerTemplate Mashup, which contains the layout that will be used in this example. Drag and drop a Property Display Widget onto the left column in the layout on the canvas.   Drag and drop an Image Widget onto the bottom right space of the canvas.   Drag and drop a Checkbox Widget onto the top part space of the of the canvas.   Click the + button in the Data panel.   Check the Dynamic checkbox. Select the AirHandler in the Select Entity text box. Filter for and find the GetPropertyValues service, then click the arrow.   Check the Execute on Load checkbox. Click Done.   You've just created a Mashup Template that will utilize the AirHandler entity for data and property values. This will allow you to continuously create new Mashups with a head start. In the next steps, we will connect the data values of the AirHandler template to the Widgets in the screen.         Step 4: Define Entity Parameter   Mashups come with a parameter named Entity. This parameter is a BaseType of ThingName and often used in dynamic Mashups as an input to Services or outlets of information. In our example, the Entity parameter is used to tell the Mashup which implementation of the AirHandler we should present.   With the updated AirHandlerTemplate Mashup still open, follow the directions below:   Select the Mashup in the Explorer pane. Select the Settings icon in the Widget properties panel.   The Configure Mashup Parameters pop-up will appead. Add a parameter named Entity with a Base Type of Thing Name. Select Done.   In the Mashup Property panel, drag the Entity parameter to the EntityName field of the DynamicThingTemplates_AirHandler data source.   Select All Data from the GetPropertyValues Service and drag it to the Property Display Widget. When prompted, select Data from the Select Binding Target pop-up.   Expand the All Data section of the GetPropertyValues service. Drag the FanStatus field to the Checkbox Widget. When prompted, select State from the Select Binding Target pop-up.   Drag the HandlerImage field from AllData section to the Image Widget. When prompted, select SourceURL.    With the Mashup selected in the Workspace pane. Drag the EntityChanged event from the Widget Properties panel to drop GetPropertyValues service. This ensures that the GetPropertyValues service will be called at runtime when the Mashup shows a new Entity.    Click Save.   NOTE: You can configure the Property Display Widget to display only certain properties. To do this, select the Property Display Widget in the Workspace pane, click the dropdown arrow and select Configure Widget. Uncheck the fields you do not want to see (for example, name, description, tags, and HandlerImage) and click Done.   You have just created a reusable Mashup to display information based on the particular incoming AirHandler. At this point, clicking View Mashup will not display any data. Proceed through the remainder of this exercise to connect it as a Contained Mashup.       Step 5: Use Mashup Template as Component   This HandlerExample Mashup is not a Mashup Template. It will be used later to contain a Mashup Template. It already contains the layout that will be used in the example.   Adding Service   The below steps are based on the HandlerExample Mashup. This completed version can be found in the provided download.   Create a new Mashup named Handler and add a column. Drag and drop a List Widget onto the left column of the Mashup layout.    Drag and drop a Contained Mashup Widget onto the right column of the Mashup layout. In the Name property for the Contained Mashup Widget, filter and select the AirHandlerTemplate Mashup.    Click the + button in the Data pane. Select AirHandler in the Select Entity search box. Filter for and find the GetImplementingThings service, then click the blue arrow.   Check the Execute on Load checkbox. Click Done.   Configuring Data Input   Select All Data from the GetImplementingThings service and drag it to the List Widget. When prompted, select Data.    Expand the Selected Row(s) section of the GetImplementingThings service. Drag the name field to the Contained Mashup Widget. When prompted, select Name.    Select the List Widget in the Workspace pane. In the Properties section, set the DisplayField and ValueField properties to name.    With the List Widget still selected, check the AutoSelectFirstRow property. Click Save, then View Mashup.    You will see Fans and Heaters in the list because they are both implementations for the AirHandler template. The Mashup can be used for both scenarios and will show the property fields for both. The AirHandlerTemplate can be used with other templates because it is only a Mashup Template.   Based on the properties of the other Thing Templates used with this particular template, determines whether an image will be shown in the right layout.   The FinishedExample Mashup is a finished example of this exercise.       Step 6: Next Steps   Congratulations on completing the guide!   The next guide in the Customize UI and Display Options to Deploy Applications learning path is Deploy an Application.    If you have questions, issues, or need additional information, refer to:    Resource       Link Build Application Development Tips & Tricks Community Developer Community Forum Support Help Center  
View full tip
    Step 4: Create and Implement State Definitions   A state definition is a collection of style definitions, along with rules for when to apply each style definition. The rule plus the style definition is a state.   In the HelloWorldPlayground Mashup, if the Gauge Widget goes to 10 and the Increment the Count button is clicked once again, the Gauge starts back at 0. This value change is displayed in the Line Chart when it is refreshed. Nevertheless, it would be helpful to have a way to show a user that they’re encroaching 10 and will have to restart, such as the Gauge changing colors in the section. This and many other uses is where State Definitions become useful and go hand and hand with Style Definitions.     Create Style Definition to Represent State Change   First, let’s create Style Definitions to represent the changes in the count. The default Style Definition for a Gauge is the DefaultGaugeFaceStyle Style Definition. We can simply duplicate and update the new Style Definition for our own purposes.   Filter and click the checkbox next to the DefaultGaugeFaceStyle Style Definition. Click Duplicate.   Name the Style Definition UpdatedGaugeFaceStyle. Click Style Information.   Set the Display String property as AlarmingCount. Change the Background Color to light red (color code #D60000 is used in this example).   Change the Secondary Background Color to a darker red (color code #960A0A is used in this example). The inside line of the Gauge Widget is very thin. As an additional exercise, update the Line Thickness property and/or Line Color to see the effect.     Configure State Definition   Now let’s create a State Definition that will use both the default Gauge Style Definition and the one we just created.   In the ThingWorx Composer, click the + New at the top of the screen.   Select State Definitions in the dropdown.   Set the Project (ie, PTCDefaultProject). Name the State Definition GaugeCount. Click States Information.   Set the Apply States dropdown to Numeric.   Set the following values for the default state: Property Value Operator Less than (<) Value 10 Display Name Under 10 Style DefaultGaugeFaceStyle 8. Click the Add State button to create the other states to match the below image:   9. Click Save.   You’ve now created a State Definition. If the value is below 10, the default Gauge format will be applied. Once the value reaches 10, notice the state-based changes you defined are displayed in the appearance of the Gauge.     Implement State Definition in Mashup   Update HelloWorldPlayground Mashup to incorporate the State-based formatting.   Select the Gauge Widget in the Workspace pane and click the ValueFormatter property.   Select the State-based Formatting radio button. Choose Count_Property for the Dependent Field drop-down and select the GaugeCount State Definition that we just created.   Click Done and Save the Mashup. Click View Mashup. If you used the color schemes mentioned, your new HelloWorldPlayground Mashup should look like this.   Click the Increment the Count button to see the state changes. The Gauge now displays a visual indication for when the count is approaching 10.     Enhance State Definition   To further enhance the user experience, you could add another color that warns the user in advance before the threshold is reached. For this example, we will update our State Definition and create a Style Definition that uses the color yellow.   Duplicate the UpdatedGaugeFaceStyle Style Definition.   Name the Style Definition UpdatedGaugeFaceStyle2. Click Style Information.   Set the Display String property to AlarmingYellowCount. Set the Background Color property to yellow (color code #F9EF6B is used in this example).    Set the Secondary Background Color property to a darker yellow (color code #D2CD0E is used in this example). Open the States Information tab of the GaugeCount State Definition. Update the State Definition to fit the image below and utilize the Style Definition we just created: Click Save and View Mashup to see the updated runtime appearance of the application.       Step 5: Implementing Event-Based State Changes   The State and Style Definition you just implemented enables the Gauge to show users when the data property value is approaching the defined threshold. To increase the effectiveness of your application, you can define Event Handling processes that alert the user. In this section we will explain two ways to handle the Event when the count is nearing the threshold value. One, with a Service that gets called whenever the Button Widget is clicked, and the other by using Expression Widgets.   Using a Service to Handle Events In this part of the exercise, we will configure the Mashup so that once the Count hits 9, we will display a more drastically changed Gauge.   Adding Data Service   The below sections are based on the HelloWorldPlayground Mashup.   Select the Gauge Widget in the Workspace pane. Click the Copy button in the toolbar.   Select the Container in the Workspace pane. Click the Paste button in the toolbar. If you Gauge Widgets will not go on top of one another, set the Z-index value of the new Gauge to a smaller number and set the Container Layout Position to static.   Click the green Add Service button in the Data tab next to Things_Hello_World_Thing1 to add two services from you Things_Hello_World_Thing1 Entity. NOTE: You just copied and pasted a Widget inside of a Mashup. While the Mashup retains the same property configurations and style definitions, the pasted Gauge will not have the same connections as the original Widget. You still need to define the inputs/outputs. For this new Gauge, we will only need to connect to the GetPropertyValues service. 6. Add the UnderWarningValue and WarningValueReached Services with the Execute on Load checked for both. 7. Click Done.   Binding Data and Event   With the original Gauge selected, scroll to the Visible property value. Drag and drop the UnderWarningValue service result to the Visible property.   With the new Gauge selected, scroll to the Visible property value. Drag and drop the WarningValueReached service result to the Visible property.   Select the Button Widget in the Workspace pane. Drag and drop the Clicked Event to the UnderWarningValue and WarningValueReached services.   This will ensure the other Services are run whenever the Increment the Count button is clicked.   The UnderWarningValue service will return true if the Count property is under 9. The WarningValueReached service will return true if the Count property is equal to or above 9. The result sent to the original Gauge controls whether the Gauge is visible to users or not.   You could choose to implement a pop-up, alert, or another visual indicator to the UI that would inform your application users. 7. Select the new Gauge in the Mashup or Explorer pane. 8. Clear the GaugeFaceStyle Style Definition and replace it with the DefaultChartStyle11.   9. Click Save and View Mashup to see the changes. Using Expression Widgets to Handle Events   Expression Widgets are a great asset to handle information being passed around inside of a Mashup and also events occurring within a Mashup. In this scenario, we will use the Count property value to create changes in the UI.   Setup Expression Widget   In the Functions Tab in the bottom right. Add a new function.   Set the Function Type to Expression and name it HighCount.   Click Next Click Add Parameter and add a Count (Number) parameter. Set the Expression property to output = Count >= 9;.   Check the Auto Evaluate and Fire on First Value checkboxes. Click Done.     Bind and Evaluate Event   In the Functions Tab in the bottom right, click the bind button of our new Function.   Click the dropdown by the Count input parameter. Click Add Source.   Select Data, then the Count_Property from the GetPropertyValues service.   Redo the past steps for a second Function. Name this function GaugeVisibility with a parameter of type Boolean with the name Visibility. Update the second Expression Widget’s Expression property to output = Visibility != true;. Ensure the checkboxes are checked and bind to the output of our last Function.   Connect the output of this Function to the second Gauge. Click Save and View Mashup.   NOTE: Move the Gauges from on top of one another if necessary to set values and parameters. The first Expression will show the newest Gauge Widget when Count hits 9. The other Expression Widget will show the original Gauge based on the evaluation of the first Expression Widget results.   Click the Increment the Count button to see how the display changes in the Mashup at runtime.   Step 6: Next Steps   The next guide in the Customize UI and Display Options to Deploy Applications learning path is 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 Style & Themes Help Center  
View full tip
Build, customize, and deploy IoT applications with ThingWorx.   NOTE: Complete the following guides in sequential order. The estimated time to complete this learning path is 270 minutes.   1. Create Your Application UI  Part 1 Part 2 Part 3 Part 4 Part 5 2. Basic Mashup Widgets  Part 1 Part 2 Part 3 3. Define Your UI Style  Part 1 Part 2 4. Object-Oriented UI Design Tips 5. Deploy an Application 6. How to Display Data in Charts  Part 1 Part 2 Part 3
View full tip
  Create Your Application Guide UI Part 5    Step 7: Test Your GUI   At this point in the lesson, your Mashup now contains: Graphics to represent data Data Logical connections between the graphical elements and the data   Run Application   Execute the following steps to test that your application works as expected. Click the View Mashup button at the top. You may have to disable your pop-up blocker to load the Mashup in a new browser tab.   2. Wait and observe the Mashup for at least 20 seconds, clicking the Manually Retrieve Counts button regularly. NOTE: The values in the Mashup will increase roughly every 10 seconds, after you press the button to manually retrieve them. This happens because the Thing you imported earlier is simulating data and the work already done by the Edge and Backend Developers in this scenario. In this simulation, different production lines are continually producing new inventory, and that information is being fed into ThingWorx Foundation. As the count for each production line reaches 100, the batch is shipped out, and the count resets to 0 for the next iteration. 3. Check the Gears Manually Set Checkbox, change the Gears Count Text Field to read 7, and click the Manually Set Counts button. After 10+ seconds have passed, click the Manually Retrieve Counts button again. NOTE: This simulates a situation where an IoT sensors in the inventory warehouse has failed. Maybe it's over or under-counting inventory. Maybe there's a network issue. Maybe the sensor has simply stopped working entirely. Regardless, the warehouse floor has contacted a user of your GUI, and asked them to manually set the inventory to the correct amount. Performing Step 4 is all that is required to do so. As long as the Gears Manually Set checkbox is active, the inventory does not increase on the 10 second timer. This is to prevent a malfunctioning sensor from providing incorrect data to your GUI. 4. Uncheck the Gears Manually Set Checkbox and click Manually Set Counts. NOTE: The Gears Count starts increasing again after 10 seconds have passed. Remember to click the Manually Retrieve Counts button to see this change. This represents the previously-malfunctioning IoT sensor having been repaired.   Spend some time interacting with your Mashup GUI to get a better sense of its functionality. For the purposes of this exercise, this is a Minimum Viable Product. After testing it and getting feedback from your users, you would likely make further enhancements.   Collect Feedback   When testing your GUI, it is a best practice to collect feedback from users regarding your design, so that you can improve the experience with your application. Example User Feedback Possible Resolution Manually Set Counts button is too easy to accidentally press. Implement a Confirmation pop-up. Manually Retrieve Counts button is not ideal, should automate Remove the manual button and implement auto-update functionality instead. Manually Set Checkboxes have confusing names. Change the text to read Disabled, indicating that the sensor-input is being ignored. User wants to use your GUI on their smartphone and on a desktop computer. Re-implement the GUI using a Responsive (rather than Static) Mashup, so that there isn’t as much dead space on larger-resolution screens. User wants a visual indication of each inventory line amount at which the pallet is shipped out. Instead of using TextBoxes to show the current inventory counts, you could implement them as Gauges, showing a minimum and maximum amount that is easy to see at-a-glance.   Now that we've gotten some feedback, let's implement one such change-request as an example.   Enhance your GUI   Set up GetProperties to automatically update whenever data changes instead of using a button to manually retrieve the data. Close your MVP Mashup browser-tab and return to the Mashup Builder. Click the button-manual-retrieve Widget to select it.   Hit your keyboard's Delete key.   Click Yes in the Remove the selected widgets? pop-up window.   Click the green </> button beside Things_MBQSThing in the top-right Data tab.   6. In the Services Filter field, type getprop. 7. Click the right-arrow beside GetProperties. Be sure to select GetProperties, not GetPropertyValues. 8. Check the Execute on Load checkbox. 9. Click Done. 10. In the Data tab on the top-right, expand the newly-added GetProperties Service. 11. Drag-and-drop Gears_Count onto textbox-gears-count. 12. On the Select Binding Target popup, click Text. 13. On the Confirm Binding Replace pop-up, click Yes. 14. Repeat steps 11-13 for Pistons_Count and Wheels_Count onto their respective TextBox Widgets. 15. Drag-and-drop Gears_Count_Manually_Set onto checkbox-gears-manual. 16. On the Select Binding Target popup, click State. 17. On the Confirm Binding Replace pop-up, click Yes. 18. Repeat steps 15-17 for Pistons_Count_Manually_Set and Wheels_Count_Manually_Set onto their respective Checkboxes. 19. Click the GetProperties Service to select it. 20. In the bottom-right Data Properties section, check the Automatically update values when able box. 21. Click Save. 22. Click View Mashup.   You have now enhanced your MVP Mashup based on user feedback. The Counts in each TextBox will automatically update whenever there is a change in the Property values, as requested. ThingWorx Foundation provides a platform that allows you to quickly create a GUI for your IoT application in an extremely flexible and agile manner. The options to continue to improve your GUI are entirely up to you.   Step 8: Next Steps   Congratulations! You've successfully completed the Create Your Application UI guide, and learned how to: Create new Mashups Choose a Static or Responsive layout Add Widgets to your Mashup Bind data Services to Widgets in your Mashup Create a functional GUI with applied usage of Widgets and Service   The next guide in the Customize UI and Display Options to Deploy Applications learning path is Basic Mashup Widgets.    Learn More   We recommend the following resources to continue your learning experience: Capability Guide Build Data Model Introduction   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 8: Tasks If you are using the built-in Tasker to drive data collection or other types of repetitive or periodic activities, create a function for the task. Task functions are registered with the Tasker and then called at the rate specified after they are registered. The Tasker is a very simple, cooperative multitasker, so these functions should not take long to return and most certainly must not go into an infinite loop. The signature for a task function is found in [C SDK HOME DIR]/src/utils/twTasker.h. The function is passed a DATETIME value with the current time and a void pointer that is passed into the Tasker when the task is registered. After creating this function, it will need to be registered using the twApi_CreateTask function after the connection is created. Below shows an example of creating this function, registering this function, and how this function can be used. #define DATA_COLLECTION_RATE_MSEC 2000 void dataCollectionTask(DATETIME now, void * params) { /* TW_LOG(TW_TRACE,"dataCollectionTask: Executing"); */ properties.TotalFlow = rand()/(RAND_MAX/10.0); properties.Pressure = 18 + rand()/(RAND_MAX/5.0); properties.Location.latitude = properties.Location.latitude + ((double)(rand() - RAND_MAX))/RAND_MAX/5; properties.Location.longitude = properties.Location.longitude + ((double)(rand() - RAND_MAX))/RAND_MAX/5; properties.Temperature = 400 + rand()/(RAND_MAX/40); /* Check for a fault. Only do something if we haven't already */ if (properties.Temperature > properties.TemperatureLimit && properties.FaultStatus == FALSE) { twInfoTable * faultData = 0; char msg[140]; properties.FaultStatus = TRUE; properties.InletValve = TRUE; sprintf(msg,"%s Temperature %2f exceeds threshold of %2f", thingName, properties.Temperature, properties.TemperatureLimit); faultData = twInfoTable_CreateFromString("message", msg, TRUE); twApi_FireEvent(TW_THING, thingName, "SteamSensorFault", faultData, -1, TRUE); twInfoTable_Delete(faultData); } /* Update the properties on the server */ sendPropertyUpdate(); } … twApi_CreateTask(DATA_COLLECTION_RATE_MSEC, dataCollectionTask); … while(1) { char in = 0; #ifndef ENABLE_TASKER DATETIME now = twGetSystemTime(TRUE); twApi_TaskerFunction(now, NULL); twMessageHandler_msgHandlerTask(now, NULL); if (twTimeGreaterThan(now, nextDataCollectionTime)) { dataCollectionTask(now, NULL); nextDataCollectionTime = twAddMilliseconds(now, DATA_COLLECTION_RATE_MSEC); } #else in = getch(); if (in == 'q') break; else printf("\n"); #endif twSleepMsec(5); }   Step 9: File Transfer Example To handle file transfers, a virtual directory is created in the SteamSensor1 entity and in the [C SDK HOME DIR]/examples/FileTransferExample application directory. The source code used for this example is found in [C SDK HOME DIR]/examples/FileTransferExample/src/main.c. Inside of the [C SDK HOME DIR]/examples/FileTransferExample folder, create the folder structure shown below: /transfer/ /transfer/incoming/ /transfer/outgoing/ Inside of the /transfer/outgoing/ directory, create and open a file with the name outgoing.txt. Once the outgoing.txt document is open, add the following text, save, and close the file: Hello. This is a file coming from the client application. Navigate to the [C SDK HOME DIR]/examples/FileTransferExample/src/main.c code and update the lines below with the appropriate information for your IP, port, and the “admin_key” Application Key’s keyId value in the ThingWorx Composer: /* Server Details */ #define TW_HOST "127.0.0.1" #define TW_PORT 80 #define TW_APP_KEY "ce22e9e4-2834-419c-9656-ef9f844c784c" To support file transfers in your client application, you must use the twFileManager_AddVirtualDir function in order to create the virtual directories in the entity with such a capability. It will also define the directories available for file operations. A virtual directory maps a unique name to an absolute path of a directory in the file system. All subdirectories of the specified directory are exposed to the server. You can define multiple virtual directories. The directories do not need to be contiguous.   Staging Directory As an optional, but recommended step, you should set the directory that the application should use for staging when performing file transfers. This can be seen in the line below and should be done before initializing the FileManager. The default directory of the FileManager is most likely owned by root and will require a change to either the location of the staging directory and the ownership of the staging directory, or running the application as a User with the correct permissions. twcfg.file_xfer_staging_dir = "staging"; The example provided uses the TW_SHARE_DIRECTORY macro to create two virtual directories that will act as the root directories in the virtual file system of this application are added. The client is then started as follows with the necessary TW_ADD_FILE_TRANSFER_SHAPE function being called: TW_ADD_FILE_TRANSFER_SHAPE(); TW_SHARE_DIRECTORY("in", "/transfer/incoming/"); TW_SHARE_DIRECTORY("out", "/transfer/outgoing/"); The creations of the payloads used to create the remote directories on the platform have been moved to a helper function below to make the design cleaner: int setupSystemRepo(const char * remoteInPath, const char * remoteOutPath, const char * remoteFile); After our remote directories and files have been setup, it is time to perform the file transfers. Normally, this would mean invoking the Copy service for a Subsystem, but two functions have been created to make this process easier: int twFileManager_GetFile(const char * sourceRepo, const char * sourcePath, const char * sourceFile, const char * targetRepo, const char * targetPath, const char * targetFile, uint32_t timeout, char asynch, char ** tid) int twFileManager_SendFile(const char * sourceRepo, const char * sourcePath, const char * sourceFile, const char * targetRepo, const char * targetPath, const char * targetFile, uint32_t timeout, char asynch, char ** tid) The table below displays an example of the first set of parameters:   Parameter     Example                              Description sourceRepo SystemRepository The name of FileRepository or RemoteThing to transfer the file FROM. sourcePath outgoing The path specifying the location of the source file. sourceFile The name of the source file.   targetRepo SteamSensor1 The name of FileRepository or RemoteThing to transfer the file TO. targetPath incoming The path specifying the destination location of the file. targetFile incoming.txt The name of the file at the target. This name can differ from the sourceName. timeout 15,000 The amount of time (in seconds) to wait for a synchronous transfer to complete before cancelling the transfer. async false If false, the service call will block for timeout seconds or until the transfer completes. tid incoming0123 The unique TID associated with the file.   The C SDK also provides the ability to create a FileCallback function that the FileManager will call that function when any file transfer events occur. You can provide a wildcard filter so that only file transfer Events of files that match the filter call the callback function. In addition, callbacks can be set up as “one-shots” such that the callback is unregistered automatically after it is invoked the first time.   NOTE: An optional file transfer callback is registered in the code and provided. You will see the output from the function as files are sent and received.   After running this application, you will notice a new file in the transfer/incoming folder after refreshing. This is the file that we created in the ThingWorx Composer file system for the SystemRepository Entity and was able to copy from that location to our local project. We have also sent a file to the server’s SystemRepository. The BrowseFileSystem and GetFileListing services can be used to check for the folders and files created. twFileManager_RegisterFileCallback(fileCallbackFunc, NULL, FALSE, NULL);   Step 10: Support Other Platforms All Websocket errors indicate some general issue communicating with the ThingWorx platform. If you experience an issue connecting, refer to the table below for a list of websocket errors, their corresponding codes, and an explanation of the issue.   Code   Message                                                                       Troubleshooting 200 TW_UNKNOWN_WEBSOCKET_ERROR An unknown error occurred on the websocket. 201 TW_ERROR_INITIALIZING_WEBSOCKET An error occurred while initializing the websocket. Check your websocket configuration parameters for validity. 202 TW_TIMEOUT_INITIALIZING_WEBSOCKET A timeout occurred while initializing the websocket. Check the status of the connection to ThingWorx. 203 TW_WEBSOCKET_NOT_CONNECTED The websocket is not connected to ThingWorx. The requested operation cannot be performed. 204 TW_ERROR_PARSING_WEBSOCKET_DATA An error occurred while parsing websocket data. The parser could not break down the data from the websocket. 205 TW_ERROR_READING_FROM_WEBSOCKET An error occurred while reading data from the websocket. Retry the read operation. If necessary, resend the data. 206 TW_WEBSOCKET_FRAME_TOO_LARGE The SDK is attempting to send a websocket frame that is too large. The Maximum Frame Size is set when calling twAPI_Initialize and should always be set to the Message Chunk Size (twcfg.message_chunk_size). 207 TW_INVALID_WEBSOCKET_FRAME_TYPE The type of the frame coming in over the websocket is invalid. 208 TW_WEBSOCKET_MSG_TOO_LARGE The application is attempting to send a message that has been broken up in to chunks that are too large to fit in a frame. You should not see this error. 209 TW_ERROR_WRITING_TO_WEBSOCKET An error occurred while writing to the Web socket. 210 TW_INVALID_ACCEPT_KEY The Accept key sent earlier from ThingWorx is not valid.   Next Steps Congratulations! You've successfully completed the C SDK Tutorial, and learned how to utilize the resources provided in the Edge SDK to create your own application.   This is the last guide in the Connect and Configure Industrial Devices and Systems Learning Path.  If you wish to return to the Learning Path, click the link.   Additional Resources If you have questions, issues, or need additional information, refer to:  Resource Link Community Developer Community Forum Support C Edge SDK Help Center
View full tip
    Step 9: File Transfer    To handle file transfers, create a virtual directory in the FileTransferExample Entity and in the project directory. The source code used for this example is found in com.thingworx.sdk.examples.FileTransferExample.java.   Set Up File Transfer   Right-click the project. Click New. Scroll and select Folder. Enter transfer/incoming into the text box at the bottom. Click Finish. Repeat steps 1 and 2, but create a folder called transfer/outgoing. Right-click the transfer/outgoing folder. Click New. Scroll and select File. Create a file with the name outgoing.txt. Click Finish. Once the outgoing.txt document is open, add the following text, click Save, and close the file: Hello. This is a file coming from the client application. Navigate to the FileTransferExample.java code and update the lines below with the appropriate information for your IP, port, and the admin_key Application Key’skeyId value in Composer: config.setUri("ws://127.0.0.1:80/Thingworx/WS"); config.setAppKey("ce22e9e4-2834-419c-9656-ef9f844c784c"); NOTE: Step 7 is only used for a time constraint of this guide. Best practice is to never use an Application Key for the Administrator. Provide a User with the necessary privileges and add an Application Key to that User.   FileTransferExampleHelper Methods   To support file transfers in your client application, you must use a FileTransferVirtualThing to enable the functionality and define the directories available for file operations. A virtual directory maps a unique name to an absolute path of a directory in the file system. All subdirectories of the specified directory are exposed to the server. You can define multiple virtual directories. The directories do not need to be contiguous.   The example provided creates the FileTransferVirtualThing with two virtual directories that will act as the root directories in the virtual file system of this application are added. The client is then started as follows:   All of the creations of the payloads have been moved to a helper class (FileTransferExampleHelper.java) to make the design cleaner.   The below table provides insight into some of the helper methods created to separate roles for a cleaner solution.   Method Purpose createSystemRepositoryIncomingPath Create the payload for the call to create the “incoming” directory on the SystemRepository in the ThingWorx Platform. createSystemRepositoryOutgoingPath Create the payload for the call to create the “outgoing” directory on the SystemRepository in the ThingWorx Platform. createTransferIncomingParameters Create the payload for the call to copy a file into the incoming directory on the FileTransferExample Thing in the ThingWorx Platform and the provided client application. createTransferOutgoingParameters Create the payload for the call to copy a file from the outgoing directory in the provided client application to the SystemRepository on the ThingWorx Platform.     Service Parameters   Once the connection is made, the script will call the four services. Here, we instruct the server to move the files from one repository to another.   Parameter Example Description sourceRepo “SystemRepository” The name of a FileRepository or RemoteThingWithFileTransfer Thing to transfer the file from. sourcePath “/outgoing” The path specifying the location in the file repository of the source file. sourceFile “example.txt” The name of the source file. targetRepo FileTransferExample The name of a FileRepository or RemoteThingWithFileTransfer Thing to transfer the file to. targetPath “in” The path specifying the destination location of the file. targetFile “example.txt” The name of the file at the target location. This name can differ from the sourceName parameter. timeout 15000 The amount of time to wait for the synchronous transfer to complete (seconds) before cancelling the transfer. async false If false, the service call will block for the length specified by the “timeout” parameter or until it completes.     After running this application, you will notice a new file in the transfer/incoming folder after refreshing. This is the file that we created in the ThingWorx Composer file system for the SystemRepository Entity and was copied from that location to our local project. We have also sent a file to the server’s SystemRepository. The BrowseFileSystem and GetFileListing Services can be used to check for the folders and files created.       Step 10: Troubleshooting   All Websocket errors indicate some general issue communicating with the ThingWorx platform. If you experience an issue connecting, refer to the table below for a list of websocket errors, their corresponding codes, and an explanation of the issue.   Code Message Troubleshooting 200 TW_UNKNOWN_WEBSOCKET_ERROR An unknown error occurred on the websocket. 201 TW_ERROR_INITIALIZING_WEBSOCKET An error occurred while initializing the websocket. Check your websocket configuration parameters for validity. 202 TW_TIMEOUT_INITIALIZING_WEBSOCKET A timeout occurred while initializing the websocket. Check the status of the connection to ThingWorx. 203 TW_WEBSOCKET_NOT_CONNECTED The websocket is not connected to ThingWorx. The requested operation cannot be performed. 204 TW_ERROR_PARSING_WEBSOCKET_DATA An error occurred while parsing websocket data. The parser could not break down the data from the websocket. 205 TW_ERROR_READING_FROM_WEBSOCKET An error occurred while reading data from the websocket. Retry the read operation. If necessary, resend the data. 206 TW_WEBSOCKET_FRAME_TOO_LARGE The SDK is attempting to send a websocket frame that is too large. The Maximum Frame Size is set when calling twAPI_Initialize and should always be set to the Message Chunk Size (twcfg.message_chunk_size). 207 TW_INVALID_WEBSOCKET_FRAME_TYPE The type of the frame coming in over the websocket is invalid. 208 TW_WEBSOCKET_MSG_TOO_LARGE The application is attempting to send a message that has been broken up in to chunks that are too large to fit in a frame. You should not see this error. 209 TW_ERROR_WRITING_TO_WEBSOCKET An error occurred while writing to the Web socket. 210 TW_INVALID_ACCEPT_KEY The Accept key sent earlier from ThingWorx is not valid.       Step 11: Tunneling Example    To handle file transfers, a virtual directory is created in the TunnelExample Entity and in the project directory. The source code used for this example is in com.thingworx.sdk.examples.TunnelExample.java.   To enable tunneling, create the configurations like other steps, and then either invoke ClientConfigurator.tunnelsEnabled(true), or set the tunnelsEnabled directive in your config file.   Once it connects to the server, this client binds thingName to the matching RemoteThingWithTunnels defined on the ThingWorx Platform. Once bound, the Thing can receive tunnel requests from the Platform, and facilitate tunnels to local applications.     Step 12: Next Steps    Congratulations! You've successfully completed the Java SDK Tutorial, and learned how to utilize the resources provided in the Java SDK create your own application.   The next guide in the Connect and Configure Industrial Devices and Systems learning path is C SDK Tutorial.   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 Support Java Edge SDK Help Center    
View full tip
  Step 11: Users   Access to functions and information on the ThingWorx Foundation server is controlled by Users. The REST API can be used to create, list, and delete Users.   Get Usernames of all Users   The REST API exposes the ability to retrieve collections of Entities so that a UI can be dynamically updated with current data.   Required Parameters   AppKey created by your Foundation server Request   Construct the URL. Include the hostname and authentication credentials for your specific ThingWorx server as described below. The Usernames of all Users can be returned by making a GET request to this endpoint: 〈Server IP:port〉/Thingworx/Users Authenticate Request. All API requests to the ThingWorx server must be authenticated either with a username and password or with an appKey. For this example we will authenticate by passing the appKey as a URL query string parameter. The parameter appKey is recognized by the ThingWorx server as an authentication credential in requests, it can be passed either as a URL query string parameter .../CreateThing?appKey=64b87... , or as request header appKey: 64b87... Send request parameters. Other than authentication, no other parameters are used in this GET request. Response   It is possible for the content to be returned in four different formats by sending an Accept header with the request.   Desired Response Type  Accept Header Values JSON application/json XML text/xml HTML text/html (or omit Accept Header) CSV text/csv   HTTPie example:   http -v -j http://52.201.57.6/Thingworx/Users appKey==64b879ae-2455-4d8d-b840-5f5541a799ae Accept:text/csv       Step 12: Troubleshooting   You should expect to get back the status code of 200 - OK either with or without content. In the case of an error, you will receive an error message. You can use the following table to diagnose the issue.   Response Code Definition  401 - Unauthorized appKey is incorrect or missing 403 - Forbidden Content-Type request header is not set to application/json Sometimes returned instead of a 404 A Property with that name already exists on the platform 404 - Not Found Incorrect URL or API endpoint Thing or Property has not been created Incorrect ThingTemplate name Required parameter missing from request 405 - Invalid Request Incorrect request verb; for example a GET was used instead of PUT or POST 406 - Not Acceptable Invalid JSON in PUT or POST request Thing [ Thing name ] already exists: A Thing with that name already exists on the platform 500 - Internal Server Error Content-Type request header is not set for a service execution POST, required even without a POST body Content-Type request header is not set for DELETE request, required despite the fact that DELETE does not send any content 503 - Service Unavailable Thing [] is not running RestartThing endpoint must be called Thing [] is not enabled EnableThing endpoint must be called       Step 13: Authentication Tags   There are different ways to authorize requests.   AppKey in HTTP Request Header   We recommend you place the appKey in the HTTP request header rather than passing the appKey as a URL parameter. This prevents the appKey from being written into server log files that may be seen by someone who is not authorized to modify the ThingWorx server.   HTTPie example:   http -v -j http://iotboston.com:8887/Thingworx/Things/aTestThing/Properties/CurrentTemp appKey:d0a68eff-2cb4-4327-81ea-7e71e26 Full request headers:   GET /Thingworx/Things/AllenTestThingFour/Properties/CurrentTemp HTTP/1.1 Accept: application/json, */* Accept-Encoding: gzip, deflate Connection: keep-alive Content-Type: application/json Host: iotboston.com:8887 appKey: d0a68eff-2cb4-4327-81ea-7e71e26bb   AppKey In URL as Parameter   To send an appkey in a URL request string parameter, check the Allow Application Key as URL Parameter checkbox in the PlatformSubsystem Configuration. If the ThingWorx server is using HTTPS, the parameter will be encrypted in transit, however the appKey may be comprised because full request URLs are often written to server log files.   HTTPie example:   http -v -j http://iotboston.com:8887/Thingworx/Things/AllenTestThingFour/Properties/CurrentTemp appKey==d0a68eff-2cb4-4327-81ea-7e71e26bb645 Full request headers:   GET /Thingworx/Things/aTestThing/Properties/CurrentTemp?appKey=d0a68eff-2cb4-4327-81ea-7e71e26 HTTP/1.1 Accept: application/json, */* Accept-Encoding: gzip, deflate Connection: keep-alive Content-Type: application/json Host: iotboston.com:8887   HTTP Basic Auth   We do not recommend Basic Auth, because the username and password used are NOT encrypted and could be used to log into the ThingWorx platform. To demonstrate that username and password are not encrypted, copy the string in the Authorization line after Basic to Base64 Decode then click DECODE.   HTTPie example:   http -v -j http://iotboston.com:8887/Thingworx/Things/aTestThing/Properties/CurrentTemp -a Administrator:password1 Full request headers:   GET /Thingworx/Things/AllenTestThingFour/Properties/CurrentTemp HTTP/1.1 Accept: application/json, */* Accept-Encoding: gzip, deflate Authorization: Basic QWRtaW5pc3RyYXRvcjpwYXNzd29yZDE= Connection: keep-alive Content-Type: application/json Host: iotboston.com:8887     Step 14: Next Steps   Congratulations! You've successfully completed the Use REST API to Access ThingWorx guide. You learned how to use the REST API to:   Create new Things on a ThingWorx Foundation Server Add Properties to Things Access Property values Execute custom Services   The next guide in the Connect and Configure Industrial Devices and Systems learning path is Java SDK Tutorial.   Learn More   We recommend the following resources to continue your learning experience:      Capability Guide Build Data Model Introduction   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource    Link Community Developer Community Forum Support REST API Help Center    
View full tip
Configure Permissions Guide Part 2   Step 5: Permissions   These permissions can be accessed on any Entity created on the platform. All Entities have permission control for both design time and run time. Permission Time Control Design time Controls what Users are able to do with Entities themselves while building the solution. Run time Controls what the Users are able to do with the data for an Entity when they use the solution.   Permission Type Description Property Read Read property values Property Write Update property values Service Execute Execute Services in this Entity Event Execute Queue or fire Events in this Entity Event Subscribe Ability to subscribe to Events in this Entity   Access Type Description Allow Allow the User's access to this feature. Deny Deny the User's access to this feature. Inherit Set the User's access to this feature based on permissions in Entities this Entity is based on or the configurations at a higher level.   Add Permissions for an Entity   Once an Entity has been selected for editing, select the Permissions tab. Based on what you would like to edit, select the Visibility, Design Time or Run Time tab. The All Properties, Services, and Events section provides blanket security to all of these features for a User Group or User. The Property, Service, or Event Overrides section is used for any overrides that need to be made for specific features. In the example blow, the User a.jones has the ability to read properties, fire events, and subscribe to events. The User does not have the ability to update a property or execute a Service. In the second section, a.jones is allowed to call the GetConfigurationTable Service (even though he was restricted from doing so in the other section).   To set a permission, filter and select a User/User Group. When their name is in the table, click the Permission Type you would like for this Entity. Default permissions are added to the User or User Group you filtered and selected. This will be full access permissions unless you've changed one of the fields.   Set Permissions Programmatically   In some cases it will be useful to set permissions using a programmable interface. This can be done through a built-in set of services which can be accessed in many different ways including: Internal service call through an entity’s service Service call using the extension framework, or REST API call to a service on the platform. The following is a list of services built into all entities on the platform. Service Name Description AddDesignTimePermission Adds a new design time permission AddRunTimePermission Adds a new run time permission CheckDesignTimePermission Checks to see if an entity has a specific design time permission for the current User CheckDesignTimePermissionForGroup Checks to see if an entity has a specific design time permission for a given User Group CheckDesignTimePermissionForUser Checks to see if an entity has a specific design time permission for a given User CheckPermission Checks to see if the entity has a specific run time permission for the current User CheckTimePermissionForGroup Checks to see if the entity has a specific run time permission for a given User Group CheckDesignTimePermissionForUser Checks to see if the entity has a specific run time permission for a given User DeleteDesignTimePermission Delete a design time permission DeleteRunTimePermission Delete a run time permission GetDesignTimePermission Get a list of design time permissions in Info Table format GetDesignTimePermissionAsJSON Get a list of design time permissions in JSON format GetPermissionsForCurrentUser Get the run time permissions for the current User GetPermissionsForGroup Get the run time permissions for a given User Group GetPermissionsForUser Get the run time permissions for a given User GetRunTimePermissions Get a list of assigned run time permissions in Info Table format GetRunTimePermissionAsJSON Get a list of assigned run time permissions in JSON form SetDesignTimePermissionAsJSON Sets all of the run time permissions for a given Entity to the given JSON list You may want to apply a set of permissions to a large group of Entities at once. This can be done using either the projects or the tags feature on the platform through the EntityServices resource. The EntityServices resource has many useful services in it, but for the purpose of this section, we will only talk about the run time permission service. This will act on all entities with the provided tags or assigned to the given project. Service Name Description SetEntityPermission Sets run time permissions for a set of Entities   Step 6: Application Keys   Application Keys   Application Keys or appKeys are security tokens used for authentication in ThingWorx when not using a standard credentials method of authentication. They are associated with a given user and have all of the permissions granted to the user to which they are associated.   Create an Application Key   Using the Application Key for the default user (Administrator) is not recommended. If administrative access is absolutely necessary, create a user and place the user as a member of the SecurityAdministrators and Administrators user groups. Create the User the Application Key will be assigned to. On the Home screen of Composer click + New. In the dropdown list, click Applications Keys. Use MyAppKey  for the name your Application Key. Set the User Name Reference to a User you created and set the Project field (ie, PTCDefaultProject). The Expiration Date field will default to 1 day. Click Save. A Key ID has been generated and can be used to make secure connections.   IP Whitelisting for Application Keys   One of the features of an Application Key is the ability to set an IP whitelist. This allows the server to specify that only certain IP addresses should be able to use a given Key ID for access. This is a great way to lock down security on the platform for anything that will maintain a static IP address. For example, connected Web-based business systems may have a static IP from which all calls should be made. Similarly, you can use wildcards to specify a network to narrow the range of IP addresses allowed while still offering some flexibility for devices with dynamic IP addresses. Extremely mobile devices should likely not attempt to implement this however as they will often change networks and IP addresses and may lose the ability to connect when the IP whitelist feature is used.   Interact with Application Keys Programmatically   Service Name Description GetKeyID Returns the ID of this application key GetUserName Get the user name associated with this application key IsExpired Returns if this application key is expired ResetExpirationDateToDefault Resets the expiration date of the application key to the default time based on configuration in the UserManagement subsystem SetClientName Sets the client name for this application key SetExpirationDate Sets the expiration date of this application key to a provided date SetIPWhiteList Sets the values for the IP whitelist for this application key SetUserName Sets the associated user name for this application key TIP: To learn more about Application Keys, refer to the Create an Application Key Guide.   Step 7: Organizations   Organizations are hierarchical structures that allow the user to assign visibility to entities in the ThingWorx Model. This model provides the top down structure from the highest level in an organization or department, to the lower levels of said entity. Each level within this structure also allows for users and groups to be added. This provides a greater level of customization to resources within the ThingWorx Composer.   Create an Organization In the ThingWorx Composer, click the + New at the top of the screen. Select Organization in the dropdown. Name your Organization Constructors. Set the Project field (ie, PTCDefaultProject) and click Save Select the Organization tab to see the hierarchy. With the top organization selected, in the Members search bar, search for the user you have created yourself and add them.   Create Organizational Units   Click the green + under the structure you would like to expand. Name your Organization unit UpperManagement. In the Members search bar, search for the user or user group you created and add it. Click Save. Repeat the steps to create the full heirarchy of the organization and its department/unit members.   Setup Entity Visibility   ThingWorx provides added security checks and access control with Entity visibility. Visibility ensures an entity is accessible to members of an organizational unit. Those members will then have access to the entity and the underlying security model determines what specific interaction any users that are members of that organization unit may have with a specific asset. If a user in the system is not granted visibility, then that asset essentially does not exist within that user’s domain. Select the Permissions tab of any custom Thing in Composer. Filter and select Constructors in the Search Organizations field. Click Save. Login Pages for Organization   Creating an Organization automatically creates a login page for you. If you would like to add more to this login screen and customize it to fit your needs, create a Mashup and set it to the Organization's Home Mashup field. If you plan to use a Login Screen, use the View Mashup URL generated from the Login Mashup you create. To view the login page of your application (whether custom or default), type the following URL: [server]/Thingworx/FormLogin/ (ie, localhost/Thingworx/FormLogin/Constructors).     Step 8: Next Steps   Congratulations! You've successfully completed the Configure Permissions guide, and learned how to: Configure and utilize the user access system Control permissions at design time and run time   The next guide in the Getting Started on the ThingWorx Platform learning path is Build a Predictive Analytics Model.    If you are completing the Connect and Configure Industrial Devices and Systems learning path, the next guide is Choose a Connectivity Method.   Learn More   We recommend the following resources to continue your learning experience: Capability Guide Build Design Your Data Model   Additional Resources   If you have questions, issues, or need additional information, refer to: Resource Link Support Help Center    
View full tip
Configure and connect industrial devices and systems in any environment.   NOTE: Complete the following guides in sequential order. The estimated time to complete this learning path is 180 minutes.   1. Configure Permissions  Part 1 Part 2 2. Choose a Connectivity Method 3. Use REST API to Access ThingWorx  Part 1 Part 2 Part 3 Part 4 4. Java SDK Tutorial  Part 1 Part 2 Part 3 Part 4 Part 5 5. C SDK Tutorial  Part 1 Part 2 Part 3 Part 4
View full tip
    Use Thing Shapes to create groups of related Properties   Guide Concept   Save time and effort by modeling a solution in ThingWorx using Thing Shapes to group Properties. A logical group of Properties can be applied to Things and Thing Templates.     You'll learn how to   Create a Thing Shape Add Properties to a Thing Shape   NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete this guide is 30 minutes       Step 1: Create Thing Shape   In this section you will create a Thing Shape for sensor properties of a MXChip development board.   Thing Shapes are components that contain Properties and Services. In Java programming terms, they are similar to an interface.   Start on the Browse folder icon of ThingWorx Composer. Under the Modeling section of the left-hand navigation panel hover over Thing Shapes, then click the + button.   Type ThermostatShape in the Name field.   If Project is not already set, click the + in the Project text box and select the PTCDefaultProject. Click Save.     Step 2: Add Properties to Thing Shape   Click Properties and Alerts tab at the top of your Thing Shape.   Click + Add. Enter the Property name in the Name field as shown in the table below. Name Base     Type           Persistent?       Logged? humidity NUMBER   X messageId STRING X   temperature NUMBER   X Select the appropriate Base Type from the drop-down menu.   Check Persistent and/or Logged according to the table. NOTE: When Persistent is selected, the property value will be retained during a system restart. Properties that are not persisted will be reset to the default during a system restart. When Logged is selected, every property value change will be automatically logged to a specified Value Stream. Click Check +. TIP: When adding multiple properties at once, click Done and Add after each, once you've entered a Name, selected a Base Type and any other criteria. If adding a single property, click Done. Repeat steps 4 through 6 for each of the properties in the rows of the table. Click the done Check. You'll see that these Properties have been created for the ThermostatShape.   Click Save.     Step 3: Next Steps   Congratulations! You've successfully completed the Create A Thing Shape, and learned how to: Create a new Thing Shape Add Properties to the Thing Shape   This is the last guide in the Azure MXChip Development Kit Learning Path.  If you wish to return to the Learning Path, click the link.   Learn More   The following resources continue your learning experience:  Resource       Link Build Data Model Introduction 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 Thing Shape Support Help Center      
View full tip
Send data from MXChip development board to ThingWorx with Azure IoT hub   NOTE: Complete the following guides in sequential order. The estimated time to complete this learning path is 90 minutes.   1. Connect MXChip to Azure IoT 2, Create An Application Key 3. Connect Azure IoT Devices Part 1 Part 2 4. Create A Thing Shape
View full tip
    Send data from an MXChip Developer kit to your Azure IoT Hub   GUIDE CONCEPT   Users of the MXChip IoT DevKit (a.k.a. MXChip), follow these quick steps to send temperature and humidity data from built-in IoT DevKit sensors to the Azure IoT Hub.   YOU'LL LEARN HOW TO   Connect the IoT DevKit to a wireless access point Create an Azure IoT Hub and register a device for the IoT DevKit Connect IoT Devkit to Azure IoT Hub   NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete this guide is 80 minutes   Step 1: Create an Azure IoT Hub   Choose +Create a resource, then choose Internet of Things. Click Iot Hub from the list on the right. You see the first screen for creating an IoT hub.   Fill in the fields.   Subscription: Select the subscription to use for your IoT hub.   Resource Group: You can create a new resource group or use an existing one. To create a new one, click Create new and fill in the name you want to use. To use an existing resource group, click Use existing and select the resource group from the dropdown list.   Region: This is the region in which you want your hub to be located. Select the location closest to you from the dropdown list.   IoT Hub Name: Put in the name for your IoT Hub. This name must be globally unique. If the name you enter is available, a green check mark appears.         3. Click Next: Size and scale to continue creating your IoT hub.     On this screen, you can take the defaults and just click Review + create at the bottom.   Pricing and scale tier: You can choose from several tiers depending on how many features you want and how many messages you send through your solution per day. The free tier is intended for testing and evaluation. It allows 500 devices to be connected to the IoT hub and up to 8,000 messages per day. Each Azure subscription can create one IoT Hub in the free tier.   IoT Hub units: The number of messages allowed per unit per day depends on your hub’s pricing tier. For example, if you want the IoT hub to support ingress of 700,000 messages, you choose two S1 tier units.   Advanced / Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most IoT hubs only need four partitions.               4. Click Review + create to review your choices. You see something similar to this screen.           5. Click Create to create your new IoT hub. Creating the hub takes a few minutes.     Step 2: Create IoT device   Navigate to the IoT Hub created and in the IoT Devices page, click + New.   2. Enter the device ID used by the demo MXChip application MyNodeDevice. Use the default settings for auto-generating authentication keys and connecting the new device to your hub. Click Save.   3. Navigate to the device created and make a note of the device connection string, which looks like: HostName={YourIoTHubName}.azure-devices.net;DeviceId=MyNodeDevice;SharedAccessKey={YourSharedAccessKey}.   Create Azure Storage   The ThingWorx Azure IoT Connector we will install in the next guide requires an Azure Storage Account. Follow the Microsoft documentation to create an Azure Storage account. NOTE: Select Blob storage as the account type and the Hot Access Tier.     Step 3: Connect to Azure IoT Hub   Download the latest version of GetStarted firmware for IoT DevKit. Connect IoT DevKit to your computer via USB. In Windows you see a new USB mass storage device in Windows Explorer called AZ3166. Drag and drop the .bin file you downloaded from step 1 into the disk named AZ3166 and wait for IoT Devkit to restart. Internet connectivity is required to connect to Azure IoT Hub. Use AP Mode on the DevKit to configure and connect to Wi-Fi.Hold down button B, push and release the Reset button, and then release button B. Your IoT DevKit enters AP mode for configuring the Wi-Fi connection. The screen displays the service set identifier (SSID) of the DevKit and the configuration portal IP address:     5. Use a Web browser on a different Wi-Fi enabled device (computer or mobile phone) to connect to the IoT DevKit SSID displayed in the previous step. If it asks for a password, leave it empty.     6. Open 192.168.0.1 in the browser. Select or input the Wi-Fi network that you want the IoT DevKit to connect to, type the password for the Wi-Fi conection and input the device connection string you made notge of in step 1. Then click Connect.     7. The WiFi credentials and device connection string will be saved in the IoT DevKit even after power cycliong. The following page will be displayed in the browser:     8. The IoT DevKit reboots in a few seconds. You then see the assigned Wi-Fi IP address on the screen of the IoT DevKit:     9. Wait for the IoT DevKit to connect to Azure IoT Hub and you will see it sending telemetry data including temperature and humidity value to Azure IoT Hub. The screen of the IoT Devkit would show message count and temperature/humidity data.       Step 4: Next Steps   Congratulations! You've successfully completed the Connect MXChip to Azure IoT guide. By following the steps in this lesson, you created an Azure IoT Hub and device.     The next guide in the Azure MXChip Development Kit learning path is Create an Application Key.   Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Analyze Build a Predictive Analytics Model Build Get Started with ThingWorx for IoT   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support Azure Support Page    
View full tip
  Setup user interfaces and ways to track events   GUIDE CONCEPT   Being able to view your logs is an important part of knowing what is happening in your system. You can't keep things secure if you don't know who is doing what.   These concepts and steps will allow you to focus on development of your application while still allowing the ability to utilize the power of ThingWorx!   We will teach you how to access the system in a way you might not have done much of before.     You'll learn how to   How to design and implement meaningful user interfaces View different logs and search for data NOTE: This guide's content aligns with ThingWorx 9.3. The estimated time to complete this guide is 30 minutes   Step 1: Example and Strategy   If you’d like to skip ahead, download the completed example of the Aerospace and Defense learning path attached: AerospaceEntitiesGuide1.zip. Import the .twx files included.   In an ever-changing world, you are going to need to protect everything that is considered private. In order to do this, you need to be able to track every bit of what is happening in your system. ThingWorx does not provide an out of the box method to log when users open a Mashup window. What if this Mashup contains secure documents? Well, we can work with you on getting that logged and tracked.   Let us start working on securing our system by adding some Mashups that are simple, but we will add complexity around them. Before designing our Mashups, we will set permissions and go from there.      Step 2: Setting Mashup Permissions We will create a Mashup, but the focus will be the security of the Mashup, not the Design and UI itself. Follow the steps below to get started. In the ThingWorx Composer, click the + New at the top of the screen. Select Mashup  in the dropdown. 3, Select Responsive for the layout option. 4. Click Ok.   5. Enter a name for the Mashup Template, such as SecureMashupExample.   6. Click Save then click the Permissions tab. 7. On the Visibility tab, in the Search Organization text box, begin typing and select PTCDefenseDepartment. This allows anyone in the organization to be able to access this Mashup.    8. On the Runtime tab, in the Search Users and User Groups text box, begin typing and select Agency.IT.  9. Set all permissions to Allow (check). This allows a User Group to run services during Runtime of your application. Keep in mind, this gives permissions to all parts of the Mashup (Events, Subscriptions, Services, Parameters). 10. If you would like to be more specific, in the Search Properties, Services, or Events text box, select a service, ie GetHomeMashup. In the text box that appears below for Users and User Groups, select Agency.HumanResources.  11. On the Design Time tab, the Search Users and User Groups text box, begin typing and select Agency.IT.  12. In the Search Users and User Groups text box, begin typing and select Agency.HumanResource. 13. For Agency.IT, set the permissions to allow Read, Update, and Delete. For the Agency.HumanResource User Groups allow Read and deny Update and Delete.   You have just begun the process to securing the application from users looking to view specific secure pages. Next, let's create a simple page and show how we can log who accesses specific pages.      Step 3: Designing Tracked Mashups We will be creating a simple Mashup with the focus of showing how to add logging to a Mashup. Let's start by opening up the Mashup we just created.   Open the SecureMashupExample Mashup and click on the Design tab. Click the Layout panel in the top left and add a Bottom Container. In the Widgets panel, drag and drop a Blog Widget to the top container.   Drag and drop a Web Frame Widget to the bottom container.   Select the Blog Widget in the top container. In the Properties panel, update the Blog property to any existing or new Blog entity (there is a Blog in the provided download).    Select the Web Frame Widget in the bottom container. In the Properties panel, update the URL field to a website you trust. In this case, I'll be using https://www.ptc.com/.   Click Save and View Mashup.   When accessing this Mashup, nothing is logged. We'll be changing that in the next steps with a service that will be called and log who is using the Mashup.   In the ThingWorx Composer, click the + New at the top of the screen.   Select Thing in the dropdown.   In the name field, enter SecureServices and select GenerticThing as the Base Thing Template. Click Save and go to the Services and Alerts tab. Click the New button. Enter LogMashupAccess as the Service name.   Click the Input section and add a required String parameter named MashupName. Click Done and Add.   Add a second String parameter named Username that is required. Click Done.   Enter the below lines of code into the canvas. It will be a simple log statement for tracking. We can add a lot more to this method if we liked. logger.trace(MashupName  +  " accessed by " + Username); Click the green Save and Continue button to save your work.   Add Log Service to Mashup   We'll now need to call this logging service to see whenever a user has logged into our secure page. Of course, this is a simplified example and much more could be done here. Go back to the SecureMashupExample Mashup. In the Data panel, click the + button to add a service. Search for our new SecureServices Entity, then add the LogMashupAccess service. Ensure the Execute on Load checkbox is checked.  Click Done. Select the LogMashupAccess service. In the Data Properties panel in the lower right. In the MashupName text box, enter SecureMashupExample.   Select the User panel in the top right. Drag and drop the name field to the Username parameter. 9. Click Save.   You now have a Mashup that will log the UI being opened and the user accessing that UI whenever it is opened. Click View Mashup and go to the ScriptLog in order to test. You filter will need to be set to All or at least Trace to see the log statement.   In the next section we'll see how we can test this and do a bit more.     Step 4: Viewing and Filtering Logs   Data logging and filtering is one of your most powerful tools not only in the ThingWorx environment, but in developing solutions. The next section of this learning path will go in depth about what each of these items in a Monitoring screen does. It will also cover tricks to help your search. For now, let's look at how we can view logs and filter them to find what we need.   No.  Item Usage  1  Search Bar  Search the log for key words and phrases. 2  Filter Button  Provides a list of options to fine tune your search. This menu is very powerful. 3  Log Configurations  Select what level of logging you'd like to see. 4  Date Range  A date range filter to help limit or set your specific date options. 5  Max Row Count  The max number of rows to search for and return. The search will continue until this number is met or your other search filters have been met (ie, date range). 6   Apply/Reset Buttons  Apply the changes for your date range and max account or reset these values to their defaults. 7  Refresh/Auto Refresh Buttons Allow the log to continue based on your filters (if any) without you having to refresh. You can also refresh it on your own. 8  Log Header and List  The logs that were found based on your filters or settings. 9  Selected Log View  After selecting a log item in the list, it will be shown here.   The are some tricks to finding what you want and need faster. We dive into that in the next guide in this learning path.     Step 5: Next Steps Congratulations! You've successfully completed the Tracking Activities and Stats guide, and learned how to use the ThingWorx Platform to help track what is happening in your application.   If you wish to return to the learning path, click Utilizing ThingWorx to Secure Your Aerospace and Defense Systems   Learn More We recommend the following resources to continue your learning experience: Capability Guide Build Design Your Data Model Manage Data Model Implementation Guide Additional Resources If you have questions, issues, or need additional information, refer to: Resource Link Community Developer Community Forum Support REST API Help Center  
View full tip
Utilize the power of ThingWorx to secure, connect, log, analyze, and see what is happening in your highly structured and secure system.   NOTE: Complete the following guides in sequential order. The estimated time to complete this learning path is 240 minutes.   1. Securing Resources and Private Data Part 1 Part 2 2. Connecting External Databases and Model  Part 1 Part 2 Part 3 3. Low Level Device Connection Part 1 Part 2 Part 3 4. Tracking Activities and Statistics 
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
  Learn how to create or update your system to be more secure   GUIDE CONCEPT   ThingWorx allows for a layer of security within your company or organization to be utilized for authentication and user management.   These concepts and steps will allow you to focus on development of your application while still allowing the ability to utilize the power of ThingWorx!   We will teach you how to enable and configure ThingWorx to perform your security needs.   YOU'LL LEARN HOW TO   Securing data and private information Use services, alerts, and subscriptions to handle processes without human interaction Handling group and organization permissions   NOTE:  The estimated time to complete this guide is 60 minutes.     Step 1: Examples and Strategy   Download the attached FoodIndustry.zip users and extract/import the contents. These are to be used as you work through this learning path. For the completed example, download FoodIndustryComplete.zip.   In this tutorial we continue with our real-world scenario for the Fizos food company. We already have our factory data, automated cooking processed for our sausage product lines, and an automated process for picking up and delivering goods. What we need now is to ensure our organization, security groups, and data is truly secure. Having security permissions at each level and each type of entity involved with our company enables us to have full control over every aspect.   Setting Up Organizations   Organizations are hierarchical structures that allow the user to assign visibility to entities in the ThingWorx Model. This model provides the top down structure from the highest level in an organization or department, to the lower levels of said entity. Each level within this structure also allows for users and groups to be added. This provides a greater level of customization to resources within the ThingWorx Composer.   We will not only create an organization that represents Fizos, but we will have membership in the organization to represent partners, external users, guests, etc. With this level of granularity, we have more control over what is happening at each level.   In the ThingWorx Composer, click the + New at the top of the screen.   Select Organization in the dropdown. Name your Organization Fizos.  Set the Project field (ie, PTCDefaultProject). Click Save   Select the Organization tab to see the hierarchy. Select Unit 1 in the middle of the canvas. Update the Name field to Company and save your changes.   Create Additional Organization Units   Now let's add a node for Employees, Interfaces(APIs), Partners, Customers, Guests, and other groups we might consider important.   Click the green + under the structure you would like to expand. Name your Organization unit Employees. Click Save. We won't add groups as yet. We will do that in the following sections.   Repeat the steps to create the full top level units. It should look similar to the following: We now have the starting structures for Fizos. Next, we will need to add security groups and more units.       Step 2: Creating Security Groups   In many IoT solutions there will be a large scale of users using the system. Because of this it doesn’t make sense to manually set the permissions of every user added to the system. This is why we created User Groups. User Groups provide a role-based approach to permissions and exist to give similar users the same permissions across multiple entities on the platform. User groups set permissions exactly the same way as users do (see next section), but you can simply add a user to a user group in order to set permissions at scale.   Creating a user group such as Fizos.External.SecurityGroup would allow you to have a group with no design time permissions, but allow run time permissions for specific aspects of your solution such as reading product pricing from a service. Similarly you could create a user group called Fizos.Developers.SecurityGroup (under the Employees unit) who would have design time and run time permissions to work on your solution.   Create Security Groups   In the ThingWorx Composer, click the + New at the top of the screen.   Select User Group in the dropdown. Name your group Fizos.Partners.SecurityGroup. Set the Project field with an existing Project (ie, PTCDefaultProject). Click Save.   Repeat these steps to create more user groups for each of the top level units we created in the last section (Customers, External, Interfaces, Employees). We can also add in some groups from the companies we listed as customers and partners earlier in this learning path. Below is an example of all the groups I created for this example:   NOTE: Individual user permissions will override group user permissions. In other words, if you initially add a user to a group so they inherit the permissions of the group, you will still be able to customize permissions for an individual user in that group as needed.   Default User Groups   The platform has a few user groups included in the platform by default. These are used to set up common roles that are often associated with using the platform and have built in permissions. These groups are not meant to be used when creating new applications or general permissions.   Step 3: Configuring Permissions   These permissions can be accessed on any entity created on the platform. All entities have permission control for both design time and run time. Permission Time Control Design time Controls what users are able to do with entities themselves while building the solution. Run time Controls what the users are able to do with the data for an entity when they use the solution. Permission Type Description Property Read Read property values Property Write Update property values Service Execute Execute Services in this Entity Event Execute Queue or fire Events in this Entity Event Subscribe Ability to subscribe to Events in this Entity Access Type Description Allow Allow the user's access to this feature. Deny Deny the user's access to this feature. Inherit Set the user's access to this feature based on permissions in Entities this Entity is based on or the configurations at a higher level.   Add Permissions for an Entity   Once an entity has been selected for editing, select the Permissions tab. Based on what you would like to edit, select the Design Time or Run Time tab.   The All Properties, Services, and Events section provides blanket security to all of these features for a group or user. The Property, Service, or Event Overrides section is used for any overrides that need to be made for specific features.   In the example blow, the User a.jones has the ability to read properties, fire events, and subscribe to events. The User does not have the ability to update a property or execute a Service. In the second section, a.jones is allowed to call the GetConfigurationTable Service (even though he was restricted from doing so in the other section).   To set a permission, filter and select a User/User Group. When their name is in the table, click the Permission Type you would like for this Entity. Default permissions are added to the User or User Group you filtered and selected. This will be full access permissions unless you've changed one of the fields.   Bulk Permissions Handling   When you would like to set the permissions to an entity in bulk, ie permissions for all Things, you can use the Collections option.   On the left hand side, click the lock. Click the Collections option under Permissions. Select the checkbox next to Things. Click Edit Permissions button. Now you will see the same interface you used above, except this time, it will be for all Things instead of a singular entity. You can use these permission settings to stop access to all of the entities you would not want an external user being able to see.   Bulk Permissions Reporting   When you would like to verify the permissions to an entity, ie permissions for all Fizos.Logistics, you can use the Access Report option.   On the left hand side, click the lock. Click the Access Report option under Permissions. Set the User or User Group. (in this case Fizos.VizosMeatMarket.SecurityGroup) Set the Entity (in this case Fizos.Logistics) Click Apply.     You will be able to see what this User Group has access to as it pertains to the Fizos.Logistics Entity. Try other Entities and User Groups.   Step 4: Next Steps   Congratulations! You've successfully completed the Securing Industry 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   If you wish to return to the learning path, click Complex and Automatic Food and Beverage Systems Learning Path   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 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
  Step 3: Creating Machine Processes   Having data and properties without moving parts would be useless. We already setup services on how to perform an inspection in the last guide. This time around, let's form processes to create our products and generate any alerts whenever we've finished production. We won't show too much into our recipe (it's a family secret), but we will highlight some concepts to help with making our machine process smoother. We won't go into creating an SMT line. For a complete guide on how to create such an application you can view our Monitor an SMT Assembly Line guide.   Events and Subscriptions   Let's create events for the cook time being done and a subscriptions on how to handle these scenarios.   Open the Fizos.BrautsMachine.ThingTemplate template and go to the Events tab. Click the + Add button and create the below alerts. Name Data Shape Description CookCompleted AlertEvent This alert is fired when the machine has completed a batch of our product TemperatureReached AlertEvent This alert is fired when the machine has reached the desired temperature.   3. Save these changes and replicate them with the Fizos.SausageMachine.ThingTemplate template. We now have alerts for the machines (alerts on properties and custom alerts). We can create subscriptions on the individual machines that will later inherit these alerts. One way to have a standard amongst these machines is to create a service in the template that will be called from subscriptions.   Let's create the simple services from now, and later, we will call these services from subscriptions. We will also use Schedules initiate the overall process. This can be a daily process, a timed process, or a process based on alerts and subscriptions. To keep this guide simple, we'll make this a process that runs every 3 hours. Create the below services in each of the Fizos.BrautsMachine.ThingTemplate and Fizos.SausageMachine.ThingTemplate templates:     Name InputReturn Type Override Async Description StartCookingProcess N/A Nothing Yes Yes Start overall product cooking process.Triggedby schedule. StartCookingIngredients N/A Nothing Yes Yes Start cooking the ingredients for the product.Triggedby subscription.   Add the following code for the StartCookingProcess service: // Mix our family secret recipe // Add in meats // Add heat me.TemperatureReached({ aackTimestamp: new Date(), alertType: "Completed", ackBy: "CookUser", ack: true, name: "TemperatureAlert", sourceProperty: "Service", description: "Optimal cooking temperature reached", message: "The desired cooking temperature has been reached. Begin next process.", priority: 1 }); // Perform top secret cooking techniques   2. Add the following code for the StartCookingIngredients service: // Temperature has already been reached if(true) { // IF COOK COMPLETED me.CookCompleted({ ackTimestamp: new Date(), alertType: "Information", ackBy: "CookUser", ack: true, name: "CookingAlert", sourceProperty: "Service", description: "Cooking process has completed", message: "The cooking time has completed. Move to next machine.", priority: 1 }); } else { //ELSE IF COOKING FAILED OR HALTED me.CookCompleted({ ackTimestamp: new Date(), alertType: "Exception", ackBy: "CookUser", ack: true, name: "CookingAlert", sourceProperty: "Service", description: "Cooking process has failed", message: "The cooking process has stopped. See logs for failure cause.", priority: 1 }); }   Let's keep in mind, these services will be triggered by by a schedule or a subscription to an alert. There will be no manual processed performed here. We also allowed for these services to be overridden, in order to allow more customization for machines that might need to be treated differently. These services are also not on the main machine templates, which allows us to create templates for machines that might have a different role in the process, ie, packaging or freeze drying.       Step 4: Automating Processes   Let's create the schedule that will start the cooking process. In the ThingWorx Composer, click the + New in the top left of the screen.   Select Schedules in the dropdown.   3. Name the new Schedule Fizos.MachineCooking.Schedule and set the Project (ie, PTCDefaultProject). 4. For the Run As User field, select the Fizos.Machine.User that was provided in the download. 5. Click Save and your entity should match the below configuration.     6. For the Schedule field, set it to 0 0 0/3 * * ?. This will run the process every 3 hours. 7. Switch to the Subscriptions tab and add a new subscription. 8. Name this new subscription StartCooking and select ScheduledEvent as the event input.   9. Add the following code to the source section:   var index = 0; var brauts = Resources["SearchFunctions"].SearchThingsByTemplate({ thingTemplate: "Fizos.BrautsMachine.ThingTemplate" }); var sausage = Resources["SearchFunctions"].SearchThingsByTemplate({ thingTemplate: "Fizos.SausageMachine.ThingTemplate" }); for(index = 0; index < brauts.rows.length; index++) { brauts.StartCookingProcess(); } for(index = 0; index < brauts.rows.length; index++) { sausage.StartCookingProcess(); } // This will begin the process to start each machines cooking process. // The process itself will then be ran by alerts, subscriptions, and services   So far the process will go as the following: A scheduler will search for all Things that inherit from the Fizos.BrautsMachine.ThingTemplate and Fizos.SausageMachine.ThingTemplate templates. Each list of these entities will have it's StartCookingProcess service called. When a temperature value is reached inside of the StartCookingProcess service, the TemperatureReached alert will be triggered. A subscription waiting for this event at the Thing level (which we create in the next section), will call the StartCookingIngredients service. This StartCookingIngredients service will finish the cooking part of the process and trigger a CookCompleted alert with a status update. A subscription waiting for this event at the Thing level (which we create in the next section), can call for another machine to take over the process.   We now have our moving parts. Let's create some examples to see how it can unfold.       Step 5: Handling Cooking Machines   We have many of our main features compeleted. Now we need to handle situations where our machine status needs to be a part of how we handle the cooking process. While much of this work can be handled in a remote process using one of our SDKs or extensions, our events and subscriptions can be a great method to do this also.   Creating Cooking Entities   In the ThingWorx Composer, click the + New in the top left of the screen.   Select Thing in the dropdown.   Set the Project (ie, PTCDefaultProject) and in the name field, enter Fizos.BrautsMachine.M02X35. In the Base Thing Template field, enter Fizos.BrautsMachine.ThingTemplate. Click Save.   6. In the ThingWorx Composer, click the + New in the top left of the screen.     7. Select Thing in the dropdown.     8. In the name field, enter Fizos.SausageMachine.KGYX20. 9. In the Base Thing Template field, enter Fizos.SausageMachine.ThingTemplate. 10, Click Save.     Creating Cooking Subscriptions   These steps will need to be in both of the entities we just created.   Switch to the Subscriptions tab and add a new subscription. Name this new subscription TemperatureReady and select TemperatureReached as the event input.   3. Add the following code to the source section: //The temperature is high enough. Start cooking me.StartCookingIngredients();   You now have a system (when enabled) will run every three hours. It will start our secret cooking process (that can be added in the service or created remotely).   To make things more fun. Add some logging or fun code to see how this works step by step.   To make things more realistic to a real world scenario, add subscriptions for our property alerts on the status or state properties.       Step 6: Next Steps   Congratulations! You've successfully completed the Factory Line Automation guide. In this guide, you learned how to:   Create automated machine 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 Automated Distribution and Logistics.    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
Design and implement a full application that runs without human interaction in the food and beverage world   NOTE: Complete the following guides in sequential order. The estimated time to complete this learning path is 3 hours.     1. ThingWorx Solutions in Food Industry Part 1 Part 2 Part 3 2. Factory Line Automation Part 1 Part 2 Part 3 3. Automated Distribution and Logistics  Part 1 Part 2 4. Securing Industry Data 
View full tip
Build an Equipment Dashboard Guide Part 2   Step 5: Display Data   Now that you have configured the visual part of your application, you need to bind the Widgets in your Mashup to a data source.   Add Services to Mashup   In the top-right, ensure the Data tab is selected. Click the green + symbol. In the Entities Filter field, search for and select MyPump. In the Services Filter field, type GetPropertyValues. Click the right-arrow beside GetPropertyValues. Note how GetPropertyValues was added to the right-side under Selected Services Check the checkbox for Execute on Load. This causes the Service to execute when the Mashup starts.        7. In the Services Filter field, type QueryPropertyHistory. 8. Click the right-arrow beside QueryPropertyHistory. 9. Check the checkbox for Execute on Load. 10. Click Done to close the pop-up. Note how the Services have been added to the Data tab in the top-right.          11. Click Save. Now that we have access to the backend data, we want to bind it to our Widgets.   Value Display   Configure the Value Display to display the SerialNumber of the pump. Under the Data tab, expand GetPropertyValues > Returned Data > All Data. Drag-and-drop GetPropertyValues > serialNumber onto the Value Display Widget in the top section. On the Select Binding Target popup, select Data. Image   We want to use an Image Widget to display a thumbnail picture of the pump for easy reference. To do that, though, you first need to upload an image to Foundation by creating a Media Entity. Right-click the image below, then click "Save image as..." to download. Click Browse > Visualization > Media. Click + New. In the Name field, type pump-thumbnail. If Project is not already set, click the + in the Project text box and select the PTCDefaultProject. Under Image, click Change. Navigate to and select the pump-image.png file you just downloaded. On the navigation pop-up, click Open to close the pop-up and confirm the image selection. At the top of Foundation, click Save. Change Image to pump   We will now update the Image Widget to display the ThingWorx Media Entity we just created. Return to the pump-dashboard Mashup. Click the Image Widget to select it, and ensure that the bottom-left Properties tab is active. In the bottom-left Properties' Filter field, type SourceURL. For the SourceURL Property, search for and select pump-thumbnail. Click Save.   Line Chart   Configure the Line Chart to display Property values changing over time. In the top-right Data tab, expand QueryPropertyHistory > Returned Data. Drag and drop QueryPropertyHistory > All Data onto the Line Chart Widget in the bottom-right Canvas section. On the Select Binding Target pop-up, select Data. Ensure the Line Chart Widget is selected. On the Line Chart's Property panel in the bottom-left, in the Filter field, type XAxisField. For the XAxisField Property, select timestamp. In the Filter field, type LegendFilter. Check the checkbox for LegendFilter. Click Save.   Verify Data Bindings   You can see the configuration of data sources bound to Widgets in the bottom-center Connections pane. In the top-right Data tab, click GetPropertyValues. Check the diagram in the bottom-center Connections window to confirm a data source is bound to the Value Display Widget.       2. Also in the top-right Data tab, click QueryPropertyHistory. Confirm that the diagram shows it is bound to the Line Chart.         3. Click Save.     Step 6: Test Application   Browse to your Mashup and click View Mashup to launch the application. NOTE: You may need to enable pop-ups in your browser to see the Mashup. 2. Confirm that data is being displayed in each of the sections. 3. Open the MyPump Thing, then click the Properties and Alerts Tab. 4. Click Set Value on the line of the serialNumber Property. 5. Enter a value for the serial number, then click the Check-mark button. 6. Click Refresh to confirm the value is changed. 7. Refresh the browser window showing the dashboard to see the new serial number value.     Step 7: Next Steps   Congratulations! You've successfully completed the Build an Equipment Dashboard guide, and learned how to: Use Composer to create a Thing Shape and a Thing Template Make a Thing using a custom Thing Template Store Property change history in a Value Stream Create an applicaton UI with Mashup Builder Display data from connected devices Test a sample application   If you like to return to previous guides in the learning path, select Connect and Monitor Industrial Plant Equipment.    
View full tip
Build robust, secure, full-featured edge integrations and gateways for any platform using C, .NET, Java (supporting Android development).  Tutorials are available for the C and Java SDK's by clicking the relevant link below.     C SDK The C SDK is the basis for ThingWorx Edge SDKs and the Edge MicroServer (EMS). You can compile C SDK applications on any platform and even run it without an operating system. Using the C SDK for your application means least amount of RAM, processing power, and disk space, frequently requiring less than 200 kilobytes. The C SDK is also the only SDK that is distributed as source code.       Java SDK The Java SDK is especially useful if you are integrating with an application that uses a Java-based API. While applications based on the Java SDK tend to use more RAM, processing power, and disk space than a C SDK equivalent application, they typically take less time to develop. To use it, you will need a platform with a supported Java Virtual Machine. The Java SDK support Android development.       .NET SDK Use the Microsoft .NET SDK when integrating with a .net based application or if your team typically works with Microsoft technologies. It may only be used on Windows based machines.  
View full tip
Announcements