Quickstart: Send telemetry to an Azure IoT hub and read it with a Java application

In this quickstart, you send telemetry to Azure IoT Hub and read it with a Java application. IoT Hub is an Azure service that enables you to ingest high volumes of telemetry from your IoT devices into the cloud for storage or processing. This quickstart uses two pre-written Java applications: one to send the telemetry and one to read the telemetry from the hub. Before you run these two applications, you create an IoT hub and register a device with the hub.

Prerequisites

  • An Azure account with an active subscription. Create one for free.

  • Java SE Development Kit 8. In Java long-term support for Azure and Azure Stack, under Long-term support, select Java 8.

    You can verify the current version of Java on your development machine using the following command:

    java -version
    
  • Apache Maven 3.

    You can verify the current version of Maven on your development machine using the following command:

    mvn --version
    
  • Download or clone the azure-iot-samples-java repository using the Code button on the azure-iot-samples-java repository page.

    This article uses the simulated-device and read-d2c-messages samples from the repository.

  • Port 8883 open in your firewall. The device sample in this quickstart uses MQTT protocol, which communicates over port 8883. This port may be blocked in some corporate and educational network environments. For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

  • Use Azure Cloud Shell using the Bash environment.

    Launch Cloud Shell in a new window

  • If you prefer, install the Azure CLI to run CLI reference commands.

    • If you're using a local installation, sign in to the Azure CLI by using the az login command. To finish the authentication process, follow the steps displayed in your terminal. For additional sign-in options, see Sign in with the Azure CLI.
    • When you're prompted, install Azure CLI extensions on first use. For more information about extensions, see Use extensions with the Azure CLI.
    • Run az version to find the version and dependent libraries that are installed. To upgrade to the latest version, run az upgrade.

Note

This article uses the newest version of the Azure IoT extension, called azure-iot. The legacy version is called azure-cli-iot-ext.You should only have one version installed at a time. You can use the command az extension list to validate the currently installed extensions.

Use az extension remove --name azure-cli-iot-ext to remove the legacy version of the extension.

Use az extension add --name azure-iot to add the new version of the extension.

To see what extensions you have installed, use az extension list.

Create an IoT hub

This section describes how to create an IoT hub using the Azure portal.

  1. Sign in to the Azure portal.

  2. From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. Select IoT Hub from the search results, and then select Create.

  4. On the Basics tab, complete the fields as follows:

    • Subscription: Select the subscription to use for your hub.

    • Resource Group: Select a resource group or create a new one. To create a new one, select Create new and fill in the name you want to use. To use an existing resource group, select that resource group. For more information, see Manage Azure Resource Manager resource groups.

    • Region: Select the region in which you want your hub to be located. Select the location closest to you. Some features, such as IoT Hub device streams, are only available in specific regions. For these limited features, you must select one of the supported regions.

    • IoT Hub Name: Enter a name for your hub. This name must be globally unique.

    Important

    Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

    Create a hub in the Azure portal

  5. Select Next: Networking to continue creating your hub.

    Choose the endpoints that can connect to your IoT Hub. You can select the default setting Public endpoint (all networks), or choose Public endpoint (selected IP ranges), or Private endpoint. Accept the default setting for this example.

    Choose the endpoints that can connect

  6. Select Next: Management to continue creating your hub.

    Set the size and scale for a new hub using the Azure portal

    You can accept the default settings here. If desired, you can modify any of the following fields:

    • Pricing and scale tier: Your selected tier. You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. The free tier is intended for testing and evaluation. It allows 500 devices to be connected to the hub and up to 8,000 messages per day. Each Azure subscription can create one IoT hub in the free tier.

      If you are working through a Quickstart for IoT Hub device streams, select the free tier.

    • IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. For details about the other tier options, see Choosing the right IoT Hub tier.

    • Defender for IoT: Turn this on to add an extra layer of threat protection to IoT and your devices. This option is not available for hubs in the free tier. For more information about this feature, see Azure Security Center for IoT.

    • Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most hubs need only four partitions.

  7. Select Next: Tags to continue to the next screen.

    Tags are name/value pairs. You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. For more information, see Use tags to organize your Azure resources.

    Assign tags for the hub using the Azure portal

  8. Select Next: Review + create to review your choices. You see something similar to this screen, but with the values you selected when creating the hub.

    Review information for creating the new hub

  9. Select Create to create your new hub. Creating the hub takes a few minutes.

Register a device

A device must be registered with your IoT hub before it can connect. In this quickstart, you use the Azure Cloud Shell to register a simulated device.

  1. Run the following command in Azure Cloud Shell to create the device identity.

    YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

    MyJavaDevice: This is the name of the device you're registering. It's recommended to use MyJavaDevice as shown. If you choose a different name for your device, you'll also need to use that name throughout this article, and update the device name in the sample applications before you run them.

    az iot hub device-identity create --hub-name {YourIoTHubName} --device-id MyJavaDevice
    
  2. Run the following command in Azure Cloud Shell to get the device connection string for the device you just registered:

    YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

    az iot hub device-identity connection-string show --hub-name {YourIoTHubName} --device-id MyJavaDevice --output table
    

    Make a note of the device connection string, which looks like:

    HostName={YourIoTHubName}.azure-devices.net;DeviceId=MyJavaDevice;SharedAccessKey={YourSharedAccessKey}

    You'll use this value later in the quickstart.

  3. You also need the Event Hubs-compatible endpoint, Event Hubs-compatible path, and service primary key from your IoT hub to enable the back-end application to connect to your IoT hub and retrieve the messages. The following commands retrieve these values for your IoT hub:

    YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

    az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {YourIoTHubName}
    
    az iot hub show --query properties.eventHubEndpoints.events.path --name {YourIoTHubName}
    
    az iot hub policy show --name service --query primaryKey --hub-name {YourIoTHubName}
    

    Make a note of these three values, which you'll use later in the quickstart.

Send simulated telemetry

The simulated device application connects to a device-specific endpoint on your IoT hub and sends simulated temperature and humidity telemetry.

  1. In a local terminal window, navigate to the root folder of the sample Java project. Then navigate to the iot-hub\Quickstarts\simulated-device folder.

  2. Open the src/main/java/com/microsoft/docs/iothub/samples/SimulatedDevice.java file in a text editor of your choice.

    Replace the value of the connString variable with the device connection string you made a note of earlier. Then save your changes to SimulatedDevice.java.

    public class SimulatedDevice {
      // The device connection string to authenticate the device with your IoT hub.
      // Using the Azure CLI:
      // az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyJavaDevice --output table
    
      //private static String connString = "{Your device connection string here}";    
      private static String connString = "HostName={YourIoTHubName}.azure-devices.net;DeviceId=MyJavaDevice;SharedAccessKey={YourSharedAccessKey}";    
    
  3. In the local terminal window, run the following commands to install the required libraries and build the simulated device application:

    mvn clean package
    
  4. In the local terminal window, run the following commands to run the simulated device application:

    java -jar target/simulated-device-1.0.0-with-deps.jar
    

    The following screenshot shows the output as the simulated device application sends telemetry to your IoT hub:

    Output from telemetry sent by the device to your IoT hub

Read the telemetry from your hub

The back-end application connects to the service-side Events endpoint on your IoT Hub. The application receives the device-to-cloud messages sent from your simulated device. An IoT Hub back-end application typically runs in the cloud to receive and process device-to-cloud messages.

  1. In another local terminal window, navigate to the root folder of the sample Java project. Then navigate to the iot-hub\Quickstarts\read-d2c-messages folder.

  2. Open the src/main/java/com/microsoft/docs/iothub/samples/ReadDeviceToCloudMessages.java file in a text editor of your choice. Update the following variables and save your changes to the file.

    Variable Value
    EVENT_HUBS_COMPATIBLE_ENDPOINT Replace the value of the variable with the Event Hubs-compatible endpoint you made a note of earlier.
    EVENT_HUBS_COMPATIBLE_PATH Replace the value of the variable with the Event Hubs-compatible path you made a note of earlier.
    IOT_HUB_SAS_KEY Replace the value of the variable with the service primary key you made a note of earlier.
    public class ReadDeviceToCloudMessages {
    
      private static final String EH_COMPATIBLE_CONNECTION_STRING_FORMAT = "Endpoint=%s/;EntityPath=%s;"
          + "SharedAccessKeyName=%s;SharedAccessKey=%s";
    
      // az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {your IoT Hub name}
      private static final String EVENT_HUBS_COMPATIBLE_ENDPOINT = "{your Event Hubs compatible endpoint}";
    
      // az iot hub show --query properties.eventHubEndpoints.events.path --name {your IoT Hub name}
      private static final String EVENT_HUBS_COMPATIBLE_PATH = "{your Event Hubs compatible name}";
    
      // az iot hub policy show --name service --query primaryKey --hub-name {your IoT Hub name}
      private static final String IOT_HUB_SAS_KEY = "{your service primary key}";    
    
  3. In the local terminal window, run the following commands to install the required libraries and build the back-end application:

    mvn clean package
    
  4. In the local terminal window, run the following commands to run the back-end application:

    java -jar target/read-d2c-messages-1.0.0-with-deps.jar
    

    The following screenshot shows the output as the back-end application receives telemetry sent by the simulated device to the hub:

    Output as back-end application receives telemetry sent to your IoT hub

Clean up resources

If you will be continuing to the next recommended article, you can keep the resources you've already created and reuse them.

Otherwise, you can delete the Azure resources created in this article to avoid charges.

Important

Deleting a resource group is irreversible. The resource group and all the resources contained in it are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the IoT Hub inside an existing resource group that contains resources you want to keep, only delete the IoT Hub resource itself instead of deleting the resource group.

To delete a resource group by name:

  1. Sign in to the Azure portal and select Resource groups.

  2. In the Filter by name textbox, type the name of the resource group containing your IoT Hub.

  3. To the right of your resource group in the result list, select ... then Delete resource group.

    Delete

  4. You will be asked to confirm the deletion of the resource group. Type the name of your resource group again to confirm, and then select Delete. After a few moments, the resource group and all of its contained resources are deleted.

Next steps

In this quickstart, you set up an IoT hub, registered a device, sent simulated telemetry to the hub using a Java application, and read the telemetry from the hub using a simple back-end application.

To learn how to control your simulated device from a back-end application, continue to the next quickstart.