Skip to content

Commit

Permalink
Merge pull request #883 from GoogleCloudPlatform/iot-snippets
Browse files Browse the repository at this point in the history
Post-launch fixes
  • Loading branch information
gguuss authored Oct 9, 2017
2 parents 6637e6b + b670749 commit f521cb5
Show file tree
Hide file tree
Showing 6 changed files with 214 additions and 97 deletions.
25 changes: 20 additions & 5 deletions iot/api-client/http_example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ The following command summarizes the sample usage:
```
mvn exec:java \
-Dexec.mainClass="com.google.cloud.iot.examples.HttpExample" \
-Dexec.args="-project_id=my-iot-project \
-registry_id=my-registry \
-device_id=my-device \
-private_key_file=rsa_private_pkcs8 \
-algorithm=RS256"
-Dexec.args="-project_id=<your-iot-project> \
-registry_id=<your-registry-id> \
-device_id=<device-id> \
-private_key_file=<path-to-keyfile> \
-message_type=<event|state> \
-algorithm=<RS256|ES256>"
```

For example, if your project ID is `blue-jet-123`, your service account
Expand All @@ -42,6 +43,20 @@ provided in the parent folder, you can run the sample as:
-algorithm=RS256"
```

To publish state messages, run the sample as follows:

```
mvn exec:java \
-Dexec.mainClass="com.google.cloud.iot.examples.HttpExample" \
-Dexec.args="-project_id=blue-jet-123 \
-registry_id=my-registry \
-device_id=my-java-device \
-private_key_file=../rsa_private_pkcs8 \
-message_type=state \
-algorithm=RS256"
```


## Reading the messages written by the sample client

1. Create a subscription to your topic.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,40 @@
/**
* Copyright 2017, Google, Inc.
*
* <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Copyright 2017, Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/


package com.google.cloud.iot.examples;

// [START cloudiotcore_http_imports]
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
// [END cloudiotcore_http_imports]

/**
* Java sample of connecting to Google Cloud IoT Core vice via HTTP, using JWT.
Expand All @@ -39,7 +48,8 @@
* folder.
*/
public class HttpExample {
/** Create a Cloud IoT Core JWT for the given project id, signed with the given private key. */
// [START cloudiotcore_http_createjwt]
/** Create a RSA-based JWT for the given project id, signed with the given private key. */
private static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
DateTime now = new DateTime();
// Create a JWT to authenticate this device. The device will be disconnected after the token
Expand All @@ -58,6 +68,7 @@ private static String createJwtRsa(String projectId, String privateKeyFile) thro
return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
}

/** Create an ES-based JWT for the given project id, signed with the given private key. */
private static String createJwtEs(String projectId, String privateKeyFile) throws Exception {
DateTime now = new DateTime();
// Create a JWT to authenticate this device. The device will be disconnected after the token
Expand All @@ -75,28 +86,62 @@ private static String createJwtEs(String projectId, String privateKeyFile) throw

return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
// [END cloudiotcore_http_createjwt]

public static void main(String[] args) throws Exception {
HttpExampleOptions options = HttpExampleOptions.fromFlags(args);
if (options == null) {
// Could not parse the flags.
System.exit(1);
}

// [START cloudiotcore_http_publishmessage]
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void publishMessage(String payload, String urlPath, String messageType,
String token, String projectId, String cloudRegion, String registryId, String deviceId)
throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
// Build the resource path of the device that is going to be authenticated.
String devicePath =
String.format(
"projects/%s/locations/%s/registries/%s/devices/%s",
options.projectId, options.cloudRegion, options.registryId, options.deviceId);
projectId, cloudRegion, registryId, deviceId);
String urlSuffix = messageType.equals("event") ? "publishEvent" : "setState";

// This describes the operation that is going to be perform with the device.
String urlSuffix = options.messageType.equals("event") ? "publishEvent" : "setState";
// Data sent through the wire has to be base64 encoded.
Base64.Encoder encoder = Base64.getEncoder();

String urlPath =
String.format(
"%s/%s/%s:%s", options.httpBridgeAddress, options.apiVersion, devicePath, urlSuffix);
String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));


urlPath = urlPath + devicePath + ":" + urlSuffix;
URL url = new URL(urlPath);
System.out.format("Using URL: '%s'\n", urlPath);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");

// Add headers.
httpCon.setRequestProperty("authorization", String.format("Bearer %s", token));
httpCon.setRequestProperty("content-type", "application/json; charset=UTF-8");
httpCon.setRequestProperty("cache-control", "no-cache");

// Add post data. The data sent depends on whether we're updating state or publishing events.
JSONObject data = new JSONObject();
if (messageType.equals("event")) {
data.put("binary_data", encPayload);
} else {
JSONObject state = new JSONObject();
state.put("binary_data", encPayload);
data.put("state", state);
}
httpCon.getOutputStream().write(data.toString().getBytes("UTF-8"));
httpCon.getOutputStream().close();

System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
}
// [END cloudiotcore_http_publishmessage]

// [START cloudiotcore_http_run]
/** Parse arguments and publish messages. */
public static void main(String[] args) throws Exception {
HttpExampleOptions options = HttpExampleOptions.fromFlags(args);
if (options == null) {
// Could not parse the flags.
System.exit(1);
}

// Create the corresponding JWT depending on the selected algorithm.
String token;
Expand All @@ -109,41 +154,18 @@ public static void main(String[] args) throws Exception {
"Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
}

// Data sent through the wire has to be base64 encoded.
Base64.Encoder encoder = Base64.getEncoder();

// Publish numMessages messages to the HTTP bridge.
for (int i = 1; i <= options.numMessages; ++i) {
String payload = String.format("%s/%s-payload-%d", options.registryId, options.deviceId, i);
System.out.format(
"Publishing %s message %d/%d: '%s'\n",
options.messageType, i, options.numMessages, payload);
String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");

// Adding headers.
httpCon.setRequestProperty("Authorization", String.format("Bearer %s", token));
httpCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

// Adding the post data. The structure of the data send depends on whether it is event or a
// state message.
JSONObject data = new JSONObject();
if (options.messageType.equals("event")) {
data.put("binary_data", encPayload);
} else {
JSONObject state = new JSONObject();
state.put("binary_data", encPayload);
data.put("state", state);
}
httpCon.getOutputStream().write(data.toString().getBytes("UTF-8"));
httpCon.getOutputStream().close();
String urlPath = String.format("%s/%s/", options.httpBridgeAddress, options.apiVersion);
System.out.format("Using URL: '%s'\n", urlPath);

// This will perform the connection as well.
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
publishMessage(payload, urlPath, options.messageType, token, options.projectId,
options.cloudRegion, options.registryId, options.deviceId);

if (options.messageType.equals("event")) {
// Frequently send event payloads (every second)
Expand All @@ -155,4 +177,5 @@ public static void main(String[] args) throws Exception {
}
System.out.println("Finished loop successfully. Goodbye!");
}
// [END cloudiotcore_http_run]
}
9 changes: 5 additions & 4 deletions iot/api-client/manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,11 @@ run the sample as:

Create a PubSub topic, `hello-java`, for the project, `blue-jet-123`:

java -cp target/cloudiot-manager-demo-1.0-jar-with-dependencies.jar \
com.example.cloud.iot.examples.DeviceRegistryExample \
-project_id=blue-jet-123 -pubsub_topic=hello-java
-command=create-iot-topic
mvn exec:java \
-Dexec.mainClass="com.example.cloud.iot.examples.DeviceRegistryExample" \
-Dexec.args="-project_id=blue-jet-123 \
-command=create-iot-topic \
-pubsub_topic=hello-java "

Create an ES device:

Expand Down
Loading

0 comments on commit f521cb5

Please sign in to comment.