

# Connect client devices to core devices
<a name="connect-client-devices"></a>

You can configure *cloud discovery* to connect client devices to core devices. When you configure cloud discovery, client devices can connect to the AWS IoT Greengrass cloud service to retrieve information about core devices to which they can connect. Then, the client devices can attempt to connect to each core device until they successfully connect.

To use cloud discovery, you must do the following:
+ Associate client devices to the core devices to which they can connect.
+ Specify the MQTT broker endpoints where client devices can connect to each core device.
+ Deploy components to the core device that enable support for client devices.

  You can also deploy optional components to do the following:
  + Relay messages between client devices, Greengrass components, and the AWS IoT Core cloud service.
  + Automatically manage core device MQTT broker endpoints for you.
  + Manage local client device shadows and synchronize shadows with the AWS IoT Core cloud service.

You must also review and update the core device's AWS IoT policy to verify that it has the permissions required to connect client devices. For more information, see [Requirements](#connect-client-devices-requirements).

After you configure cloud discovery, you can test communications between a client device and a core device. For more information, see [Test client device communications](test-client-device-communications.md).

**Topics**
+ [

## Requirements
](#connect-client-devices-requirements)
+ [

## Greengrass components for client device support
](#cloud-discovery-components)
+ [

## Configure cloud discovery (console)
](#configure-cloud-discovery-console)
+ [

## Configure cloud discovery (AWS CLI)
](#configure-cloud-discovery-cli)
+ [

# Associate client devices
](associate-client-devices.md)
+ [

# Authenticating clients while offline
](offline-authentication.md)
+ [

# Manage core device endpoints
](manage-core-device-endpoints.md)
+ [

# Choose an MQTT broker
](choose-local-mqtt-broker.md)
+ [

# Connecting client devices to an AWS IoT Greengrass Core device with an MQTT broker
](connecting-to-mqtt.md)
+ [

# Test client device communications
](test-client-device-communications.md)
+ [

# Greengrass discovery RESTful API
](greengrass-discover-api.md)

## Requirements
<a name="connect-client-devices-requirements"></a>

To connect client devices to a core device, you must have the following:
+ The core device must run [Greengrass nucleus](greengrass-nucleus-component.md) v2.2.0 or later.
+ The Greengrass service role associated with AWS IoT Greengrass for your AWS account in the AWS Region where the core device operates. For more information, see [Configure the Greengrass service role](#configure-service-role-requirement).
+ The core device's AWS IoT policy must allow the following permissions:<a name="core-device-iot-policy-client-device-permissions"></a>
  + <a name="core-device-iot-policy-client-device-permissions-putcertificateauthorities"></a>`greengrass:PutCertificateAuthorities`
  + <a name="core-device-iot-policy-client-device-permissions-verifyclientdeviceidentity"></a>`greengrass:VerifyClientDeviceIdentity`
  + <a name="core-device-iot-policy-client-device-permissions-verifyclientdeviceiotcertificateassociation"></a>`greengrass:VerifyClientDeviceIoTCertificateAssociation`
  + <a name="core-device-iot-policy-client-device-permissions-getconnectivityinfo"></a>`greengrass:GetConnectivityInfo`
  + <a name="core-device-iot-policy-client-device-permissions-updateconnectivityinfo"></a>`greengrass:UpdateConnectivityInfo` – (Optional) This permission is required to use the [IP detector component](ip-detector-component.md), which reports the core device's network connectivity information to the AWS IoT Greengrass cloud service.
  + <a name="core-device-iot-policy-client-device-permissions-shadows"></a>`iot:GetThingShadow`, `iot:UpdateThingShadow`, and `iot:DeleteThingShadow` – (Optional) These permissions are required to use the [shadow manager component](shadow-manager-component.md) to sync client device shadows with AWS IoT Core. This feature requires [Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 or later, shadow manager v2.2.0 or later, and [MQTT bridge](mqtt-bridge-component.md) v2.2.0 or later.

  For more information, see [Configure the AWS IoT thing policy](#configure-iot-policy-requirement).
**Note**  
If you used the default AWS IoT policy when you [installed the AWS IoT Greengrass Core software](install-greengrass-core-v2.md), the core device has an AWS IoT policy that allows access to all AWS IoT Greengrass actions (`greengrass:*`).
+ AWS IoT things that you can connect as client devices. For more information, see [Create AWS IoT resources](https://docs.aws.amazon.com/iot/latest/developerguide/create-iot-resources.html) in the *AWS IoT Core Developer Guide*.
+ The client device must connect using a client ID. A client ID is a thing name. No other client ID will be accepted.
+ Each client device's AWS IoT policy must allow the `greengrass:Discover` permission. For more information, see [Minimal AWS IoT policy for client devices](device-auth.md#client-device-minimal-iot-policy).

**Topics**
+ [

### Configure the Greengrass service role
](#configure-service-role-requirement)
+ [

### Configure the AWS IoT thing policy
](#configure-iot-policy-requirement)

### Configure the Greengrass service role
<a name="configure-service-role-requirement"></a>

<a name="greengrass-service-role-intro"></a>The Greengrass service role is an AWS Identity and Access Management (IAM) service role that authorizes AWS IoT Greengrass to access resources from AWS services on your behalf. This role makes it possible for AWS IoT Greengrass to verify the identity of client devices and manage core device connectivity information.

If you haven't previously set up the [Greengrass service role](greengrass-service-role.md) in this Region, you must associate a Greengrass service role with AWS IoT Greengrass for your AWS account in this Region.

When you use the **Configure core device discovery** page in the [AWS IoT Greengrass console](https://console.aws.amazon.com/greengrass), AWS IoT Greengrass sets up the Greengrass service role for you. Otherwise, you can manually set it up using the [AWS IoT console](https://console.aws.amazon.com/iot) or AWS IoT Greengrass API.

In this section, you check whether the Greengrass service role is set up. If it isn't set up, you create a new Greengrass service role to associate with AWS IoT Greengrass for your AWS account in this Region.

#### Configure the Greengrass service role (console)
<a name="configure-service-role-requirement-console"></a>

1. Check if the Greengrass service role is associated with AWS IoT Greengrass for your AWS account in this Region. Do the following:

   1. <a name="open-iot-console"></a>Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot).

   1. In the navigation pane, choose **Settings**.

   1. In the **Greengrass service role** section, find **Current service role** to see whether a Greengrass service role is associated.

      If you have a Greengrass service role associated, you meet this requirement to use the IP detector component. Skip to [Configure the AWS IoT thing policy](#configure-iot-policy-requirement).

1. If the Greengrass service role isn't associated with AWS IoT Greengrass for your AWS account in this Region, create a Greengrass service role and associate it. Do the following:

   1. Navigate to the [IAM console](https://console.aws.amazon.com/iam).

   1. Choose **Roles**.

   1. Choose **Create role**.

   1. On the **Create role** page, do the following:

      1. Under **Trusted entity type**, choose **AWS service**.

      1. Under **Use case**, **Use cases for other AWS services**, choose **Greengrass**, select **Greengrass**. This option specifies to add AWS IoT Greengrass as a trusted entity that can assume this role.

      1. Choose **Next**.

      1. Under **Permissions policies**, select the **AWSGreengrassResourceAccessRolePolicy** to attach to the role.

      1. Choose **Next**.

      1. In **Role name**, enter a name for the role, such as **Greengrass\$1ServiceRole**.

      1. Choose **Create role**.

   1. <a name="open-iot-console"></a>Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot).

   1. In the navigation pane, choose **Settings**.

   1. In the **Greengrass service role** section, choose **Attach role**.

   1. In the **Update Greengrass service role** modal, select the IAM role that you created, and then choose **Attach role**.

#### Configure the Greengrass service role (AWS CLI)
<a name="configure-service-role-requirement-cli"></a>

1. Check if the Greengrass service role is associated with AWS IoT Greengrass for your AWS account in this Region.

   ```
   aws greengrassv2 get-service-role-for-account
   ```

   If the Greengrass service role is associated, the operation returns a response that contains information about the role.

   If you have a Greengrass service role associated, you meet this requirement to use the IP detector component. Skip to [Configure the AWS IoT thing policy](#configure-iot-policy-requirement).

1. If the Greengrass service role isn't associated with AWS IoT Greengrass for your AWS account in this Region, create a Greengrass service role and associate it. Do the following:

   1. <a name="create-greengrass-service-role-step-create-role"></a>Create a role with a trust policy that allows AWS IoT Greengrass to assume the role. This example creates a role named `Greengrass_ServiceRole`, but you can use a different name. We recommend that you also include the `aws:SourceArn` and `aws:SourceAccount` global condition context keys in your trust policy to help prevent the *confused deputy* security problem. The condition context keys restrict access to allow only those requests that come from the specified account and Greengrass workspace. For more information about the confused deputy problem, see [Cross-service confused deputy prevention](cross-service-confused-deputy-prevention.md).

------
#### [ Linux or Unix ]

      ```
      aws iam create-role --role-name Greengrass_ServiceRole --assume-role-policy-document '{
        "Version": "2012-10-17",		 	 	 
        "Statement": [
          {
            "Effect": "Allow",
            "Principal": {
              "Service": "greengrass.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
              "ArnLike": {
                "aws:SourceArn": "arn:aws:greengrass:region:account-id:*"
              },
              "StringEquals": {
                "aws:SourceAccount": "account-id"
              }
            }
          }
        ]
      }'
      ```

------
#### [ Windows Command Prompt (CMD) ]

      ```
      aws iam create-role --role-name Greengrass_ServiceRole --assume-role-policy-document "{\\"Version\\":\\"2012-10-17		 	 	 \\",\\"Statement\\":[{\\"Effect\\":\\"Allow\\",\\"Principal\\":{\\"Service\\":\\"greengrass.amazonaws.com\\"},\\"Action\\":\\"sts:AssumeRole\\",\\"Condition\\":{\\"ArnLike\\":{\\"aws:SourceArn\\":\\"arn:aws:greengrass:region:account-id:*\\"},\\"StringEquals\\":{\\"aws:SourceAccount\\":\\"account-id\\"}}}]}"
      ```

------
#### [ PowerShell ]

      ```
      aws iam create-role --role-name Greengrass_ServiceRole --assume-role-policy-document '{
        "Version": "2012-10-17",		 	 	 
        "Statement": [
          {
            "Effect": "Allow",
            "Principal": {
              "Service": "greengrass.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
              "ArnLike": {
                "aws:SourceArn": "arn:aws:greengrass:region:account-id:*"
              },
              "StringEquals": {
                "aws:SourceAccount": "account-id"
              }
            }
          }
        ]
      }'
      ```

------

   1. <a name="create-greengrass-service-role-step-copy-role-arn"></a>Copy the role ARN from the role metadata in the output. You use the ARN to associate the role with your account.

   1. <a name="create-greengrass-service-role-step-attach-policy"></a>Attach the `AWSGreengrassResourceAccessRolePolicy` policy to the role.

      ```
      aws iam attach-role-policy --role-name Greengrass_ServiceRole --policy-arn arn:aws:iam::aws:policy/service-role/AWSGreengrassResourceAccessRolePolicy
      ```

   1. Associate the Greengrass service role with AWS IoT Greengrass for your AWS account. Replace *role-arn* with the ARN of the service role.

      ```
      aws greengrassv2 associate-service-role-to-account --role-arn role-arn
      ```

      The operation returns the following response if it succeeds.

      ```
      {
        "associatedAt": "timestamp"
      }
      ```

### Configure the AWS IoT thing policy
<a name="configure-iot-policy-requirement"></a>

Core devices use X.509 device certificates to authorize connections to AWS. You attach AWS IoT policies to device certificates to define the permissions for a core device. For more information, see [AWS IoT policies for data plane operations](device-auth.md#iot-policies) and [Minimal AWS IoT policy to support client devices](device-auth.md#client-device-support-minimal-iot-policy).

To connect client devices to a core device, the core device's AWS IoT policy must allow the following permissions:<a name="core-device-iot-policy-client-device-permissions"></a>
+ <a name="core-device-iot-policy-client-device-permissions-putcertificateauthorities"></a>`greengrass:PutCertificateAuthorities`
+ <a name="core-device-iot-policy-client-device-permissions-verifyclientdeviceidentity"></a>`greengrass:VerifyClientDeviceIdentity`
+ <a name="core-device-iot-policy-client-device-permissions-verifyclientdeviceiotcertificateassociation"></a>`greengrass:VerifyClientDeviceIoTCertificateAssociation`
+ <a name="core-device-iot-policy-client-device-permissions-getconnectivityinfo"></a>`greengrass:GetConnectivityInfo`
+ <a name="core-device-iot-policy-client-device-permissions-updateconnectivityinfo"></a>`greengrass:UpdateConnectivityInfo` – (Optional) This permission is required to use the [IP detector component](ip-detector-component.md), which reports the core device's network connectivity information to the AWS IoT Greengrass cloud service.
+ <a name="core-device-iot-policy-client-device-permissions-shadows"></a>`iot:GetThingShadow`, `iot:UpdateThingShadow`, and `iot:DeleteThingShadow` – (Optional) These permissions are required to use the [shadow manager component](shadow-manager-component.md) to sync client device shadows with AWS IoT Core. This feature requires [Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 or later, shadow manager v2.2.0 or later, and [MQTT bridge](mqtt-bridge-component.md) v2.2.0 or later.

In this section, you review the AWS IoT policies for your core device and add any required permissions that are missing. If you used the [AWS IoT Greengrass Core software installer to provision resources](quick-installation.md), your core device has an AWS IoT policy that allows access to all AWS IoT Greengrass actions (`greengrass:*`). In this case, you must update the AWS IoT policy only if you plan to deploy the shadow manager component to sync device shadows with AWS IoT Core. Otherwise, you can skip this section.

#### Configure the AWS IoT thing policy (console)
<a name="configure-iot-policy-requirement-console"></a>

1. <a name="update-iot-policy-console-open-greengrass-console"></a>In the [AWS IoT Greengrass console](https://console.aws.amazon.com/greengrass) navigation menu, choose **Core devices**.

1. <a name="update-iot-policy-console-choose-core-device"></a>On the **Core devices** page, choose the core device to update.

1. <a name="update-iot-policy-console-choose-core-device-thing"></a>On the core device details page, choose the link to the core device's **Thing**. This link opens the thing details page in the AWS IoT console.

1. <a name="update-iot-policy-console-choose-thing-security"></a>On the thing details page, choose **Certificates**.

1. <a name="update-iot-policy-console-choose-thing-certificate"></a>In the **Certificates** tab, choose the thing's active certificate.

1. <a name="update-iot-policy-console-choose-certificate-policies"></a>On the certificate details page, choose **Policies**.

1. <a name="update-iot-policy-console-choose-policy"></a>In the **Policies** tab, choose the AWS IoT policy to review and update. You can add the required permissions to any policy that is attached to the core device's active certificate.
**Note**  <a name="quick-installation-iot-policies-note"></a>
If you used the [AWS IoT Greengrass Core software installer to provision resources](quick-installation.md), you have two AWS IoT policies. We recommend that you choose the policy named **GreengrassV2IoTThingPolicy**, if it exists. Core devices that you create with the quick installer use this policy name by default. If you add permissions to this policy, you are also granting these permissions to other core devices that use this policy.

1. <a name="update-iot-policy-console-edit-policy"></a>In the policy overview, choose **Edit active version**.

1. Review the policy for the required permissions, and add any required permissions that are missing.<a name="core-device-iot-policy-client-device-permissions"></a>
   + <a name="core-device-iot-policy-client-device-permissions-putcertificateauthorities"></a>`greengrass:PutCertificateAuthorities`
   + <a name="core-device-iot-policy-client-device-permissions-verifyclientdeviceidentity"></a>`greengrass:VerifyClientDeviceIdentity`
   + <a name="core-device-iot-policy-client-device-permissions-verifyclientdeviceiotcertificateassociation"></a>`greengrass:VerifyClientDeviceIoTCertificateAssociation`
   + <a name="core-device-iot-policy-client-device-permissions-getconnectivityinfo"></a>`greengrass:GetConnectivityInfo`
   + <a name="core-device-iot-policy-client-device-permissions-updateconnectivityinfo"></a>`greengrass:UpdateConnectivityInfo` – (Optional) This permission is required to use the [IP detector component](ip-detector-component.md), which reports the core device's network connectivity information to the AWS IoT Greengrass cloud service.
   + <a name="core-device-iot-policy-client-device-permissions-shadows"></a>`iot:GetThingShadow`, `iot:UpdateThingShadow`, and `iot:DeleteThingShadow` – (Optional) These permissions are required to use the [shadow manager component](shadow-manager-component.md) to sync client device shadows with AWS IoT Core. This feature requires [Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 or later, shadow manager v2.2.0 or later, and [MQTT bridge](mqtt-bridge-component.md) v2.2.0 or later.

1. (Optional) To allow the core device to sync shadows with AWS IoT Core, add the following statement to the policy. If you plan to interact with client device shadows, but not sync them with AWS IoT Core, skip this step. Replace *region* and *account-id* with the Region that you use and your AWS account number.
   + This example statement allows access to all things' device shadows. To follow best security practices, you can restrict access to only the core device and the client devices that you connect to the core device. For more information, see [Minimal AWS IoT policy to support client devices](device-auth.md#client-device-support-minimal-iot-policy).

   ```
   {
     "Effect": "Allow",
     "Action": [
       "iot:GetThingShadow",
       "iot:UpdateThingShadow",
       "iot:DeleteThingShadow"
     ],
     "Resource": [
       "arn:aws:iot:region:account-id:thing/*"
     ]
   }
   ```

   After you add this statement, the policy document might look similar to the following example.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Action": [
           "iot:Connect",
           "iot:Publish",
           "iot:Subscribe",
           "iot:Receive",
           "greengrass:*"
         ],
         "Resource": "*"
       },
       {
         "Effect": "Allow",
         "Action": [
           "iot:GetThingShadow",
           "iot:UpdateThingShadow",
           "iot:DeleteThingShadow"
         ],
         "Resource": [
           "arn:aws:iot:us-east-1:123456789012:thing/*"
         ]
       }
     ]
   }
   ```

------

1. <a name="update-iot-policy-console-set-as-active-version"></a>To set a new policy version as the active version, under **Policy version status**, select **Set the edited version as the active version for this policy**.

1. <a name="update-iot-policy-console-save-policy"></a>Choose **Save as new version**.

#### Configure the AWS IoT thing policy (AWS CLI)
<a name="configure-iot-policy-requirement-cli"></a>

1. <a name="update-iot-policy-cli-list-thing-principals"></a>List the principals for the core device's AWS IoT thing. Thing principals can be X.509 device certificates or other identifies. Run the following command, and replace *MyGreengrassCore* with the name of the core device.

   ```
   aws iot list-thing-principals --thing-name MyGreengrassCore
   ```

   The operation returns a response that lists the core device's thing principals.

   ```
   {
       "principals": [
           "arn:aws:iot:us-west-2:123456789012:cert/certificateId"
       ]
   }
   ```

1. <a name="update-iot-policy-cli-identify-active-certificate"></a>Identify the core device's active certificate. Run the following command, and replace *certificateId* with the ID of each certificate from the previous step until you find the active certificate. The certificate ID is the hexadecimal string at the end of the certificate ARN. The `--query` argument specifies to output only the certificate's status.

   ```
   aws iot describe-certificate --certificate-id certificateId --query 'certificateDescription.status'
   ```

   The operation returns the certificate status as a string. For example, if the certificate is active, this operation outputs `"ACTIVE"`.

1. <a name="update-iot-policy-cli-list-certificate-policies"></a>List the AWS IoT policies that are attached to the certificate. Run the following command, and replace the certificate ARN with the ARN of the certificate.

   ```
   aws iot list-principal-policies --principal arn:aws:iot:us-west-2:123456789012:cert/certificateId
   ```

   The operation returns a response that lists the AWS IoT policies that are attached to the certificate.

   ```
   {
       "policies": [
           {
               "policyName": "GreengrassTESCertificatePolicyMyGreengrassCoreTokenExchangeRoleAlias",
               "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/GreengrassTESCertificatePolicyMyGreengrassCoreTokenExchangeRoleAlias"
           },
           {
               "policyName": "GreengrassV2IoTThingPolicy",
               "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/GreengrassV2IoTThingPolicy"
           }
       ]
   }
   ```

1. <a name="update-iot-policy-cli-choose-policy"></a>Choose the policy to view and update.
**Note**  <a name="quick-installation-iot-policies-note"></a>
If you used the [AWS IoT Greengrass Core software installer to provision resources](quick-installation.md), you have two AWS IoT policies. We recommend that you choose the policy named **GreengrassV2IoTThingPolicy**, if it exists. Core devices that you create with the quick installer use this policy name by default. If you add permissions to this policy, you are also granting these permissions to other core devices that use this policy.

1. <a name="update-iot-policy-cli-get-policy-document"></a>Get the policy's document. Run the following command, and replace *GreengrassV2IoTThingPolicy* with the name of the policy.

   ```
   aws iot get-policy --policy-name GreengrassV2IoTThingPolicy
   ```

   The operation returns a response that contains the policy's document and other information about the policy. The policy document is a JSON object serialized as a string. 

   ```
   {
       "policyName": "GreengrassV2IoTThingPolicy",
       "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/GreengrassV2IoTThingPolicy",
       "policyDocument": "{\
     \\"Version\\": \\"2012-10-17		 	 	 \\",\
     \\"Statement\\": [\
       {\
         \\"Effect\\": \\"Allow\\",\
         \\"Action\\": [\
                   \\"iot:Connect\\",\
                   \\"iot:Publish\\",\
                   \\"iot:Subscribe\\",\
                   \\"iot:Receive\\",\
                   \\"greengrass:*\\"\
   ],\
         \\"Resource\\": \\"*\\"\
       }\
     ]\
   }",
       "defaultVersionId": "1",
       "creationDate": "2021-02-05T16:03:14.098000-08:00",
       "lastModifiedDate": "2021-02-05T16:03:14.098000-08:00",
       "generationId": "f19144b798534f52c619d44f771a354f1b957dfa2b850625d9f1d0fde530e75f"
   }
   ```

1. <a name="update-iot-policy-cli-create-policy-document-file"></a>Use an online converter or other tool to convert the policy document string to a JSON object, and then save it to a file named `iot-policy.json`.

   For example, if you have the [jq](https://stedolan.github.io/jq/) tool installed, you can run the following command to get the policy document, convert it to a JSON object, and save the policy document as a JSON object.

   ```
   aws iot get-policy --policy-name GreengrassV2IoTThingPolicy --query 'policyDocument' | jq fromjson >> iot-policy.json
   ```

1. Review the policy for the required permissions, and add any required permissions that are missing.

   <a name="nano-command-intro-existing-file"></a>For example, on a Linux-based system, you can run the following command to use GNU nano to open the file.

   ```
   nano iot-policy.json
   ```<a name="core-device-iot-policy-client-device-permissions"></a>
   + <a name="core-device-iot-policy-client-device-permissions-putcertificateauthorities"></a>`greengrass:PutCertificateAuthorities`
   + <a name="core-device-iot-policy-client-device-permissions-verifyclientdeviceidentity"></a>`greengrass:VerifyClientDeviceIdentity`
   + <a name="core-device-iot-policy-client-device-permissions-verifyclientdeviceiotcertificateassociation"></a>`greengrass:VerifyClientDeviceIoTCertificateAssociation`
   + <a name="core-device-iot-policy-client-device-permissions-getconnectivityinfo"></a>`greengrass:GetConnectivityInfo`
   + <a name="core-device-iot-policy-client-device-permissions-updateconnectivityinfo"></a>`greengrass:UpdateConnectivityInfo` – (Optional) This permission is required to use the [IP detector component](ip-detector-component.md), which reports the core device's network connectivity information to the AWS IoT Greengrass cloud service.
   + <a name="core-device-iot-policy-client-device-permissions-shadows"></a>`iot:GetThingShadow`, `iot:UpdateThingShadow`, and `iot:DeleteThingShadow` – (Optional) These permissions are required to use the [shadow manager component](shadow-manager-component.md) to sync client device shadows with AWS IoT Core. This feature requires [Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 or later, shadow manager v2.2.0 or later, and [MQTT bridge](mqtt-bridge-component.md) v2.2.0 or later.

1. <a name="update-iot-policy-cli-create-policy-version"></a>Save the changes as a new version of the policy. Run the following command, and replace *GreengrassV2IoTThingPolicy* with the name of the policy.

   ```
   aws iot create-policy-version --policy-name GreengrassV2IoTThingPolicy --policy-document file://iot-policy.json --set-as-default
   ```

   The operation returns a response similar to the following example if it succeeds.

   ```
   {
       "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/GreengrassV2IoTThingPolicy",
       "policyDocument": "{\
     \\"Version\\": \\"2012-10-17		 	 	 \\",\
     \\"Statement\\": [\
       {\
         \\"Effect\\": \\"Allow\\",\
         \\"Action\\": [\
   \\t\\t\\"iot:Connect\\",\
   \\t\\t\\"iot:Publish\\",\
   \\t\\t\\"iot:Subscribe\\",\
   \\t\\t\\"iot:Receive\\",\
   \\t\\t\\"greengrass:*\\"\
         ],\
         \\"Resource\\": \\"*\\"\
       }\
     ]\
   }",
       "policyVersionId": "2",
       "isDefaultVersion": true
   }
   ```

## Greengrass components for client device support
<a name="cloud-discovery-components"></a>

**Important**  <a name="client-device-support-nucleus-requirement"></a>
The core device must run [Greengrass nucleus](greengrass-nucleus-component.md) v2.2.0 or later to support client devices.

To enable client devices to connect and communicate with a core device, you deploy the following Greengrass components to the core device:
+ <a name="client-device-component-overview-client-device-auth"></a>[Client device auth](client-device-auth-component.md) (`aws.greengrass.clientdevices.Auth`)

  Deploy the client device auth component to authenticate client devices and authorize client device actions. This component allows your AWS IoT things to connect to a core device.

  This component requires some configuration to use it. You must specify groups of client devices and the operations that each group is authorized to perform, such as to connect and communicate over MQTT. For more information, see [client device auth component configuration](client-device-auth-component.md#client-device-auth-component-configuration).
+ <a name="client-device-component-overview-mqtt-broker-moquette"></a>[MQTT 3.1.1 broker (Moquette)](mqtt-broker-moquette-component.md) (`aws.greengrass.clientdevices.mqtt.Moquette`)

  Deploy the Moquette MQTT broker component to run a lightweight MQTT broker. The Moquette MQTT broker is compliant with MQTT 3.1.1 and includes local support for QoS 0, QoS 1, QoS 2, retained messages, last will messages, and persistent subscriptions.

  You aren't required to configure this component to use it. However, you can configure the port where this component operates the MQTT broker. By default, it uses port 8883.
+ <a name="client-device-component-overview-mqtt-broker-emqx"></a>[MQTT 5 broker (EMQX)](mqtt-broker-emqx-component.md) (`aws.greengrass.clientdevices.mqtt.EMQX`)
**Note**  
To use the EMQX MQTT 5 broker, you must use [Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 or later and client device auth v2.2.0 or later.

  Deploy the EMQX MQTT broker component to use MQTT 5.0 features in communication between client devices and the core device. The EMQX MQTT broker is compliant with MQTT 5.0 and includes support for session and message expiration intervals, user properties, shared subscriptions, topic aliases, and more.

  You aren't required to configure this component to use it. However, you can configure the port where this component operates the MQTT broker. By default, it uses port 8883.
+ <a name="client-device-component-overview-mqtt-bridge"></a>[MQTT bridge](mqtt-bridge-component.md) (`aws.greengrass.clientdevices.mqtt.Bridge`)

  (Optional) Deploy the MQTT bridge component to relay messages between client devices (local MQTT), local publish/subscribe, and AWS IoT Core MQTT. Configure this component to sync client devices with AWS IoT Core and interact with client devices from Greengrass components.

  This component requires configuration to use. You must specify the topic mappings where this component relays messages. For more information, see [MQTT bridge component configuration](mqtt-bridge-component.md#mqtt-bridge-component-configuration).
+ <a name="client-device-component-overview-ip-detector"></a>[IP detector](ip-detector-component.md) (`aws.greengrass.clientdevices.IPDetector`)

  (Optional) Deploy the IP detector component to automatically report the core device's MQTT broker endpoints to the AWS IoT Greengrass cloud service. You cannot use this component if you have a complex network setup, such as one where a router forwards the MQTT broker port to the core device.

  You aren't required to configure this component to use it.
+ <a name="client-device-component-overview-shadow-manager"></a>[Shadow manager](shadow-manager-component.md) (`aws.greengrass.ShadowManager`)
**Note**  
To manage client device shadows, you must use [Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 or later, shadow manager v2.2.0 or later, and [MQTT bridge](mqtt-bridge-component.md) v2.2.0 or later.

  (Optional) Deploy the shadow manager component to manage client device shadows on the core device. Greengrass components can get, update, and delete client device shadows to interact with client devices. You can also configure the shadow manager component to synchronize client device shadows with the AWS IoT Core cloud service.

  To use this component with client device shadows, you must configure the MQTT bridge component to relay messages between client devices and shadow manager, which uses local publish/subscribe. Otherwise, this component doesn't require configuration to use, but it does require configuration to sync device shadows.

**Note**  <a name="note-deploy-one-mqtt-broker"></a>
We recommend that you deploy only one MQTT broker component. The [MQTT bridge](mqtt-bridge-component.md) and [IP detector](ip-detector-component.md) components work with only one MQTT broker component at a time. If you deploy multiple MQTT broker components, you must configure them to use different ports.

## Configure cloud discovery (console)
<a name="configure-cloud-discovery-console"></a>

You can use the AWS IoT Greengrass console to associate client devices, manage core device endpoints, and deploy components to enable client device support. For more information, see [Step 2: Enable client device support](client-devices-tutorial.md#enable-client-device-support).

## Configure cloud discovery (AWS CLI)
<a name="configure-cloud-discovery-cli"></a>

You can use the AWS Command Line Interface (AWS CLI) to associate client devices, manage core device endpoints, and deploy components to enable client device support. For more information, see the following:
+ [Manage client device associations (AWS CLI)](associate-client-devices.md#manage-client-device-associations-cli)
+ [Manage core device endpoints](manage-core-device-endpoints.md)
+ [AWS-provided client device components](client-device-components.md)
+ [Create deployments](create-deployments.md)

# Associate client devices
<a name="associate-client-devices"></a>

To use cloud discovery, associate client devices with a core device so that they can discover the core device. Then, they can use the [Greengrass discovery API](greengrass-discover-api.md) to retrieve connectivity information and certificates for their associated core devices.

Likewise, disassociate client devices from a core device to stop them from discovering the core device.

**Topics**
+ [

## Manage client device associations (console)
](#manage-client-device-associations-console)
+ [

## Manage client device associations (AWS CLI)
](#manage-client-device-associations-cli)
+ [

## Manage client device associations (API)
](#manage-client-device-associations-api)

## Manage client device associations (console)
<a name="manage-client-device-associations-console"></a>

You can use the AWS IoT Greengrass console to view, add, and delete client device associations.

**To view client device associations for a core device (console)**

1. <a name="navigate-greengrass-console"></a>Navigate to the [AWS IoT Greengrass console](https://console.aws.amazon.com/greengrass).

1. Choose **Core devices**.

1. Choose the core device to manage.

1. On the core device's details page, choose the **Client devices** tab.

1. In the **Associated client devices** section, you can see which client devices (AWS IoT things) are associated with the core device.

**To associate client devices with a core device (console)**

1. <a name="navigate-greengrass-console"></a>Navigate to the [AWS IoT Greengrass console](https://console.aws.amazon.com/greengrass).

1. Choose **Core devices**.

1. Choose the core device to manage.

1. On the core device's details page, choose the **Client devices** tab.

1. In the **Associated client devices** section, choose **Associate client devices**.

1. In the **Associate client devices with core device** modal, do the following for each client device to associate:

   1. Enter the name of the AWS IoT thing to associate as a client device.

   1. Choose **Add**.

1. Choose **Associate**.

   The client devices that you associated can now use the Greengrass discovery API to discover this core device.

**To disassociate client devices from a core device (console)**

1. <a name="navigate-greengrass-console"></a>Navigate to the [AWS IoT Greengrass console](https://console.aws.amazon.com/greengrass).

1. Choose **Core devices**.

1. Choose the core device to manage.

1. On the core device's details page, choose the **Client devices** tab.

1. In the **Associated client devices** section, select each client device to disassociate.

1. Choose **Disassociate**.

1. In the confirmation modal, choose **Disassociate**.

   The client devices that you disassociated can no longer use the Greengrass discovery API to discover this core device.

## Manage client device associations (AWS CLI)
<a name="manage-client-device-associations-cli"></a>

You can use the AWS Command Line Interface (AWS CLI) to manage client device associations for a core device.

**To view client device associations for a core device (AWS CLI)**
+ Use the following command: [list-client-devices-associated-with-core-device](https://docs.aws.amazon.com/cli/latest/reference/greengrassv2/list-client-devices-associated-with-core-device.html).

**To associate client devices with a core device (AWS CLI)**
+ Use the following command: [batch-associate-client-device-with-core-device](https://docs.aws.amazon.com/cli/latest/reference/greengrassv2/batch-associate-client-device-with-core-device.html).

**To disassociate client devices from a core device (AWS CLI)**
+ Use the following command: [batch-disassociate-client-device-from-core-device](https://docs.aws.amazon.com/cli/latest/reference/greengrassv2/batch-disassociate-client-device-from-core-device.html).

## Manage client device associations (API)
<a name="manage-client-device-associations-api"></a>

You can use the AWS API to manage client device associations for a core device.

**To view client device associations for a core device (AWS API)**
+ Use the following operation: [ListClientDevicesAssociatedWithCoreDevice](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_ListClientDevicesAssociatedWithCoreDevice.html).

**To associate client devices with a core device (AWS API)**
+ Use the following operation: [BatchAssociateClientDeviceWithCoreDevice](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_BatchAssociateClientDeviceWithCoreDevice.html).

**To disassociate client devices from a core device (AWS API)**
+ Use the following operation: [BatchDisassociateClientDeviceFromCoreDevice](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_BatchDisassociateClientDeviceFromCoreDevice.html).

# Authenticating clients while offline
<a name="offline-authentication"></a>

With *offline authentication* you can configure your AWS IoT Greengrass Core device so that client devices can connect to a core device, even when the core device isn't connected to the cloud. When you use offline authentication, your Greengrass devices can continue to work in a partially offline environment.

To use offline authentication for a client device with a connection to the cloud, you need the following:
+ An AWS IoT Greengrass Core device with the [Client device auth](client-device-auth-component.md) component deployed. You must use version 2.3.0 or greater for offline authentication.
+ A cloud connection for the core device during the initial connection of client devices.

## Storing client credentials
<a name="offline-auth-store-credentials"></a>

When a client device connects to a core device for the first time, the core device calls the AWS IoT Greengrass service. When called, Greengrass validates the client device's registration as an AWS IoT thing. It also validates that the device has a valid certificate. The core device then stores this information locally.

The next time that the device connects, the Greengrass core device attempts to validate the client device with the AWS IoT Greengrass service. If it can't connect to AWS IoT Greengrass, the core device uses its locally stored device information to validate the client device.

You can configure the length of time that the Greengrass core device stores credentials. You can set the timeout from one minute to 2,147,483,647 minutes by setting the `clientDeviceTrustDurationMinutes` configuration option in the [client device auth component configuration](https://docs.aws.amazon.com//greengrass/v2/developerguide/client-device-auth-component.html#client-device-auth-component-configuration). The default is one minute, which effectively turns off offline authentication. When you set this timeout, we recommend that you consider your security needs. You should also consider how long you expect core devices to run while disconnected from the cloud.

The core device updates its credential storage at three times:

1. When a device connects to the core device for the first time.

1. If the core device is connected to the cloud, when a client device reconnects to the core device.

1. If the core device is connected to the cloud, once a day to refresh the entire credential store.

When the Greengrass core device refreshes its credential store, it uses the [ ListClientDevicesAssociatedWithCoreDevice](https://docs.aws.amazon.com//greengrass/v2/APIReference/API_ListClientDevicesAssociatedWithCoreDevice.html) operation. Greengrass only refreshes the devices returned by this operation. To associate a client device with a core device, see [Associate client devices](associate-client-devices.md).

To use the `ListClientDevicesAssociatedWithCoreDevice` operation, you must add permission for the operation to the AWS Identity and Access Management (IAM) role associated with the AWS account that runs AWS IoT Greengrass. For more information, see [Authorize core devices to interact with AWS services](device-service-role.md).

# Manage core device endpoints
<a name="manage-core-device-endpoints"></a>

When you use cloud discovery, you store MQTT broker endpoints for core devices in the AWS IoT Greengrass cloud service. Client devices connect to AWS IoT Greengrass to retrieve these endpoints and other information for their associated core devices.

For each core device, you can automatically or manually manage endpoints.
+ **Automatically manage endpoints with IP detector**

  You can deploy the [IP detector component](ip-detector-component.md) to automatically manage core device endpoints for you if you have a non-complex network setup, such as where the client devices are on the same network as the core device. You can't use the IP detector component if the core device is behind a router that forwards the MQTT broker port to the core device, for example.

  The IP detector component is also useful if you deploy to thing groups, because it manages the endpoints for all core devices in the thing group. For more information, see [Use IP detector to automatically manage endpoints](#use-ip-detector).
+ **Manually manage endpoints**

  If you can't use the IP detector component, you must manually manage core device endpoints. You can update these endpoints with the console or the API. For more information, see [Manually manage endpoints](#manually-manage-endpoints).

**Topics**
+ [

## Use IP detector to automatically manage endpoints
](#use-ip-detector)
+ [

## Manually manage endpoints
](#manually-manage-endpoints)

## Use IP detector to automatically manage endpoints
<a name="use-ip-detector"></a>

If you have a simple network setup, such as the client devices on the same network as the core device, you can deploy the [IP detector component](ip-detector-component.md) to do the following:
+ Monitor the Greengrass core device's local network connectivity information. This information includes the core device's network endpoints and the port where the MQTT broker operates.
+ Report the core device's connectivity information to the AWS IoT Greengrass cloud service.

The IP detector component overwrites endpoints that you set manually.

**Important**  
The core device's AWS IoT policy must allow the `greengrass:UpdateConnectivityInfo` permission to use the IP detector component. For more information, see [AWS IoT policies for data plane operations](device-auth.md#iot-policies) and [Configure the AWS IoT thing policy](connect-client-devices.md#configure-iot-policy-requirement).

You can do either of the following to deploy the IP detector component:
+ Use the **Configure discovery** page in the console. For more information, see [Configure cloud discovery (console)](connect-client-devices.md#configure-cloud-discovery-console).
+ Create and revise deployments to include the IP detector. You can use the console, AWS CLI, or AWS API to manage deployments. For more information, see [Create deployments](create-deployments.md).

### Deploy the IP detector component (console)
<a name="deploy-ip-detector-console"></a>

1. In the [AWS IoT Greengrass console](https://console.aws.amazon.com/greengrass) navigation menu, choose **Components**.

1. On the **Components** page, choose the **Public components** tab, and then choose **aws.greengrass.clientdevices.IPDetector**.

1. On the **aws.greengrass.clientdevices.IPDetector** page, choose **Deploy**.

1. <a name="deploy-component-choose-deployment-step"></a>From **Add to deployment**, choose an existing deployment to revise, or choose to create a new deployment, and then choose **Next**.

1. <a name="deploy-component-choose-target-step"></a>If you chose to create a new deployment, choose the target core device or thing group for the deployment. On the **Specify target** page, under **Deployment target**, choose a core device or thing group, and then choose **Next**.

1. On the **Select components** page, verify that the **aws.greengrass.clientdevices.IPDetector** component is selected, choose **Next**.

1. On the **Configure components** page, select **aws.greengrass.clientdevices.IPDetector**, and then do the following:

   1. Choose **Configure component**.

   1. In the **Configure aws.greengrass.clientdevices.IPDetector** modal, under **Configuration update**, in **Configuration to merge**, you can enter a configuration update to configure the IP detector component. You can specify any of the following configuration options:
      + `defaultPort` – <a name="ip-detector-component-configuration-default-port-definition"></a>(Optional) The MQTT broker port to report when this component detects IP addresses. You must specify this parameter if you configure the MQTT broker to use a different port than the default port 8883. 
      + `includeIPv4LoopbackAddrs` – <a name="ip-detector-component-configuration-include-ipv4-loopback-addrs-definition"></a>(Optional) You can enable this option to detect and report IPv4 loopback addresses. These are IP addresses, such as `localhost`, where a device can communicate with itself. Use this option in test environments where the core device and client device run on the same system. 
      + `includeIPv4LinkLocalAddrs` – <a name="ip-detector-component-configuration-include-ipv4-link-local-addrs-definition"></a>(Optional) You can enable this option to detect and report IPv4 [link-local addresses](https://en.wikipedia.org/wiki/Link-local_address). Use this option if the core device's network doesn't have Dynamic Host Configuration Protocol (DHCP) or statically assigned IP addresses. 
      + `includeIPv6LoopbackAddrs` – <a name="ip-detector-component-configuration-include-ipv6-loopback-addrs-definition"></a>(Optional) You can enable this option to detect and report IPv6 loopback addresses. These are IP addresses, such as `localhost`, where a device can communicate with itself. Use this option in test environments where the core device and client device run on the same system. You must set `includeIPv4Addrs` to `false` and `includeIPv6Addrs` to `true` to use this option. You must have IP detector v2.2.0 or later to use this option.
      + `includeIPv6LinkLocalAddrs` – <a name="ip-detector-component-configuration-include-ipv6-link-local-addrs-definition"></a>(Optional) You can enable this option to detect and report IPv6 [link-local addresses](https://en.wikipedia.org/wiki/Link-local_address). Use this option if the core device's network doesn't have Dynamic Host Configuration Protocol (DHCP) or statically assigned IP addresses. You must set `includeIPv4Addrs` to `false` and `includeIPv6Addrs` to `true` to use this option. You must have IP detector v2.2.0 or later to use this option.
      + `includeIPv4Addrs` – <a name="ip-detector-component-configuration-include-ipv4-addrs-definition"></a>(Optional) The default is set to true. You can enable this option to publish IPv4 addresses found on the core device. You must have IP detector v2.2.0 or later to use this option.
      + `includeIPv6Addrs` – <a name="ip-detector-component-configuration-include-ipv6-addrs-definition"></a>(Optional) You can enable this option to publish IPv6 addresses found on the core device. Set `includeIPv4Addrs` to `false` to use this option. You must have IP detector v2.2.0 or later to use this option.

      The configuration update might look similar to the following example.

      ```
      {
        "defaultPort": "8883",
        "includeIPv4LoopbackAddrs": false,
        "includeIPv4LinkLocalAddrs": false
      }
      ```

   1. Choose **Confirm** to close the modal, and then choose **Next**.

1. <a name="deploy-component-configure-advanced-settings-step"></a>On the **Configure advanced settings** page, keep the default configuration settings, and choose **Next**.

1. <a name="deploy-component-review-and-deploy-step"></a>On the **Review** page, choose **Deploy**.

   The deployment can take up to a minute to complete.

### Deploy the IP detector component (AWS CLI)
<a name="deploy-ip-detector-cli"></a>

To deploy the IP detector component, create a deployment document that includes `aws.greengrass.clientdevices.IPDetector` in the `components` object, and specify the configuration update for the component. Follow instructions in [Create deployments](create-deployments.md) to create a new deployment or revise an existing deployment.

You can specify any of the following options to configure the IP detector component when you create the deployment document:
+ `defaultPort` – <a name="ip-detector-component-configuration-default-port-definition"></a>(Optional) The MQTT broker port to report when this component detects IP addresses. You must specify this parameter if you configure the MQTT broker to use a different port than the default port 8883. 
+ `includeIPv4LoopbackAddrs` – <a name="ip-detector-component-configuration-include-ipv4-loopback-addrs-definition"></a>(Optional) You can enable this option to detect and report IPv4 loopback addresses. These are IP addresses, such as `localhost`, where a device can communicate with itself. Use this option in test environments where the core device and client device run on the same system. 
+ `includeIPv4LinkLocalAddrs` – <a name="ip-detector-component-configuration-include-ipv4-link-local-addrs-definition"></a>(Optional) You can enable this option to detect and report IPv4 [link-local addresses](https://en.wikipedia.org/wiki/Link-local_address). Use this option if the core device's network doesn't have Dynamic Host Configuration Protocol (DHCP) or statically assigned IP addresses. 
+ `includeIPv6LoopbackAddrs` – <a name="ip-detector-component-configuration-include-ipv6-loopback-addrs-definition"></a>(Optional) You can enable this option to detect and report IPv6 loopback addresses. These are IP addresses, such as `localhost`, where a device can communicate with itself. Use this option in test environments where the core device and client device run on the same system. You must set `includeIPv4Addrs` to `false` and `includeIPv6Addrs` to `true` to use this option. You must have IP detector v2.2.0 or later to use this option.
+ `includeIPv6LinkLocalAddrs` – <a name="ip-detector-component-configuration-include-ipv6-link-local-addrs-definition"></a>(Optional) You can enable this option to detect and report IPv6 [link-local addresses](https://en.wikipedia.org/wiki/Link-local_address). Use this option if the core device's network doesn't have Dynamic Host Configuration Protocol (DHCP) or statically assigned IP addresses. You must set `includeIPv4Addrs` to `false` and `includeIPv6Addrs` to `true` to use this option. You must have IP detector v2.2.0 or later to use this option.
+ `includeIPv4Addrs` – <a name="ip-detector-component-configuration-include-ipv4-addrs-definition"></a>(Optional) The default is set to true. You can enable this option to publish IPv4 addresses found on the core device. You must have IP detector v2.2.0 or later to use this option.
+ `includeIPv6Addrs` – <a name="ip-detector-component-configuration-include-ipv6-addrs-definition"></a>(Optional) You can enable this option to publish IPv6 addresses found on the core device. Set `includeIPv4Addrs` to `false` to use this option. You must have IP detector v2.2.0 or later to use this option.

The following example partial deployment document specifies to report port 8883 as the MQTT broker port.

```
{
  ...,
  "components": {
    ...,
    "aws.greengrass.clientdevices.IPDetector": {
      "componentVersion": "2.1.1",
      "configurationUpdate": {
        "merge": "{\"defaultPort\":\"8883\",}"
      }
    }
  }
}
```

## Manually manage endpoints
<a name="manually-manage-endpoints"></a>

You can manually manage MQTT broker endpoints for core devices.

Each MQTT broker endpoint has the following information:

**Endpoint** (`HostAddress`)  
An IP address or DNS address where client devices can connect to an MQTT broker on the core device.

**Port** (`PortNumber`)  
The port where the MQTT broker operates on the core device.  
You can configure this port on the [Moquette MQTT broker component](mqtt-broker-moquette-component.md), which defaults to use port 8883.

**Metadata** (`Metadata`)  
Additional metadata to provide to client devices that connect to this endpoint.

**Topics**
+ [

### Manage endpoints (console)
](#manually-manage-endpoints-console)
+ [

### Manage endpoints (AWS CLI)
](#manually-manage-endpoints-cli)
+ [

### Manage endpoints (API)
](#manually-manage-endpoints-api)

### Manage endpoints (console)
<a name="manually-manage-endpoints-console"></a>

You can use the AWS IoT Greengrass console to view, update, and remove endpoints for a core device.

**To manage endpoints for a core device (console)**

1. <a name="navigate-greengrass-console"></a>Navigate to the [AWS IoT Greengrass console](https://console.aws.amazon.com/greengrass).

1. Choose **Core devices**.

1. Choose the core device to manage.

1. On the core device's details page, choose the **Client devices** tab.

1. In the **MQTT broker endpoints** section, you can see the core device's MQTT broker endpoints. Choose **Manage endpoints**.

1. In the **Manage endpoints** modal, add or remove MQTT broker endpoints for the core device.

1. Choose **Update**.

### Manage endpoints (AWS CLI)
<a name="manually-manage-endpoints-cli"></a>

You can use the AWS Command Line Interface (AWS CLI) to manage endpoints for a core device.

**Note**  
Because client device support in AWS IoT Greengrass V2 is backward compatible with AWS IoT Greengrass V1, you can use AWS IoT Greengrass V2 or AWS IoT Greengrass V1 API operations to manage core device endpoints.

**To get endpoints for a core device (AWS CLI)**
+ Use either of the following commands:
  + [greengrassv2: get-connectivity-info](https://docs.aws.amazon.com/cli/latest/reference/greengrassv2/get-connectivity-info.html)
  + [greengrass: get-connectivity-info](https://docs.aws.amazon.com/cli/latest/reference/greengrass/get-connectivity-info.html)

**To update endpoints for a core device (AWS CLI)**
+ Use either of the following commands:
  + [greengrassv2: update-connectivity-info](https://docs.aws.amazon.com/cli/latest/reference/greengrassv2/update-connectivity-info.html)
  + [greengrass: update-connectivity-info](https://docs.aws.amazon.com/cli/latest/reference/greengrass/update-connectivity-info.html)

### Manage endpoints (API)
<a name="manually-manage-endpoints-api"></a>

You can use the AWS API to manage endpoints for a core device.

**Note**  
Because client device support in AWS IoT Greengrass V2 is backward compatible with AWS IoT Greengrass V1, you can use AWS IoT Greengrass V2 or AWS IoT Greengrass V1 API operations to manage core device endpoints.

**To get endpoints for a core device (AWS API)**
+ Use either of the following operations:
  + [V2: GetConnectivityInfo](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_GetConnectivityInfo.html)
  + [V1: GetConnectivityInfo](https://docs.aws.amazon.com/greengrass/v1/apireference/getconnectivityinfo-get.html)

**To update endpoints for a core device (AWS API)**
+ Use either of the following operations:
  + [V2: UpdateConnectivityInfo](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_UpdateConnectivityInfo.html)
  + [V1: UpdateConnectivityInfo](https://docs.aws.amazon.com/greengrass/v1/apireference/updateconnectivityinfo-put.html)

# Choose an MQTT broker
<a name="choose-local-mqtt-broker"></a>

AWS IoT Greengrass provides options for you to choose which local MQTT broker to run on your core devices. Client devices connect to the MQTT broker that runs on a core device, so choose an MQTT broker that is compatible with the client devices that you want to connect.

**Note**  <a name="note-deploy-one-mqtt-broker"></a>
We recommend that you deploy only one MQTT broker component. The [MQTT bridge](mqtt-bridge-component.md) and [IP detector](ip-detector-component.md) components work with only one MQTT broker component at a time. If you deploy multiple MQTT broker components, you must configure them to use different ports.

You can choose from the following MQTT brokers:
+ **[MQTT 3.1.1 broker (Moquette)](mqtt-broker-moquette-component.md)** – `aws.greengrass.clientdevices.mqtt.Moquette`

  Choose this option for a lightweight MQTT broker that is compliant with the MQTT 3.1.1 standard. The AWS IoT Core MQTT broker and AWS IoT Device SDK are also compliant with the MQTT 3.1.1 standard, so you can use these features to create an application that uses MQTT 3.1.1 across your devices and the AWS Cloud.
+ **[MQTT 5 broker (EMQX)](mqtt-broker-emqx-component.md)** – `aws.greengrass.clientdevices.mqtt.EMQX`

  Choose this option to use MQTT 5 features in communication between core devices and client devices. This component uses more resources than the Moquette MQTT 3.1.1 broker, and on Linux core devices, it requires Docker.

  MQTT 5 is backward-compatible with MQTT 3.1.1, so you can connect client devices that use MQTT 3.1.1 to this broker. If you run the Moquette MQTT 3.1.1 broker, you can replace it with the EMQX MQTT 5 broker, and client devices can continue to connect and operate as usual.

  <a name="note-local-mqtt-broker-mqtt-5-features"></a>
+ **Implement a custom broker**

  Choose this option to create a custom local broker component to communicate with client devices. You can create a custom local broker that uses a protocol other than MQTT. AWS IoT Greengrass provides a component SDK that you can use to authenticate and authorize client devices. For more information, see [Use the AWS IoT Device SDK to communicate with the Greengrass nucleus, other components, and AWS IoT CoreCommunicate with the Greengrass nucleus, other components, and AWS IoT Core](interprocess-communication.md) and [Authenticate and authorize client devices](ipc-client-device-auth.md).

# Connecting client devices to an AWS IoT Greengrass Core device with an MQTT broker
<a name="connecting-to-mqtt"></a>

When you use an MQTT broker on your AWS IoT Greengrass Core device, the device uses a *core device certificate authority (CA)* unique to the device to issue a certificate to the broker for making mutual TLS connections with clients. 

AWS IoT Greengrass will autogenerate a core device CA, or you can provide your own. The core device CA is registered with AWS IoT Greengrass when the [Client device auth](client-device-auth-component.md) component is connected. The autogenerated core device CA is persistent, the device will continue to use the same CA as long as the client device auth component is configured.

When the MQTT broker starts, it requests a certificate. The client device auth component issues an X.509 certificate using the core device CA. The certificate is rotated when the broker starts, when the certificate expires, or when connectivity information such as the IP address changes. For more information, see [Certificate rotation on the local MQTT broker](device-auth.md#mqtt-certificate-expiration).

To connect a client to the MQTT broker, you need the following:
+ The client device must have the AWS IoT Greengrass Core device CA. You can get this CA through cloud discovery, or by providing the CA manually. For more information, see [Using your own certificate authority](#use-your-own-CA).
+ The fully-qualified domain name (FQDN) or IP address of the core device must be present in the broker certificate issued by the core device CA. You ensure this using the [IP detector](ip-detector-component.md) component or manually configuring the IP address. For more information, see [Manage core device endpoints](manage-core-device-endpoints.md).
+ The client device auth component must give the client device permission to connect to the Greengrass core device. For more information, see [Client device auth](client-device-auth-component.md).

## Using your own certificate authority
<a name="use-your-own-CA"></a>

If your client devices can't access the cloud to discover your core device, you can provide a *core device certificate authority (CA)*. Your Greengrass core device uses the core device CA to issue certificates for your MQTT broker. Once you configure the core device and provision your client device with its CA, your client devices can connect to the endpoint and verify the TLS handshake using the core device CA (own provided CA or autogenerated).

To configure the [Client device auth](client-device-auth-component.md) component to use your core device CA, set the `certificateAuthority` configuration parameter when you deploy the component. You must provide the following details during configuration:
+ The location of a core device CA certificate.
+ The private key of the core device CA certificate.
+ (Optional) The certificate chain to the root certificate if the core device CA is an intermediate CA.

If you provide a core device CA, AWS IoT Greengrass registers the CA with the cloud.

You can store your certificates in a hardware security module or on the file system. The following example shows a `certificateAuthority` configuration for a intermediate CA stored using HSM/TPM. Note that the certificate chain can only be stored on disk.

```
  "certificateAuthority": {
      "certificateUri": "pkcs11:object=CustomerIntermediateCA;type=cert",
      "privateKeyUri": "pkcs11:object=CustomerIntermediateCA;type=private"
      "certificateChainUri": "file:///home/ec2-user/creds/certificateChain.pem",
    }
```

In this example, the `certificateAuthority` configuration parameter configures the client device auth component to use an intermediate CA from the file system:

```
  "certificateAuthority": {
      "certificateUri": "file:///home/ec2-user/creds/intermediateCA.pem",
      "privateKeyUri": "file:///home/ec2-user/creds/intermediateCA.privateKey.pem",
      "certificateChainUri": "file:///home/ec2-user/creds/certificateChain.pem",
    }
```

To connect the devices to your AWS IoT Greengrass Core device, do the following:

1. Create an intermediate certificate authority (CA) for the Greengrass core device using your organization's root CA. We recommend that you use an intermediate CA as a security best practice.

1. Provide the intermediate CA certificate, private key, and the certificate chain to your root CA to the Greengrass core device. For more information, see [Client device auth](client-device-auth-component.md). The intermediate CA becomes the core device CA for the Greengrass core device, and the device registers the CA with AWS IoT Greengrass.

1. Register the client device as an AWS IoT thing. For more information, see [Create a thing object](https://docs.aws.amazon.com/iot/latest/developerguide/create-iot-resources.html#create-aws-thing) in the *AWS IoT Core Developer Guide*. Add the private key, public key, device certificate, and root CA certificate to your client device. How you add the information depends on your device and software.

Once you configure your device, you can use the certificate and public key chain to connect to the Greengrass core device. Your software is responsible for finding the core device endpoints. You can set the endpoint manually for the core device. For more information, see [Manually manage endpoints](manage-core-device-endpoints.md#manually-manage-endpoints).

# Test client device communications
<a name="test-client-device-communications"></a>

Client devices can use the AWS IoT Device SDK to discover, connect, and communicate with a core device. You can use the Greengrass discovery client in the AWS IoT Device SDK to use the [Greengrass discovery API](greengrass-discover-api.md), which returns information about core devices to which a client device can connect. The API response includes MQTT broker endpoints to connect and certificates to use to verify the identity of each core device. Then, the client device can try each endpoint until it successfully connects to a core device.

Client devices can discover only core devices to which you associate them. Before you test communications between a client device and a core device, you must associate the client device to the core device. For more information, see [Associate client devices](associate-client-devices.md).

The Greengrass discovery API returns the core device MQTT broker endpoints that you specify. You can use the [IP detector component](ip-detector-component.md) to manage these endpoints for you, or you can manually manage them for each core device. For more information, see [Manage core device endpoints](manage-core-device-endpoints.md).

**Note**  
To use the Greengrass discovery API, a client device must have the `greengrass:Discover` permission. For more information, see [Minimal AWS IoT policy for client devices](device-auth.md#client-device-minimal-iot-policy).

The AWS IoT Device SDK is available in multiple programming languages. For more information, see [AWS IoT Device SDKs](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html) in the *AWS IoT Core Developer Guide*.

**Topics**
+ [

## Test communications (Python)
](#test-client-device-communications-python)
+ [

## Test communications (C\$1\$1)
](#test-client-device-communications-cpp)
+ [

## Test communications (JavaScript)
](#test-client-device-communications-javascript)
+ [

## Test communications (Java)
](#test-client-device-communications-java)

## Test communications (Python)
<a name="test-client-device-communications-python"></a>

In this section, you use Greengrass discovery sample in the [AWS IoT Device SDK v2 for Python](https://github.com/aws/aws-iot-device-sdk-python-v2) to test communications between a client device and a core device.

**Important**  
To use the AWS IoT Device SDK v2 for Python, a device must run Python 3.6 or later.

**To test communications (AWS IoT Device SDK v2 for Python)**

1. <a name="download-iot-device-sdk-python-v2"></a>Download and install the [AWS IoT Device SDK v2 for Python](https://github.com/aws/aws-iot-device-sdk-python-v2) to the AWS IoT thing to connect as a client device.

   On the client device, do the following:

   1. Clone the AWS IoT Device SDK v2 for Python repository to download it.

      ```
      git clone https://github.com/aws/aws-iot-device-sdk-python-v2.git
      ```

   1. Install the AWS IoT Device SDK v2 for Python.

      ```
      python3 -m pip install --user ./aws-iot-device-sdk-python-v2
      ```

1. <a name="cd-iot-device-sdk-python-v2"></a>Change to the samples folder in the AWS IoT Device SDK v2 for Python.

   ```
   cd aws-iot-device-sdk-python-v2/samples/greengrass
   ```

1. <a name="test-client-device-communications-application-intro"></a>Run the sample Greengrass discovery application. This application expects arguments that specify the client device thing name, the MQTT topic and message to use, and the certificates that authenticate and secure the connection. The following example sends a Hello World message to the `clients/MyClientDevice1/hello/world` topic.<a name="test-client-device-communications-application-command-replace"></a>
   + Replace *MyClientDevice1* with the client device's thing name.
   + Replace *\$1/certs/AmazonRootCA1.pem* with the path to the Amazon root CA certificate on the client device.
   + Replace *\$1/certs/device.pem.crt* with the path to the device certificate on the client device.
   + Replace *\$1/certs/private.pem.key* with the path to the private key file on the client device.
   + Replace *us-east-1* with the AWS Region where your client device and core device operate.

   ```
   python3 basic_discovery.py \\
     --thing_name MyClientDevice1 \\
     --topic 'clients/MyClientDevice1/hello/world' \\
     --message 'Hello World!' \\
     --ca_file ~/certs/AmazonRootCA1.pem \\
     --cert ~/certs/device.pem.crt \\
     --key ~/certs/private.pem.key \\
     --region us-east-1 \\
     --verbosity Warn
   ```

   <a name="test-client-device-communications-application-output-intro"></a>The discovery sample application sends the message 10 times and disconnects. It also subscribes to the same topic where it publishes messages. If the output indicates that the application received MQTT messages on the topic, the client device can successfully communicate with the core device.

   ```
   Performing greengrass discovery...
   awsiot.greengrass_discovery.DiscoverResponse(gg_groups=[awsiot.greengrass_discovery.GGGroup(gg_group_id='greengrassV2-coreDevice-MyGreengrassCore', cores=[awsiot.greengrass_discovery.GGCore(thing_arn='arn:aws:iot:us-east-1:123456789012:thing/MyGreengrassCore', connectivity=[awsiot.greengrass_discovery.ConnectivityInfo(id='203.0.113.0', host_address='203.0.113.0', metadata='', port=8883)])], certificate_authorities=['-----BEGIN CERTIFICATE-----\
   MIICiT...EXAMPLE=\
   -----END CERTIFICATE-----\
   '])])
   Trying core arn:aws:iot:us-east-1:123456789012:thing/MyGreengrassCore at host 203.0.113.0 port 8883
   Connected!
   Published topic clients/MyClientDevice1/hello/world: {"message": "Hello World!", "sequence": 0}
   
   Publish received on topic clients/MyClientDevice1/hello/world
   b'{"message": "Hello World!", "sequence": 0}'
   Published topic clients/MyClientDevice1/hello/world: {"message": "Hello World!", "sequence": 1}
   
   Publish received on topic clients/MyClientDevice1/hello/world
   b'{"message": "Hello World!", "sequence": 1}'
   
   ...
   
   Published topic clients/MyClientDevice1/hello/world: {"message": "Hello World!", "sequence": 9}
   
   Publish received on topic clients/MyClientDevice1/hello/world
   b'{"message": "Hello World!", "sequence": 9}'
   ```

   <a name="test-client-device-communications-application-troubleshooting"></a>If the application outputs an error instead, see [Troubleshooting Greengrass discovery issues](troubleshooting-client-devices.md#greengrass-discovery-issues).

   <a name="test-client-device-communications-application-view-core-logs"></a>You can also view the Greengrass logs on the core device to verify if the client device successfully connects and sends messages. For more information, see [Monitor AWS IoT Greengrass logs](monitor-logs.md).

## Test communications (C\$1\$1)
<a name="test-client-device-communications-cpp"></a>

In this section, you use Greengrass discovery sample in the [AWS IoT Device SDK v2 for C\$1\$1](https://github.com/aws/aws-iot-device-sdk-cpp-v2) to test communications between a client device and a core device.

<a name="iot-device-sdk-cpp-v2-build-requirements-intro"></a>To build the AWS IoT Device SDK v2 for C\$1\$1, a device must have the following tools:<a name="iot-device-sdk-cpp-v2-build-requirements"></a>
+ C\$1\$1 11 or later
+ CMake 3.1 or later
+ One of the following compilers:
  + GCC 4.8 or later
  + Clang 3.9 or later
  + MSVC 2015 or later

**To test communications (AWS IoT Device SDK v2 for C\$1\$1)**

1. Download and build the [AWS IoT Device SDK v2 for C\$1\$1](https://github.com/aws/aws-iot-device-sdk-cpp-v2) to the AWS IoT thing to connect as a client device.

   On the client device, do the following:

   1. Create a folder for the AWS IoT Device SDK v2 for C\$1\$1 workspace, and change to it.

      ```
      cd
      mkdir iot-device-sdk-cpp
      cd iot-device-sdk-cpp
      ```

   1. Clone the AWS IoT Device SDK v2 for C\$1\$1 repository to download it. The `--recursive` flag specifies to download submodules.

      ```
      git clone --recursive https://github.com/aws/aws-iot-device-sdk-cpp-v2.git
      ```

   1. Create a folder for the AWS IoT Device SDK v2 for C\$1\$1 build output, and change to it.

      ```
      mkdir aws-iot-device-sdk-cpp-v2-build
      cd aws-iot-device-sdk-cpp-v2-build
      ```

   1. Build the AWS IoT Device SDK v2 for C\$1\$1.

      ```
      cmake -DCMAKE_INSTALL_PREFIX="~/iot-device-sdk-cpp" -DCMAKE_BUILD_TYPE="Release" ../aws-iot-device-sdk-cpp-v2
      cmake --build . --target install
      ```

1. Build the Greengrass discovery sample application in the AWS IoT Device SDK v2 for C\$1\$1. Do the following:

   1. Change to the Greengrass discovery sample folder in the AWS IoT Device SDK v2 for C\$1\$1.

      ```
      cd ../aws-iot-device-sdk-cpp-v2/samples/greengrass/basic_discovery
      ```

   1. Create a folder for the Greengrass discovery sample build output, and change to it.

      ```
      mkdir build
      cd build
      ```

   1. Build the Greengrass discovery sample application.

      ```
      cmake -DCMAKE_PREFIX_PATH="~/iot-device-sdk-cpp" -DCMAKE_BUILD_TYPE="Release" ..
      cmake --build . --config "Release"
      ```

1. <a name="test-client-device-communications-application-scanner-intro"></a>Run the sample Greengrass discovery application. This application expects arguments that specify the client device thing name, the MQTT topic to use, and the certificates that authenticate and secure the connection. The following example subscribes to the `clients/MyClientDevice1/hello/world` topic and publishes a message that you enter on the command line to the same topic.<a name="test-client-device-communications-application-command-replace"></a>
   + Replace *MyClientDevice1* with the client device's thing name.
   + Replace *\$1/certs/AmazonRootCA1.pem* with the path to the Amazon root CA certificate on the client device.
   + Replace *\$1/certs/device.pem.crt* with the path to the device certificate on the client device.
   + Replace *\$1/certs/private.pem.key* with the path to the private key file on the client device.
   + Replace *us-east-1* with the AWS Region where your client device and core device operate.

   ```
   ./basic-discovery \
     --thing_name MyClientDevice1 \
     --topic 'clients/MyClientDevice1/hello/world' \
     --ca_file ~/certs/AmazonRootCA1.pem \
     --cert ~/certs/device.pem.crt \
     --key ~/certs/private.pem.key \
     --region us-east-1
   ```

   <a name="test-client-device-communications-application-scanner-output-intro"></a>The discovery sample application subscribes to the topic and prompts you to enter a message to publish. 

   ```
   Connecting to group greengrassV2-coreDevice-MyGreengrassCore with thing arn arn:aws:iot:us-east-1:123456789012:thing/MyGreengrassCore, using endpoint 203.0.113.0:8883
   Connected to group greengrassV2-coreDevice-MyGreengrassCore, using connection to 203.0.113.0:8883
   Successfully subscribed to clients/MyClientDevice1/hello/world
   Enter the message you want to publish to topic clients/MyClientDevice1/hello/world and press enter. Enter 'exit' to exit this program.
   ```

   <a name="test-client-device-communications-application-troubleshooting"></a>If the application outputs an error instead, see [Troubleshooting Greengrass discovery issues](troubleshooting-client-devices.md#greengrass-discovery-issues).

1. <a name="test-client-device-communications-application-scanner-input"></a>Enter a message, such as **Hello World\$1**.

   ```
   Enter the message you want to publish to topic clients/MyClientDevice1/hello/world and press enter. Enter 'exit' to exit this program.
   Hello World!
   ```

   <a name="test-client-device-communications-application-scanner-input-output"></a>If the output indicates that the application received the MQTT message on the topic, the client device can successfully communicate with the core device.

   ```
   Operation on packetId 2 Succeeded
   Publish received on topic clients/MyClientDevice1/hello/world
   Message:
   Hello World!
   ```

   <a name="test-client-device-communications-application-view-core-logs"></a>You can also view the Greengrass logs on the core device to verify if the client device successfully connects and sends messages. For more information, see [Monitor AWS IoT Greengrass logs](monitor-logs.md).

## Test communications (JavaScript)
<a name="test-client-device-communications-javascript"></a>

In this section, you use Greengrass discovery sample in the [AWS IoT Device SDK v2 for JavaScript](https://github.com/aws/aws-iot-device-sdk-js-v2) to test communications between a client device and a core device. 

**Important**  
To use the AWS IoT Device SDK v2 for JavaScript, a device must run Node v10.0 or later.

**To test communications (AWS IoT Device SDK v2 for JavaScript)**

1. Download and install the [AWS IoT Device SDK v2 for JavaScript](https://github.com/aws/aws-iot-device-sdk-js-v2) to the AWS IoT thing to connect as a client device.

   On the client device, do the following:

   1. Clone the AWS IoT Device SDK v2 for JavaScript repository to download it.

      ```
      git clone https://github.com/aws/aws-iot-device-sdk-js-v2.git
      ```

   1. Install the AWS IoT Device SDK v2 for JavaScript.

      ```
      cd aws-iot-device-sdk-js-v2
      npm install
      ```

1. Change to the Greengrass discovery sample folder in the AWS IoT Device SDK v2 for JavaScript.

   ```
   cd samples/node/greengrass/basic_discovery
   ```

1. Install the Greengrass discovery sample application.

   ```
   npm install
   ```

1. <a name="test-client-device-communications-application-intro"></a>Run the sample Greengrass discovery application. This application expects arguments that specify the client device thing name, the MQTT topic and message to use, and the certificates that authenticate and secure the connection. The following example sends a Hello World message to the `clients/MyClientDevice1/hello/world` topic.<a name="test-client-device-communications-application-command-replace"></a>
   + Replace *MyClientDevice1* with the client device's thing name.
   + Replace *\$1/certs/AmazonRootCA1.pem* with the path to the Amazon root CA certificate on the client device.
   + Replace *\$1/certs/device.pem.crt* with the path to the device certificate on the client device.
   + Replace *\$1/certs/private.pem.key* with the path to the private key file on the client device.
   + Replace *us-east-1* with the AWS Region where your client device and core device operate.

   ```
   node dist/index.js \
     --thing_name MyClientDevice1 \
     --topic 'clients/MyClientDevice1/hello/world' \
     --message 'Hello World!' \
     --ca_file ~/certs/AmazonRootCA1.pem \
     --cert ~/certs/device.pem.crt \
     --key ~/certs/private.pem.key \
     --region us-east-1 \
     --verbose warn
   ```

   <a name="test-client-device-communications-application-output-intro"></a>The discovery sample application sends the message 10 times and disconnects. It also subscribes to the same topic where it publishes messages. If the output indicates that the application received MQTT messages on the topic, the client device can successfully communicate with the core device.

   ```
   Discovery Response:
   {"gg_groups":[{"gg_group_id":"greengrassV2-coreDevice-MyGreengrassCore","cores":[{"thing_arn":"arn:aws:iot:us-east-1:123456789012:thing/MyGreengrassCore","connectivity":[{"id":"203.0.113.0","host_address":"203.0.113.0","port":8883,"metadata":""}]}],"certificate_authorities":["-----BEGIN CERTIFICATE-----\nMIICiT...EXAMPLE=\n-----END CERTIFICATE-----\n"]}]}
   Trying endpoint={"id":"203.0.113.0","host_address":"203.0.113.0","port":8883,"metadata":""}
   [WARN] [2021-06-12T00:46:45Z] [00007f90c0e8d700] [socket] - id=0x7f90b8018710 fd=26: setsockopt() for NO_SIGNAL failed with errno 92. If you are having SIGPIPE signals thrown, you may want to install a signal trap in your application layer.
   Connected to endpoint={"id":"203.0.113.0","host_address":"203.0.113.0","port":8883,"metadata":""}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":1}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":2}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":3}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":4}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":5}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":6}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":7}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":8}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":9}
   Publish received. topic:"clients/MyClientDevice1/hello/world" dup:false qos:0 retain:false
   {"message":"Hello World!","sequence":10}
   Complete!
   ```

   <a name="test-client-device-communications-application-troubleshooting"></a>If the application outputs an error instead, see [Troubleshooting Greengrass discovery issues](troubleshooting-client-devices.md#greengrass-discovery-issues).

   <a name="test-client-device-communications-application-view-core-logs"></a>You can also view the Greengrass logs on the core device to verify if the client device successfully connects and sends messages. For more information, see [Monitor AWS IoT Greengrass logs](monitor-logs.md).

## Test communications (Java)
<a name="test-client-device-communications-java"></a>

In this section, you use Greengrass discovery sample in the [AWS IoT Device SDK v2 for Java](https://github.com/aws/aws-iot-device-sdk-java-v2) to test communications between a client device and a core device.

**Important**  
To build the AWS IoT Device SDK v2 for Java, a device must have the following tools:  
Java 8 or later, with `JAVA_HOME` pointing to the Java folder.
Apache Maven

**To test communications (AWS IoT Device SDK v2 for Java)**

1. Download and build the [AWS IoT Device SDK v2 for Java](https://github.com/aws/aws-iot-device-sdk-java-v2) to the AWS IoT thing to connect as a client device.

   On the client device, do the following:

   1. Clone the AWS IoT Device SDK v2 for Java repository to download it.

      ```
      git clone https://github.com/aws/aws-iot-device-sdk-java-v2.git
      ```

   1. Change to the AWS IoT Device SDK v2 for Java folder.

   1. Build the AWS IoT Device SDK v2 for Java.

      ```
      cd aws-iot-device-sdk-java-v2
      mvn versions:use-latest-versions -Dincludes="software.amazon.awssdk.crt*"
      mvn clean install
      ```

1. <a name="test-client-device-communications-application-scanner-intro"></a>Run the sample Greengrass discovery application. This application expects arguments that specify the client device thing name, the MQTT topic to use, and the certificates that authenticate and secure the connection. The following example subscribes to the `clients/MyClientDevice1/hello/world` topic and publishes a message that you enter on the command line to the same topic.<a name="test-client-device-communications-application-command-replace"></a>
   + Replace both instances of *MyClientDevice1* with the client device's thing name.
   + Replace *\$1HOME/certs/AmazonRootCA1.pem* with the path to the Amazon root CA certificate on the client device.
   + Replace *\$1HOME/certs/device.pem.crt* with the path to the device certificate on the client device.
   + Replace *\$1HOME/certs/private.pem.key* with the path to the private key file on the client device.
   + Replace *us-east-1* with the AWS Region where your client device and core device operate.

   ```
   DISCOVERY_SAMPLE_ARGS="--thing_name MyClientDevice1 \
     --topic 'clients/MyClientDevice1/hello/world' \
     --ca_file $HOME/certs/AmazonRootCA1.pem \
     --cert $HOME/certs/device.pem.crt \
     --key $HOME/certs/private.pem.key \
     --region us-east-1"
   
   mvn exec:java -pl samples/Greengrass/Discovery \
     -Dexec.mainClass=greengrass.BasicDiscovery \
     -Dexec.args="$DISCOVERY_SAMPLE_ARGS"
   ```

   <a name="test-client-device-communications-application-scanner-output-intro"></a>The discovery sample application subscribes to the topic and prompts you to enter a message to publish. 

   ```
   Connecting to group ID greengrassV2-coreDevice-MyGreengrassCore, with thing arn arn:aws:iot:us-east-1:123456789012:thing/MyGreengrassCore, using endpoint 203.0.113.0:8883
   Started a clean session
   Enter the message you want to publish to topic clients/MyClientDevice1/hello/world and press Enter. Type 'exit' or 'quit' to exit this program:
   ```

   <a name="test-client-device-communications-application-troubleshooting"></a>If the application outputs an error instead, see [Troubleshooting Greengrass discovery issues](troubleshooting-client-devices.md#greengrass-discovery-issues).

1. <a name="test-client-device-communications-application-scanner-input"></a>Enter a message, such as **Hello World\$1**.

   ```
   Enter the message you want to publish to topic clients/MyClientDevice1/hello/world and press Enter. Type 'exit' or 'quit' to exit this program:
   Hello World!
   ```

   <a name="test-client-device-communications-application-scanner-input-output"></a>If the output indicates that the application received the MQTT message on the topic, the client device can successfully communicate with the core device.

   ```
   Message received on topic clients/MyClientDevice1/hello/world: Hello World!
   ```

   <a name="test-client-device-communications-application-view-core-logs"></a>You can also view the Greengrass logs on the core device to verify if the client device successfully connects and sends messages. For more information, see [Monitor AWS IoT Greengrass logs](monitor-logs.md).

# Greengrass discovery RESTful API
<a name="greengrass-discover-api"></a>

AWS IoT Greengrass provides the `Discover` API operation that client devices can use to identify Greengrass core devices where they can connect. Client devices use this data plane operation to retrieve information required to connect to Greengrass core devices where you associate them with the [BatchAssociateClientDeviceWithCoreDevice](https://docs.aws.amazon.com/greengrass/v2/APIReference/API_BatchAssociateClientDeviceWithCoreDevice.html) API operation. When a client device comes online, it can connect to the AWS IoT Greengrass cloud service and use the discovery API to find:
+ The IP address and port for each associated Greengrass core device.
+ The core device CA certificate, which client devices can use to authenticate the Greengrass core device.

**Note**  
Client devices can also use the discovery client in the AWS IoT Device SDK to discover connectivity information for Greengrass core devices. The discovery client uses the discovery API. For more information, see the following:  
[Test client device communications](test-client-device-communications.md)
[Greengrass Discovery RESTful API](https://docs.aws.amazon.com/greengrass/v1/developerguide/gg-discover-api.html) in the *AWS IoT Greengrass Version 1 Developer Guide*.

To use this API operation, send HTTP requests to the discovery API on the Greengrass data plane endpoint. This API endpoint has the following format.

```
https://greengrass-ats.iot.region.amazonaws.com:port/greengrass/discover/thing/thing-name
```

For a list of supported AWS Regions and endpoints for the AWS IoT Greengrass discovery API, see [AWS IoT Greengrass V2 endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/greengrassv2.html) in the *AWS General Reference*. This API operation is available only on the Greengrass data plane endpoint. The control plane endpoint that you use to manage components and deployments is different from the data plane endpoint.

**Note**  
The discovery API is the same for AWS IoT Greengrass V1 and AWS IoT Greengrass V2. If you have client devices that connect to an AWS IoT Greengrass V1 core, you can connect them to AWS IoT Greengrass V2 core devices without changing the code on the client devices. For more information, see [Greengrass Discovery RESTful API](https://docs.aws.amazon.com/greengrass/v1/developerguide/gg-discover-api.html) in the *AWS IoT Greengrass Version 1 Developer Guide*.

**Topics**
+ [

## Discovery authentication and authorization
](#greengrass-discover-auth)
+ [

## Request
](#greengrass-discover-request)
+ [

## Response
](#greengrass-discover-response)
+ [

## Test the discovery API with cURL
](#greengrass-discover-test-request)

## Discovery authentication and authorization
<a name="greengrass-discover-auth"></a>

To use the discovery API to retrieve connectivity information, a client device must use TLS mutual authentication with an X.509 client certificate to authenticate. For more information, see [X.509 client certificates](https://docs.aws.amazon.com/iot/latest/developerguide/x509-client-certs.html) in the *AWS IoT Core Developer Guide*.

A client device must also have permission to perform the `greengrass:Discover` action. The following example AWS IoT policy allows an AWS IoT thing named `MyClientDevice1` to perform `Discover` for itself.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "greengrass:Discover",
      "Resource": [
        "arn:aws:iot:us-west-2:123456789012:thing/MyClientDevice1"
      ]
    }
  ]
}
```

------

**Important**  
<a name="thing-policy-variable-not-supported"></a>[Thing policy variables](https://docs.aws.amazon.com/iot/latest/developerguide/thing-policy-variables.html) (`iot:Connection.Thing.*`) aren't supported for in AWS IoT policies for core devices or Greengrass data plane operations. Instead, you can use a wildcard that matches multiple devices that have similar names. For example, you can specify `MyGreengrassDevice*` to match `MyGreengrassDevice1`, `MyGreengrassDevice2`, and so on. 

For more information, see [AWS IoT Core policies](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html) in the *AWS IoT Core Developer Guide*.

## Request
<a name="greengrass-discover-request"></a>

The request contains the standard HTTP headers and is sent to the Greengrass discovery endpoint, as shown in the following examples.

The port number depends on whether the core device is configured to send HTTPS traffic over port 8443 or port 443. For more information, see [Connect on port 443 or through a network proxy](configure-greengrass-core-v2.md#configure-alpn-network-proxy).

**Note**  
These examples use the Amazon Trust Services (ATS) endpoint, which works with the recommended ATS root CA certificates. Endpoints must match the root CA certificate type.

Port 8443  

```
HTTP GET https://greengrass-ats.iot.region.amazonaws.com:8443/greengrass/discover/thing/thing-name
```

Port 443  

```
HTTP GET https://greengrass-ats.iot.region.amazonaws.com:443/greengrass/discover/thing/thing-name
```
Clients that connect on port 443 must implement the [Application Layer Protocol Negotiation (ALPN)](https://tools.ietf.org/html/rfc7301) TLS extension and pass `x-amzn-http-ca` as the `ProtocolName` in the `ProtocolNameList`. For more information, see [Protocols](https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html) in the *AWS IoT Developer Guide*.

## Response
<a name="greengrass-discover-response"></a>

Upon success, the response header includes the HTTP 200 status code and the response body contains the discover response document.

**Note**  
Because AWS IoT Greengrass V2 uses the same discovery API as AWS IoT Greengrass V1, the response organizes information according to AWS IoT Greengrass V1 concepts, such as Greengrass groups. The response contains a list of Greengrass groups. In AWS IoT Greengrass V2, each core device is in its own group, where the group contains only that core device and its connectivity information.

### Example discover response documents
<a name="greengrass-discover-response-examples"></a>

The following document shows the response for a client device that is associated to one Greengrass core device. The core device has one endpoint and one CA certificate.

```
{
  "GGGroups": [
    {
      "GGGroupId": "greengrassV2-coreDevice-core-device-01-thing-name",
      "Cores": [
        {
          "thingArn": "core-device-01-thing-arn",
          "Connectivity": [
            {
              "id": "core-device-01-connection-id",
              "hostAddress": "core-device-01-address",
              "portNumber": core-device-01-port,
              "metadata": "core-device-01-description"
            }
          ]
        }
      ],
      "CAs": [
        "-----BEGIN CERTIFICATE-----cert-contents-----END CERTIFICATE-----"
      ]
    }
  ]
}
```

The following document shows the response for a client device that is associated to two core devices. The core devices have multiple endpoints and multiple group CA certificates.

```
{
  "GGGroups": [
    {
      "GGGroupId": "greengrassV2-coreDevice-core-device-01-thing-name",
      "Cores": [
        {
          "thingArn": "core-device-01-thing-arn",
          "Connectivity": [
            {
              "id": "core-device-01-connection-id",
              "hostAddress": "core-device-01-address",
              "portNumber": core-device-01-port,
              "metadata": "core-device-01-connection-1-description"
            },
            {
              "id": "core-device-01-connection-id-2",
              "hostAddress": "core-device-01-address-2",
              "portNumber": core-device-01-port-2,
              "metadata": "core-device-01-connection-2-description"
            }
          ]
        }
      ],
      "CAs": [
        "-----BEGIN CERTIFICATE-----cert-contents-----END CERTIFICATE-----",
        "-----BEGIN CERTIFICATE-----cert-contents-----END CERTIFICATE-----",
        "-----BEGIN CERTIFICATE-----cert-contents-----END CERTIFICATE-----"
      ]
    },
    {
      "GGGroupId": "greengrassV2-coreDevice-core-device-02-thing-name",
      "Cores": [
        {
          "thingArn":"core-device-02-thing-arn",
          "Connectivity" : [
            {
              "id": "core-device-02-connection-id",
              "hostAddress": "core-device-02-address",
              "portNumber": core-device-02-port,
              "metadata": "core-device-02-connection-1-description"
            }
          ]
        }
      ],
      "CAs": [
        "-----BEGIN CERTIFICATE-----cert-contents-----END CERTIFICATE-----",
        "-----BEGIN CERTIFICATE-----cert-contents-----END CERTIFICATE-----",
        "-----BEGIN CERTIFICATE-----cert-contents-----END CERTIFICATE-----"
      ]
    }
  ]
}
```

## Test the discovery API with cURL
<a name="greengrass-discover-test-request"></a>

If you have `cURL` installed, you can test the discovery API. The following example specifies a client device's certificates to authenticate a request to the Greengrass discovery API endpoint.

```
curl -i \
  --cert 1a23bc4d56.cert.pem \
  --key 1a23bc4d56.private.key \
  https://greengrass-ats.iot.us-west-2.amazonaws.com:8443/greengrass/discover/thing/MyClientDevice1
```

**Note**  
The `-i` argument specifies to output HTTP response headers. You can use this option to help identify errors.

If the request succeeds, this command outputs a response similar to the following example.

```
{
  "GGGroups": [
    {
      "GGGroupId": "greengrassV2-coreDevice-MyGreengrassCore",
      "Cores": [
        {
          "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyGreengrassCore",
          "Connectivity": [
            {
              "Id": "AUTOIP_192.168.1.4_1",
              "HostAddress": "192.168.1.5",
              "PortNumber": 8883,
              "Metadata": ""
            }
          ]
        }
      ],
      "CAs": [
        "-----BEGIN CERTIFICATE-----\ncert-contents\n-----END CERTIFICATE-----\n"
      ]
    }
  ]
}
```

If the command outputs an error, see [Troubleshooting Greengrass discovery issues](troubleshooting-client-devices.md#greengrass-discovery-issues).