Android Developers Guide - PTC

Transcription

ThingWorx AndroidSDK Developer’sGuideVersion 6.6.0ThingWorxJava SDKAugust 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 alicense agreement that restricts copying, disclosure, and use of such documentation. PTC hereby grants to thelicensed software user the right to make copies in printed form of this documentation if provided on softwaremedia, but only for internal/personal use and in accordance with the license agreement under which theapplicable software is licensed. Any copy made shall include the PTC copyright notice and any otherproprietary notice provided by PTC. Training materials may not be copied without the express written consentof PTC. This documentation may not be disclosed, transferred, modified, or reduced to any form, includingelectronic media, or transmitted or made publicly available by any means without the prior written consent ofPTC 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 liabilityfor any errors or inaccuracies that may appear in this document.The software described in this document is provided under written license agreement, contains valuable tradesecrets and proprietary information, and is protected by the copyright laws of the United States and othercountries. It may not be copied or distributed in any form or medium, disclosed to third parties, or used in anymanner 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 CIVILDAMAGES AND CRIMINAL PROSECUTION. PTC regards software piracy as the crime it is, and we viewoffenders accordingly. We do not tolerate the piracy of PTC software products, and we pursue (both civillyand criminally) those who do so using all legal means available, including public and private surveillanceresources. As part of these efforts, PTC uses data monitoring and scouring technologies to obtain and transmitdata on users of illegal copies of our software. This data collection is not performed on users of legallylicensed software from PTC and its authorized distributors. If you are using an illegal copy of our softwareand do not consent to the collection and transmission of such data (including to the United States), ceaseusing the illegal version, and contact PTC to obtain a legally licensed copy.Important Copyright, Trademark, Patent, and Licensing Information: See the About Box, or copyrightnotice, of your PTC software.UNITED STATES GOVERNMENT RESTRICTED RIGHTS LEGENDThis 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 areprovided to the US Government under a limited commercial license only. For procurements predating theabove clauses, use, duplication, or disclosure by the Government is subject to the restrictions set forth insubparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software Clause at DFARS 252.2277013 (OCT’88) or Commercial Computer Software-Restricted Rights at FAR 52.227-19(c)(1)-(2) (JUN’87),as applicable. 01012015PTC Inc., 140 Kendrick Street, Needham, MA 02494 USA

ContentsAbout this Guide . 7The Java SDK . 11About the Java SDK . 12Developing Your Client Application . 27Primary Components of the Java SDK . 29ClientConfigurator Component. 30ConnectedThingClient Component . 32VirtualThing Component . 33Setting up an Application. 35The Client . 36Virtual Things . 46Base Types and Primitives . 60Java SDK Logging . 63Java SDK and File Transfers . 67Configuring File Transfers . 68Performing a File Transfer Using the Copy Service . 68Performing a File Transfer from a Client Application . 69Tunneling . 71Configuring Tunneling . 72Content Loader Services. 73Troubleshooting . 75Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.5

About this GuideThingWorx has introduced Software Development Kits (SDKs) in severalprogramming languages that allow companies to develop machine/devicefunctionality for their products, and to easily connect their products to aThingWorx Platform Server.All ThingWorx SDKs share a common reference implementation and provide asecure 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 thisguide, a JavaDoc is available in the SDK bundle.NoteThis document is accurate as of the release and is subject to change. For thelatest documentation, see the Help Center available at PTC ThingWorxeSupport, equisitesThe only system requirement is that you have the following version of the JavaJRE installed:Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.7

Java JRE 1.7.0.51 or later.This document assumes that you have a solid background in the Javaprogramming language. Further, it assumes that you have had at least basictraining in ThingWorx. For example, you know how to use the ThingWorxComposer and understand the main concepts of Things, DataShapes, Properties,Events, and Services.Technical SupportContact PTC Technical Support via the PTC Web site, phone, fax, or e-mail if youencounter problems using your product or the product documentation.For complete details, refer to Contacting Technical Support in the PTC CustomerService Guide. This guide can be found under the Related Resources section of thePTC Web site at:http://www.ptc.com/support/The PTC Web site also provides a search facility for technical documentation ofparticular interest. To access this search facility, use the URL above and search theknowledge base.You must have a Service Contract Number (SCN) before you can receivetechnical support. If you do not have an SCN, contact the PTC MaintenanceDepartment using the instructions found in your PTC Customer Service Guideunder Contacting Your Maintenance Support Representative.Documentation for PTC ThingWorx ProductsYou can access PTC ThingWorx documentation, using the following resources: PTC ThingWorx Help Center — The PTC ThingWorx Help Center includesdocumentation for the PTC ThingWorx Platform, the PTC ThingWorx EdgeMicroServer (EMS), and all the SDKs. You can browse the entiredocumentation 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 Documentswebsite provides access to the PDF documents available for the PTCThingWorx Edge SDKs and the PTC ThingWorx Platforms at , These PDF documents include SystemRequirements documents.A Service Contract Number (SCN) is required to access the PTCdocumentation from the Reference Documents website. If you do not knowyour SCN, see “Preparing to contact TS” on the Processes tab of the PTCCustomer Support Guide for information about how to locate it: sguide.jsp. When you enter a keyword inCopyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.8

the, "Search Our Knowledge" field on the PTC eSupport portal, your searchresults include both knowledge base articles and PDF guides.CommentsPTC welcomes your suggestions and comments on our documentation. To submityour feedback, you can: Send an email to documentation@ptc.com. To help us more quickly addressyour concern, include the name of the PTC product and its release numberwith your comments. If your comments are about a specific help topic orbook, include the title. Click the feedback icon in the PTC ThingWorx Help Center toolbar andcomplete the feedback form. The title of the help topic you were viewingwhen you clicked the icon is automatically included with your feedback.Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.9

1The Java SDKAbout the Java SDK . 12Developing Your Client Application . 27Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.11

About the Java SDKThis chapter provides an overview of the Java SDK, explaining the relationshipbetween the SDK and the ThingWorx server and summarizing the purpose of theJava SDK.The Java SDK is designed for portability while making it easy to integrateapplications into the ThingWorx distributed computing view of the Internet ofThings (IoT). The goal of the Java SDK is to make it simple to connect any Javaenabled devices and/or systems to the ThingWorx server. In addition, the SDK isdesigned to give developers enough flexibility to start simple and move quickly tocreating 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 theWebSockets protocol for communication. The WebSockets protocol allowspersistent (AlwaysOn ) connections that can operate through a firewall. Thepersistence enables two-way, low latency communication between the device andserver. If required, the connection can be configured to remain open only forspecific time periods, or duty cyclesThe purpose of the Java SDK includes the following: To establish and manage a secure AlwaysOn connectionwith a ThingWorx server, which includes: TLS negotiation Duty-cycle modulation Connection maintenance, such as reestablishing a connection after networkconnectivity is lost and restored.To enable simple programmatic interaction with the properties, services, andevents that are exposed by RemoteThings created on a ThingWorx server. To easily define properties and services that can be accessed from theThingWorx server.Installing and Navigating the Java SDK DirectoriesInstallationTo install the Java SDK, download the Java SDK bundle to your computer, andextract the files.Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.12

Directories and FilesThe Java SDK installation contains the following directories: lib — Contains the JARs listed in the table, Contents of the lib Directory onpage 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 DirectoryFile n2.3.3DescriptionJackson Annotations forJackson Data Processor2.3.3Jackson JSON .jarthingworx-commonv.v.v-bnn.jar1.0.13Jackson Databinding forJackson Data ProcessorJoda Time date and timeclassesLogback logging1.0.13Logback logging4.0.24NIO Client serverframeworkSimple Logging Façadefor JavaThingWorx ersion (e.g., 6.0.3–b10)Java DependenciesHere is a dependency tree that shows the required jar files for a sample applicationthat uses the jackson-annotations.jar, jackson-core.jar, joda-time.jar, ture-thing:jar:1.1-SNAPSHOT - 3.1:compileCopyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.13

:2.3.0:compile \- 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 - mple ApplicationsThe samples directory contains the SteamSensor example code files(SteamSensor.java and SteamSensorClient.java) that you shouldexamine before attempting your own application. You can find documentation forthe example in the ThingWorx Help Center.In addition, the samples directory contains code examples that are shown in thefollowing sections: Connecting an Application to thee ThingWorx Platform on page 15Reading a Property on page 18Writing a Property on page 19Invoking a Service on page 19Firing Events on page 20Setting Up the ThingWorx Platform to Communicatewith a ClientBefore running a client application from a device, you must create a Thing on theThingWorx Platform that represents your application and allows it tocommunicate with the ThingWorx Platform Within ThingWorx Composer, add anew RemoteThing, using the RemoteThing template. If you need assistance, referto the help for the application.Using ThingWorx and the Java SDKThe ThingWorx Java SDK is designed to be flexible enough to be used across awide variety of products and services for smart, connected products. From verysimply connecting a device to the ThingWorx Platform for monitoring purposes tohigh-end, sophisticated data collection and processing for use in analyticalsoftware, applications written using the ThingWorx Java SDK can run on anydevice, machine, or system that has a JRE (v1.7.51 or later).Together with the ThingWorx Platform, the ThingWorx Java SDK enables you toachieve the following goals: Collect data from physical devices and push it to the ThingWorx Platform. Forexample, collect speed, acceleration, and heading for a bicycle and push thisinformation to theCopyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.14

Platform. Sensors may be capable of determining if the bicycle is skidding andwhen that information reaches the Platform, an alert might be triggered.Note that calls to the Platform to update a RemoteThing are queued andapplied in sequence, based on timestamp. To ensure updates happen when youexpect, the clocks of the remote application and the Platform hosts must besynchronized. Access the current value of properties on the remote device and display themin Mashups created with the ThingWorx Plat AlwaysOn form.How is this possible? First, you should understand how clients connect to theserver and then the basic concepts of Things and how to work with them.Connecting an Application to the ThingWorx PlatformThe Java SDK follows a three-step process when connecting to the ThingWorxPlatform. In the process detailed below, “client” refers to the application andJava SDK running on or near the device and “server” refers to the ThingWorxPlatform:1. Establish the physical websocket: The client opens a websocket to theThingWorx server, using the host and port that it has been configured to use. Ifconfigured, 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 andpassword combination. This message is part of the ThingWorx AlwaysOn protocol. If the client attempts to send any other message before theauthentication message, the server disconnects it. The server also disconnectsthe client if it does not receive an authentication message within 15seconds. This time is configurable in the WSCommunicationSubsystemCopyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.15

which can be found inside the ThingWorx composer underSystem Subsystems Entity Information Configuration. The settingnamed, "Amount of time to wait for authentication message (secs)".isEstablishing a connection and authenticating are both performedwhenever a new SDK client is created and its start() method iscalled. Once authenticated, the client can interact with the serveraccording 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. TheSDK client allows one or more VirtualThings to be associated with awebsocket connection, using thing names or identifiers. When theclient binds a VitrualThing class, the server links the associatedRemoteThing on the server with the websocket from which it receivedthe request. Binding enables the server to send request messages to aVirtualThing over the associated websocket. The server also updatesthe isConnected property to true and the time value of the3. lastConnected property for the newly bound Thing to indicate whenthe binding was established.A client can also send an unbind request. This message tells the serverto remove the association between the Thing and the websocket. TheisConnected property of the Thing is then updated to false.To enable your application to connect to the Platform, you need to create aClientConfigurator and then use it to create aConnectedThingClient that will then establishyour connection to the server. Here is an example of howthis is done:public static void main(String[] args) {ClientConfigurator config newClientConfigurator();// Set the URI of the server that we are going to connect x/WS");// Set the ApplicationKey. This will allow the client to authenticatewith// the server. It will also dictate what the client isauthorized to// do once 5a-376ff92aae02");// To test against a server using a self-signed certificate, useCopyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.16

// the ignoreSSLErrors method. HOWEVER make sure that you remove// this line for a production system.config.ignoreeSSLErrors(true); //All self-signed certificatestry {// 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 nowconnected.");} 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 datachannel between the ThingWorx Platform and as many remote processes as youwant. The AlwaysOn protocol enables this communication. What can you dowith this channel? Make remote calls to any ThingWorx RemoteThing or Resource (API). Youcan expose functions within your process that can be called by the server inresponse to changes on the server side, providing you with notifications of thatchange. Transfer files bidirectionally.Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.17

Tunnel other protocols through this connection. Take advantage of a Thing synchronization framework that simplifies the taskof updating server RemoteThings by creating remote versions of themwithin your remote process. You then update the state of the VirtualThing inyour process, and the SDK manages the transfer of that state information to theserver, either when you want to push it or when the server requests it. Fordetails about this synchronization framework, see Synchronization Frameworkon page 26.Best PracticeUse of the ignoreSSLErrors method is purely for development purposes. It isstrongly recommended that you use SSL/TLS for connections between yourdevices and the ThingWorx Platform. For an example of setting up X.509parameters 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 fireevents.Reading a PropertyNow that the client has connected to ThingWorx, you can read a property from aThing on the server:// We may now interact with the ThingWorx Server;// Reading a property of a //////////////////// Request a property from a Thing on the Platform.// Here we access the 'name' property of a Thing.InfoTable result ingName,"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 fo("The name of the Thing {} is: {}", ThingName, name);// We can also access the value as a Primitive.// This will work for all primitive types.Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.18

StringPrimitive prim (StringPrimitive) ("The name of the Thing {} is: {}", ThingName, prim.getValue());Writing a PropertyYou can also write a property://// Writing a /////////////////////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, s, ThingName, "CurrentLocation",location, 5000);LOG.info("Wrote to the property 'CurrentLocation' of Thing {}. value: {}",ThingName, location.toString());Invoking a ServiceYou can invoke a service on a Thing://// Invoking a service on a ////////////////////A ValueCollection is used to specify a service's parametersValueCollection 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 .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();Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.19

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: {}", eLOG.info("size: {}", row.getValue("size"));Firing EventsYou can trigger an event on a Thing on a ThingWorx server://// Firing an ////////////////// 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 e", new e", new DatetimePrimitive());payload.put("size", new NumberPrimitive(256));// This will trigger the 'FileEvent' of a RemoteThing// on the gs, ThingName,"FileEvent", payload, 5000);.Working with ThingsMultiple terms exist for things. Here are the basic definitions as used in thisdocument: A Thing is a collection of Properties, Services, and Events. Typically in theThingWorx 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 thatmodels an asset that is connected to the ThingWorx Platform from a remotelocation.A VirtualThing is a representation of a Thing in the Java SDK. Typically, aVirtualThing is used to represent the properties and services that compriseyour device, application, or system.The RemoteThing and VirtualThing are related to each other by the name assignedto them. A VirtualThing collects and stores the values of its properties. It can thenforward these values to its corresponding RemoteThing on the ThingWorxPlatform.To use a VirtualThing in an application extend the VirtualThing class. Thefollowing code would go in a new file, SimpleThing.java:Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.20

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 atour SimpleClient.java example again://// Create a VirtualThing and bind it to the ///////////////////// 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 isConnectedproperty set to true and its lastConnection property updated to the current time.You can verify that it is connected by requesting the isConnected property throughthe Platform’s REST 1/Properties/isConnectedServicesA VirtualThing can define services and make those services available to beexecuted from the ThingWorx Platform. Since the AlwaysOn connectionenables bi-directional communication, the Platform can invoke these services ondemand.Defining a Service on a VirtualThingA service on a VirtualThing is simply a method with the proper ThingWorxannotation applied to it. For instance, take a simple method that adds twonumbers: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,Copyright 2015 PTC Inc. and/or Its Subsidiary Companies.All rights reserved.21

@ThingworxServiceParameter(name "p2", description "Second param",baseType "NUMBER" ) Double p2) throws Exception {return p1 p2;}Note: you can call t

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