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

Community Tip - You can Bookmark boards, posts or articles that you'd like to access again easily! X

IoT Tips

Sort by:
As of May 24, 2023, ThingWorx 9.4.0 is available for download!  Here are some of the highlights from the recent ThingWorx release.   What’s new in ThingWorx 9.4? Composer and Mashup Builder  New Combo chart and Pie chart based on modern Web Components architecture along with several other widget enhancements such as Grid toolbar improvements for custom actions, highlighting newly added rows for Grid widget and others Ability to style the focus on each widget when they are selected to get specific styling for different components Absolute positioning option with a beta flag to use by default is available now Several other Mashup improvements, such as Export function support is made available; improved migration dialogue (backported to 9.3 as well) to allow customers to move to new widgets; and legacy widgets language changes   Foundation  Heavily subscribed events could now be distributed across the ThingWorx HA cluster nodes to be scaled horizontally for better performance and processing of ThingWorx subscriptions. Azure Database for PostgreSQL Flex Server GA support with ThingWorx 9.4.1 for customers deploying ThingWorx Foundation on their own Azure Cloud infrastructure Improved ThingWorx APIs for InfluxDB to avoid Data loss at a high scale with additional monitoring metrics in place for guardrails Several security fixes and key third-party stack updates   Remote Access and Control (RAC) Remote Service Edge Extension (RSEE) for C-SDK, currently under Preview and planned to be Generally Available (GA) by Sept 2023, would allow ThingWorx admins to use Remote Access and Control with the C-SDK based connected devices to use Global Access Server (GAS) for a stable, secure, and large number of remote sessions With 9.4, a self-signed certificate or certificate generated by the trusted certificate authority can be used for RAC with the ThingWorx platform Ability to use parameter substitution to update Auto Launch commands dynamically based on data from the ThingWorx platform is now available   Software Content Management  Support for 100k+ assets with redesigned and improved performance on Asset Search Better control over package deployment with redesigned package tracking, filtering, and management Improved overall SCM stability, performance, and scalability and a more user-friendly and intuitive experience   Analytics  Improvements to the scalability of property transforms to enable stream processing of the larger number of properties within a ThingWorx installation Refactoring of Analytics Builder UI to use updated widgets and align with the PTC design system Updates to underlying libraries to enable the creation and scoring of predictive models in the latest version of PMML (v4.4) End of Support for Analytics Manager .NET Agent SDK     View release notes here and be sure to upgrade to 9.4!     Cheers, Ayush Tiwari Director, Product Management, ThingWorx      
View full tip
Learn how to use the DBConnection building block to create your own DB tables in ThingWorx.
View full tip
This video is Module 11: ThingWorx Analytics Mashup Exercise of the ThingWorx Analytics Training videos. It shows you how to create a ThingWorx project and populate it with entities that collectively comprise a functioning application. 
View full tip
This video concludes Module 9: Anomaly Detection of the ThingWorx Analytics Training videos. It gives an overview of the "Statistical Process Control (SPC) Accelerator"
View full tip
This video continues Module 3: Data Profiling of the ThingWorx Analytics Training videos. It describes metadata, and how it is used to ensure that your data is handled appropriately when running Signals, Profiles, Training, Scoring, and other jobs inside ThingWorx Analytics.
View full tip
This video begins Module 3: Data Profiling of the ThingWorx Analytics Training videos. It describes the process of examining your data to make sure that it is suitable for the use case you would like to explore.
View full tip
Welcome to the ThingWorx Analytics Training Course! Through these 11 modules, you will learn all about the functionality of this software, as well as techniques to help you build a successful and meaningful predictive analytics application.
View full tip
Pre-built apps for manufacturing operations that rapidly deliver value.   Overview   Think Big, Start Small, Scale Fast   Getting started on an industrial IoT project can be daunting, especially deciding where and how to begin. After collecting the experiences gained by working with over 1500 companies on IIoT applications, PTC has made the process to get up and running easier. By grouping IIoT capabilities together in functionally oriented programs, PTC built out-of-the-box applications that rapidly deploy and scale across new or existing system infrastructure. Instead of starting from scratch, you can use ThingWorx ready-to-configure apps to quickly lay the foundation for industrial transformation and implement IIoT solutions in as little as 90 days. ThingWorx Apps offer a comprehensive, basic IIoT scheme to connect to your equipment, collect real-time data, create notification work flows, deliver role based dashboards, and more. Need something more tailored to your operation? No problem. You can iteratively extend and customize ThingWorx Apps into additional use cases for continuous innovation.     Manufacturing Apps   Manufacturers are under constant pressure to minimize downtime, improve quality, and respond faster to individual customer requirements, all while lowering costs. The ThingWorx Manufacturing Apps are pre-built solutions that can be tried in less than 60 minutes without disrupting production. These apps provide manufacturers with real-time visibility into factory floor operations, from individual PLCs to assets to plants to enterprise-wide operations.   ThingWorx Connected Work Cell   Connected Work Cell streamlines how information is delivered to frontline workers by aggregating critical data from multiple data siloes into a simplified visual application. It presents step-by-step work instructions with accurate, up-to-date information to drive efficiency, links instructions to work orders, assigns resources, and validates proper execution to ensure quality. Capabilities Lite work instruction authoring with multiple step types and versioning Workpiece routes editor and work order scheduling Step-by-Step tracking of operator execution  Smart tool configuration Work station dashboard display File storage and document management Benefits Present accurate, up-to-date work instructions using 3D models Aggregate work requirements from multiple sources into one simplified display at the work station Increase workforce flexibility by reducing upfront training before being assigned to a new work cell Improve quality by collecting actual tool use data Rapid implementation and fast time to value   ThingWorx Real-Time Production and Performance Monitoring   Real-Time Production and Performance Monitoring provides manufacturing executives and plant managers with top-down, real-time visibility into consistent KPIs such as overall equipment effectiveness, mean time between failure, and mean time to repair.   Capabilities Connect existing assets and gather real-time data View overall equipment effectiveness (OEE), mean time between failure (MTBF), and mean time to repair (MTTR) in real-time  Compare geographically separated assets, lines, or products based on date, time, shift or crew Benefits Improve operational performance of existing assets by increasing throughput and decreasing waste Balance labor vs. capital expenditures to meet production needs Determine true overall equipment effectiveness for multiple facilities   ThingWorx Asset Monitoring and Utilization   Asset Monitoring and Utilization helps manufacturers connect to existing assets, remotely monitor them in real-time, generate alerts based on abnormal conditions, and deliver critical insights with data trending and analysis tools.   Capabilities Performance Dashboards with real-time access to open alarms Email and SMS distribution rules for messaging and alarm acknowledgment Integration to maintenance systems Detailed screens showing asset health, configuration parameters, and sensor trends  Benefits Quickly identify anomalous data trends and perform Root Cause Analysis Maximize asset uptime and availability with alerts on critical issues before they impact performance Rapidly connect to and catalog existing assets Quickly Identify Anomalous Data Trends and perform Root Cause Analysis  
View full tip
Learning Paths combine guides into one experience to teach related skills efficiently from start to finish. Begin your learning journey to reduce time to proficiency to get up and running with ThingWorx quickly.   Featured Learning   Utilizing ThingWorx to Secure Your Aerospace and Defense Systems Connect and Monitor Industrial Plant Equipment Vehicle Predictive Pre-Failure Detection with ThingWorx Platform   Industry Solutions   Complex and Automatic Food and Beverage Systems Connect and Configure Industrial Devices and Systems Medical Device Service Monitor Factory Supplies and Consumables Using an Allen-Bradley PLC with ThingWorx   Learn ThingWorx   Getting Started on the ThingWorx Platform Design and Implement Data Models to Enable Predictive Analytics Customize UI and Display Options to Deploy Applications Azure MXChip Development Kit    
View full tip
Challenges Manufacturers of factory equipment often rely on manual processes to maintain adequate supply levels of consumables in equipment at customer sites. But a clipboard-and-pen process for ordering supplies are error prone, and can quickly grow wrought with problems that often go unreported until they affect assembly line production, resulting in unexpected costs—such as overnight shipping charges—and risking downtime, which ultimately leads to customer dissatisfaction.   Solution One such manufacturer implemented ThingWorx to connect to equipment installed at customer sites, and created a custom web application using ThingWorx Foundation to remotely monitor supply levels. ThingWorx Industrial Connectivity provides the bi-directional connection to send data that is displayed in graphs on the web application created using ThingWorx Mashup Builder. Features of ThingWorx Analytics were used to generate alerts before maintenance problems affected production.   Outcomes The manufacturer is able to monitor supply levels to more effectively anticipate when consumables will need to be replenished. Supplies are now consistently ground shipped on time to meet assembly line demand, reducing interruptions to operations and allowing expansion to multiple plants with improved service level.   NOTE: Complete the following guides in sequential order. The estimated time to complete this learning path is 120 minutes.   1. Implement Services, Events, and Subscriptions  Part 1 Part 2 2. Build a Predictive Analytics Model  Part 1 Part 2
View full tip
This video begins Module 1: ThingWorx Analytics Overview of the ThingWorx Analytics Training videos. It covers some of the functionality of the ThingWorx platform, as well as ThingWorx Analytics capabilities.
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
    Step 5: Create Event   Events are automatic analysis jobs which are submitted based on a pre-defined condition. In this step, we'll configure an Analysis Event which will execute automatically whenever there is a datachange in our simulated engine.   On the ThingWorx Composer Analytics tab, click ANALYTICS MANAGER > Analysis Events.   Click New....   In Source, search for and select AMQS_Thing. In Event, select DataChange. In Property, select FlipFlop. In Provider Name, select Vibration_Provider. In Model Name, select the published Model.   Click Save.     Map Event Data   Map the Properties of AMQS_Thing, to the fields required to evoke an Analysis Job.   Select the previously-created Event, and click Map Data....   Click Inputs Mapping.   In Source Type, select Thing. In Source, search for and select AMQS_Thing.   On the left, select s1_fb1, one of the sub-fields of AMQS_Thing's InfoTable Property. On the right, select _s1_fb1, the first frequency band required for the Model to make a prediction.   Click the Map button in the center.   Repeat this mapping process for for s1_fb2 through s1_fb5.   Map causalTechnique in the same manner. This is a String Property in AMQS_Thing with a Default Value of FULL_RANGE, the same technique we used in our earlier true/false testing. Map goalName to goalField in the same manner. This is a String Property in AMQS_Thing with a Default Value of low_grease, the same goal we used in our earlier testing.   Click Results Mapping on the left.   Map _low_grease to Result_low_grease.   Map _low_grease_mo to Result_low_grease_mo.   Click Close to close the mapping pop-up.   Enable Event   Now that we've done the mapping from Foundation to Analytics, let's confirm that everything is correct.   If so, we'll then Enable the Analysis Event so that it can automatically generate and process Analysis Jobs.   Select the mapped Analysis Event.   Click View....   Click Inputs Mapping and confirm that all mappings are correct.   Click Results Mapping and confirm that all mappings are correct.   At the top-left, expand the Actions... drop-down.   Select Enable.   Now that you have enabled the Analysis Event, whenever AMQS_Thing's InfoTable Property changes, the new data will be submitted to Analytics Manager.   An Analysis Job will automatically run, with a predictive score sent back and stored in AMQS_Thing's Result_low_grease (Boolean) and Result_low_grease_mo (Number) Properties.       Step 6: Test Model   In this step, we'll confirm that the automatic analysis of information coming from remote devices is operational.   On the ThingWorx Composer Analytics tab, click ANALYTICS MANAGER > Analysis Jobs.   Uncheck Filter Completed Jobs.   Select a Job and click View.... Click Results. NOTE: You will see true or false, just as when you manually tested the Model, so you know that Analytics Manager is now automatically submitting and completing jobs with a resulting prediction. Test Mashup   Follow these steps to confirm that the results are being sent back to ThingWorx Foundation in a way in an actionable way.   Return to the AMQS_Mashup browser tab. Wait at least ~20 seconds to see multiple cycles of good and bad data (which should generate a false or true result from Analytics Manager). Note the Text Field Widgets on the right now have data.   This analytical result is coming from Analytics Manager, and is the exact same output you saw in ANALYSIS JOBS.   Using this technology, you could create a paid customer service, where you offered to monitor remote engines, in return for automatically shutting them down before they experience catastrophic engine failure.   For that example implementation, you would utilize the AMQS_Thing.Result_low_grease BOOLEAN Property to trigger other actions.   For instance, you could create an Alert Event which would be triggered on a true reading.   You could then have a Subscription which paid attention to that Alert Event, and performed an action, such as sending an automatic shutdown command to the engine when it was experiencing a likely low grease event.   NOTE: We recommend that you return to the ThingWorx Composer Analytics > ANALYTICS MANAGER > Analysis Events tab and Disable the Event prior to continuing. Since the simulator generates an Event every ~10 seconds, this can create a large number of Events, which can fill up your log.       Step 7: Next Steps   Congratulations. You've completed the Operationalize an Analytics Model guide. In this guide you learned how to:   Define an Analysis Provider that uses the built-in Analytics Server Connector Publish a Model from Analytics Builder to Manager Create an Analysis Event which takes data from ThingWorx Foundation and decides whether or not a failure is likely   This is the last guide in the Design and Implement Data Models to Enable Predictive Analytics learning path.   Learn More   We recommend the following resources to continue your learning experience:       Capability Guide Build Implement Services, Events, and Subscriptions Guide   Additional Resources   If you have questions, issues, or need additional information, refer to:       Resource Link Community Developer Community Forum Support Analytics Manager Help Center
View full tip
    Build a remote monitoring application with our developer toolkit for real-time insight into a simulated SMT assembly line.   Guide Concept   This project will introduce methods to creating your IoT application with the ability to analyze real time information as the goal. Following the steps in this guide, you will create an IoT application with the ThingWorx Java SDK that is based on the functionality of an SMT assembly line. We will teach you how to use the ThingWorx Java SDK, ThingWorx Composer, and the ThingWorx Mashup Builder to connect and build a fully functional IoT application running numerous queues and "moving parts".   You'll learn how to   Use ThingWorx Composer to build an application that uses simulated data Track diagnostics and performance in real-time   NOTE: The estimated time to complete this guide is 60 minutes       Step 1: Completed Example   Download the completed files for this tutorial attached here: ManagementApplication.zip.   In this tutorial, we walk through a real-world scenario for a Raspberry Pi assembly line. The ManagementApplication.zip file provided to you contains a completed example of an SMT application. Utilize this file to see a finished example and return to it as a reference if you become stuck creating your own fully flushed out application. Keep in mind, this download uses the exact names for Entities used in this tutorial. If you would like to import this example and also create Entities on your own, change the names of the Entities you create. The download contains the following Java classes that support this scenario:    Name                          Description Motherboard Abstract representation of a Thing inheriting from a MotherboardTemplate AssemblyLine Abstract representation of a Thing inheriting from a SMTAssemblyLineTemplate AssemblyMachine Abstract representation of a Thing inheriting from a AssemblyMachineTemplate   Once you complete the Java environment setup by installing a Java JDK, import the Entities/ThingWorxEntities.xml file into ThingWorx Composer. This file contains various Data Shapes, Mashups, Value Streams, Things, and Thing Templates necessary to support the application. The more important Entities are as follows:    Feature                                                 Entity Type          Description RaspberryPi 1 - 6 Thing Things that inherit from the motherboard template SolderPasteAssemblyMachine Thing A Thing that inherits from the assembly machine template PickPlaceAssemblyMachine Thing A Thing that inherits from the assembly machine template ReflowSolderAssemblyMachine Thing A Thing that inherits from the assembly machine template InspectionAssemblyMachine Thing A Thing that inherits from the assembly machine template RaspberryPiSMTAssemblyLine Thing A Thing that inherits from the assembly line template MotherboardTemplate ThingTemplate A template used for building motherboard devices AssemblyMachineTemplate ThingTemplate A template used to create the various types of SMT assembly machines SMTAssemblyLineTemplate ThingTemplate A template used to represent the entire assembly line and all devices in it Advisor User User created to be used with the Java SDK examples   NOTE: An Application Key is NOT included in the zip file you downloaded. You will need to create your Application Key and assign it to the Advisor user provided in the ThingWorxEntities.xml file, the Administrator (which is not recommended for production applications), or any user you've created. If you do not know how to create one or just need a refresher, visit the Create An Application Key guide, then come back to this guide.       Step 2: Run Application   The Java code provided in the download is pre-configured to run and connect to the entities in the ThingWorxEntities.xml file. Open the Executable/Script in a text editor, and edit the script with your host and port.  Operating System   File Name Mac/Linux Script.sh Windows Script.bat Update the <HOST> and <PORT> arguments to that of your ThingWorx Composer and update the Application Key argument to the one you have created. Use the examples in the file for assistance. NOTE: If you are using the hosted trial server, follow the HTTPS example and use 443 as the port. After updating the script that pertains to your operating system, double-click or run Script.sh (Linux, Mac) or Script.bat (Windows) to run the Java program. In your browser, proceed to the following URL (replace the host field with your ThingWorx Composer host) in order to see the application work:   <host>/Thingworx/Runtime/index.html#master=AssemblyLineMaster&mashup=RaspberryPiAssemblyLine   You can also open the RaspberryPiAssemblyLine Mashup in the Composer and click View Mashup.   You should be able to see rows of assembly machines with buttons. Click the Start button to start the assembly line. Click the Add Board button to add Raspberry Pi motherboards.   NOTE: The screen will not update and properties cannot be changed until the Java backend starts running. Ensure the connection is made before attempting to start the assembly line.   Functional Breakdown   At runtime, the Mashup executes the following functions:                Mashup Component        Function 1  Assembly Machines Selecting an assembly machine will provide you with information on the diagnostic status of that assembly machine and access to charts highlighting its performance. 2  Start Button Start up the assembly line and all assembly machines. 3  Shutdown Button Stop the assembly line and shutdown all assembly machines. Queues will not be purged. 4  Motherboard Add Dropdown A dropdown that shows the available motherboards that can be added to the assembly line. 5  Add Boards Button If a MotherboardTemplate Entity is selected in the Motherboard Add dropdown, that Raspberry Pi will be added to the assembly line. If no Motherboard is selected, this will add a new Raspberry Pi Thing to the assembly line. 6  Motherboard Image Show all motherboards currently inside the assembly line queue of Raspberry Pi. 7  Motherboard Pick Up Dropdown A dropdown that shows the motherboards in the assembly line that are not in a Complete Stage. 8  Add Pick Up Button If a MotherboardTemplate entity is selected in the Motherboard Pick Up dropdown, that Raspberry Pi will be removed from the assembly line and no longer be available. This can be done if a Raspberry Pi is slowing down the other queues. 9  Box Image Show all motherboards currently in the Complete Stage.         Step 3: Services and Java Implementation   JavaScript using ThingWorx Services   To support and run the application quickly, ThingWorx Services are utilized as much as possible. This ensures the speed and quality of the application are maintained while also ensuring code changes can be made quickly.   Opening and Starting Up   Open the RaspberryPiAssemblyLine Mashup by going to the URL provided in the last section. The machines will all be in a shut-down (RED) state. This is ensured by a call to the Shutdown service within the SMTAssemblyLineTemplate ThingTemplate. This method begins the process of resetting the Motherboards to their default states and AssemblyMachines to a shutdown state.   Click the Start button to call the StartUp Service. This call will notify the Java Code to turn the simulated machines on and begin waiting for any motherboards to be added to the queue.   INFO: The StartUp and Shutdown services call other services, some of which can be overrided. If you would like to make a change to the implementation, make the change in an implementation of the SMTAssemblyLineTemplate ThingTemplate. You can use RaspberryPiSMTAssemblyLine as an example.   New Raspberry Pi Names   The CommonServices Entity provides services that can be reused by other entities easily. The GenerateRandomThingName service is utilized to create a psuedo-random name for a new Motherboard. You can use this service to create names - names may start with “Raspberry,” but not necessarily - they are based on how you set the parameters.   Creating and Adding Boards   Select the Add Board button to make a call to the AddBoard service of the SMTAssemblyLineTemplate ThingTemplate. This service will call the CommonServices Thing to create a new name for the Motherboard, then begin the process of creating, enabling, and adding that Motherboard to the simulated devices in the Java code.   Pickup Boards   Select the Pickup Board button to make a call to the PickUpMotherboard service of the SMTAssemblyLineTemplate ThingTemplate. This service will remove a Motherboard from the assembly line, update the status to having been picked up, and ensure the simulated devices are updated with this new information.   Queue Processing   Add a Motherboard to the available queue of a machine when the Motherboard is ready to be worked on that machine. A machine will NOT know information about a Motherboard until that motherboard is ready for that stage of processing.   The Motherboard is then added to the internal queue of the machine based on the size of the internal queue of that machine. Being in the internal queue of a machine does not mean it is being worked on. The Motherboard is ONLY being worked on when the machine has added the Motherboard to it’s working queue. The size of the working queue is based on the machine’s placement heads. You can play with these values to increase or descrease queue performance.   INFO: The heads, speeds, and queue sizes of the machines are created in the RaspberryPiSMTAssemblyLine Thing. To change these configurations, update the AddStartingMachines service with new values or new machines.   Java Implementation using ThingWorx Java SDK   The Java code we created for the Assembly Line scenario creates a connection to the ThingWorx Composer as any ThingWorx SDK utility would. This code is used to allow extended functionality for the application, and mimics the behavior of devices or machines connected to the ThingWorx Composer.   Motherboard Class   The Motherboard Class contains several methods to ensure the location of the motherboard is known at all times. It also updates the status level from 0 to 100 as the motherboard is being assembled.   AssemblyMachine Class   The fields in the AssemblyMachine class ensure that the queues handled by the machine are working correctly. When an AssemblyMachine is created, it will load both the available queue and the internal queue if the machine will be the first stage in the assembly line (Soldering). If not a solder machine, the queues will be empty, as no device is pending its task. If the machine is on, it will continue to work based on its current status of the motherboards in its queue. When a machine is turned on or the current task is complete, the AssemblyMachine will re-evaluate the queues to optimize timing and decrease idle time.   Challenge: Find a way to improve the timing of the queue and reduce the idle time even more. Think of a problem an assembly line might have when machines are waiting on a prior machine to complete a task.   SMTAssemblyLine Class   The SMTAssemblyLine class handles the overall process and controls how motherboards are handled when entering and exiting the assembly line. There are also listeners to start up the assembly machines.   When a board is added to the queue of the assembly line, it will instantly be added to the available queue for a solder machine to begin processing. This is the only machine that will have immediate access to the motherboard. When a board is picked up from the assembly line queue, the status of the board is set to “PICKED UP”. That motherboard will be available later for processing by the assembly line.     Click here to view Part 2 of this guide.  
View full tip
Learn how to create a web application to monitor and control an Allen-Bradley PLC.   GUIDE CONCEPT   This guide will create a ThingWorx Foundation Mashup GUI to monitor and control an Allen-Bradley PLC connected via ThingWorx Kepware Server.   YOU'LL LEARN HOW TO   Create a Mashup Add Widgets Access backend data via Mashup Data Services Tie data to Widgets Create a simple web application that monitors and controls a PLC   NOTE:  The estimated time to complete all parts of this guide is 30 minutes.     Step 1: Learning Path Overview   Assuming you are using this guide as part of the Rockwell Automation Learning Path, then you have now completed each of the following installations:   Connected Components Workbench ThingWorx Kepware Server ThingWorx Foundation (for Windows)   You've also connected an Allen-Bradely PLC to Connected Components Workbench and then to ThingWorx Kepware Server.   You have propagated that information further from ThingWorx Kepware Server into Foundation.   In this final step, we'll create a simple Mashup to visualize the interface from Foundation to ThingWorx Kepware Server to the PLC.   NOTE: Both Rockwell Automation's Connected Components Workbench and ThingWorx Kepware Server are time-limited trials. If significant time has passed while persuing this Learning Path, you may need to reinitialize them. Consult the Troubleshooting step of this guide for more information.       Step 2: New Mashup   A Mashup is a Graphical User Interface (GUI) to interact with your application.   In this step, you will create a new, blank Mashup. You will later populate it with Widgets (graphical elements) and tie those elements to data.   In the top-left of ThingWorx Composer, click the Browse folder icon. Click VISUALIZATION > Mashups.   Click + New.   Select Responsive, then click OK. A new Mashup tab will open.     In the Name field, enter RWLP_Mashup. If Project is not already set, click the + in the Project text box and select the PTCDefaultProject. At the top, click Save.     Step 3: Add Widgets   Widgets are drag-and-drop, stand-alone, graphical elements which you can add to your Mashup to represent certain pieces of backend data.   In this step, you will add a pair of Checkboxes to represent the PLC functionality.   At the top of the RWLP_Mashup tab, click Design. It may take a few moments for the Mashup Builder interface to load.     Click The Widgets tab, then In the Filter field on the left, enter check. Drag-and-drop a Checkbox widget onto the central Canvas area.   Drag-and-drop a second Checkbox onto the Canvas.   At the top, click Save.     Step 4: Add Data    To have the Checkbox Widgets actually interact with the PLC, you need to bind them to the backend data.   To do so, you will make use of a Mashup Data Service from the previously-created PLCcoils Thing. At the top-right, click the Data tab, then click the + symbol.   In the Add Data pop-up window, enter plc in the Entity Filter search box.   Select the PLCcoils Thing. In the Services Filter search box, search for getprop.   Click the right arrow to select GetProperties. Check the box for Execute on Load under Selected Services. This causes the Service to be automatically executed upon the Mashup being loaded. In the Services Filter search box, search for setprop. Click the right arrow to select SetProperties. Note that you should keep Execute on Load un-checked for this Service, as we do NOT want it to automatically execute on Mashup load.     Click Done, then click the > to expand both GetProperties and SetProperties.   At the top, click Save.     Click here to view Part 2 of this guide.
View full tip
    Step 8: Verify Connectivity   The EMS is now attempting to talk to ThingWorx Foundation.   However, ThingWorx does not have detailed information about the Edge device that is attempting to connect to it, so it will show up in the Unbound category of Remote Things.   Open ThingWorx Composer.     On the left, click Monitoring.   Click Status -> Remote Things.     Click Unbound.     Confirm that you see the PiThing listed in the Unbound section. NOTE: The name PiThing comes from the config.lua script. PiThing is simply the name that is in that script, hence the name that you see in ThingWorx. To change the name of the device, you could stop both wsems and luaScriptResource, edit config.lua to use a different Thing name other than PiThing, and then restart both of the EMS programs. At that point, the Thing showing up in Remote Things -> Unbound would be whatever name you changed to in config.lua.   Create a Remote Thing   Now that the EMS is communicating with ThingWorx Foundation, let's create a Remote Thing to which Foundation can tie said connection.   In ThingWorx Composer, click Browse > Modeling > Things.     At the top-left, click + New.       In the Name field, enter PiThing. Note that the name must match the spelling and capitalization of the Thing's name that you entered in the EMS's config.lua for it to auto-connect.   If Project is not already set, search for and select PTCDefaultProject. In the Base Thing Template field, search for remotethingwith.     Select RemoteThingWithTunnelsAndFileTransfer. At the top, Click Save. Note the status-indication pop-up indicating that PiThing is now connected.       Use Services to Explore EMS Files   Now that your Remote Thing is Saved and Connected, we can use some of the built-in Services to explore the EMS folders and files which we previously created for testing purposes.   At the top of PiThing, click Services.   Under the Execute column, click the Play Symbol for BrowseDirectory.   In the top-left path field, type / and click the bottom-right Execute button. Note the other and tw folders which we previously created for testing.   In the top-left path field, type /tw and click the bottom-right Execute button. Note the tw_test_01.txt file which we previously created for testing.     As the tw_test_01.txt file (and its parent folder) were items which we custom-created for this guide, you should now be 100% convinced that connectivity between Foundation and the EMS is dynamically working.   If so desired, you could explore into other folders (or even add additional files to these folders), run the BrowseDirectory Service again, and confirm that Foundation is now aware of the EMS and actively communicating.     Step 9: Next Steps   Congratulations! You've successfully completed the Setup a Raspberry Pi as an IoT Device guide, and learned how to:   Set up Raspberry Pi Install, configure, and launch the EMS Connect a remote device to ThingWorx   The next guide in the Medical Device Service learning path is Medical Data Storage and Display.    Learn More   We recommend the following resources to continue your learning experience:   Capability Guide Manage Data Model Introduction Connect Connect Industrial Devices and Systems   Additional Resources   If you have questions, issues, or need additional information, refer to:   Resource Link Community Developer Community Forum Support ThingWorx Edge MicroServer (EMS) Help Center External Raspberry Pi Documentation
View full tip
    Step 4: Connect Peripherals and Initial Configuration   Connect Peripherals   Now that we have a working microsdhc flash card with the Raspbian OS, we want to insert it into the Pi, as well as connect our other peripherals and power.   Remove the microsdhc card from the adapter.       With the power supply NOT connected, insert the microsdhc card into the Pi. Note that it may help to turn the Pi over.     With the power supply NOT connected to a wall-socket, connect the power, monitor, USB keyboard, and USB mouse.       Plug-in the power-supply to a wall-socket and wait for the Pi to boot.     Pi Initial Configuration   The Raspbian OS needs some initial configuration to set things such as your location and to connect to a WiFi network.   Click Next on the initial Raspbian start pop-up. Set your Country, Language, TimeZone, Use English language (if applicable), and Use US keyboard (if applicable), then click Next.       Enter and Confirm a new password, then click Next. If applicable, check the This screen shows a black border around the desktop checkbox, and click Next.     Select an appropriate WiFi network, and click Next.   Enter the WiFi password, and click Next.     On the Update Software screen, it is recommended to click Skip. If you have a microsdhc card with 16GB or more, then you may click Next to peform an OS update. Note that this process may be time-intensive... 30+ minutes.     If you performed an OS update, and it has completed with a System is up to date pop-up, click OK.     When the Setup is complete, click Restart. After the reboot, you will be automatically re-logged into Raspbian.       Step 5: Install EMS   Now that the Pi is fully setup, you want to download the Edge MicroServer (EMS) onto the Pi. On the Raspberry Pi, open a web browser and navigate to this guide, then download MED-61060-CD-054_SP10_Microserver-Linux-arm-hwfpu-openssl-5-4-10-1509.zip.   Click the download's options drop-down, and select Show in folder.       Right-click on the .zip file and select Extract Here.       Navigate into the newly-extracted /microserver folder.     The primary executables which enable the EMS functionality are the following: File Name Description wsems An executable file that runs the Edge MicroServer. luascriptresource The Lua utility that is used to run Lua scripts, configure remote things, and integrate with the host system.     Create Additional Directories   New folders may be added to the /microserver directory for various purposes. Some of these will be utilized within this guide, while others may be utilized in future guides using the EMS.   In the /microserver folder, create a /logs directory. Create a /other directory. Create a /staging directory. Create a /tw directory. Create a /updates directory.   Create Test Files   It can also be helpful during testing to have some small files in these folders to further demonstrate connectivity.   As these files were custom-created for the guide, seeing them within ThingWorx Foundation ensures that the connection between Foundation and the EMS is real and current.   In the /tw directory, create a text file named tw_test_01.txt. In the /other directory, create a text file named other_test_01.txt.     Click here to view Part 3 of this guide.
View full tip
    Step 6: Configure EMS   The EMS consists of two distinct components that perform slightly different operations and communicate with each other.   The first is the EMS itself which creates an AlwaysOn™ connection to ThingWorx Foundation. It binds Things to the platform and automatically provides features like file transfer and tunneling.   The second is the Lua Script Resource (LSR). It is used as a scripting language so that you can add Properties, Services, and Events to the Things that you create in the EMS.     Now that you have "installed" (i.e. downloaded, unzipped, and moved to an appropriate location) the EMS on your Raspberry Pi, it needs to be configured.   The primary method of doing so is via the config.json and config.lua files.   In this step, we'll create these files and paste some JSON / Lua configuration into them.   Navigate to the /etc directory.       Right-click inside the folder’s white-space and select New File.... Enter config.json and click OK.   Right-click on the new config.json file and select Text Editor.     Copy and Paste the following code into the empty config.json file: Note that the backslashes (\) in the JSON below are escape characters necessary to properly address special characters, such as the forward-slashes (/) indicating path directories. { "ws_servers": [{ "host": "YOUR_IP_ADDRESS_HERE", "port": 443 }], "appKey": "YOUR_APP_KEY_HERE", "logger": { "level": "INFO", "publish_directory": "\/home\/pi\/Downloads\/microserver\/logs", "publish_level": "INFO", "max_file_storage": 2000000, "auto_flush": true }, "http_server": { "ssl": false, "authenticate": false }, "ws_connection": { "encryption": "ssl" }, "certificates": { "validate": false, "disable_hostname_validation": true }, "tunnel": { "buffer_size": 8192, "read_timeout": 10, "idle_timeout": 300000, "max_concurrent": 4 }, "file": { "buffer_size": 8192, "max_file_size": 8000000000, "virtual_dirs": [ {"other": "\/home\/pi\/Downloads\/microserver\/other"}, {"tw": "\/home\/pi\/Downloads\/microserver\/tw"}, {"updates": "\/home\/pi\/Downloads\/microserver\/updates"} ], "staging_dir": "\/home\/pi\/Downloads\/microserver\/staging" } } When the EMS runs, the config.json file will answer the following questions: Code Section Questions Answered ws_servers At what IP address / port is the ThingWorx Server located? appKey What is your Application Key? logger Where, and at what level, should we log errors? http_server What port should the WSEMS use to setup an HTTP server? ws_connection Should we use encryption? certificates Are we using Security Certificates? tunnel What are the configuration parameters for remote-tunneling? file What are the configuration parameters for file-transfer? We pre-defined the parameters for everything that we could, but you will still need to tell the WSEMS the IP address where the ThingWorx instance is located and a valid Application Key you either created earlier or may create now.   TIP: You may have noticed the pre-existing config.json.complete and config.json.minimal files. These are example files that come with the WSEMS and are provided as an aid. The code above which you copied into your own config.json file is simply a customization of these aids. In particular, you may wish to look through the config.json.complete file, as it shows every available option which you might want to configure if you choose to make a custom application with the WSEMS. The config.json.complete file also contains comments for each of these options. However, a functional config.json file may NOT contain comments of any kind, so you would need to remove all comments if you choose to copy/paste some code from that file into a functional config.json of your own making.     Modify config.json to point to ThingWorx Foundation   Change YOUR_IP_ADDRESS_HERE to the IP address of your hosted ThingWorx instance. You may wish to e-mail yourself the Foundation IP address using a web-mail account so that you can copy/paste on the Pi from your e-mail to the config.json file. Note that you may use a URL, such as "pp-180207xx36jd.devportal.ptc.io". Either way, the IP or URL must be enclosed in quotation marks (""). Also, Port 443 is the appropriate port for the ThingWorx hosted server. Ports for local-install may vary. 2. Change YOUR_APP_KEY_HERE to an Application Key which you have previously created. Or create a new Application Key now. You may wish to e-mail yourself the Application Key using a web-mail account so that you can copy/paste on the Pi from your e-mail to the config.json file.   3. Save and exit the file.   Create a config.lua file   Navigate to the /etc directory. Right-click inside the folder’s white-space and select New File.... Enter config.lua and click OK. Right-click on the new config.lua file and select Text Editor. Copy and Paste the following code into the empty config.lua file: scripts.log_level = "WARN" scripts.script_resource_ssl = false scripts.script_resource_authenticate = false scripts.PiThing = { file = "thing.lua", template = "YourEdgeThingTemplate", scanRate = 120000, sw_update_dir = "\/home\/pi\/Downloads\/microserver\/updates" } Save and exit the file.   Create a Custom Template for the EdgeThing   Navigate to /etc/custom/templates. Right-click inside the folder’s white-space and select New File.... Enter YourEdgeThingTemplate.lua and click OK. Right-click on the new YourEdgeThingTemplate.lua file and select Text Editor. Copy and Paste the following code into the empty YourEdgeThingTemplate.lua file: require "shapes.swupdate" module ("templates.YourEdgeThingTemplate", thingworx.template.extend) Save and exit the file.      Step 7: Connect EMS   In this step, you'll launch the EMS so that it can communicate with your ThingWorx Foundation platform.   On the Raspberry Pi , open a Terminal by clicking the Terminal icon in the top-left.   Navigate to the EMS's root folder, i.e. /home/pi/Downloads/microserver , by issuing the following command and then pressing Enter : cd /home/pi/Downloads/microserver   In the Terminal window, enter the command sudo ./wsems and press Enter . Note: Do not close this window, or the connection to the ThingWorx platform will close. Also, look through the output in the wsems window. Near the end, you should see Successfully connected. Saving .booted config file . If you do not see the Saving .booted comment, then you likely have an error in your config.json file... especially with either the address or Application Key .   Open another Terminal window as per the above instructions.   In this second Terminal window, Navigate to the EMS's root directory, i.e. /home/pi/Downloads/microserver , by issuing the following command and pressing Enter : cd /home/pi/Downloads/microserver In the second Terminal window, enter the command sudo ./luaScriptResource and press Enter . Note: Do not close this second Terminal window, or the connection to the ThingWorx platform will close.   NOTE: When the scripts start running, the EMS attempts to talk to the ThingWorx platform. However, at this point in the tutorial, ThingWorx does not have detailed information about the Edge device that is attempting to connect to it, so you will see an error message. This is the expected behavior which we will resolve in the next step. The wsems program runs through the config.json file in order to extract the basic connectivity information to reach the ThingWorx platform. The luaScriptResource program runs through the config.lua file to extract to which Thing the WSEMS should be connecting. Both programs must be running in order to achieve connectivity with ThingWorx. Program File Accessed Purpose wsems config.json Extracts basic connectivity information to reach the ThingWorx platform. luaScriptResource config.lua Determines to which Thing the WSEMS should connect. NOTE : Since the config.lua file which we previously created has a reference to a custom template, it also accesses the YourEdgeThingTemplate.lua file to extend the base functionality. Both programs must be running in order to achieve connectivity with ThingWorx. Troubleshoot Connectivity Issues   If the websocket does not connect successfully, check the following:   Issue Solution WEBSOCKET CLOSED - Warning seen immediately after Websocket gets connected. Ensure that the host IP address, port, and appKey of the ThingWorx composer instance are accurately set. If, in config.json, you have selected the option to validate certification, then make sure the path to the certificate file is correctly set. twWs_Connect - Error trying to connect. Ensure that the host IP address and port running the ThingWorx Composer is accurately set. Check if the certification parameter is set or not. By default, the WS EMS validates certificates. To ensure that the validation is performed correctly without errors, ensure that the certificates configuration parameters are set accurately with the correct path to the certificate file. If you do not wish to validate the certificate, you may explicitly set the validate parameter in certificates parameter set to false. twTlsClient_Connect - Error intializing TLS connection. Invalid certificate. Check if the ws_encryption parameter is present in your config.json file. By default, WS EMS enables TLS connection to the ThingWorx Platform. Ensure that the certificate file mentioned in config.json is valid and stored in the path specified. For debugging purposes, you can set the ssl parameter to none in ws_encryption configuration parameter. [WARN ] ... Main - Unable to connect to server. Trying .booted config file. Ensure that the host is up and running at the IP address and port number mentioned in the config.json file. Ensure that ThingWorx is running on the host address at the correct port number. Ensure that all necessary ports are open for communication.     Click here to view Part 4 of this guide.
View full tip
  Connect a Raspberry Pi to ThingWorx using the Edge MicroServer (EMS).   GUIDE CONCEPT   This project will utilize the Edge MicroServer (EMS) to connect ThingWorx Foundation to a Raspberry Pi.   YOU'LL LEARN HOW TO   Set up Raspberry Pi Install, configure, and launch the Edge MicroServer (EMS) Connect a remote device to ThingWorx Foundation   NOTE:  The estimated time to complete all parts of this guide is 60 minutes.     Step 1: Introduction   A Raspberry Pi is a small, single-board computer that utilizes an ARM processor and typically runs a variant of Linux.   Due to its small size, relatively affordable cost, and ability to run a full operating system, the Pi is a near-ideal device to utilize as a Proof-of-Concept (PoC) IoT Edge device.   In addition, there is a version of the ThingWorx Edge MicroServer (EMS) built to work on ARM processors. Therefore, this guide will explore getting the EMS running on a Raspberry Pi to connect to ThingWorx Foundation.       As stated in the Overview, you may purchase a Pi directly from the Raspberry Pi web site or from a distribution partner such as Digi-Key or RS.   You will also need an SD card (8+GB... 16+GB recommended) with the Raspbian operating system installed... though this guide will instruct you on installing the Raspbian OS on a microsdhc flash card if you prefer to purchase an SD card separately.   You may alternately wish to purchase a "Pi Canakit". Canakits, depending on the version, typically include a Pi, SD card with a version of Raspbian pre-installed, and various other items like sensors, a case, an HDMI cable, and other accessories.   To make this guide as straight-forward as possible, we'll assume a monitor, USB keyboard, USB mouse, and WiFi connectivity to interact with the Pi.   Note that the Pi has an HDMI port, so you may also need an HDMI-to-DVI convertor or similar if your monitor doesn't natively support HDMI.     Step 2: Format MicroSDHC Card   The microSDHC flash card which the Pi accepts may (or may not) come pre-installed with the Raspbian OS. If Raspbian is pre-installed and working, you may skip this step.   However, these flash cards are susceptible to corruption, especially if proper static-control guards are not followed or if the Pi is powered-down without going through a proper shutdown procedure.   As such, the steps immediately below will assume that you are installing (or re-installing) Raspbian on your microSDHC card.   Depending on your PC's ports, you may also require a microSDHC adapter to insert the flash card into your computer.   Locate your microSDHC card. Remember that 8+GB is mandatory, but 16+GB is recommended to ensure that the Pi has enough swap-space.   Locate your flash card adapter. Note that you may have a different type of adapter. Simply ensure that your PC can recognize the microSDHC card.   Insert the microSDHC card into the adapter.     Insert the adapter-plus-microsdhc card into your PC.     Assuming a Windows PC and either a pre-installed or corrupted flash card, you will receive a pop-up stating that it needs to be formatted prior to use; click Format disk.   On the following Format SDHC Card pop-up, click Start.   On the following Format Confirmation pop-up, click OK.     On the following Format Complete pop-up, click OK.   On the previous Format pop-up which is still open, click Close.   You now have a formatted microSDHC card which Windows can recognize.       Step 3: Flash MicroSDHC Card   Now that the flash card is accessible to Windows, you want to install the Raspbian OS on it.   Once again, this step assumes that you are installing (or re-installing) the Raspbian OS.   If your microSDHC card came pre-installed with Raspbian, then you may skip this step.   Download the Raspbian OS .zip file. Navigate to the download location and locate the Raspbian .zip file.   3. Right-click on the file and select Extract All....   4. On the Extract Pop-up, click Extract.   5. Download the balenaEtcher "flasher" software. 6. Navigate to the download location and locate the balenaEtcher .exe file.   7. Double-click on the balenaEtcher .exe to begin the installation process.   8. On the balenaEtcher installer pop-up, click I Agree. After the installation completes, balenaEtcher will automatically open.   9. Click Select image and navigate to the previously-extracted Raspbian OS .img file.   10. Select the .img file and click Open. Assuming the only microSDHC card currently inserted into your PC is the one for the Pi, then the SD SCSI Disk Device will be pre-selected; otherwise, choose the correct flash disk.   11. Click Flash!. Accept allowing the etcher to make changes to your computer.   12. Wait for balenaEtcher to complete the flashing process; this may take ~5-10 minutes.   13. Remove the microSDHC card and adapter from your PC.     Click here to view Part 2 of this guide.
View full tip
    Step 3 : Sending and Receiving JSON Objects   The ThingWorx platform handles REST requests by default. This enables all services to be outsourced to REST requests based on the permissions of the user.   Nevertheless, part of the problem with allowing the default JSON result might be the organization of the response. For example, making a request to a service with an InfoTable response will return information for the DataShape used by the InfoTable and a 'rows' field containing the data of the InFoTable. This can be troublesome or a nuisance when creating efficient B2B communication or parsers for the ThingWorx response.   Receiving JSON   First, let's handle the necessary security measures and configure our permissions to create a new User and Application Key. Then, handle how to parse a JSON object in the body of the POST REST request to the ThingWorx Platform. As an example, you will create a service that will take in a person JSON object and perform some simple calculations for the response. The simple JSON object is as follows: { "person": { "first_name": "John", "last_name": "Doe", "dob": "03/16/1989", "roles": [ { "role": "Manager" }, { "role": "Executive" } ] } }   Follow the steps below to set up a helper function to perform age calculations, and another to take this JSON object and simply return a response based on the age of the person: In ThingWorx Composer, click the + New at the top of the screen. Select Thing in the dropdown. Name the Thing JSONResponseExample and click Save. Click the Services tab. Create a new service called CalculatePersonAge. Set the Output as Integer. Add the following Input: Name Base Type Required dob String True   8. Add the following JavaScript to help encode the string and return an HTML friendly string. var result = 0; try { if(dob) { var today = new Date(); var birthDate = new Date(dob); var age = today.getFullYear() - birthDate.getFullYear(); var month = today.getMonth() - birthDate.getMonth(); if (month < 0 || (month === 0 && today.getDate() < birthDate.getDate())) { age--; } result = age; } } catch(err) { logger.error("JSONResponseThing.CalculatePersonAge(): An error occured while calculating an age - " + err.message); }   9. Click Done. 10. Click Save and you're all done with this helper service. This is a simple function to calculate a person's age with limited error handling for simplicity. Now let's handle the JSON object coming in the request and our response.   In the Services tab of the JSONResponseExample Thing, create a new service called HandleJSONRequest. The service will have the below properties as parameters. Name Base Type Required person JSON True   3. Set the Output as JSON. 4. Add the following JavaScript to help encode the string and return an HTML friendly string. var result = {}; result.message = ""; if(!person) { result.message = "We need a person to calculate their age."; } else if(!person.dob) { result.message = "We need the person's date of birth to calculate their age."; } else { if(!person.first_name) { result.message = "The person you provided is " + me.CalculatePersonAge({dob: person.dob}) + " years old"; } else { result.message = person.first_name + " is " + me.CalculatePersonAge({dob: person.dob}) + " years old"; } }   5. Click Done and go to the Permissions tab. 6. Configure the permissions of the JSONResponseExample thing to allow access to the User you created earlier. This user will need to have runtime permissions to execute the service and must belong in an organization with visibility (ie, Everyone). 7. Click Save, and you're done.   You've just created a service that takes JSON and returns JSON. There are numerous services to work with JSON objects. There is also a service to convert your JSON object to an InfoTable, FromJSON in the InfoTableFunctions Resource. Keep in mind, you will need to set the JSON to a form that can be translated to an InfoTable. If this format is unknown, use the ToJSON service from this Resource to see an example.   Running REST Request   If you need a quick refresher on how to run a REST request to the ThingWorx Platform, please see our REST API guide. The request to the ThingWorx Platform will be a POST method and you will need to set your Application Key in the header.   Sending JSON   Because services are based on JavaScript (Rhino JavaScript Engine), you can create objects the same way you would anywhere else. This is a very simple concept, but it becomes more complex as you try to create data based on ThingWorx-specific entities or models.   To convert an InfoTable to a better-formed JSON object, you will need to process the InfoTable rows based on the DataShape fields. The following code will do that: /* ...Perform code that creates an InfoTable called values... */ //Begin Processing the rows of data var result = {}; result.some_information = "some values"; result.data = []; var fields = values.dataShape.fields; for (var index = 0; index < values.getRowCount(); index++) { var entry = {}; for (var name in fields) { entry[name] = values.rows[index][name]; } result.data.push(entry); } Looking for a quick translation to JSON? Try the ReadEntityAsJSON service of the EntityServices Resource. You can use this to respond with complex ThingWorx models or just to see the setup for the JSON object in order to translate it to something simple the way the code above handles InfoTables. For a quick example, create a User, then create a service based on the below JavaScript (set the name field of the parameter to the name of the user you create): var params = { name: 'NameOfUserYouCreated' /* STRING */, type: 'Users' /* STRING */, key: 'SomeValue /* STRING - Encryption-Decrption Key Name is Optional*/ }; // result: JSON var result = Resources["EntityServices"].ReadEntityAsJSON(params);     Step 4: Sending XML Based Requests    There are many B2B services and applications that prefer to use XML over JSON. ThingWorx can send/receive XML via SOAP requests (POST) using the ContentLoaderFunctions Resource.   To get started, create a Thing using the below steps. You will create new services in this Thing to make SOAP requests.   NOTE: Examples of these services can be found in the XMLRequestThing entity, which is provided in the download.   You will use the PostXML service of the ContentLoaderFunctions Resource. This service takes parameters from the proxy information to handle SSL issues. All of the parameters are optional.   Perform the following steps to create your ThingWorx service to make requests.   In the ThingWorx Composer, click the + New at the top of the screen. Select Thing in the dropdown. Name the Thing XMLRequestExample and click Save. Click the Services tab and create a service called SendXMLRequest. The service will have the below properties as parameters. Name Base Type Required url String True body XML True   6. In the Snippets section, filter and search for PostXML. 7. Once you’ve found PostXML under the ContentLoaderFunctions section, add it to the editor. You’ll see all of the possible parameters for the request. In this example, you will set only the url and content values. 8. Update the code snippet to include the parameters. Use the below code as a reference: try { var params = { url: url /* STRING */, content: body /* XML */, }; // result: XML var result = Resources["ContentLoaderFunctions"].PostXML(params); logger.info(" XMLRequestThing.SendXMLRequest(): Results From Calling Service - " + JSON.stringify(result)); } catch(error) { logger.error(" XMLRequestThing.SendXMLRequest(): Error Calling Service - " + error.message); }   9. Click Save and you’re done with your first SOAP request. You can now enter your XML string as a parameter to call your new service. You can also assign your XML string directly to a variable in the service.   /*jshint multistr: true */ var body = ' \ <?xml version="1.0" encoding="UTF-8"?> \ <menu> \ <header> \ <title>A Cool Title</title> \ </header> \ <body> \ <lunch_menu> \ <food> \ <name>Belgian Waffles</name> \ <price>$5.95</price> \ <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description> \ <calories>650</calories> \ </food> \ <food> \ <name>Strawberry Belgian Waffles</name> \ <price>$7.95</price> \ <description>Light Belgian waffles covered with strawberries and whipped cream</description> \ <calories>900</calories> \ </food> \ </lunch_menu> \ <breakfast_menu> \ <food> \ <name>Belgian Waffles</name> \ <price>$5.95</price> \ <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description> \ <calories>650</calories> \ </food> \ <food> \ <name>Strawberry Belgian Waffles</name> \ <price>$7.95</price> \ <description>Light Belgian waffles covered with strawberries and whipped cream</description> \ <calories>900</calories> \ </food> \ <food> \ <name>Berry-Berry Belgian Waffles</name> \ <price>$8.95</price> \ <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> \ <calories>900</calories> \ </food> \ <food> \ <name>French Toast</name> \ <price>$4.50</price> \ <description>Thick slices made from our homemade sourdough bread</description> \ <calories>600</calories> \ </food> \ <food> \ <name>Homestyle Breakfast</name> \ <price>$6.95</price> \ <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> \ <calories>950</calories> \ </food> \ </breakfast_menu> \ </body> \ </menu>'; ```   Click here to view Part 3 of this guide.
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