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

Community Tip - Learn all about PTC Community Badges. Engage with PTC and see how many you can earn! X

IoT Tips

Sort by:
ThingWorx Manufacturing Apps Setup and Configuration Guide 8.1.0 ThingWorx Manufacturing Apps Customization Guide  8.1.0
View full tip
This design session introduces a real-world product scenario along with requirements for developing a related IoT-based application. You will also be introduced to core ThingWorx terminology and concepts that will help to map out an efficient design plan for the model hierarchy.     For full-sized viewing, click on the YouTube link in the player controls.   Visit the Online Success Guide to access our Expert Session videos at any time as well as additional information about ThingWorx training and services.
View full tip
This Expert Session consists of the general overview for platform export and import. It discusses the available options for safely exporting and importing entities, data, and extensions. It also provides information on the use of exported entities during the system upgrading and/or moving from QA to production server.  It’s assumed that the audience is familiar with the Composer and its navigation.     For full-sized viewing, click on the YouTube link in the player controls.   Visit the Online Success Guide to access our Expert Session videos at any time as well as additional information about ThingWorx training and services.
View full tip
This Expert Session will provide you with an in depth explanation behind how Signals are calculated in ThingWorx Analytics, what purpose they serve, and why we use them.  Some basic mathematical concepts are discussed so viewers will have a better idea of how ThingWorx Analytics operates behind the scenes.     For full-sized viewing, click on the YouTube link in the player controls.   Visit the Online Success Guide to access our Expert Session videos at any time as well as additional information about ThingWorx training and services.
View full tip
How to enable ThingWorx Performance Advisor Applies To ThingWorx 7.2+ Description How to enable ThingWorx Performance Advisor Resolution In the ThingWorx Composer, go to Systems > Subsystems, select the PlatformSubsystem and choose Configuration In the Metrics Reporting Service Configuration Select the "Enable Metrics Reporting" checkbox to activate Performance Advisor reporting Enter your current PTC credentials (username and password) for either the customer support portal or the developer portal After providing those details, use the Request button to request an Authorization Key. Customer Number and Name will be filled automatically and an Authorization Key is generated which allows the server identifying itself to the PTC environment. Those fields are read-only. ThingWorx is now ready to send Performance Advisor data and metrics to PTC Related FAQ - Performance Advisor for ThingWorx | PTC https://community.thingworx.com/community/developers/blog/2017/05/22/performance-advisor-for-thingworx-explore-configure…
View full tip
This Expert Session is about platform sizing with dependency on the type of environment and correlated scalability options. It talks about federation and high availability as well as provides visual diagrams to understand the architecture of different ThingWorx solutions.   For full-sized viewing, click on the YouTube link in the player controls.   Visit the Online Success Guide to access our Expert Session videos at any time as well as additional information about ThingWorx training and services.
View full tip
This video will provide you with a brief introduction to the New Composer interface, which has been made available in the 7.4 and later releases of the ThingWorx Platform.  For complete details on what functionality is available within this next generation composer interface, and to also see what lies ahead on our road map, please refer to the following post in the ThingWorx Community: NG Composer feature availability
View full tip
I've been working with the 7.x and 8.x versions of Thingworx over the last several months doing integrations. So I have a few development instances I've been working with. I'd like to go over some of the issues I've encountered and provide some potential best practices around how you work with Thingworx in development mode and transition to production. Typically, I'll create an instance and develop the integration using the Administrator user which is the only user created as you start up Thingworx instances. Lately, I've been having trouble with a lot of authentication failures as I build. Problem number 1: The new User Lockout feature. Around 7.2 a new User Lockout feature was added to Thingworx to help prevent brute-force cracking of passwords. You now are allowed only so many authentication failures in a given period of time before the user is automatically put in lock mode for a number of minutes. Unfortunately, (but realistically in a more secure manner), a lockout appears as more authentication failures. In reality, it is because the user you have just successfully authenticated to has been automatically locked. I came very close to wiping out an entire instance because I just couldn't get signed in. Then I remembered the lockout, so I worked on something else for a while and then tried to get back into the server and I was successful because the lock timeout had expired. To see the settings in your system, look at the User Management Subsystem configuration page. The Account Lockout Settings default to 5 failures in a 5 minute period that will result in a 15 minute lockout. One note is that setting the lockout to 0 doesn't disable it, it permanently locks out the account. It will have to be reset by a member of the administrators group. The screenshot below shows Problem number 2: AppKeys There is a new setting in the PlatformSubsystem that by default prevents the use of AppKeys in a URL. This setting is present because it is more secure. If you use an appKey as a query parameter in a URL, the appKey will be logged as clear text in your web browser's access log. This is a security risk - an AppKey, especially one not using a whitelist setting might make it possible for someone to gain access to your system by managing to see the access log for your system (maybe via some log analysis tool you feed your logs to). You can disable this setting, but it is not recommended for production - you may have to for a while because you may have code that uses this technique that must be updated before you can enforce the policy. You should deal with this in your production systems as soon as practical. See the graphic below on where this setting shows up. Problem number 3: REST API testing ​As a Thingworx developer, you're probably aware of tools like Curl, Postman and even the Web Browser that can let you exercise a REST API as you develop your code so you can validate your functionality. The REST guidelines specify that you should use the GET method to retrieve data, PUT to create data, POST to update data, etc. The issue is that it is easiest to test an API call if you can execute it from a web browser. However, the web browser always uses the GET method to make a request. This means that PUT and POST (along with other methods) will not work from your browser. Thingworx originally interpreted the incoming request and would internally reroute incoming requests to the POST or PUT functionality. This is also insecure because it makes it too easy to execute services from a browser. A setting was added to the PlatformSubsystem allow for a gradual transition to the more secure configuration. Turn this on in developer mode to simplify your testing of REST calls, but you should not leave it on in production mode as it provides a potential attack vector for your server. So I have some recommendations: 1) Set up an additional Administrative user upon installation If you only have one user defined and it gets locked out, you're stuck until the lockout times out. Worse, if for some reason you set the timeout value to 0, you're locked out forever by Thingworx. You're only choice will be to hack the database to unlock the user or to wipe out the instance and start over. I just went through a situation where I did create the second user and forgot to add it to the Administrators group. So I did something else for 20 minutes to make sure the lockout had cleared. Then I added the user to the Administrators group but got distracted and never pressed the Save button so it locked up again. Make sure you have the user created and functional immediately upon installing the instance - don't wait until you're getting locked out by some loop that's not authenticating properly. Even if you were logged in as your Administrator user, the lockout will cause a failure the next time you try to do something in Composer, like turn off the lockout checkbox! 2) Test your REST Calls with Curl or Postman - not the web browser Don't test your code in a loop until you've tested it in isolation to be sure it's not going to fail authentication for some reason (which may include violating the PlatformSubsystem settings above). Don't use the browser to do the testing - it will require disabling the secure settings. Use Curl or even better, Postman or a similar tool to test your REST calls - it will give you better formatted output than Curl. And you can easily put appKey in as a header (where it should be) instead of a parameter on the URL or in the body. 3) Tighten up your appKeys where possible. Since an appKey is effectively a user/password replacement, you should protect them in the same manner - keep them out of log files by not allowing them as URL parameters, and use the whitelist to keep them from being used for other purposes. If you have a server to server connection, whitelist the server who will be making the calls to you. What I'm not sure of is just whether this is really IP addresses only or if you can use a DNS name and it will look up the IP address and insure it is in fact coming from the expected source. Someone else might be able to comment on this. 4) Test with the PlatformSubsystem settings off Make sure you can run your server without the method redirect or appKey as parameter settings in the PlatformSubsystem. Those settings are potential security vulnerabilities. You may find some Thingworx code that requires one or the other of those settings. Please be sure to report this through PTC Tech Support so it can be fixed.
View full tip
Please refer to the release notes: PTC Here are some common questions and answers in regards to the Uprade change: Extension: The removal of dependencies was almost impossible. Do the changes allow extension updates without removal? That is correct Is uninstalling extensions "easier" possible? For example, having extensions with many dependencies which results in a struggle when manually deleting all include files...it would be great to have just 1 uninstall function. Unfortunately, that is still the case when one is uninstalling extension Is there an easy way to see all entity dependencies on an extension (vs. on any one template etc)? Not currently at the extension level.  That's certainly something to be considered adding If one made a mistake on changing an extension mashup, how do  they recover? Is it necessary to remove and then import newer extension? Yes, at the moment that is the only recourse.
View full tip
This article https://support.ptc.com/appserver/cs/view/solution.jsp?n=CS264270 and the blog post provide information on the technical changes in Thingworx 8.0, New Technical Changes in ThingWorx 8.0.0 Here are some common questions and answers in regards to the change. Is there any way that one could lose access to the Appkey keystore? (restore a backup, etc) Yes, it is possible to  lose the key store. If one for some reason simply deletes it or renames it, the existing application keys would no longer be able to be decrypted - thus unusable. Is there a way to back up the appkey store and any necessary secrets such that it can be recovered then? Yes, but this would be handled at the file system, not inside of ThingWorx. We do have some best practices documented for managing the keystore. For developers who configure Edge applications and Connectors to connect to the platform, where do they copy the app key from? Are they copyring the encrypted version of the app key? They would do the same as before. We are not encrypting the app key in the UI, only on disk. Is there any way to get a summary of appkeys that are being used via URL? We do have some requirements for highlighting "repeat offenders". In 8.0, one can query the logs to find those app keys. We don't log the app key id, only the app key name.
View full tip
Recently, mentor.axeda.com was retired. The content has not yet been fully migrated to Thingworx Community, though a plan is in place to do this over the coming weeks. Attached, please find OneNote 2016 and PDF attachments that contain the content that was previously available on the Axeda Mentor website.
View full tip
The following is a set of custom objects that will trigger from an Expression Rule, and cause a file uploaded by a remote agent to be sent on to the Thingworx platform instance of your choice once completed.  The expression rules should be configured as so: ​Type: ​File ​IF: ​1 == 1 ​THEN: ​ExecuteCustomObject("SendUploadedFiles") SendUploadedFiles.groovy: import com.axeda.drm.sdk.data.UploadedFile import static com.axeda.sdk.v2.dsl.Bridges.* logger.info("Executing AsyncExecutor") //Spawn async thread for each upload compressedFile.getFiles().each {   UploadedFile upFile ->     // last parameter is a timeout for the execution measured in seconds (200 minutes)     customObjectBridge.initiateAsync("SendToThingWorx",                                     [                                       fileID: upFile.id,                                       hint: parameters.hint,                                       deviceID: context.device.id                                     ], 200 * 60) }     SendToThingworx.groovy: import static com.axeda.sdk.v2.dsl.Bridges.* import com.axeda.services.v2.* import com.axeda.sdk.v2.exception.* import groovyx.net.http.HTTPBuilder import static groovyx.net.http.ContentType.* import static groovyx.net.http.Method.* import com.axeda.drm.sdk.data.*  // UploadedFileFinder stuff. import com.axeda.drm.sdk.Context import com.axeda.common.sdk.id.Identifier import org.apache.commons.codec.binary.Base64 def retStr = "this is a sample groovy script. your username: ${parameters.username}\n" def context = Context.getAdminContext() def thingName = 'ExampleThing' def thingworxHost = 'sample.cloud.thingworx.com' def twxApplicationKey = '00000000-0000-0000-0000-00000000000' def fileid = parameters.fileID def finder = new UploadedFileFinder(context) finder.setId( new Identifier( fileid.toLong()) ) UploadedFile uf = finder.find() def is = new FileInputStream( uf.extractFile() ) retStr += "UF: ${uf.name} ${uf.fileSize} ${uf.actualFileName}\n" logger.info  "UF: ${uf.name} ${uf.fileSize} ${uf.actualFileName}\n" def bOut = new ByteArrayOutputStream() int b = 0 int count = 0 while ( (b = is.read()) != -1  ) {     count ++     bOut.write(b) } is?.close() byte[] bRes = bOut.toByteArray() logger.info "Length: ${bRes.length}" retStr += "Count: ${count}  Length: ${bRes.length}\n" def b64 = new Base64() def outputStr = b64.encodeBase64String(bRes) retStr += "Length of base64 string: ${outputStr.length()}\n" logger.info "Length of base64 string: ${outputStr.length()}\n" logger.info "===========================================" logger.info outputStr logger.info "===========================================" def http = new HTTPBuilder("https://${thingworxHost}") http.request(POST, JSON) {     uri.path = "/Thingworx/Things/${thingName}/Services/SaveBinary"     body  = [path: uf.name, content: outputStr ]     headers = [appKey: twxApplicationKey ,                       Accept: 'application/json',                       "content-type": "application/json"             ]     response.success = { resp ->         println "POST response status: ${resp.statusLine}"         logger.info "POST RESPONSE status: ${resp.statusLine}"     }     response.failure = { resp ->         logger.info "RequestMessage: ${resp.statusLine}"         logger.info "Request failed: ${resp.status}"     } } return retStr    
View full tip
Sometimes M2M Assets should poll the platform on demand, such as in the case of avoiding excessive data charges from chatty assets.  A mechanism was developed that instructs the Asset to contact (poll) the platform for actions that the Asset needs to act on such as File Uploads, Set DataItem, etc. The Shoulder Tap SMS message is the platform’s way of contacting the Asset – tapping it on the shoulder to let it know there’s a message waiting for it.  The Asset responds by polling for the waiting message.  This implementation in the platform provides a way to configure the Model Profile that is responsible for sending an SMS Shoulder Tap message to an M2M Asset.  The Model Profile contains model-wide instructions for how and when a Shoulder Tap message should be sent. How does it work? The M2M asset is set not to poll the Axeda Platform for a long period, but the Enterprise user has some actions that the Asset needs to act upon such as FOTA (Firmware Over-the-Air).       Software package deployed to M2M Asset from Axeda Platform and put into Egress queue.       The Shoulder Tap mechanism executes a Custom Object that then sends a message to the Asset through a delivery method like SMS, UDP, etc.       The Asset’s SMS, etc. handler receives the message and the Asset then sends a POLL to the Platform and acts upon the action in the egress queue How do you make Shoulder Tap work for your M2M Assets? The first step is to create a Model Profile, the model profile will tell Asset of this model, how to communicate. For Example, if the Model Profile is Shoulder Tap, then the mechanism used to communicate to the Asset will imply Shoulder Tap.  Execute the attached custom object, createSMSModelProfile.groovy, and it will create a Model Profile named "SMSModelProfile". When you create a new Model, you will see  “SMSModelProfile“ appear in the Communication Profile dropdown list as follows: The next step is to create the Custom Object Transport script which is responsible for sending out the SMS or other method of communication to the Asset.  In this example the custom object is be named SMSCustomObject​.  The contents of this custom object are outside the scope of this article, but could be REST API calls to Twilio, Jasper or to a wireless provider's REST APIs to communicate with the remote device using an SMS message.   This could also be used with the IntegrationPublisher API to send a JMS message to a server the customer controls which could then be used to talk directly with custom libraries that are not directly compatible with the Axeda Platform. Once the Shoulder Tap scripting has been tested and is working correctly, you can now directly send a Shoulder Tap to the Asset from an action or through an ExtendedUI Module, such as shown below: import com.axeda.platform.sdk.v1.services.ServiceFactory; final ServiceFactory sFact = new ServiceFactory() def assetId = (Long)parameters.get("assetId") def stapService = ServiceFactory.getShoulderTapService() stapService.sendShoulderTap( assetId ) See Extending the Axeda Platform UI - Custom Tabs and Modules for more about creating and configuring Extended UI Modules. What about Retries? maxRetryCount  - This built in attribute’s value defines the number of times the platform will retry to send the Shoulder Tap message before it gives up. retryInterval -The retry interval that can be used if the any message delivery needs to be retried. Retry Count and Interval are configured in the Model Profile Custom Object like so: final DeliveryMethodDescriptor dmd = new DeliveryMethodDescriptor(); fdmd.setMaxRetryCount(2); fdmd.setRetryInterval(60);
View full tip
Objective Learn how the Scripto Web Service helps you to present platform information in your HTML with JavaScript and dynamic page updating.  After this tutorial, you will know how to create Axeda Custom Objects that return formatted results to JavaScript using XmlHttpResponse, and how a very simple page can incorporate platform data into your browser-based user interface. Part 1 - Simple Scripto In Using Scripto, you learned how Scripto can be called from very simple clients, even the most basic HTTP tools. This tutorial builds on the examples in that tutorial. The following HelloWorld script accepts a parameter named "foo". This means that the caller of the script may supply a value for this parameter, and the script simple returns a message that includes the value supplied. import static com.axeda.sdk.v2.dsl.Bridges.* import com.axeda.services.v2.* import com.axeda.sdk.v2.exception.* return "Hello world, ${parameters.foo}" In the first part of this tutorial, we'll be creating an HTML page with some JavaScript that simply calls the HelloWorld script and puts the result on the page. Create an HTML File Open up your favorite text editor and create a blank document. Paste in this simple scaffold, which includes a very simple FORM with fields for your developer platform email and password, and the "foo" parameter. <html> <head> <title>Axeda Developer Connection Simple Ajax HelloWorld Example</title> </head> <body> <form name="f1">         Platform email (login): <input name="username" type="text"><br/>         Password: <input name="password" type="password"><br/>         foo: <input name="foo" type="text"><br/> <input value="Go" type="button" onclick='JavaScript: callScripto()'/></p> <div id="result"></div> </form> </body> </html> Pretty basic HTML that you've seen lots of times. Notice the form onclick refers to a JavaScript function. We'll be adding that next. Add the JavaScript Directly under the <title> tag, add the following <script language="Javascript"> var scriptoURL ="http://dev6.axeda.com/services/v1/rest/Scripto/execute/"; var scriptName ="HelloWorld2"; </script> This defines our JavaScript block, and a couple of constants to tell our script where the server's Scripto REST endpoint is, and the name of the script we will be running. Let's add in our callScripto() function. Paste the following directly under the scriptName variable declaration: function callScripto(){ try{                 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); }catch(e){ // must be IE }    var xmlHttpReq =false;    var self =this;    // Mozilla/Safari    if(window.XMLHttpRequest){                 self.xmlHttpReq =new XMLHttpRequest();    }// IE elseif(window.ActiveXObject){                 self.xmlHttpReq =new ActiveXObject("Microsoft.XMLHTTP"); }    var form = document.forms['f1'];    var username = form.username.value;    var password = form.password.value;    var url = scriptoURL + scriptName +"?username="+ username +"&password="+ password;             self.xmlHttpReq.open('POST', url,true);             self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');             self.xmlHttpReq.onreadystatechange =function() {       if(self.xmlHttpReq.readyState ==4){                     updatepage(self.xmlHttpReq.responseText);       }    }    var foo = form.foo.value;    var qstr ='foo='+escape(foo);    self.xmlHttpReq.send(qstr); } That was a lot to process in one chunk, so let's examine each piece. This piece just tells the browser that we'll be wanting to make some Ajax calls to a remote server. We'll be running the example right off a local file system (at first), so this is necessary to ask for permission. try{                 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); }catch(e){ // must be IE } This part creates an XmlHttpRequest object, which is a standard object available in browsers via JavaScript. Because of slight browser differences, this code creates the correct object based on the browser type. var xmlHttpReq =false; var self =this; // Mozilla/Safari if(window.XMLHttpRequest){                 self.xmlHttpReq =new XMLHttpRequest(); } // IE elseif(window.ActiveXObject){                 self.xmlHttpReq =new ActiveXObject("Microsoft.XMLHTTP"); } Next we create the URL that will be used to make the HTTP call. This simply combines our scriptoURL, scriptName, and platform credentials. var form = document.forms['f1']; var username = form.username.value; var password = form.password.value; var url = scriptoURL + scriptName +"?username="+ username +"&password="+ password; Now let's tell the xmlHttpReq object what we want from it. we'll also reference the name of another JavaScript function which will be invoked when the operation completes. self.xmlHttpReq.open('POST', url,true);     self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');     self.xmlHttpReq.onreadystatechange =function(){ if(self.xmlHttpReq.readyState ==4){             updatepage(self.xmlHttpReq.responseText); } } Finally, for this function, we'll grab the "foo" parameter from the form and tell the prepped xmlHttpReq object to post it. var qstr ='foo='+escape(foo);     self.xmlHttpReq.send(qstr); almost done. We just need to supply the updatepage function that we referenced above. Add this code directly before the </script> close tag: function updatepage(str){             document.getElementById("result").innerHTML = str; } Try it out Save your file as helloworld.html and open it in a browser by starting your browser and choosing "Open File". You can also download a zip with the file prepared for you at the end of this page. If you are using Internet Explorer, IE will pop a bar asking you if it is OK for the script inside this page to execute a script. Choose "Allow Blocked Content". Type in your platform email address (the address you registered for the developer connection with) and your password. Enter any text that you like for "foo". When you click "Go", the area below the button will display the result of the Scripto call. Note that if you are using Mozilla Firefox, you will be warned about the script wanting to access a remote server. Click "Allow". Congratulations! You have learned how to call a Custom Object-backed Scripto service to display dynamic platform content inside a very simple HTML page. Next Steps Be sure to check out the tutorial on Hosting Custom Applications to learn how you can make this page get directly served from your platform account, with its very own URL. Also explore code samples that show more sophisticated HTML+AJAX examples using Google Charts and other presentation tools.
View full tip
Expression rules are the heart of the Axeda Platforms processing capability. These rules have an If-Then-Else structure that's easy to create and understand. We think they're like a formula in a spreadsheet. For example, say your asset has a dataitem reading for temperature: IF: temperature > 80 THEN: CreateAlarm("High Temp", 100)                      This rule compares the temperature to 80 every time a reading is received. When this happens, the rule creates an alarm with name "High Temp" and severity 100. Dataitems represent readings from an asset. They are typically sensors or monitoring parameters in an application. But also think of dataitems as variables. The rule can be changed to IF: temperature > threshold                      so that each asset has its own threshold that can be adjusted independently. Look at the complete list of Expression Rule triggers - the events that trigger a rule to run variables - the information you can access in an expression functions - the functions that can be used within an expression actions - these are called in the Then or Else part of an expression to make something happen A rule can calculate a new value. For example, if you wanted to know the max temperature IF: temperature > maxTemperature THEN: SetDataItem("maxTemperature" temperature) To convert a temperature in celsius to fahrenheit IF: temperature THEN: SetDataItem("tempF", temperature*9/5 + 32) The If simply names the variable, so any change to that variable triggers the rule to run. There may be lots of other dataitems reported for an asset, and changes to the other dataitems should not recalculate the temperature. When rules should run only when an asset is in a particular mode or state, or when there is a complex sequence to model, read about how State Machines come to the rescue. Creating and Testing an Expression Rule ​ We're going to create a simple Expression Rule and show it running in a few steps. Above, you saw a rule that created an alarm when temperature > 80. Now, we will make one that converts a temperature in F to one in C. An Expression Rule consists of a few things: Name Description - an optional field to describe the rule Trigger - what makes this rule run? The trigger tells the rule if it applies to Alarms, Data, Files, or many others. If - the logic expression for the condition to evaluate Then - the logic to run if the condition is true Else - the logic to run if the condition is false To begin, log into an Axeda Platform instance. Navigate to the Manage tab Select ​New​, then ​Expression Rule​ Enter this Expression Rule information Name: TempConvert Type: Data Description: Enabled: Leave checked If: TempC Then: SetDataItem("TempF", TempC*9/5 + 32) If you click on functions or scroll down for actions in the Expression Tree, you will see a description in Details. Click the Apply to Asset​ button to select models and specific assets to apply this rule to. Now that you have an Expression Rule, lets try it. Testing the Expression Rule (NEEDS UPDATING) You can test the expression rule by simulating the TempC data using Axeda Simulator, as instructed below. Or, you can use the Expression Rules Debugger to simulate the reading and display the results. For information about using the Expression Rules Debugger, see the Expression Rules Debugger documentation in the on-line Help system.Simulate a TempC reading Launch the Axeda Simulator The Axeda Simulator will launch in a new browser window Enter your registered email address, Developer Connection password, and click Login.       Select asset1 from the Asset dropdown. Under the Data tab, enter the dataitem name TempC, and a value like 28: Then Click Send. To see the exciting result, go back to the Platform window and navigate to the Service tab: and you should see that 28C = 82.4F. You created an Expression Rule that triggers when a value of TempC is received, and creates a new dataitem TempF with a calculated value. This rule applies to your model, but if you had many models of assets, it could apply to as many as you want. You could change the rule to do the conversion only If: TempC > 9 and simulate inputs to see that this is the new behavior. Further Reading Read about how Rule Timers can trigger rules to run on a scheduled basis. (TODO)
View full tip
This example shows how a file can be retrieved via Scripto and then displayed on a Web page. Precondition is that an asset has an uploaded file. This script assumes the file is there and that it is not extremely large (under 1 megabyte). This example uses base64 encoding to convert the file into a string. Future versions of Scripto will support other data streams so that base64 encoding will not be necessary. import com.axeda.drm.sdk.Context import com.axeda.drm.sdk.data.UploadedFile import com.axeda.drm.sdk.data.UploadedFileFinder import com.axeda.drm.sdk.device.Device import com.axeda.drm.sdk.device.DeviceFinder // This script requires parameter "id" Context ctx = Context.create(parameters.username); def response = '' try {     DeviceFinder deviceFinder = new DeviceFinder(ctx, new Identifier(parameters.id as Integer));     Device device = deviceFinder.find();     UploadedFileFinder uff = new UploadedFileFinder(ctx)     uff.device = device     uff.hint = 'photo'     def ufiles = uff.findAll()     UploadedFile ufile     if (ufiles.size() > 0) {         ufile = ufiles[0]         File f = ufile.extractFile()         response = getBytes(f).encodeBase64(false).toString()     } } catch (Exception e) {     logger.info(e.message);     response = [             faultcode: 'Groovy Exception',             faultstring: e.message     ]; } return ['Content-Type': 'data:image/png;base64', 'Content': response]; static byte[] getBytes(File file) throws IOException {     return getBytes(new FileInputStream(file)); } static byte[] getBytes(InputStream is) throws IOException {     ByteArrayOutputStream answer = new ByteArrayOutputStream(); // reading the content of the file within a byte buffer     byte[] byteBuffer = new byte[8192];     int nbByteRead /* = 0*/;     try {         while ((nbByteRead = is.read(byteBuffer)) != -1) { // appends buffer             answer.write(byteBuffer, 0, nbByteRead);         }     } finally {         is.close()     }     return answer.toByteArray(); }
View full tip
This groovy script creates an xml output of the audit log filtered by the User Access category, so dates of when users logged in or logged out. Parameter: days - number of days to search import com.axeda.drm.sdk.device.ModelFinder import com.axeda.drm.sdk.Context import com.axeda.common.sdk.id.Identifier import com.axeda.drm.sdk.device.Model import com.axeda.drm.sdk.device.DeviceFinder import com.axeda.drm.sdk.device.Device import com.axeda.drm.sdk.audit.AuditCategoryList import com.axeda.drm.sdk.audit.AuditCategory import com.axeda.drm.sdk.audit.AuditEntryFinder import com.axeda.drm.sdk.audit.SortType import com.axeda.drm.sdk.audit.AuditEntry import groovy.xml.MarkupBuilder /* * AuditEntryList.groovy * * Creates an xml output of the audit log filtered by the User Access category, so dates of when users logged in or logged out. * * @param days        -   (REQ):Str number of days to search. * * @author Sara Streeter <sstreeter@axeda.com> */ def writer = new StringWriter() def xml = new MarkupBuilder(writer) try {     def ctx = Context.getUserContext()     ModelFinder modelFinder = new ModelFinder(ctx, new Identifier(1))     Model model = modelFinder.find()     DeviceFinder deviceFinder = new DeviceFinder(ctx, new Identifier(1))     Device device = deviceFinder.find()     AuditCategoryList acl = new AuditCategoryList()     acl.add(AuditCategory.USER_ACCESS)     long now = System.currentTimeMillis()     Date today = new Date(now)     def paramdays = parameters.days ? parameters.days: 5     long days = 1000 * 60 * 60 * 24 * Integer.valueOf(paramdays)     AuditEntryFinder aef = new AuditEntryFinder(ctx)     aef.setCategories(acl)     aef.setToDate(today)     aef.setFromDate(new Date(now - (days)))     aef.setSortType(SortType.DATE)     aef.sortDescending()     List<AuditEntry> audits = aef.findAll() // assemble the response     xml.Response() {         audits.each { AuditEntry audit ->                   Audit() {                 id(audit?.id.value)                 user(audit?.user?.username)                 date(audit?.date)                 category(audit?.category?.bundleKey)                 message(audit?.message)             }         }     } } catch (def ex) {     xml.Response() {         Fault {             Code('Groovy Exception')             Message(ex.getMessage())             StringWriter sw = new StringWriter();             PrintWriter pw = new PrintWriter(sw);             ex.printStackTrace(pw);             Detail(sw.toString())         }     } } return ['Content-Type': 'text/xml', 'Content': writer.toString()]
View full tip
Recently I have been accompanying an integration partner and end customer around an issue experienced with ThingWorx resource exhaustion.  Early on it seemed like this was an issue with the ThingWorx Azure IoT Hub Connector as it would freeze up and become unresponsive.  Following a root cause analysis it became clear that it was actually caused by a lack of a number of standard cloud design patterns, which if used would have automatically adapted operation of the overall solution to be far more resilient as well as resource optimized.   The way that the logic was structured, it prioritized job execution on entities with the oldest last success time and would continue to retry these executions (IoT Direct Methods) every few seconds until successful.  There were a number of problems here, but I'll unpack a few in order to tie the problem to the solution via design patterns.   1) No exception handling When the direct method execution failed/timed out or the system reported being unable to execute the remote service, this response was not used to adapt the solutions behavior. 2) No backoff retry mechanism As exceptions were not caught, an adaptive retry mechanism with incremental or exponential backoff could not be leveraged to limit the impact of the build up of the failing retries. 3) No exception tracking Tracking that exceptions were occurring and counting them would allow powering an exponential backoff retry algorithm (with jitter), a Cancel or Circuit Breaker pattern (stop doing something which is just broken), as well as provided alerting to address specific areas of the distributed solution experiencing issues. 4) Conflicting priorities It was interesting to see the manifestation of the conflicting interests of wanting to ensure checks and balances (had all needed data) and system resiliency.  Retries and resource usage built up exponentially due to the transient error instead of backing them off.  Trying so hard to get the needed data from failing sensors meant that operational sensors were deprioritized and their data was not received either - spreading the localized issue to the whole system.   Around the time that I shared my recommendations and some examples of how to make the solution more resilient, one of my technical colleagues at Microsoft shared some extremely interesting and relevant design patterns documented by Microsoft as a part of the "Microsoft Azure Well-Architected Framework".  This framework with included Design Patterns for specific cloud application goals allows applying well-known industry standard approaches to dealing with the challenges of large scale distributed enterprise systems (reliability, performance, cost optimization).   She later then shared this blog post describing exactly the exponential backoff retry with jitter pattern which we had together recommended to the systems integrator.   What's interesting for us ThingWorx people is that this framework from Microsoft is about well-architected cloud solutions and does not specifically reference the Azure stack, and as such many of these approaches and design practices can be employed in your ThingWorx applications.  What are you waiting for?  Go check them out!
View full tip