77
ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015

android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Embed Size (px)

Citation preview

Page 1: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

 

                                                                             

ThingWorx Android SDK Developer’s

Guide Version 6.6.0

ThingWorx Java SDK

August 2015

Page 2: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

 

Page 3: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

     

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All Rights Reserved.  

User and training guides and related documentation from PTC Inc. and its subsidiary companies (collectively “PTC”) are subject to the copyright laws of the United States and other countries and are provided under a license agreement that restricts copying, disclosure, and use of such documentation. PTC hereby grants to the licensed software user the right to make copies in printed form of this documentation if provided on software media, but only for internal/personal use and in accordance with the license agreement under which the applicable software is licensed. Any copy made shall include the PTC copyright notice and any other proprietary notice provided by PTC. Training materials may not be copied without the express written consent of PTC. This documentation may not be disclosed, transferred, modified, or reduced to any form, including electronic media, or transmitted or made publicly available by any means without the prior written consent of PTC and no authorization is granted to make copies for such purposes.

Information described herein is furnished for general information only, is subject to change without notice, and should not be construed as a warranty or commitment by PTC. PTC assumes no responsibility or liability for any errors or inaccuracies that may appear in this document.

The software described in this document is provided under written license agreement, contains valuable trade secrets and proprietary information, and is protected by the copyright laws of the United States and other countries. It may not be copied or distributed in any form or medium, disclosed to third parties, or used in any manner not provided for in the software licenses agreement except with written prior approval from PTC.

UNAUTHORIZED USE OF SOFTWARE OR ITS DOCUMENTATION CAN RESULT IN CIVIL DAMAGES AND CRIMINAL PROSECUTION. PTC regards software piracy as the crime it is, and we view offenders accordingly. We do not tolerate the piracy of PTC software products, and we pursue (both civilly and criminally) those who do so using all legal means available, including public and private surveillance resources. As part of these efforts, PTC uses data monitoring and scouring technologies to obtain and transmit data on users of illegal copies of our software. This data collection is not performed on users of legally licensed software from PTC and its authorized distributors. If you are using an illegal copy of our software and do not consent to the collection and transmission of such data (including to the United States), cease using the illegal version, and contact PTC to obtain a legally licensed copy.

 Important Copyright, Trademark, Patent, and Licensing Information: See the About Box, or copyright notice, of your PTC software.

UNITED STATES GOVERNMENT RESTRICTED RIGHTS LEGEND  

This document and the software described herein are Commercial Computer Documentation and Software, pursuant to FAR 12.212(a)-(b) (OCT’95) or DFARS 227.7202-1(a) and 227.7202-3(a) (JUN’95), and are provided to the US Government under a limited commercial license only. For procurements predating the above clauses, use, duplication, or disclosure by the Government is subject to the restrictions set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software Clause at DFARS 252.227- 7013 (OCT’88) or Commercial Computer Software-Restricted Rights at FAR 52.227-19(c)(1)-(2) (JUN’87), as applicable. 01012015

PTC Inc., 140 Kendrick Street, Needham, MA 02494 USA

Page 4: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

 

Page 5: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 5

 

     

Contents      

About this Guide .............................................................................................................................. 7

The Java SDK ................................................................................................................................ 11 About the Java SDK .............................................................................................................. 12 Developing Your Client Application ..................................................................................... 27

Primary Components of the Java SDK ....................................................................................... 29 ClientConfigurator Component ............................................................................................ 30 ConnectedThingClient Component .................................................................................... 32 VirtualThing Component ....................................................................................................... 33

Setting up an Application .............................................................................................................. 35 The Client ............................................................................................................................... 36 Virtual Things ......................................................................................................................... 46 Base Types and Primitives ................................................................................................... 60 Java SDK Logging ................................................................................................................. 63

Java SDK and File Transfers ......................................................................................................... 67 Configuring File Transfers ...................................................................................................... 68 Performing a File Transfer Using the Copy Service .......................................................... 68 Performing a File Transfer from a Client Application ........................................................ 69

Tunneling .......................................................................................................................................... 71 Configuring Tunneling ............................................................................................................. 72

Content Loader Services .............................................................................................................. 73

Troubleshooting ............................................................................................................................... 75

Page 6: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

 

 

Page 7: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 7

 

                       

About this Guide    

ThingWorx has introduced Software Development Kits (SDKs) in several programming languages that allow companies to develop machine/device functionality for their products, and to easily connect their products to a ThingWorx Platform Server. All ThingWorx SDKs share a common reference implementation and provide a secure communication channel to a ThingWorx Platform, allowing a machine/ device to be a full participant in a ThingWorx solution. This document describes how to use the ThingWorx Java SDK. In addition to this guide, a JavaDoc is available in the SDK bundle.

     

Note This document is accurate as of the release and is subject to change. For the latest documentation, see the Help Center available at PTC ThingWorx eSupport, https://support.ptc.com/appserver/cs/portal/.

   

Pre-requisites The only system requirement is that you have the following version of the Java JRE installed:

Page 8: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 8

 

 

       

• Java JRE 1.7.0.51 or later. This document assumes that you have a solid background in the Java programming language. Further, it assumes that you have had at least basic training in ThingWorx. For example, you know how to use the ThingWorx Composer and understand the main concepts of Things, DataShapes, Properties, Events, and Services.

 Technical Support Contact PTC Technical Support via the PTC Web site, phone, fax, or e-mail if you encounter problems using your product or the product documentation. For complete details, refer to Contacting Technical Support in the PTC Customer Service Guide. This guide can be found under the Related Resources section of the PTC Web site at: http://www.ptc.com/support/ The PTC Web site also provides a search facility for technical documentation of particular interest. To access this search facility, use the URL above and search the knowledge base. You must have a Service Contract Number (SCN) before you can receive technical support. If you do not have an SCN, contact the PTC Maintenance Department using the instructions found in your PTC Customer Service Guide under Contacting Your Maintenance Support Representative.

 Documentation for PTC ThingWorx Products You can access PTC ThingWorx documentation, using the following resources:

• PTC ThingWorx Help Center — The PTC ThingWorx Help Center includes documentation for the PTC ThingWorx Platform, the PTC ThingWorx Edge MicroServer (EMS), and all the SDKs. You can browse the entire documentation set, or use the search capability to perform a keyword search. To access the PTC ThingWorx Help Center, visit ThingWorx Help Center.

• PTC ThingWorx Reference Documentation — The Reference Documents website provides access to the PDF documents available for the PTC ThingWorx Edge SDKs and the PTC ThingWorx Platforms at http://support. ptc.com/appserver/cs/doc/refdoc.jsp, These PDF documents include System Requirements documents.

A Service Contract Number (SCN) is required to access the PTC documentation from the Reference Documents website. If you do not know your SCN, see “Preparing to contact TS” on the Processes tab of the PTC Customer Support Guide for information about how to locate it: http://support. ptc.com/appserver/support/csguide/csguide.jsp. When you enter a keyword in

Page 9: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 9

 

 

       

the, "Search Our Knowledge" field on the PTC eSupport portal, your search results include both knowledge base articles and PDF guides.

 Comments PTC welcomes your suggestions and comments on our documentation. To submit your feedback, you can:

• Send an email to [email protected]. To help us more quickly address your concern, include the name of the PTC product and its release number with your comments. If your comments are about a specific help topic or book, include the title.

• Click the feedback icon in the PTC ThingWorx Help Center toolbar and complete the feedback form. The title of the help topic you were viewing when you clicked the icon is automatically included with your feedback.

Page 10: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

 

 

 

Page 11: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 11

 

 

                       

1 The Java SDK

About the Java SDK ...................................................................................................................... 12 Developing Your Client Application ............................................................................................. 27

Page 12: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 12

 

 

   

About the Java SDK This chapter provides an overview of the Java SDK, explaining the relationship between the SDK and the ThingWorx server and summarizing the purpose of the Java SDK. The Java SDK is designed for portability while making it easy to integrate applications into the ThingWorx distributed computing view of the Internet of Things (IoT). The goal of the Java SDK is to make it simple to connect any Java- enabled devices and/or systems to the ThingWorx server. In addition, the SDK is designed to give developers enough flexibility to start simple and move quickly to creating highly sophisticated applications. The ThingWorx Java SDK allows you to create an application for your machines/ devices that communicates with the ThingWorx Platform. The SDK uses the WebSockets protocol for communication. The WebSockets protocol allows persistent (AlwaysOn™) connections that can operate through a firewall. The persistence enables two-way, low latency communication between the device and server. If required, the connection can be configured to remain open only for specific time periods, or duty cycles The purpose of the Java SDK includes the following: • To establish and manage a secure AlwaysOn™ connection

with a ThingWorx server, which includes: ○ TLS negotiation ○ Duty-cycle modulation ○ Connection maintenance, such as reestablishing a connection after network

connectivity is lost and restored. • To enable simple programmatic interaction with the properties, services, and

events that are exposed by RemoteThings created on a ThingWorx server. ○ To easily define properties and services that can be accessed from the

ThingWorx server.  

 Installing and Navigating the Java SDK Directories Installation To install the Java SDK, download the Java SDK bundle to your computer, and extract the files.

Page 13: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 13

 

 

       

Directories and Files The Java SDK installation contains the following directories: • lib — Contains the JARs listed in the table, Contents of the lib Directory on

page 13. • resources — Contains the XML template for the logback fefature,

logback-template.xml, • samples — Contains the Java source files for the sample applications. HAVE ANY OTHER JARS BEEN ADDED FOR THE UPCOMING RELEASE?

Contents of the lib Directory  

File Name Version Description jackson- annotations- 2.3.3.jar

2.3.3 Jackson Annotations for Jackson Data Processor

jackson-core- 2.3.3.jar

2.3.3 Jackson JSON processor

jackson-databind- 2.3.3.jar

2.3.3 Jackson Databinding for Jackson Data Processor

joda-time.2.3.jar 2.3 Joda Time date and time classes

logback-classic- 1.0.13.jar

1.0.13 Logback logging

logback-core- 1.0.13.jar

1.0.13 Logback logging

netty-all- 4.0.24.Final.jar

4.0.24 NIO Client server framework

slf4j-api- 1.7.5.jar

1.7.5 Simple Logging Façade for Java

thingworx-common- v.v.v-bnn.jar

Current ThingWorxPlatform version (e.g., 6.0.3–b10)

ThingWorx SDK implementation

 Java Dependencies Here is a dependency tree that shows the required jar files for a sample application that uses the jackson-annotations.jar, jackson-core.jar, joda-time.jar, slf4j-api- 1.7.5.jar com.ptcmanaged.thingworx:temperature-thing:jar:1.1-SNAPSHOT

 +- com.fasterxml.jackson.core:jackson-databind:jar:2.3.1:compile

Page 14: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 14

 

 

       

+- com.fasterxml.jackson.core:jackson-annotations:jar:2.3.0:compile | \- com.fasterxml.jackson.core:jackson-core:jar:2.3.1:compile +- joda-time:joda-time:jar:2.3:compile +- ch.qos.logback:logback-classic:jar:1.0.13:compile | \- org.slf4j:slf4j-api:jar:1.7.5:compile +- ch.qos.logback:logback-core:jar:1.0.13:compile +- io.netty:netty-all:jar:4.0.19.Final:compile +- com.thingworx:thingworx-common:jar:5.0.1:compile

 Sample Applications The samples directory contains the SteamSensor example code files (SteamSensor.java and SteamSensorClient.java) that you should examine before attempting your own application. You can find documentation for the example in the ThingWorx Help Center. In addition, the samples directory contains code examples that are shown in the following sections: • Connecting an Application to thee ThingWorx Platform on page 15 • Reading a Property on page 18 • Writing a Property on page 19 • Invoking a Service on page 19 • Firing Events on page 20

   

Setting Up the ThingWorx Platform to Communicate with a Client Before running a client application from a device, you must create a Thing on the ThingWorx Platform that represents your application and allows it to communicate with the ThingWorx Platform Within ThingWorx Composer, add a new RemoteThing, using the RemoteThing template. If you need assistance, refer to the help for the application.

   

Using ThingWorx and the Java SDK The ThingWorx Java SDK is designed to be flexible enough to be used across a wide variety of products and services for smart, connected products. From very simply connecting a device to the ThingWorx Platform for monitoring purposes to high-end, sophisticated data collection and processing for use in analytical software, applications written using the ThingWorx Java SDK can run on any device, machine, or system that has a JRE (v1.7.51 or later). Together with the ThingWorx Platform, the ThingWorx Java SDK enables you to achieve the following goals:

• Collect data from physical devices and push it to the ThingWorx Platform. For example, collect speed, acceleration, and heading for a bicycle and push this information to the

Page 15: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 15

 

 

       

Platform. Sensors may be capable of determining if the bicycle is skidding and when that information reaches the Platform, an alert might be triggered.

Note that calls to the Platform to update a RemoteThing are queued and applied in sequence, based on timestamp. To ensure updates happen when you expect, the clocks of the remote application and the Platform hosts must be synchronized.

• Access the current value of properties on the remote device and display them in Mashups created with the ThingWorx Plat AlwaysOn™ form.

How is this possible? First, you should understand how clients connect to the server and then the basic concepts of Things and how to work with them.

 Connecting an Application to the ThingWorx Platform The Java SDK follows a three-step process when connecting to the ThingWorx Platform. In the process detailed below, “client” refers to the application and Java SDK running on or near the device and “server” refers to the ThingWorx Platform:

1. Establish the physical websocket: The client opens a websocket to the ThingWorx server, using the host and port that it has been configured to use. If configured, TLS is negotiated at this time.

2. Authenticate: The client sends an authentication message to the server, containing either an Application Key (recommended) or a user name and password combination. This message is part of the ThingWorx AlwaysOn™ protocol. If the client attempts to send any other message before the authentication message, the server disconnects it. The server also disconnects the client if it does not receive an authentication message within 15 seconds. This time is configurable in the WSCommunicationSubsystem

Page 16: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 16

 

 

       

which can be found inside the ThingWorx composer under System>Subsystems>Entity Information>Configuration. The setting is named, "Amount of time to wait for authentication message (secs)".

Establishing a connection and authenticating are both performed whenever a new SDK client is created and its start() method is called. Once authenticated, the client can interact with the server according to the permissions granted to its credentials. At this point, the client can make requests to the server and interact with it. Note, however, that the server can not yet direct requests to the client.

3. Bind: Binding is an optional step in the client connection process. The SDK client allows one or more VirtualThings to be associated with a websocket connection, using thing names or identifiers. When the client binds a VitrualThing class, the server links the associated RemoteThing on the server with the websocket from which it received the request. Binding enables the server to send request messages to a VirtualThing over the associated websocket. The server also updates the isConnected property to true and the time value of the

3. lastConnected property for the newly bound Thing to indicate when the binding was established.

A client can also send an unbind request. This message tells the server to remove the association between the Thing and the websocket. The isConnected property of the Thing is then updated to false.

To enable your application to connect to the Platform, you need to create a ClientConfigurator and then use it to create a ConnectedThingClient that will then establish your connection to the server. Here is an example of how this is done:

   

public static void main(String[] args) {

ClientConfigurator config = new

ClientConfigurator();

 // Set the URI of the server that we are going to connect to

config.setUri("wss://yourserver.com:443/Thingworx/WS");

 // Set the ApplicationKey. This will allow the client to authenticate

with

// the server. It will also dictate what the client is authorized to

// do once connected.

config.setAppKey("32491397-fffff-5555-555a-376ff92aae02");      

// To test against a server using a self-signed certificate, use

Page 17: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 17

 

 

// the ignoreSSLErrors method. HOWEVER< make sure that you remove

// this line for a production system.

config.ignoreeSSLErrors(true); //All self-signed certificates

 try {

   

// Create our client.

SimpleClient client = new SimpleClient(config);    

// Start the client. The client will connect to the server and

// authenticate, using the ApplicationKey specified above.

client.start();

 // Wait for the client to connect.

if (client.waitForConnection(30000)) {

System.out.println("The client is now

connected.");

} else {

// Log this as a warning. In production the application could

// continue to execute, and the client would attempt to

// reconnect periodically.

System.err.println ("Client did not connect within 30 seconds. Exiting");

}    

client.shutdown();    

} catch (Exception e) {

System.err.println("An exception occured while initializing the client", e);

}  

System.out.println("SimpleClient is done. Exiting");

}

 With this connection, you have a fast, continuously connected, bidirectional data channel between the ThingWorx Platform and as many remote processes as you want. The AlwaysOn™ protocol enables this communication. What can you do with this channel?

• Make remote calls to any ThingWorx RemoteThing or Resource (API). You can expose functions within your process that can be called by the server in response to changes on the server side, providing you with notifications of that change.

• Transfer files bidirectionally.

Page 18: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 18

 

 

       

• Tunnel other protocols through this connection. • Take advantage of a Thing synchronization framework that simplifies the task

of updating server RemoteThings by creating remote versions of them within your remote process. You then update the state of the VirtualThing in your process, and the SDK manages the transfer of that state information to the server, either when you want to push it or when the server requests it. For details about this synchronization framework, see Synchronization Framework on page 26.

     

Best Practice Use of the ignoreSSLErrors method is purely for development purposes. It is strongly recommended that you use SSL/TLS for connections between your devices and the ThingWorx Platform. For an example of setting up X.509 parameters for an SSL/TLS connection, refer to the code example in the topic, Using Security Claims to Protect the Connection on page 38.

 

 

Now lets take a look at how to read and write properties, invoke services, and fire events.

 Reading a Property Now that the client has connected to ThingWorx, you can read a property from a Thing on the server: // We may now interact with the ThingWorx Server;

  // Reading a property of a Thing ///////////////////////////////////////////////////////////////

 // Request a property from a Thing on the Platform. // Here we access the 'name' property of a Thing. InfoTable result = client.readProperty(ThingworxEntityTypes.Things, ThingName,

"name", 10000);  

// Result is returned as an InfoTable, so we must extract the value. // An InfoTable is a collection of one or more rows. A row can have // multiple fields. Each field has a name and a base type. In this // case, the field name is 'name' and the base type is STRING, so // we can use the getStringValue() helper. String name = result.getFirstRow().getStringValue("name");

LOG.info("The name of the Thing {} is: {}", ThingName, name);

// We can also access the value as a Primitive. // This will work for all primitive types.

Page 19: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 19

 

 

       

StringPrimitive prim = (StringPrimitive) result.getFirstRow().getPrimitive("name");

LOG.info("The name of the Thing {} is: {}", ThingName, prim.getValue());

Writing a Property You can also write a property: //

// Writing a property

///////////////////////////////////////////////////////////////

LocationPrimitive location = new LocationPrimitive(42.36, -71.06, 10.0);

// This code sets the CurrentLocation property of the Thing to the GPS

// coordinates of Boston, MA.

client.writeProperty(ThingworxEntityTypes.Things, ThingName, "CurrentLocation",

location, 5000);

 LOG.info("Wrote to the property 'CurrentLocation' of Thing {}. value: {}",

ThingName, location.toString());  

 

Invoking a Service You can invoke a service on a Thing: // // Invoking a service on a Thing ///////////////////////////////////////////////////////////////

 //A ValueCollection is used to specify a service's parameters ValueCollection params = new ValueCollection();

 params.put("path", new StringPrimitive("/simple.txt")); params.put("data", new StringPrimitive("Here is the contents of the file.")); params.put("overwrite", new BooleanPrimitive(true));

 // Use the SystemRepository Thing to create a text file on the Platform. // This service's result type is NOTHING, so we can ignore the response. client.invokeService(ThingworxEntityTypes.Things, "SystemRepository",

"CreateTextFile", params, 5000);  

// If a service does have a result, it is returned within an InfoTable. params.clear(); // Clear the params used in the previous service invocation. params.put("path", new StringPrimitive("/simple.txt"));

 // This service queries the SystemRepository for information about the file // we just created. result = client.invokeService(ThingworxEntityTypes.Things, "SystemRepository",

"GetFileInfo", params, 5000);  

// The rows of an InfoTable are ValueCollections. ValueCollection row = result.getFirstRow();

Page 20: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 20

 

 

         

LOG.info("The file info is: name: {}", row.getStringValue("name")); LOG.info(" path: {}", row.getStringValue("path")); LOG.info(" type: {}", row.getStringValue("fileType")); LOG.info(" date: {}", row.getPrimitive("lastModifiedDate").getStringValue LOG.info(" size: {}", row.getValue("size"));

   

Firing Events You can trigger an event on a Thing on a ThingWorx server: // // Firing an event /////////////////////////////////////////////////////////////

 // A ValueCollection is used to specify the payload of // an event. ValueCollection payload = new ValueCollection();

 payload.put("name", new StringPrimitive("FileName")); payload.put("path", new StringPrimitive("/file.txt")); payload.put("fileType", new StringPrimitive("F")); payload.put("lastModifiedDate", new DatetimePrimitive()); payload.put("size", new NumberPrimitive(256));

 // This will trigger the 'FileEvent' of a RemoteThing // on the Platform. cient.fireEvent(ThingworxEntityTypes.Things, ThingName,

"FileEvent", payload, 5000);..    

Working with Things Multiple terms exist for things. Here are the basic definitions as used in this document: • A Thing is a collection of Properties, Services, and Events. Typically in the

ThingWorx environment, a Thing represents a real world asset, edge device, and/or system.

• A RemoteThing is a special type of Thing in the ThingWorx Platform that models an asset that is connected to the ThingWorx Platform from a remote location.

• A VirtualThing is a representation of a Thing in the Java SDK. Typically, a VirtualThing is used to represent the properties and services that comprise your device, application, or system.

The RemoteThing and VirtualThing are related to each other by the name assigned to them. A VirtualThing collects and stores the values of its properties. It can then forward these values to its corresponding RemoteThing on the ThingWorx Platform. To use a VirtualThing in an application extend the VirtualThing class. The following code would go in a new file, SimpleThing.java:

Page 21: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 21

 

 

       

public class SimpleThing extends VirtualThing {  

public SimpleThing(String name, String description, ConnectedThingClient client) { super(name, description, client);

}  

}

Once you have constructed a VirtualThing you can bind it to a client. Looking at our SimpleClient.java example again: // // Create a VirtualThing and bind it to the client ///////////////////////////////////////////////////////////////

 // Create a new VirtualThing. The name parameter should match the // name of a RemoteThing on the Platform. SimpleThing thing = new SimpleThing("Simple1", "A basic virtual thing", client);

 // Bind the VirtualThing to the client. This bind method tells the // Platform that the RemoteThing 'Simple1' is now connected and that // it is ready to receive requests. client.bindThing(thing);

The RemoteThing Simple1on the Platform should now have its isConnected property set to true and its lastConnection property updated to the current time. You can verify that it is connected by requesting the isConnected property through the Platform’s REST API: https://yourserver.com/Thingworx/Things/Simple1/Properties/isConnected

 Services A VirtualThing can define services and make those services available to be executed from the ThingWorx Platform. Since the AlwaysOn™ connection enables bi-directional communication, the Platform can invoke these services on demand.

 Defining a Service on a VirtualThing A service on a VirtualThing is simply a method with the proper ThingWorx annotation applied to it. For instance, take a simple method that adds two numbers: public Double Add(Double p1, Double p2) throws Exception { return p1 + p2; }

Using annotations, we can expose this method as a remote service: @ThingworxServiceDefinition(name="Add", description="Add two numbers") @ThingworxServiceResult(name="result", description="The sum", baseType= "NUMBER") public Double Add( @ThingworxServiceParameter(name="p1", description="First param", baseType="NUMBER" ) Double p1,

Page 22: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 22

 

 

       

@ThingworxServiceParameter(name="p2", description="Second param", baseType="NUMBER" ) Double p2) throws Exception {

 return p1 + p2; }

Note: you can call this.initializeFromAnnotations() when using any annotations on your VirtualThing. This function will set the current value of a property on your virtual thing to whatever you have designated the default value to be in your annotations : public SimpleThing(String name, String description, ConnectedThingClient client) { super(name, description, client); this.initializeFromAnnotations(); }

Now, run the application: 1. Log in to ThingWorx Composer and use the RemoteThing template to create

the Simple1 RemoteThing.

If you have an existing Simple1 RemoteThing, browse to it. 2. Select the Properties tab. Here, you should see the isConnected property set to

True if you are sucesfully connected. 3. Browse to the Services tab. 4. At the top, select Browse Remote Services. Under Available Services, you

should see the Add service.. 5. Click the arrow to the right of the service name to place it in the list of

services to be added to the Simple1

6. Select Create Services. The new Add service now appears in the list of services for the RemoteThing.

7. At the top of the screen, click Save to save the change to the RemoteThing.

You can now test the Add service.

8. Click Test 9. When prompted for the p1 and p2 parameters, type in the values you want to

add for this test

Page 23: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 23

 

 

       

10. Click Execute Service. This action causes the Platform to send a message, over the AlwaysOn™ connection, to the VirtualThing in the SDK application. The SDK then invokes the Add method and returns a result, shown here:

       

Note If the service fails, make sure you saved the RemoteThing after adding the

new service.  

 Using this mechanism, the remote application can expose complex functionality to the Platform. In addition, the Platform can invoke these services based on user input, system events, property changes, or calls from other Platform services.

 Properties Using the Java SDK in conjunction with the ThingWorx Platform, you can collect and store information about a device in the form of properties and property values. The Java SDK and the ThingWorx Platform provide three ways to collect information about a device:

Page 24: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 24

 

 

       

• Fetch a property value when needed by the server sending a request to the device. The device sends the current property value only on request.

• Collect a new value at the device, store it, and then forward it to the server. The device sends the value only when it changes.

• Set up a cycle at the device for collecting property values and pushing them to the server. You can use subscribed properties to set up this cycle to regularly send a set of property values, whether or not they have changed.

For example, suppose you want to monitor the temperature of a machine. You can add a property for the VirtualThing in the Java SDK called Temperature. When the VirtualThing registers with the ThingWorx Platform, the property is added to the corresponding RemoteThing in the server. It is visible in the Properties tab for the RemoteThing in ThingWorx Composer. Now suppose you want to know whenever the temperature changes by more than 5 degrees. You can set up your application to check the temperature value every 10 seconds and evaluate how much it has changed. If it has changed more than 5 degrees, you can push the individual property value to the server. You can also create a Mashup that displays the temperature change and triggers alerts based on the change. Alternatively, your application can look at all properties for the machine, detect that the temperature changed by more than 5 degrees, and then push all the properties to the server. The Java SDK can do much of this work for you. All your application needs to do is to set the new value when it changes and set up the property so that it is pushed to the server when you want to push it, and the Java SDK does everything else. For details on how to set up the properties, refer to the section, Defining Properties on page 48.

 The State of Things A RemoteThing can preserve the state in case of the ThingWorx Platform shutting down and restarting. In addition, a RemoteThing can take action when its state changes. This action can consist of generating notification events for runtime listeners or executing code to respond directly to these changes. . The state of a Thing consists of ALL its property values. A RemoteThing in the ThingWorx server is updated when it receives new property values from the VirtualThing on the device. The RemoteThing holds its state in memory. If the server is shut down, this memory is discarded. When the server starts again, this RemoteThing is re-initialized, using the default values of its properties, unless the properties are marked with the isPersistent aspect. In this case, the current state of the RemoteThing is stored in the database when it is updated, allowing these values to be used instead of the defaults values when the RemoteThing is re- created on server restart.

Page 25: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 25

 

 

       

The Java SDK has the concept of VirtualThing, which represents the state of a thing that is not stored on the server and does not benefit from the isPersistent feature. Their job is to store the state of a device/machine/system on the remote machine. Sensors on the remote machine update the state of this VirtualThing. This state sits on the remote system until it is either pushed to the isPersistentThingWorx server or pulled as a result of a request made by the server. A Value Cache on the server controls the push and pull processes. The Value Cache stores all states reported to the server (values pushed to the server by a Java SDK application). You can designate whether the properties are cached forever, cached for a set amount of time, or not cached at all. If you refer to one or more properties in a mashup, for example, the state is delivered to your browser. That state is determined by retrieving the values of the properties from the local database of the server, unless some of those properties are bound. Bound properties must be evaluated. If a property is bound to a RemoteThing, that value is stored in the Value Cache when the remote VirtualThing pushes it there. A timeout setting is applied to cached values. If the timeout period has not expired when a bound value is requested, the cached value is returned to the mashup. This process is very fast. Now consider a last cached value that is too old (timeout period expired). To evaluate the binding, the server must send a request to the remote system (if it is currently connected). This request pulls the current state of the corresponding VirtualThing from the remote system into the cache, forcing it to update. This process provides the latest value, but it can be slow and it can fail, so this behavior is not the default. You may have seen these settings in a RemoteThing configured on a ThingWorx server. The following figure provides an example of a Properties page and highlights bound/not bound properties, cached values, and properties for which the isPersistent, isReadOnly, and isLogged aspects are set (or not):

 Properties of a RemoteThing

Page 26: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 26

 

 

       

Note the differences between properties that are bound and those that are not. Any remotely bound property has the additional settings shown in this figure. The settings allow you to control the caching as well as the push and pull behaviors of each property that is bound to a value in the cache. The Data Change Info tab allows you to control how or even if the cache is used. Here is a closer look at this tab:

   

Synchronization Framework Synchronization of a remote VirtualThing with the ThingWorx server simplifies the data delivery process. You could make these updates on your own by directly calling a server RemoteThing over your SDK connection. However, the advantage of using a VirtualThing is that it introduces a cache between your remote data and its analog RemoteThing on the ThingWorx server. This cache allows you to efficiently manage requests between the server and your remote VirtualThing, preventing the server from making too many requests to your remote process. In addition, the cache allows you to easily bind the values in the cache to specific properties on a server RemoteThing. This process of binding remote data to properties of a server RemoteThing allows you to compose server RemoteThings from the properties of multiple remote VirtualThings, enabling multiple remote devices or machines to contribute to the properties of a single RemoteThing on the server. One remote device or machine could contribute data collected from a real sensor and push it to the server. The

Page 27: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 27

 

 

       

server could then notify a remote application that data had changed. That remote application could update itself and then contribute additional properties back to the server, based on its own calculations When it receives sensor data, a VirtualThing posts this data to the server cache. A RemoteThing on the server is bound to this property. This RemoteThing subscribes to changes in this property value. When this value changes, the subscription function is called. This subscription function notifies a VirtualThing in a remote application that new data is available. This update could also be done using bindings since they can also trigger code within the remote machine. The result from the ThingWorx server perspective is that there is a single RemoteThing, whose state (its properties) is updated from multiple sources but appears to be a single entity as far as its use in mashups is concerned. At the same time, it is providing a real-time, synchronized copy of its state that you can then use to manipulate a Virtual Twin (for example, a CAD model).

   

Developing Your Client Application You have seen how easy it is to connect a client application to the ThingWorx Platform and read/write properties, invoke services, and fire events. To develop your client application using the Java SDK, you may want a more specific flow of what you need to do. The steps below provide a basic flow, with links to additional details available in later sections of this document. For complete information about the interfaces, classes, and methods of the Java SDK, refer to the javadoc provided in the SDK bundle.

1. Create a class that extends the VirtualThing class. It is possible to create multiple VirtualThing classes and use many at a time. The VirtualThing is a representation of a Thing in the Java SDK that has properties, services, and events. It is the building block for interacting with the ThingWorx Platform. For more information, refer to VirttualThing Component on page 33 and Setting Up VirtualThings on page 46

2. Add properties, services, and events to the extended VirtualThing class above. Use one of the following two ways to add them:

• Use annotations. It is preferable to use annotations for well-known properties, services, and events that do not change.

• Directly call methods in code. It is preferable to use methods for areas where annotation/attribute is not supported or for properties, services, and events that do change.

For more information, refer to the following sections: Defining Properties on page 48, Defining Services on page 54, and Defining Events on page 57.

3. Create an instance of the ClientConfigurator class. The ClientConfigurator contains the parameters required to communicate

Page 28: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 28

 

 

       

with ThingWorx over WebSockets. For more information, refer to ClientConfigurator Component on page 30 and to Creating a ClientConfigurator on page 36.

4. Set the Uri and SecurityClaims properties. For details, refer to Security Claims on page 38.

5. Optionally set the MinThreads, MaxThreads, ReconnectInterval, and Name properties of the ClientConfigurator instance created in Step 3.

6. Create an instance of the ConnectedThingClient class, passing in the instance of the ClientConfigurator created above. The ConnectedThingClient facilitates communication to ThingWorx, as well as manages the contained VirtualThing’s. For more information, refer to the sections, ConnectedThingClient Component on page 32 and Creating a ConnectedThingClient on page 37.

7. Create an instance of the extended VirtualThing class created in Step 1. For more information, refer to Setting Up VirtualThings on page 46.

8. To bind the subscribed properties, services, and events with the ThingWorx on page 69 server, execute the bindThing method of the ConnectedThingClient, passing in the VirtualThing instance. For more information, refer to Binding to the Platform on page 47.

9. To start message processing and connection monitoring tasks, execute the start method of the ConnectedThingClient.

10. To implement the details of your specific project, write your custom code. The client may be long running, in which case some sort of loop to handle processing would be necessary. The client may connect, do something, and then disconnect. It depends on the specific requirements of your solution.

11. Execute the shutdown() method to stop the client from processing.

Page 29: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 29

 

 

                       

2 Primary Components of the Java

SDK ClientConfigurator Component ................................................................................................... 30 ConnectedThingClient Component ............................................................................................ 32 VirtualThing Component ............................................................................................................... 33

Page 30: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 30

 

 

   

ClientConfigurator Component The ClientConfigurator is a base class that configures an instance of a ConnectedThingClient. It contains the parameters required to communicate with theThingWorx Platform over WebSockets. The ClientConfigurator always contains the address for the ThingWorx Platform. This address is a URL, beginning with ws if it is an HTTP connection or beginning with wss if it is an HTTPS connection. The ClientConfigurator also has the security credentials to access the ThingWorx Platform. The following table lists, briefly describes, and shows the default values for the fields in a ClientConfigurator:

 

Field Description Default Value Name A string that specifies a name

for the device/machine/system to use in the application.

Default Thing Name

Uri The address of the ThingWorx server

http://localhost + RESTAPIConstants, WEBSOCKET_ RELATIVE_URL

AppKey The secure code that this application needs to access the ThingWorx server. You need to obtain this key from the server.

SharedConstants/ EMPTY_STRING

Type WHAT IS THIS FOR? OTHER TYPES ARE DEFINED — SDKType, ClientType, ConnectionServerType, ThingworxServerType

SharedConstants/ EMPTY_STRING

PipeCount The pipe count is the number of web sockets that the client opens. The default value of 1 suffices in most applications. An example of using a value greater than 1 would be the Connection Server. Since it handles a lot of inbound traffic, a single web socket connection (or ‘pipe’) could become overwhelmed. Additional pipes allow the Connection Server to disperse the load over multiple connections. Unless your application is sending a lot of requests, and you have the

1

Page 31: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 31

 

 

       

Field Description Default Value   network connection to support

the bandwidth, use the default value of 1.

 

MinPoolSize The smallest number of threads that the ClientConfigurator creates in the pool to handle processes.

4

MaxPoolSize The largest number of threads that the ClientConfigurator creates in the pool to handle processes.in the pool.

10

ThreadTimeout The number of milliseconds that the SDK waits for a thread to respond before timing out.

10000 ms

ConnectTimeout The number of milliseconds that the SDK waits for the connection to be established before timing out.

1000 ms

PingRate The maximum number of seconds without any activity that the client waits before sending a ping to the server to keep the connection alive.

45 seconds

QueueSize The number of messages that the queue can hold before it starts deleting the oldest message.

1000

ReconnectInterval The number of seconds that the SDK waits after a connection is dropped before it attempts to reconnect to the ThingWorx server.

60 seconds

IgnoreSSLErrors A Boolean that specifies whether the SDK ignores SSL errors when establishing a connection.

true

ProxyHost The URL for the proxy server through which to connect to the ThingWorx server.

SharedConstants/ EMPTY_STRING

ProxyPort The port number on the proxy host to use for the connection.

3128 (HTTP port)

ProxyUser If the proxy server requires SharedConstants/

Page 32: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 32

 

 

       

Field Description Default Value   authentication, the user name to

pass in. EMPTY_STRING

ProxyPass If the proxy server requires authentication, the password to pass in.

SharedConstants/ EMPTY_STRING

ProxyConfig An array of name/value pairs for configuring the connection to the proxy server.

[ ]

FileTransferEna- bled

A Boolean that specifies whether to enable the file transfer component.

false (file transfer is disabled)

TunnelEnabled A Boolean that specifies whether to enable the tunnel manager component.

false (disabled)

ContentLoader A Boolean that specifies whether to enable the content loader component.

false (disabled)

VirtualDirs An array of virtual directory names. A virtual directory maps a unique name to an absolute path of a directory in the file system. Note that all subdirectories of the specified directory will be exposed to the server. Multiple directories can be defined and there is no requirement that they be contiguous.

[ ]

 

For information on creating a ClientConfigurator, refer to Creating a ClientConfigurator on page 36.

   

ConnectedThingClient Component The ConnectedThingClient component facilitates communication to ThingWorx server, as well as managing the contained virtual things. The ConnectedThingClient object is a base class for managing connections and binding VirtualThing objects to the ThingWorx server. The ConnectedThingClient object provides start and shutdown methods for managing connections and the bindThing(VirtualThing) and unbindThing(VirtualThing) methods to bind VirtualThings to the server.

Page 33: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 33

 

 

       

Each ConnectedThingClient class has an instance of the following: • Logger for logging messages to the console • VirtualThingCollection contains multiple representations — the components

of a system???? • DataShapeDefinitionCollection • FileTransferManager • TunnelManager • ContentLoader To initialize an instance of a ConnectedThingClient, you use a ClientConfigurator and an IClientConnectionFactory. The start() method establishes a WebSocket connection, performs authentication, and binds any registered VirtualThings with the server. This class can be extended to provide common Java SDK Client implementation functionality when connected as a RemoteThing to the ThingWorx Platform.

 

 

VirtualThing Component The VirtualThing is a client-side representation of a device, machine, or system. A VirtualThing has properties, services, and events. It is the building block for interacting with the ThingWorx Platform. Associated with a VirtualThing are a ConnectedThingClient, a ThingShape, and DataShapes. A VirtualThing may or may not have an identifier. If you use an identifier in the Platform, you must use the same identifier in the client-side application. To enable a device/machine/system to communicate with the Platform, the client application must bind the VirtualThing that represents the device to a specific Platform instance. When binding the device, the client-side application provides a bind name for the device.

Page 34: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

 

 

 

Page 35: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 35

 

 

                       

3 Setting up an Application

The Client ....................................................................................................................................... 36 Virtual Things ................................................................................................................................. 46 Base Types and Primitives ........................................................................................................... 60 Java SDK Logging ......................................................................................................................... 63

Page 36: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 36

 

 

   

The Client  

Creating a ClientConfigurator by Extending ConnectedThingClient The ClientConfigurator parameters set the configuration for the ConnectedThingClient. Here is an example of code that extends the ConnectedThingClient clase and then creates a ClientConfigurator to set up the connection to the ThingWorx server:. public class SimpleClient extends ConnectedThingClient {

private static final Logger LOG = LoggerFactory.getLogger(SimpleClient.class);

public SimpleClient(ClientConfigurator config) throws Exception { super(config); }

 public static void main(String[] args) {

ClientConfigurator config = new ClientConfigurator();  

// Set the URI of the server that we are going to connect to config.setUri("wss://yourserver.com:443/Thingworx/WS");

 // Set the ApplicationKey. This will allow the client to authenticate with // the server. It will also dictate what the client is authorized to do // once connected. config.setAppKey("32491397-fffff-5555-555a-376ff92aae02");

 // This will allow us to test against a server using a self-signed certificate. // This should be removed for production systems. config.ignoreSSLErrors(true); // All self signed certs

 try {

 // Create our client. SimpleClient client = new SimpleClient(config);

 // Start the client. The client will connect to the server and // authenticate, using the ApplicationKey specified above. client.start();

 // Wait for the client to connect. if (client.waitForConnection(30000)) {

LOG.info("The client is now connected.");

} else { // Log this as a warning. In production the application could

// continue to execute, and the client would attempt to // reconnect periodically. LOG.warn("Client did not connect within 30 seconds. Exiting"); }

Page 37: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 37

 

 

       

client.shutdown();  

} catch (Exception e) { LOG.error("An exception occured while initializing the client", e);

}  

LOG.info("SimpleClient is done. Exiting"); }

}      

Note For examples of using a ClientConfigurator when setting up a connection through a proxy server, refer to Connecting Through a Proxy Server on page

42.  

 Another way to create a ClientConfigurator is to use a configuration file, as follows: ClientConfigurator configurationFromFile(String configFile) throws IOException { String confFilePath = configFile; assertTrue(new File(configFile).exists()); ClientConfigurator config = ClientConfiguratorFactory.from(confFilePath); return config; }

   

Managing the Connection Using Methods of the ConnectedThingClient Class The ConnectedThingClient class contains methods that manage the connection to the ThingWorx server as well as the VirtualThings. It requires the ClientConfigurator for configuration of its parameters. A ConnectedThingClient can contain multiple VirtualThings as demonstrated in the Steam Sensor example. The following table explains which methods to use for what you want to do:

 

To Use Notes Bind a VirtualThing to theThingWorx server, so that property, service, and event data can be exchanged.

bindThing(Virtual Thing thing)

The bind occurs only if the connection has been established.

Start the client communications and operation.

start() This method also starts the connection monitor, which continues to monitor the connection. If

Page 38: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 38

 

 

       

To Use Notes     the connection fails, it

tries to reconnect based on the reconnect interval.

Determine if the client is connected to the ThingWorx server.

isConnected() Returns true if the client is connected, false otherwise.

Determine if the client is shut down.

isShutdown() Returns true if the client is shut down, false otherwise.

Stop the client and connection monitor.

shutdown() Attach the shutdown code to the termination signal so that the client disconnects when the program is stopped with a CTRL-C (as shown above).

   

Using Security Claims to Protect the Connection A security claim contains the security settings for connecting to a ThingWorx server. The Java SDK provides two different security claims: Application Key and Credentials (user and password). For better security, it is recommended that you use an Application Key. For example: SecurityClaims claims = SecurityClaims.fromAppKey(“xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”);

If you choose to provide a user name and password, use the fromCredentials(String uid, String pwd) method of the SecurityClaims object. For example: SecurityClaims claims = SecurityClaims.fromCredentials(“Administrator”, “admin”);

If the security claim is well known, you can use the addClaim(String name, String value) method of theSecurityClaims object to pass in the appropriate value for either the Application Key or the user name and password (Credentials). Here are examples of using this method: // Application Key Example

 SecurityClaims claims = new SecurityClaims()

claims.addClaim(RESTAPIConstants.PARAM_APPKEY,“xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”);

// Credentials Example  

SecurityClaims claims = new SecurityClaims();

Page 39: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 39

 

 

       

claims.addClaim(RESTAPIConstants.PARAM_USERID, "Administrator");

claims.addClaim(RESTAPIConstants.PARAM_PASSWORD, "admin");

Example

You can add security claims code to the ClientConfigurator, as shown in the following example: public class SimpleClient extends ConnectedThingClient {

private static final Logger LOG = LoggerFactory.getLogger(SimpleClient.class);

public SimpleClient(ClientConfigurator config) throws Exception {

super(config);

}    

public static void main(String[] args) {

ClientConfigurator config = new ClientConfigurator();

 // Set the URI of the server that we are going to connect to

config.setUri("wss://yourserver.com:443/Thingworx/WS");      

// Set the ApplicationKey. This will allow the client to authenticate with

// the server. It will also dictate what the client is authorized to do

// once connected.

config.setAppKey("32491397-fffff-5555-555a-376ff92aae02");      

// Create a connection that requires spcific X509 fields for the

// issuer and subject

config.getSecurityClaims().addClaim("e9274d87-58aa-4d60-b27f-

e67962f3e5c4",

                   

...

appKey);

config.setIssuerCN("Entrust.net Certification Authority (2048)");

config.setIssuerO("(c) 1999 Entrust.net Limited");

config.setIssuerOU("www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)");

config.setSubjectCN("*.reddit.com");

config.setSubjectO("Gandi Standard Wildcard SSL");

config.setSubjectOU("Domain Control Validated");

Page 40: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 40

 

 

       

Setting Parameters for the Connection to the Server The ClientConfigurator class contains settings that the ConnectedThingClient uses to connect to a ThingWorx server and control its behavior. To set parameters for the connection or provide information about the client to the server, use the methods shown in the following table.

 

To Set Use this Method Notes The security settings for the ConnectedThing Client to use when connecting to the ThingWorx server.

setSecurity Claims(Security Claims value)

See also: Using Security Claims to Protect the Connection on page 38

The address (Universal Resource Indicator) for connecting to the ThingWorx server.

setUri(String uri) The URI is in the form of: • Non—secure

Websockets: ws:// <server>:< port>/ ThingWorx/WS

• Secure Websockets: wss:// <server>:< port>/ ThingWorx/WS

Where <server> is the IP address or domain name of the ThingWorx server and <port> is the port that the ThingWorx server is using.

The number of websockets that the client opens for communication. The default number is 1 and should suffice for most applications.

setPipeCount(int count)

Do not change this value unless instructed by ThingWorx technical support.

The idle ping rate, which is the maximum amount of time in seconds without any activity that the client waits before sending a ping to the

setIdlePingRa te(int value)

This ping keeps the websocket connection open.

Page 41: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 41

 

 

       

To Set Use this Method Notes server.    The minimum number of threads for process handling.

setMinThreads(int minThreads)

It is recommended that this value not be modified.

The maximum amount of time in milliseconds that a thread can execute before it times out.

setThreadTimeou t(int threadTimeout)

 

The maximum amount of time in milliseconds that the client waits to connect before it times out.

setConnectTimeou t(int connectTimeout)

 

The amount of time in seconds that the client waits before trying to reconnect to the ThingWorx server after a disconnect has been detected.

setReconnectInter val(int reconnectInterv al)

 

The maximum number of items in the thread processing queue before messages are denied.

setQueueSize(int queueSize)

It is recommended that this value not be modified.

The name of the client. setName(String value)

 

The type of the client. setType(String value)

 

To Tell the Server That Use  The client is an SDK client for the ThingWorx server.

setAsSDKType()  

This client is a representation of a ThingWorx server type.

setAsThingWorxSer verType()

 

Page 42: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 42

 

 

       

Controlling Time Connected Using Duty Cycle Modulation Duty Cycle Modulation is the ability for an SDK application to regulate time connected to the ThingWorx server. Periodically, the application checks to see if it is above or below its threshold for connections (a percentage), and connects to or disconnects from the server accordingly. Duty Cycle Modulation is useful when power and resource conservation is important. When a disconnect is initiated, pending requests are not terminated. The application waits for pending requests to finish before executing the disconnect. The Client API supports forcing a connection to be established for multiple operations: • Invoking a service • Reading a property value • Writing a value to a property • Firing an event Duty Cycle Modulation has two parameters that you can set in the ClientConfigurator class: 1. dutyCyclePeriod specifies how often to check the percentage. The

default value is every 40 seconds. 2. dutyCycleConnectionPercentage specifies the percentage of online

time to maintain a connection to the server. The default value is 100 percent.      

Connecting Through a Proxy Server The Java SDK supports connecting to a ThingWorx server that is behind an HTTP proxy server. Connecting through a proxy server is often reqruied when data is being collected at remote locations outside of your local network. Authentication with the proxy server is also supported if required. The type of authentication used is determined when the Java SDK connects to it. The Java SDK queries a proxy server to determine what type of authentication it supports and then provides either Basic or Digest authentication methods.

     

Note The Java SDK does not support NTLM authentication for proxy servers.

 

 In your application, you need to set at most four parameters to use a proxy server:

Page 43: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 43

 

 

       

• Proxy host • Proxy port number • If authentication is required:

○ A user name ○ A password

     

Note If using a proxy that requires authentication, it is important to note that the proxy user name and password have nothing to do with the ThingWorx Platform. The user name and password combination is never passed beyond

the proxy server.      

The Java SDK provides the following ways to access a ThingWorx server through a proxy server:

• Using a ClientConfigurator on page 43 • Using a ConnectionFactory on page 44 The next two sections provide examples of these ways.

 Using a Client Configurator The examples of using a ClienConfigurator for a proxy connection are based on the example of creating a ClientConfigurator in the section, Creating a Client Configurator on page 36. In your application, you need to build the ClientConfigurator and then set the additional parameters described above. The following example shows how to modify the ClientConfigurator configuration to create a secure websocket connection (WSS) through a proxy server that does not require authentication: String uri="wss://localhost:443/Thingworx/WS"; String appKey = "32491397-f468-4dbc-858a-376ff92aae02"; // Obtained from your ThingWorx se IClientConnectionFactory factory = null; // We will use the default factory

 ClientConfigurator config = new ClientConfigurator(); config.setUri(uri); config.getSecurityClaims().addClaim(RESTAPIConstants.PARAM_APPKEY, appKey); config.ignoreSSLErrors(true); // For self signed certs config.setReconnectInterval(300);//seconds config.setConnectTimeout(20000);//ms config.setProxyHost("proxy.your-company.com");//Put your proxy server hosts here config.setProxyPort(3100); ConnectedThingClient client = new ConnectedThingClient(config, factory); client.connect();

Page 44: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 44

 

 

       

The following example shows how to modify the ClientConfigurator configuration to create the configuration for a WSS connection with a proxy server that requires Basic or Digest authentication: String uri="wss://localhost:443/Thingworx/WS"; String appKey = "32491397-f468-4dbc-858a-376ff92aae02"; // Obtained from your server IClientConnectionFactory factory = null; // We will use the default factory

 ClientConfigurator config = new ClientConfigurator(); config.setUri(uri); config.getSecurityClaims().addClaim(RESTAPIConstants.PARAM_APPKEY, appKey); config.ignoreSSLErrors(true); // For self signed certs config.setReconnectInterval(300);//seconds config.setConnectTimeout(20000);//ms config.setProxyHost("proxy.your-company.com");//Put your proxy server hosts here config.setProxyPort(3100); config.setUsername("yourproxyusername"); config.setPassword("yourproxypassword") ConnectedThingClient client = new ConnectedThingClient(config, factory); client.connect();

 Using a Connection Factory Builder This method of connecting to a ThingWorx server through a proxy server lets you reuse a pre-configured connection factory. In the ClientConfigurator example, you were using the default connection factory since the value of your connection factory was null. Depending on your needs, you may find that this method of configuring a proxy server connection is more convenient to plug in to your application. A Netty connection factory builder can create a connection factory that is proxy aware and that you can reuse. You construct the connection factory through a builder. The following example shows connecting through an Anonymous HTTP proxy using a Netty connection factory builder String proxyHost="proxy.your-company.com"; int proxyPort=3100; String uri="wss://localhost:443/Thingworx/WS"; String appKey = "32491397-f468-4dbc-858a-376ff92aae02";

 // Obtained from your server IClientConnectionFactory factory = new NettyClientConnectionFactory.Builder()

.setIdlePingRate(5000)

.setConnectTimeout(10000)

.useHttpProxy( proxyHost, proxyPort

) .build();

   

ClientConfigurator config = new ClientConfigurator(); config.setUri(uri);

Page 45: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 45

 

 

       

config.getSecurityClaims().addClaim(RESTAPIConstants.PARAM_APPKEY, appKey); config.ignoreSSLErrors(true); // For self signed certs config.setReconnectInterval(300);//seconds config.setConnectTimeout(20000);//ms

 ConnectedThingClient client = new ConnectedThingClient(config, factory); client.connect();

Here is an example of accessing a ThingWorx server though a proxy server that requires authentication: String proxyHost="proxy.your-company.com"; int proxyPort=3100; String proxyUsername="yourproxyuser"; String proxyPassword="yourproxypassword"; String uri="wss://localhost:443/Thingworx/WS"; String appKey = "32491397-f468-4dbc-858a-376ff92aae02"; // Obtained from your server IClientConnectionFactory factory = new NettyClientConnectionFactory.Builder()

.setIdlePingRate(5000)

.setConnectTimeout(10000)

.useHttpProxy( proxyHost, proxyPort, proxyUsername, proxyPassword

) .build();

   

ClientConfigurator config = new ClientConfigurator(); config.setUri(uri); config.getSecurityClaims().addClaim(RESTAPIConstants.PARAM_APPKEY, appKey); config.ignoreSSLErrors(true); // For self signed certs config.setReconnectInterval(300);//seconds config.setConnectTimeout(20000);//ms

 ConnectedThingClient client = new ConnectedThingClient(config, factory); client.connect();

 What Happens If You Have Two Proxy Configurations? What happens if you have both proxy configurations to create a single client? That is, you used both the one using the ClientConfigurator and the one using a connection factory. In this situation, the connection factory configuration is used.

Page 46: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 46

 

 

       

Reading Responses

Parsing an InfoTable

Virtual Things  

Setting Up Virtual Things The VirtualThing class represents a device, machine, or system in a client-side application. On theThingWorx server side, a device, machine, or system is represented by a RemoteThing. The VirtualThing.is the foundation for providing properties, services, and events that are accessible from a ThingWorx user interface. Properties, Services, and Events can be defined using annotations. If the custom Virtual Thing uses any annotations, it is important to call the initializeFromAnnotations() method in the constructor of the VirtualThing.

   

Setting Up Data Shapes Data Shapes are required for InfoTable base types and for event data. You can define data shapes using the Java SDK classes, DataShapeDefinition and FieldDefinition, as explained below.

 DataShapeDefinition DataShapeDefinitions are for modeling metadata of ThingWorx Data Shapes. They are defined in the VirtualThing. DataShapeDefinitions are required for InfoTable base types and event data. The only mechanism for defining a data shape is in code.

 FieldDefinition DataShapeDefinitions are just a collection of FieldDefinitions. FieldDefinitions represent a field in a ThingWorx datashape.

• name — The name of the field. • description — A description of the field. • baseType — The base type that the field represents. For example: // Create a collection to hold the field definitions

FieldDefinitionCollection fields = new FieldDefinitionCollection();

 // Define the fields

Page 47: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 47

 

 

       

fields.addFieldDefinition(new FieldDefinition("Field1", BaseTypes.STRING));

fields.addFieldDefinition(new FieldDefinition("Field2", BaseTypes.NUMBER));

fields.addFieldDefinition(new FieldDefinition("Field3", BaseTypes.INTEGER));

 // Add the DataShapeDefinition to the VirtualThing

this.defineDataShapeDefinition("MyDataShape", fields);    

Binding to the Platform A BIND message is one type of message in the ThingWorx AlwaysOn™ protocol. Your application needs to send a BIND message to the server. The message must contain the VirtualThing name for the device where it is running. When the server receives the BIND message, it associates the RemoteThing with the websocket where the BIND message was received. The server can then send request messages to your VirtualThing, over the websocket. It also updates the isConnected property (to true) and the time value of the lastConnection property for the newly bound device. Your application can also send an UNBIND request to tell the server to remove the association between the RemoteThing and the websocket. The server updates the isConnected property to false. To unregister (UNBIND) the device, your application needs to call /Thingworx/Things/LocalEms/RemoveEdgeThing.

 Identifiers Identifiers provide an alternate way to address a device, machine, or system uniquely in the ThingWorx server and at the device. It is important to remember that if you assign an identifer at the server, you must use that identifier in your client application.

 Overrides After Binding The following functions can be overridden in classes derived from VirtualThing, but are not required. • afterBinding() — Called after the binding of the VirtualThing is

complete. • afterUnbinding() — Called after the unbinding of the VirtualThing is

complete. • afterEnable() — Called after the VirtualThing has been enabled. • afterDisable() — Called after the VirtualThing has been disabled.

Page 48: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 48

 

 

       

• processScanRequest() — Called for every scan request. Usually this function is called by the code that is processing the VirtualThings. See the SteamSensorClient for an example of its use.

• synchronizedState() — Called when theThingWorx server requests values of properties from the VirtualThing. This method is useful when first connecting to the ThingWorx server to send the initial data (if it does not change regularly) or when a reconnect occurs.

   

Defining Properties You can define properties by using annotations or by calling the methods of the VirtualThing class directly. Use annotations for properties that are static and methods when the values of peoperties are expected to change often. The section that follows explains how to used the methods of the VirtualThing. For examples of using annotations to define properties, refer to Annotations on page 53.

 Property Definitions Property definitions describe properties that are available to the ThingWorx server and can be added to a VirtualThing in two ways. To create a property definition, call one of the defineProperty methods of the base VirtualThing. One of these methods takes a PropertyDefinition, and the other takes the essential parameters of a PropertyDefinition, as shown here: defineProperty(PropertyDefinition propertyDefinition)

 defineProperty(String name, String description, BaseTypes baseType,

AspectCollection aspects)

When using the first method, you need to create a PropertyDefinition, which can define several parameters. When using the second method, you specify the parameters that are required in a PropertyDefinition. The following parameters are required: • name — The name of the property. This string appears in the ThingWorx user

interface when a user browses for the properties of a device. • description — The description of the property that can be used to give

further context to the property. • baseType — The data type of the property. For a list of baseTypes, refer to

the section, Overview of Base Types on page 61. • aspects — Aspects further define the ways to interact with properties. For

code examples, see the section, Aspects of Properties on page 51. In a PropertyDefinition, you can also specify the following parameters:

Page 49: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 49

 

 

       

• dataChangeType — The data change type describes how the ThingWorx server responds when the value in the VirtualThing changes. Subscriptions to these value changes can be modeled in the server. If nothing needs to react to the property change, it is recommended that this value be set to NEVER. The possible values are listed and briefly described here:

 

Value Description ALWAYS Always notify of the value change even if the same value

comes in multiple times in a row VALUE Notify only if the value changes ON For BOOLEAN types, notify only if the value is true. OFF For BOOLEAN types notify only if the value is false. NEVER The ThingWorx server should do nothing based on the

value change.

• dataChangeThreshold — Defines how much the value must change to trigger a change event. For example 0 (zero) indicates that any change triggers an event. A value of 10, for example, means that an update is not triggered unless the value changes by an amount greater or equal to 10.

• cacheTime — Tells the ThingWorx server how long to cache the value before reading it again. This parameter can take the following values: ○ -1 — Indicates that the VirtualThing always sends its value, and the

ThingWorx server should never request it. ○ 0 — Indicates that every time the ThingWorx server uses the value, it

should request it from the VirtualThing. ○ Any other positive value — Indicates that the ThingWorx server should

cache the value for that many seconds and then retrieve it from the VirtualThing only after that time expires.

     

Note Set this parameter to -1 if the VirtualThing sets the value every time

it changes.  

• isPersistent — Set to true for the ThingWorx server to persist the value even if the server restarts. It is extremely expensive to have persistent values, so it is recommended to set this value to false unless persistence is absolutely necessary.

• isReadOnly — Set to true to inform the ThingWorx server that this value is only readable and cannot be written.

Page 50: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 50

 

 

       

• pushType — Informs the ThingWorx server how the VirtualThing pushes its values to the server. The possible values are as follows:

 

Push Type Description ALWAYS The VirtualThing sends updates even if the value

has not changed. NEVER The VirtualThing never sends the value. This value

would indicates that theThingWorx server would be writing to this value only.

VALUE The VirtualThing sends updates only when the value changes.

• defaultValue — The default value is the value that the ThingWorx server uses when the RemoteThing connected to the VirtualThing first starts up and has not had an update from the VirtualThing. The value is different based on the type for each parameter.

 

   

Modifying Property Values To update the value of a property, call one of the following methods:

• setPropertyVTQ — Sets a property’s value using a VTQ (value, time, and quality) structure. This method takes the following parameters: ○ name — The name of the property. ○ value — The VTQ (value, time, and quality) for the property's value. ○ forceChange — Set this value to true to force the value to be sent to

ThingWorx even if it has not changed. Use this option to send the first value or a value immediately after reconnect.

• setPropertyValue — Sets a property’s value using a Primitive type. This method takes the following parameters: ○ name — The name of the property.

○ value — The VTQ (value, time, and quality) for the property’s value. • setProperty — Sets a property's value from an object.

○ name — The name of the property. ○ value — An object representing the value to set. The value is cast to the

type of property if possible. Otherwise, an exception is thrown.

Page 51: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 51

 

 

 

           

Note Updating a property value does not send the value to the ThingWorx server. To send the value to the ThingWorx server, the updateSubscribedProperties method of the VirtualThing class must be called.

   

Here are examples of using these methods to change a property value:    

setPropertyVTQ

VTQ vtq = new VTQ();

vtq.setValue(new NumberPrimitive(123.456));

vtq.setTime(new DateTime());

vtq.setQuality(QualityStatus.GOOD);

super.setPropertyVTQ("MyProperty", vtq);

 setPropertyValue

NumberPrimitive value = new NumberPrimitive(123.456);

super.setPropertyValue("MyProperty", value);

 setProperty

super.setProperty("MyProperty", 123.456);      

Note Call the updateSubscribedProperties method on the VirtualThing, or the property values are not sent to the ThingWorx server. A common paradigm for this is illustrated in the full Steam Sensor example.

     

Aspects of Properties For example: //Create the property definition with name, description, and baseType

PropertyDefinition property1 = new PropertyDefinition(

"Property1",    

"Description for Property1",

Page 52: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 52

 

 

       

BaseTypes.BOOLEAN);    

//Create an aspect collection to hold all of the different aspects

AspectCollection aspects = new AspectCollection();

//Add the dataChangeType aspect

aspects.put(Aspects.ASPECT_DATACHANGETYPE,

new StringPrimitive(DataChangeType.NEVER.name()));    

//Add the dataChangeThreshold aspect

aspects.put(Aspects.ASPECT_DATACHANGETHRESHOLD, new NumberPrimitive(0.0));

//Add the cacheTime aspect    

aspects.put(Aspects.ASPECT_CACHETIME, new IntegerPrimitive(0));    

//Add the isPersistent aspect    

aspects.put(Aspects.ASPECT_ISPERSISTENT, new BooleanPrimitive(false));    

//Add the isReadOnly aspect    

aspects.put(Aspects.ASPECT_ISREADONLY, new BooleanPrimitive(false));    

//Add the pushType aspect    

aspects.put("pushType", new StringPrimitive(DataChangeType.NEVER.name()));    

//Add the defaultValue aspect    

aspects.put(Aspects.ASPECT_DEFAULTVALUE, new BooleanPrimitive(true));    

//Set the aspects of the property definition

property1.setAspects(aspects);

//Add the property definition to the Virtual Thing

this.defineProperty(property1);

Page 53: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 53

 

 

       

Annotations The preferred method of defining properties is to use asnnotations. Here are some examples. The ThingWorxPropertyDefinitions annotation contains all the child ThingWorxPropertyDefinition annotations. Example: @ThingWorxPropertyDefinitions(properties = {

 @ThingWorxPropertyDefinition(

name="Property1", description="Description of Property1", baseType="BOOLEAN", aspects={

"dataChangeType:NEVER", "dataChangeThreshold:0", "cacheTime:-1", "isPersistent:FALSE", "isReadOnly:FALSE", "pushType:VALUE", "defaultValue:true" }

),  

@ThingWorxPropertyDefinition( name="Property2", description="Description of Property2", baseType="NUMBER", aspects={

"dataChangeType:NEVER", "dataChangeThreshold:0", "cacheTime:-1", "isPersistent:FALSE", "isReadOnly:FALSE", "pushType:VALUE", "defaultValue:0" }

),  

@ThingWorxPropertyDefinition( name="Property3", description="Description of Property3", baseType="STRING", aspects={

"dataChangeType:NEVER", "dataChangeThreshold:0", "cacheTime:-1", "isPersistent:FALSE", "isReadOnly:FALSE", "pushType:VALUE", "defaultValue:Test String" }

) }

Page 54: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 54

 

 

       

Defining Services Service definitions describe functions that the ThingWorx server can call on the VirtualThing. A service may have several or no inputs and only one result. The most effective and maintainable way to define services is with annotations (listed below). Both declarative and explicit code examples are outlined.

• ThingWorxServiceDefinition — Add this to a method to indicate that this is a service that the ThingWorx server can use. ○ name — A label for the service.

     

Note This name must match the name of the Java method.

 

 

○ description — An explanation of the action or operation provided by the service.

• ThingWorxServiceResult — Add this to a method to indicate the result of the service. ○ name — A label for the result for the ThingWorx server to use when

presenting the result. This name should always be result and a constant is defined for it: CommonPropertyNames.PROP_RESULT.

○ description — Explanatory information for the result. ○ baseType — The base type of the result. The value of this parameter is a

string value, representing the possible base types. For a table of available base types, refer to the section, Overview of Base Types on page 61.

     

Note To indicate a void result, use the NOTHING base type.

 

 

• ThingWorxServiceParameter — Append this to each input parameter. ○ name — A label for the parameter. ○ description — Explanation of the parameter. ○ baseType — The base type of the parameter. The value is a one of the

possible base types. For a table of available base types, refer to the section, Overview of Base Types on page 61.

Page 55: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 55

 

 

       

Examples The following service returns the results of adding two numbers:: @ThingWorxServiceDefinition(

   

name="Add",

description="Add two numbers")    

@ThingWorxServiceResult(

name=CommonPropertyNames.PROP_RESULT,

description="The sum of the two parameters",

baseType=BaseTypes.NUMBER.name())

 public Double Add(

   

@ThingWorxServiceParameter(

name="p1",

description="The first addend of the operation",

baseType=BaseTypes.NUMBER.name()) Double p1,

 @ThingWorxServiceParameter(

name="p2",

description="The second addend of the operation",

baseType=BaseTypes.NUMBER.name()) Double p2)

 throws Exception {

return p1 + p2;

}    

//The following service returns the current date and time    

@ThingWorxServiceDefinition(

name="WhatTimeIsIt",

description="Returns the current time")

 @ThingWorxServiceResult(

name= CommonPropertyNames.PROP_RESULT,

description="",

baseType=BaseTypes.DATETIME.name())

 public DateTime WhatTimeIsIt() {

 return new DateTime();

}  

//The following function takes no parameters and returns nothing

Page 56: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 56

 

 

 

         

@ThingWorxServiceDefinition(

name="SimpleService",

description="Returns nothing")

 @ThingWorxServiceResult(

name=CommonPropertyNames.PROP_RESULT,

description="",

baseType=BaseTypes.NOTHING.name())

 public void SimpleService() {

 //Do something here...

}  

Code To add a service definition, call the defineService method of the base VirtualThing. There are two defineService methods. One that takes a ServiceDefinition and one that takes the essential parameters of a ServiceDefinition. defineService(ServiceDefinition serviceDefinition) defineService(String name, String description, FieldDefinitionCollection parameterTypes, F

The code for the following examples should be in the constructor of the extended VirtualThing (or a method called from the constructor). Also, these examples will work as long as the actual service is defined. You can see from the examples below that the annotation methodology is much cleaner. Examples: //Put this code in the constructor (or a method called from the constructor)

ServiceDefinition serviceDef = new ServiceDefinition(

"Add",    

"Add two numbers");    

FieldDefinitionCollection parameterFields = new FieldDefinitionCollection();

parameterFields.addFieldDefinition(

new FieldDefinition(

"p1",

"The first addend of the operation",

Page 57: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 57

 

 

 

         

BaseTypes.NUMBER)    

);    

parameterFields.addFieldDefinition(

new FieldDefinition(

"p2",    

"The second addend of the operation",

BaseTypes.NUMBER)

);    

FieldDefinition resultField = new FieldDefinition(

CommonPropertyNames.PROP_RESULT,

"The sum of the two parameters",

BaseTypes.NUMBER);

serviceDef.setParameters(parameterFields);

serviceDef.setResultType(resultField);

super.defineService(serviceDef);

//Actual service definition    

public Double Add(Double p1, Double p2) throws Exception {

return p1 + p2;

}    

Defining Events Event definitions describe interrupts that the ThingWorx server can subscribe to for purposes of receiving notifications when something happens. Events require a data shape for event data. Events can be defined directly in code or by using annotations (listed below), but the data shape required by the event must be defined in code.

Page 58: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 58

 

 

       

The examples use the following data shape (put this code in the constructor or a method called from the constructor): FieldDefinitionCollection fields = new FieldDefinitionCollection(); fields.addFieldDefinition( new FieldDefinition("ErrorMessage", BaseTypes.STRING)); this.defineDataShapeDefinition("ErrorEventShape", fields);

• ThingWorxEventDefinitions — This annotation is a collection of ThingWorxEventDefinition annotations.

• ThingWorxEventDefinition — Defines an event. ○ name — Unique identifier of an event. ○ decription — An explanation of the event. ○ dataShape — The name of the data shape for the event data. ○ category — A category name for the event. ○ isInvocable — A Boolean, indicating whether the event can be invoked

from code. ○ isPropertyEvent — A Boolean, indicating whether the event is associated

with a property. Example: @ThingWorxEventDefinitions(events = {

 @ThingWorxEventDefinition(

name="ErrorEvent",

description="Event that sends an error",

dataShape="ErrorEventShape",

category="Faults",

isInvocable=true,

isPropertyEvent=false)

}

)  

Code To create an event, call the defineEvent method on the base VirtualThing. There are two defineEvent methods: one that takes an EventDefinition and one that takes the essential parameters for an EventDefinition. defineEvent(EventDefinition eventDefinition)

 defineEvent(String name, String description, String dataShape, AspectCollection aspects)

The parameters for an event definition are:

• name — The unique identifier for the event. • description — An explanation of the event.

Page 59: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 59

 

 

       

• dataShape — The name of the data shape for the event data. • aspects — The AspectCollection for the event definition. For example: super.defineEvent(

"ErrorEvent",

"Event that sends an error",

"ErrorEventShape",

null);  

Triggering an Event Triggering an event that the ThingWorx server will receive (if subscribed) is straightforward.

     

Note Just triggering an event is not enough to send it to the ThingWorx server. The updateSubscribedEvents method of the VirtualThing must be called for the event to be sent.

   

Example: ValueCollection eventInfo = new ValueCollection();

eventInfo.put(“ErrorMessage”, new StringPrimitive(“There was an error…”)); super.queueEvent(“ErrorEvent”, DateTime.Now(), eventInfo);

   

Using Subscribed Properties You can also use a feature called subscribed properties, which has its own manager (Subscribed Properties Manager). The classes and methods you can use for subscribed properties are listed in the table below. You can set values for each subscribed property individually and then push them all at once to the ThingWorx server.

 

To Use Define subscribed properties  

Create a subscribed property  

Create a subscribed property from a stream

 

Delete a subscribed property  

Write a subscribed property to a stream  

Page 60: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 60

 

 

       

To Use Get the length of a subscribed property  

Send a list of subscribed properties to the ThingWorx Platform

 

   

Queueing and Pushing Updates

Folding

Base Types and Primitives BaseTypes Base types are the classification of different data values. Below is a list of all of the base types supported by the SDK:

 

Type Name Description BOOLEAN True or false values only DATETIME Date and time value GROUPNAME ThingWorx Group Name HTML HTML value HYPERLINK Hyperlink value IMAGE Image Value IMAGELINK Image link value INFOTABLE ThingWorx InfoTable INTEGER 32 bit integer value JSON JSON structure LOCATION ThingWorx Location structure MASHUPNAME ThingWorx Mashup name MENUNAME ThingWorx Menu name NOTHING No type (used for services to define

void result) NUMBER Double precision value STRING String value QUERY ThingWorx Query structure TEXT Text value THINGNAME ThingWorx Thing name USERNAME ThingWorx User name XML XML structure

Page 61: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 61

 

 

       

Overview of Base Types Base types are the classification of different data values. Below is a list of all of the base types supported by the SDK:

 

Type Name Description BOOLEAN True or false values only DATETIME Date and time value GROUPNAME ThingWorx Group Name HTML HTML value HYPERLINK Hyperlink value IMAGE Image Value IMAGELINK Image link value INFOTABLE ThingWorx InfoTable INTEGER 32–bit integer value JSON JSON structure LOCATION ThingWorx Location structure MASHUPNAME ThingWorx Mashup name MENUNAME ThingWorx Menu name NOTHING No type (used for services to define void result) NUMBER Double-precision value STRING String value QUERY ThingWorx Query structure TEXT Text value THINGNAME ThingWorx Thing name USERNAME ThingWorx User name XML XML structure

   

Example Using the InfoTable Base Type The following example describes the procedure for creating a property and service that uses an InfoTable base type. The InfoTable contains an integer ID and a string Value. The property is an InfoTable property. The service takes an InfoTable as a parameter and returns the same InfoTable. It is only for demonstration purposes. // Class Annotations for the property

 @ThingWorxPropertyDefinitions(

properties = {

@ThingWorxPropertyDefinition(

name="StringIndex",

Page 62: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 62

 

 

         

description="String Index Property",

baseType="INFOTABLE",

aspects = {

"dataChangeType:NEVER",

"dataChangeThreshold:0",

"cacheTime:-1",

"isPersistent:FALSE",

"isReadOnly:FALSE",

"pushType:VALUE",

"dataShape:StringMap"

}  

)  

}  

)  

     

// This needs to be in the constructor or the a method called from the  

// constructor.  

// First a data shape definition needs to be added to the VirtualThing

FieldDefinitionCollection fields = new FieldDefinitionCollection();

   

// Define the fields  

fields.addFieldDefinition(new FieldDefinition("ID", BaseTypes.INTEGER));

fields.addFieldDefinition(new FieldDefinition("Value", BaseTypes.STRING));

   

// Add the DataShapeDefinition to the VirtualThing

this.defineDataShapeDefinition("StringMap", fields);

   

// Service Definition

Page 63: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 63

 

 

         

@ThingWorxServiceDefinition(

name="StringMapService",

description="Returns the passed in String Map")  

@ThingWorxServiceResult(

name=CommonPropertyNames.PROP_RESULT,

baseType="INFOTABLE",

description="",

aspects={"dataShape:StringMap"})

public InfoTable StringMapService(

@ThingWorxServiceParameter(

name="value",

baseType="INFOTABLE",

description="",

aspects={"dataShape:StringMap"}) InfoTable value )

throws Exception {

return value;  

}    

Working with Primitives, ValueCollections, and InfoTables

 Java SDK Logging The Java SDK contains logging methods that provide a mechanism for writing data to text files. The logging mechanism is designed to isolate logging by class to help log only what is of interest. The Java SDK uses the logback (http://logback.qos.ch/) and SLF4J (http://www. slf4j.org/) for its logging mechanism. An overview of how logging is performed with the SDK will be outlined, but for more information, please visit the aforementioned sites.

Page 64: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 64

 

 

       

Log Levels The following log levels are supported: • Trace • Debug • Info • Warn • Error Each level will write out any messages in a lower level. For example, if the logging of the application is set to Trace, then Debug, Info, Warn, and Error levels will be written to the log file. If the logging of the application is set to Warn, then only Warn and Error levels will be written to the log.

 Implementation The following outlines the implementation of logging in the Java code.

 LoggerFactory The LoggerFactory class is a helper class that makes logging much simpler than having to create the logging from scratch. It is part of the SLF4JJ logging.

• Logger getLogger(Class clazz) — The getLogger method returns a Logger to perform logging for a specific class. This is usually done on a static non-modifiable member variable. For example: // The following will create a logger based on the SteamThing class private static final Logger LOG = LoggerFactory.getLogger(SteamThing.class);

 Logger The Logger class performs the logging. There are methods for each log level. Only the most used trace methods will be outlined, but they can all be interpolated from these. The same method signatures are available for debug, info, warn, and error. For more information, see the reference links above. NOTE: All the examples below assume that a Logger named LOG was previously created.

• trace(String arg0) — Will log a simple message. For example: LOG.trace(“Initialization complete.);

• trace(String arg0, Object arg1) — Will log a message with a single object argument. For example: LOG.trace(“Thing {} has successfully started.”, thing.getName());

Page 65: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 65

 

 

       

• trace(String arg0, Throwable arg1) — Will log a message with a throwable type as well. For example: LOG.trace(“Exception occurred”, e);

• trace(String arg0, Object… arg1) — Will log a message with many object arguments. For example: LOG.trace(“Thing {} was started with {} properties at {}”, thing.getName(), thing.getPro

 

Configuration The configuration of logging requires a logback.xml file be placed in the same folder as the application. An example is discussed below, but the configuration of the logback.xml file is beyond the scope of this document. It is recommended that you reference the sites above for more information.

     

Note The package entered below for logging “com.mycompany” will need to be modified to the name of the package where the SteamSensorClient and SteamThing are contained.

   

<configuration> <!--

 Create an appender for standard out using the following format

DateTime [L: LEVEL] [O: class] [T: Thread] message

--> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%date{yyyy-MM-dd HH:mm:ss.SSSZ} [L: %level] [O: %logger{8}] [T: %thread] %msg%n%rootExceptionpattern>%date{yyyy-MM-dd HH:mm:ss.SSSZ} [L: %level] [O: %logg </encoder> </appender> <!--

 Create an appender that will write to a file named

 /SteamSensor/Logs/SteamSensor.log

 

     

The file will rollover daily and be named  

/SteamSensor/Logs/SteamSensor-<date>.0.log  

     

The file will rollover after it reaches 100 MB and be named

Page 66: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 66

 

 

       

/SteamSensor/Logs/SteamSensor-<date>.<count>.log        

With the following format  

DateTime [L: LEVEL] [O: class] [T: Thread] message  

--> <appender name="ROLLING" class= "ch.qos.logback.core.rolling.RollingFileAppender"> <file>/SteamSensor/Logs/SteamSensor.logfile>/SteamSensor/Logs/ SteamSensor.log> <rollingPolicy class= "ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily --> <fileNamePattern>/SteamSensor/Logs/SteamSensor-%d.%i.logfileNamePattern>/ SteamSensor/Logs/SteamSensor-%d.%i.log> <timeBasedFileNamingAndTriggeringPolicy class= "ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- or whenever the file size reaches 100MB --> <maxFileSize>100MBmaxFileSize>100MB> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <encoder> <pattern>%date{yyyy-MM-dd HH:mm:ss.SSSZ} [L: %level] [O: %logger{8}] [T: %thread] %msg%n%rootExceptionpattern>%date{yyyy-MM-dd HH:mm:ss.SSSZ} [L: %level] [O: %logg </encoder> </appender> <!-- Log the SteamSensor at TRACE level --> <logger name="com.mycompany" level="TRACE">>/logger> <!-- Log all classes in the com.ThingWorx namespace at ERROR level --> <logger name="com.ThingWorx" level="ERROR"></logger> <!-- Set the default log level to WARN and log to the standard output and to a file --> <root level="WARN"> <appender-ref ref="STDOUT" /> <appender-ref ref="ROLLING" /> </root> </configuration>

   

Using Logback  

Integrating the Logging of Your Application

Page 67: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 67

 

 

                       

4 Java SDK and File Transfers

Configuring File Transfers .............................................................................................................. 68 Performing a File Transfer Using the Copy Service .................................................................. 68 Performing a File Transfer from a Client Application ................................................................ 69

The ThingWorx Java SDK can support file transfer to and from the ThingWorx Platform. File transfers are performed over the web socket connection maintained with the Platform, so there is no need for the client application to open another connection.

Page 68: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 68

 

 

   

Configuring File Transfers To support file transfers in your client application, you must implement the FileTransferVirtualThing. The FileTransferVirtualThing constructor requires an additional parameter, virtualDirectories, which you use to define the directories available for file operations. For example: public class FileTransferThing extends FileTransferVirtualThing {

public FileTransferThing(String name, String description,

ConnectedThingClient client, HashMap<String, String> virtualDirectories)

{

super(name, description, client, virtualDirectories);

}

}

Usage:

HashMap<String, String> virtualDirs = new HashMap<String, String>();

String userDir = System.getProperty("user.dir");

 virtualDirs.put("logs", userDir + File.separator + “logs”); virtualDirs.put("incoming", userDir + File.separator + “incoming”);

 FileTransferThing thing = new FileTransferThing(“MyThing,

“File Transfer Example", client, virtualDirs); client.bindThing(thing);

Once it connects to the server, this client binds MyThing to the matching MyThing RemoteThingWithFileTransfer defined in ThingWorx. Once bound, the various FileSystemServices found on RemoteThingWithFileTransfer can be used to interact with the file system of the client machine. For example, from the Platform, the BrowseDirectory service of MyThing could be called. If a forward slash (‘/’) is used for the path parameter, the two configured virtual directories would be returned. If /logs were passed in, a list of the files and directories in <user_home>/logs would be returned.

   

Performing a File Transfer Using the Copy Service The FileTransferSubsystem Copy service can be used to transfer files to and from the Remote Thing. The service takes the following parameters: • sourceRepo — The name of FileRepository or RemoteThing to transfer the

file from. • sourcePath — The path specifying the location in the file repository of the

source file.

Page 69: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 69

 

 

       

• sourceFile — The name of the source file. • targetRepo — The name of the FileRepository or RemoteThing to transfer

the file to. • targetPath — The path specifying the destination location of the file. • targetFile — The name of the file at the target. This name can differ from

the sourceName. • timeout — The amount of time to wait for a synchronous transfer to

complete, in seconds, before cancelling the transfer. • async — If false, the service call will block for ‘timeout’ seconds, or until

the transfer completes. When specifying the path parameter and the associated repository parameter for a RemoteThing, the first portion of the Path should be the name of a virtual directory:

• sourceRepo — SystemRepository • sourcePath — /outbound/files • sourceFile — directions.txt • targetRepo — MyThing • targetPath — /incoming/storage • targetFile — newdirections.txt • async — false • timeout — 120

 

 Performing a File Transfer from a Client Application A client application can execute file transfers through the BaseClient.invokeService() method. Triggering a transfer through the SDK is similar to triggering a transfer from a REST API – it is just an invocation of the FileTransferSubsystem Copy service: client.invokeService((ThingworxEntityTypes.Subsystems, "FileTransferSubsystem",

"Copy", parameters, timeout);

Here, the parameters argument is a ValueCollection containing the parameters of the Copy service. For synchronous transfers, the timeout argument of the invokeService method should be at least as long as the timeout parameter of the Copy service. Note that the timeout argument of the invokeService is in milliseconds, while the timeoutparameter of the Copy service is in seconds.

Page 70: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

 

 

 

Page 71: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 71

 

 

                       

5 Tunneling

Configuring Tunneling ..................................................................................................................... 72

The JavaSDK has full support for application tunneling. Application tunnels allow for secure, firewall transparent tunneling of TCP client server applications such as VNC and SSH. To use this functionality, you must implement the ??? class. This feature will add ~5KB of code space to your application, and upwards of 100KB RAM, depending on usage, so severely constrained environments may want to omit this functionality.

Page 72: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 72

 

 

   

Configuring Tunneling

Page 73: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 73

 

 

                       

6 Content Loader Services

Suppose you have a Web application running at the Edge, either on your devices or on the same network as the devices, and you want these applications to interact with the ThingWorx Platform. The ContentLoader services allow the Platform to send an HTTP request to the SDK, which then invokes the request on your Web application. The response is then returned to the Platform where it can be parsed and acted upon. The ContentLoader services return XML or JSON to the Platform, allowing you to make requests to the Web interface, parse the returned data, and work with it at the Platform. On the Platform side, a Content Loader Thing shape supports this capability. The SDKs provide an import file for the shape that provides a set of services. You can use the HTTP PUT, GET, and POST commands as services to load different types of content, including JSON, Text, XML, binary, image, and media. The following table lists and briefly describes the available Content Loader services:

 

Use To Delete Invoke an HTTP delete request on a URL GetCookies Issue a URL call and get the returned cookies

back GetText Get text content from a URL. GetXML Get XML content from a URL. GetJSON Get JSON content from a URL LoadBinary Load binary content from a URL. LoadImage Load image content from a URL. LoadJSON Load JSON content from a URL. LoadMediaEntity Load and capture a media entity via URL LoadText Load Text content from a URL. LoadXML Load XML content from a URL. PostBinary Post binary content from a URL using HTTP

Page 74: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 74

 

 

       

Use To   POST. PostImage Post image content from a URL using HTTP

POST. PostJSON Post JSON content from a URL using HTTP

POST. PostText Post text content from a URL using HTTP

POST. PostXML Post XML content from a URL using HTTP

POST. PutBinary Load binary content from a URL via HTTP

PUT. PutJSON Load JSON content from a URL via HTTP

PUT. PutText Load text content from a URL via HTTP PUT. PutXML Load XML content from a URL via HTTP

PUT.    

In addition, the SDK provides “execute<service_name>” services that are wrappers around the other services. These services do not "execute" anything else. For example: postjson test

The inputs to this service include headers, content, a user name and password combination, the URL that exists on the resource, and a timeout. Note that you cannot see the JSON results in the Composer user interface.

     

Note The Content Loader service interacts with web servers to download their files or documents. In this capacity, it supports NTLM to allow you to access Microsoft-based web server.

Page 75: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 75

 

 

                       

7 Troubleshooting

The following examples outline common operations that are a little more complex than the normal.

Page 76: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!

Copyright © 2015 PTC Inc. and/or Its Subsidiary Companies. All rights reserved. 76

 

 

       

Problem Description Resolutions Cannot connect to ThingWorx.

The SDK cannot connect to ThingWorx via WebSockets.

• Verify that the port is supplied in the uri, even if it is a default port for ws or wss. The following uri will not connect: ws:// localhost/ ThingWorx/WS. Change this uri to be: ws:// localhost:80/ ThingWorx/WS.

• Verify that a virus program is not running and blocking WebSocket communication.

• Verify that a firewall is not blocking the port.

• Verify that the following subsystems are started on the ThingWorx Server: WSCommunications- Subsystem and WSExecutionProces- singSubsystem.

Page 77: android developers guide - PTC · ThingWorx Android SDK Developer’s Guide Version 6.6.0 ThingWorx Java SDK August 2015!!!!