1 Star 0 Fork 0

callmedevil / aws-iot-device-sdk-java

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

New Version Available

A new AWS IoT Device SDK is now available. It is a complete rework, built to improve reliability, performance, and security. We invite your feedback!

This SDK will no longer receive feature updates, but will receive security updates.

AWS IoT Device SDK for Java

The AWS IoT Device SDK for Java enables Java developers to access the AWS IoT Platform through MQTT or MQTT over the WebSocket protocol. The SDK is built with AWS IoT device shadow support, providing access to thing shadows (sometimes referred to as device shadows) using shadow methods, including GET, UPDATE, and DELETE. It also supports a simplified shadow access model, which allows developers to exchange data with their shadows by just using getter and setter methods without having to serialize or deserialize any JSON documents.

To get started, use the Maven repository or download the latest JAR file.

Overview

This document provides instructions for installing and configuring the AWS IoT device SDK for Java. It also includes some examples that demonstrate the use of different APIs.

MQTT Connection Types

The SDK is built on top of the Paho MQTT Java client library. Developers can choose from two types of connections to connect to the AWS IoT service:

  • MQTT (over TLS 1.2) with X.509 certificate-based mutual authentication
  • MQTT over WebSocket with AWS Signature Version 4 authentication

For MQTT over TLS (port 8883), a valid certificate and private key are required for authentication. For MQTT over WebSocket (port 443), a valid AWS Identity and Access Management (IAM) access key ID and secret access key pair is required for authentication.

Thing Shadows

A thing shadow represents the cloud counterpart of a physical device or thing. Although a device is not always online, its thing shadow is. A thing shadow stores data in and out of the device in a JSON based document. When the device is offline, its shadow document is still accessible to the application. When the device comes back online, the thing shadow publishes the delta to the device (which the device didn't see while it was offline).

The SDK implements the protocol for applications to retrieve, update, and delete shadow documents mentioned here. When you use the simplified access model, you have the option to enable strict document versioning. To reduce the overhead of subscribing to shadow topics for each method requested, the SDK automatically subscribes to all of the method topics when a connection is established.

Simplified Shadow Access Model

Unlike the shadow methods, which operate on JSON documents, the simplified shadow access model allows developers to access their shadows with getter and setter methods.

To use this feature, you must extend the device class AWSIotDevice, use the annotation AWSIotDeviceProperty to mark class member variables to be managed by the SDK, and provide getter and setter methods for accessing these variables. The getter methods will be used by the SDK to report to the shadow periodically. The setter methods will be invoked whenever there is a change to the desired state of the shadow document. For more information, see Use the SDK later in this document.

Install the SDK

Minimum Requirements

To use the SDK, you will need Java 1.7+.

Install the SDK Using Maven

The recommended way to use the AWS IoT Device SDK for Java in your project is to consume it from Maven. Simply add the following dependency to the POM file of your Maven project.

<dependencies>
  <dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-iot-device-sdk-java</artifactId>
    <version>1.3.7</version>
  </dependency>
</dependencies>

The sample applications included with the SDK can also be installed using the following dependency definition.

<dependencies>
  <dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-iot-device-sdk-java-samples</artifactId>
    <version>1.3.7</version>
  </dependency>
</dependencies>

Install the SDK Using the Latest JAR

The latest JAR files can be downloaded here. You can simply extract and copy the JAR files to your project's library directory, and then update your IDE to include them to your library build path.

You will also need to add two libraries the SDK depends on:

Build the SDK from the GitHub Source

You can build both the SDK and its sample applications from the source hosted at GitHub.

$ git clone https://github.com/aws/aws-iot-device-sdk-java.git
$ cd aws-iot-device-sdk-java
$ mvn clean install -Dgpg.skip=true

Use the SDK

The following sections provide some basic examples of using the SDK to access the AWS IoT service over MQTT. For more information about each API, see the API documentation.

Initialize the Client

To access the AWS IoT service, you must initialize AWSIotMqttClient. The way in which you initialize the client depends on the connection type (MQTT or MQTT over WebSocket) you choose. In both cases, a valid client endpoint and client ID are required for setting up the connection.

  • Initialize the Client with MQTT (over TLS 1.2): For this MQTT connection type (port 8883), the AWS IoT service requires TLS mutual authentication, so a valid client certificate (X.509) and RSA keys are required. You can use the AWS IoT console or the AWS command line tools to generate certificates and keys. For the SDK, only a certificate file and private key file are required.
String clientEndpoint = "<prefix>.iot.<region>.amazonaws.com";       // replace <prefix> and <region> with your own
String clientId = "<unique client id>";                              // replace with your own client ID. Use unique client IDs for concurrent connections.
String certificateFile = "<certificate file>";                       // X.509 based certificate file
String privateKeyFile = "<private key file>";                        // PKCS#1 or PKCS#8 PEM encoded private key file

// SampleUtil.java and its dependency PrivateKeyReader.java can be copied from the sample source code.
// Alternatively, you could load key store directly from a file - see the example included in this README.
KeyStorePasswordPair pair = SampleUtil.getKeyStorePasswordPair(certificateFile, privateKeyFile);
AWSIotMqttClient client = new AWSIotMqttClient(clientEndpoint, clientId, pair.keyStore, pair.keyPassword);

// optional parameters can be set before connect()
client.connect();
  • Initialize the Client with MQTT Over WebSocket: For this MQTT connection type (port 443), you will need valid IAM credentials to initialize the client. This includes an AWS access key ID and secret access key. There are a number of ways to get IAM credentials (for example, by creating permanent IAM users or by requesting temporary credentials through the Amazon Cognito service). For more information, see the developer guides for these services.

As a best practice for application security, do not embed credentials directly in the source code.

String clientEndpoint = "<prefix>.iot.<region>.amazonaws.com";       // replace <prefix> and <region> with your own
String clientId = "<unique client id>";                              // replace with your own client ID. Use unique client IDs for concurrent connections.

// AWS IAM credentials could be retrieved from AWS Cognito, STS, or other secure sources
AWSIotMqttClient client = new AWSIotMqttClient(clientEndpoint, clientId, awsAccessKeyId, awsSecretAccessKey, sessionToken);

// optional parameters can be set before connect()
client.connect();

Publish and Subscribe

After the client is initialized and connected, you can publish messages and subscribe to topics.

To publish a message using a blocking API:

String topic = "my/own/topic";
String payload = "any payload";

client.publish(topic, AWSIotQos.QOS0, payload);

To publish a message using a non-blocking API:

public class MyMessage extends AWSIotMessage {
    public MyMessage(String topic, AWSIotQos qos, String payload) {
        super(topic, qos, payload);
    }

    @Override
    public void onSuccess() {
        // called when message publishing succeeded
    }

    @Override
    public void onFailure() {
        // called when message publishing failed
    }

    @Override
    public void onTimeout() {
        // called when message publishing timed out
    }
}

String topic = "my/own/topic";
AWSIotQos qos = AWSIotQos.QOS0;
String payload = "any payload";
long timeout = 3000;                    // milliseconds

MyMessage message = new MyMessage(topic, qos, payload);
client.publish(message, timeout);

To subscribe to a topic:

public class MyTopic extends AWSIotTopic {
    public MyTopic(String topic, AWSIotQos qos) {
        super(topic, qos);
    }

    @Override
    public void onMessage(AWSIotMessage message) {
        // called when a message is received
    }
}

String topicName = "my/own/topic";
AWSIotQos qos = AWSIotQos.QOS0;

MyTopic topic = new MyTopic(topicName, qos);
client.subscribe(topic);

Shadow Methods

To access a shadow using a blocking API:

String thingName = "<thing name>";                    // replace with your AWS IoT Thing name

AWSIotDevice device = new AWSIotDevice(thingName);

client.attach(device);
client.connect();

// Delete existing shadow document
device.delete();

// Update shadow document
State state = "{\"state\":{\"reported\":{\"sensor\":3.0}}}";
device.update(state);

// Get the entire shadow document
String state = device.get();

To access a shadow using a non-blocking API:

public class MyShadowMessage extends AWSIotMessage {
    public MyShadowMessage() {
        super(null, null);
    }

    @Override
    public void onSuccess() {
        // called when the shadow method succeeded
        // state (JSON document) received is available in the payload field
    }

    @Override
    public void onFailure() {
        // called when the shadow method failed
    }

    @Override
    public void onTimeout() {
        // called when the shadow method timed out
    }
}

String thingName = "<thing name>";      // replace with your AWS IoT Thing name

AWSIotDevice device = new AWSIotDevice(thingName);

client.attach(device);
client.connect();

MyShadowMessage message = new MyShadowMessage();
long timeout = 3000;                    // milliseconds
device.get(message, timeout);

Simplified Shadow Access Model

To use the simplified shadow access model, you need to extend the device class AWSIotDevice, and then use the annotation class AWSIotDeviceProperty to mark the device attributes and provide getter and setter methods for them. The following very simple example has one attribute, someValue, defined. The code will report the attribute to the shadow, identified by thingName every 5 seconds, in the reported section of the shadow document. The SDK will call the setter method setSomeValue() whenever there's a change to the desired section of the shadow document.

public class MyDevice extends AWSIotDevice {
    public MyDevice(String thingName) {
        super(thingName);
    }

    @AWSIotDeviceProperty
    private String someValue;

    public String getSomeValue() {
        // read from the physical device
    }

    public void setSomeValue(String newValue) {
        // write to the physical device
    }
}

MyDevice device = new MyDevice(thingName);

long reportInterval = 5000;            // milliseconds. Default interval is 3000.
device.setReportInterval(reportInterval);

client.attach(device);
client.connect();

Other Topics

Enable Logging

The SDK uses java.util.logging for logging. To change the logging behavior (for example, to change the logging level or logging destination), you can specify a property file using the JVM property java.util.logging.config.file. It can be provided through JVM arguments like so:

-Djava.util.logging.config.file="logging.properties" 

To change the console logging level, the property file logging.properties should contain the following lines:

# Override of console logging level 
java.util.logging.ConsoleHandler.level=INFO 

Load KeyStore from File to Initialize the Client

You can load a KeyStore object directly from JKS-based keystore files. You will first need to import X.509 certificate and the private key into the keystore file like so:

$ openssl pkcs12 -export -in <certificate-file> -inkey <private-key-file> -out p12.keystore -name alias
(type in the export password)

$ keytool -importkeystore -srckeystore p12.keystore -srcstoretype PKCS12 -srcstorepass <export-password> -alias alias -deststorepass <keystore-password> -destkeypass <key-password> -destkeystore my.keystore 

After the keystore file my.keystore is created, you can use it to initialize the client like so:

String keyStoreFile = "<my.keystore>";                               // replace with your own key store file
String keyStorePassword = "<keystore-password>";                     // replace with your own key store password
String keyPassword = "<key-password>"                                // replace with your own key password

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(keyStoreFile), keyStorePassword.toCharArray());

String clientEndpoint = "<prefix>.iot.<region>.amazonaws.com";       // replace <prefix> and <region> with your own
String clientId = "<unique client id>";                              // replace with your own client ID. Use unique client IDs for concurrent connections.

AWSIotMqttClient client = new AWSIotMqttClient(clientEndpoint, clientId, keyStore, keyPassword);

Use ECC-Based Certificates

You can use Elliptic Curve Cryptography (ECC)-based certificates to initialize the client. To create an ECC key and certificate, see this blog post. After you have created and registered the key and certificate, use the following command to convert the ECC key file to PKCK#8 format.

$ openssl pkcs8 -topk8 -nocrypt -in ecckey.key -out ecckey-pk8.key
(type in the key password)

You can then use the instruction described in this section to initialize the client with just this one change.

// SampleUtil.java and its dependency PrivateKeyReader.java can be copied from the sample source code.
// Alternatively, you could load key store directly from a file - see the example included in this README.
KeyStorePasswordPair pair = SampleUtil.getKeyStorePasswordPair(certificateFile, privateKeyFile, "EC");

Sample Applications

There are three samples applications included with the SDK. The easiest way to run these samples is through Maven, which will take care of getting the dependencies.

  • Publish/Subscribe sample: This sample consists of two publishers publishing one message per second to a topic. One subscriber subscribing to the same topic receives and prints the messages.

  • Shadow sample: This sample consists of a simple demo of the simplified shadow access model. The device contains two attributes: window state and room temperature. Window state can be modified (therefore, controlled) remotely through desired state. To demonstrate this control function, you can use the AWS IoT console to modify the desired window state, and then see its change from the sample output.

  • Shadow echo sample: This sample consists of a simple demo that uses Shadow methods to send a shadow update and then retrieve it back every second.

Arguments for the Sample Applications

To run the samples, you will also need to provide the following arguments through the command line:

  • clientEndpoint: client endpoint, in the form of <prefix>.iot.<region>.amazonaws.com
  • clientId: client ID
  • thingName: AWS IoT thing name (not required for the Publish/Subscribe sample)

You will also need to provide either set of the following arguments for authentication. For an MQTT connection, provide these arguments:

  • certificateFile: X.509 based certificate file (For Just-in-time registration, this is the concatenated file from both the device certificate and CA certificate. For more information about Just-in-Time Registration, please see this blog.
  • privateKeyFile: private key file
  • keyAlgorithm: (optional) RSA or EC. If not specified, RSA is used.

For an MQTT over WebSocket connection, provide these arguments:

  • awsAccessKeyId: IAM access key ID
  • awsSecretAccessKey: IAM secret access key
  • sessionToken: (optional) if temporary credentials are used

Run the Sample Applications

You can use the following commands to execute the sample applications (assuming TLS mutual authentication is used).

  • To run the Publish/Subscribe sample, use the following command:
$ mvn exec:java -pl aws-iot-device-sdk-java-samples -Dexec.mainClass="com.amazonaws.services.iot.client.sample.pubSub.PublishSubscribeSample" -Dexec.args="-clientEndpoint <prefix>.iot.<region>.amazonaws.com -clientId <unique client id> -certificateFile <certificate file> -privateKeyFile <private key file>"
  • To run the Shadow sample, use the following command:
$ mvn exec:java -pl aws-iot-device-sdk-java-samples -Dexec.mainClass="com.amazonaws.services.iot.client.sample.shadow.ShadowSample" -Dexec.args="-clientEndpoint <prefix>.iot.<region>.amazonaws.com -clientId <unique client id> -thingName <thing name> -certificateFile <certificate file> -privateKeyFile <private key file>"
  • To run the Shadow echo sample, use the following command:
$ mvn exec:java -pl aws-iot-device-sdk-java-samples -Dexec.mainClass="com.amazonaws.services.iot.client.sample.shadowEcho.ShadowEchoSample" -Dexec.args="-clientEndpoint <prefix>.iot.<region>.amazonaws.com -clientId <unique client id> -thingName <thing name> -certificateFile <certificate file> -privateKeyFile <private key file>"

Sample Source Code

You can get the sample source code either from the GitHub repository as described here or from the latest SDK binary. They both provide you with Maven project files that you can use to build and run the samples from the command line or import them into an IDE, such as Eclipse.

The sample source code included with the latest SDK binary is shipped with a modified Maven project file (pom.xml) that allows you to build the sample source indepedently, without the need to reference the parent POM file as with the GitHub source tree.

API Documentation

You'll find the API documentation for the SDK here.

License

This SDK is distributed under the Apache License, Version 2.0. For more information, see LICENSE.txt and NOTICE.txt.

Support

If you have technical questions about the AWS IoT Device SDK, use the AWS IoT Forum. For any other questions about AWS IoT, contact AWS Support.

Apache License Version 2.0, January 2004 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and 2. You must cause any modified files to carry prominent notices stating that You changed the files; and 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Note: Other license terms may apply to certain, identified software files contained within or distributed with the accompanying software if such terms are included in the directory containing the accompanying software. Such other license terms will then apply in lieu of the terms of the software license above. JSON processing code subject to the JSON License from JSON.org: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

Java SDK for connecting to AWS IoT from a device. 展开 收起
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/olove8761/aws-iot-device-sdk-java.git
git@gitee.com:olove8761/aws-iot-device-sdk-java.git
olove8761
aws-iot-device-sdk-java
aws-iot-device-sdk-java
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891