<commit_before>======================================
Java Client Library - Managed Gateway
======================================

Introduction
-------------

Gateway plays an important role in the device management of devices connected to it. Many of these devices will be too basic to be managed. For a managed device, the device management agent on the gateway acts as a proxy for the connected device. The protocol used by the gateway to manage the connected devices is arbitrary, and there need not be a device management agent on the connected devices. It is only necessary for the gateway to ensure that devices connected to it perform their responsibilities as managed devices, performing any translation and processing required to achieve this. The management agent in gateway will act as more than a transparent tunnel between the attached device and the Watson IoT Platform.

For example, It is unlikely that a device connected to a gateway will be able to download the firmware itself. In this case, the gateway’s device management agent will intercept the request to download the firmware and perform the download to its own storage. Then, when the device is instructed to perform the upgrade, the gateway’s device management agent will push the firmware to the device and update it.

This section contains information on how gateways (and attached devices) can connect to the Internet of Things Platform Device Management service using Java and perform device management operations like firmware update, location update, and diagnostics update.

----

Create DeviceData
------------------------------------------------------------------------
The `device model <https://docs.internetofthings.ibmcloud.com/reference/device_model.html>`__ describes the metadata and management characteristics of a device or a gateway. The device database in the IBM Watson Internet of Things Platform is the master source of device information. Applications and managed devices are able to send updates to the database such as a location or the progress of a firmware update. Once these updates are received by the IBM Watson Internet of Things Platform, the device database is updated, making the information available to applications.

The device model in the WIoTP client library is represented as DeviceData and to create a DeviceData one needs to create the following objects,

* DeviceInfo (Optional)
* DeviceLocation (Optional, required only if the device wants to be notified about the location set by the application through Watson IoT Platform API)
* DeviceFirmware (Optional)
* DeviceMetadata (optional)

The following code snippet shows how to create the object DeviceInfo along with DeviceMetadata with sample data:

.. code:: java

     DeviceInfo deviceInfo = new DeviceInfo.Builder().
				serialNumber("10087").
				manufacturer("IBM").
				model("7865").
				deviceClass("A").
				description("My RasPi Device").
				fwVersion("1.0.0").
				hwVersion("1.0").
				descriptiveLocation("EGL C").
				build();
	
     /**
       * Create a DeviceMetadata object 
      **/
     JsonObject data = new JsonObject();
     data.addProperty("customField", "customValue");
     DeviceMetadata metadata = new DeviceMetadata(data);

The following code snippet shows how to create the DeviceData object with the above created DeviceInfo and DeviceMetadata objects:

.. code:: java

	DeviceData deviceData = new DeviceData.Builder().
				 deviceInfo(deviceInfo).
				 metadata(metadata).
				 build();

Each gateway and attached devices must have its own DeviceData to represent itself in the Platform. In the case of gateway, the DeviceData will be passed to the library as part of constructing the ManagedGateway instance, and in the case of attached device, the DeviceData will be passed as part of the sendDeviceManageRequest(). 

----

Construct ManagedGateway
-------------------------------------------------------------------------------
ManagedGateway - A gateway class that connects the gateway as managed gateway to IBM Watson Internet of Things Platform and enables the gateway to perform one or more Device Management operations for itself and attached devices. Also the ManagedGateway instance can be used to do normal gateway operations like publishing gateway events, attached device events and listening for commands from application.

ManagedGateway exposes 2 different constructors to support different user patterns, 

**Constructor One**

Constructs a ManagedGateway instance by accepting the DeviceData and the following properties,

* Organization-ID - Your organization ID.
* Gateway-Type - The type of your gateway device.
* Gateway-ID - The ID of your gateway device.
* Authentication-Method - Method of authentication (The only value currently supported is "token"). 
* Authentication-Token - API key token
* clean-session - true or false (required only if you want to connect the Gateway in durable subscription. By default the clean-session is set to true).
* Port - Specify the port to connect to, supported ports are 8883 and 443. (default port is 8883). 
* WebSocket - true or false (default is false, required if you want to connect the device using websockets).
* MaxInflightMessages - Sets the maximum number of inflight messages for the connection (default value is 100).
* Automatic-Reconnect - true or false (default: false). When set, the library will automatically attempt to reconnect to the Watson IoT Platform while the client is in disconnected state.
* Disconnected-Buffer-Size - The maximum number of messages that will be stored in memory while the client is disconnected. Default: 5000.

**Note:** One must set clean-session to false to connect the Gateway in durable subscription. Refer to `Subscription Buffers and Clean Session <https://docs.internetofthings.ibmcloud.com/reference/mqtt/index.html#/subscription-buffers-and-clean-session#subscription-buffers-and-clean-session>`__ for more information about the clean session.


All these properties are required to interact with the IBM Watson Internet of Things Platform. 

The following code shows how to create a ManagedGateway instance:

.. code:: java

	Properties options = new Properties();
	options.setProperty("Organization-ID", "uguhsp");
	options.setProperty("Gateway-Type", "iotsample-arduino");
	options.setProperty("Gateway-ID", "00aabbccde03");
	options.setProperty("Authentication-Method", "token");
	options.setProperty("Authentication-Token", "AUTH TOKEN FOR DEVICE");
	
	ManagedGateway ManagedGateway = new ManagedGateway(options, deviceData);

**Constructor Two**

Construct a ManagedGateway instance by accepting the DeviceData and the MqttClient instance. This constructor requires the DeviceData to be created with additional device attributes like Device Type and Device Id as follows:

.. code:: java
	
	// Code that constructs the MqttClient (either Synchronous or Asynchronous MqttClient)
	.....
	
	// Code that constructs the DeviceData
	DeviceData deviceData = new DeviceData.Builder().
				 typeId("Gateway-Type").
				 deviceId("Gateway-ID").
				 deviceInfo(deviceInfo).
				 metadata(metadata).
				 build();
	
	....
	ManagedGateway ManagedGateway = new ManagedGateway(mqttClient, deviceData);
	
Note this constructor helps the custom device users to create a ManagedGateway instance with the already created and connected MqttClient instance to take advantage of device management operations. But we recommend the users to use the library for all the device functionalities.

----

Manage request - gateway
-------------------------------------------------------

The gateway can invoke sendGatewayManageRequest() method to participate in device management activities. The manage request will initiate a connect request internally if the device is not connected to the IBM Watson Internet of Things Platform already:

.. code:: java

	managedGateway.sendGatewayManageRequest(0, true, true);
	
As shown, this method accepts following 3 parameters,

* *lifetime* The length of time in seconds within which the gateway must send another **Manage** request in order to avoid being reverted to an unmanaged device and marked as dormant. If set to 0, the managed gateway will not become dormant. When set, the minimum supported setting is 3600 (1 hour).
* *supportFirmwareActions* Tells whether the gateway supports firmware actions or not. The gateway must add a firmware handler to handle the firmware requests.
* *supportDeviceActions* Tells whether the gateway supports Device actions or not. The gateway must add a Device action handler to handle the reboot and factory reset requests.

Manage request - attached devices
--------------------------------------

The gateway can invoke sendDeviceManageRequest() method to make the attached devices participate in the device management activities. 

.. code:: java

	managedGateway.sendDeviceManageRequest(typeId, deviceId, lifetime, true, true);

As shown, this method accepts the details of the attached device apart from the lifetime and device/firmware support parameters. The gateway can also use the overloaded sendDeviceManageRequest() method to specify the DeviceData for the attached device.

Refer to the `documentation <https://docs.internetofthings.ibmcloud.com/devices/device_mgmt/index.html#/manage-device#manage-device>`__ for more information about the manage operation.

----

Unmanage request - gateway
-----------------------------------------------------

A gateway can invoke sendGatewayUnmanageRequest() method when it no longer needs to be managed. The IBM Watson Internet of Things Platform will no longer send new device management requests for this gateway and all device management requests from the gateway (only for the gateway and not for the attached devices) will be rejected other than a **Manage** request.

.. code:: java

	managedGateway.sendGatewayUnmanageRequest();<commit_msg>Restored typo in command as per confirmation from Sathish.<commit_after>======================================
Java Client Library - Managed Gateway
======================================

Introduction
-------------

Gateway plays an important role in the device management of devices connected to it. Many of these devices will be too basic to be managed. For a managed device, the device management agent on the gateway acts as a proxy for the connected device. The protocol used by the gateway to manage the connected devices is arbitrary, and there need not be a device management agent on the connected devices. It is only necessary for the gateway to ensure that devices connected to it perform their responsibilities as managed devices, performing any translation and processing required to achieve this. The management agent in gateway will act as more than a transparent tunnel between the attached device and the Watson IoT Platform.

For example, It is unlikely that a device connected to a gateway will be able to download the firmware itself. In this case, the gateway’s device management agent will intercept the request to download the firmware and perform the download to its own storage. Then, when the device is instructed to perform the upgrade, the gateway’s device management agent will push the firmware to the device and update it.

This section contains information on how gateways (and attached devices) can connect to the Internet of Things Platform Device Management service using Java and perform device management operations like firmware update, location update, and diagnostics update.

----

Create DeviceData
------------------------------------------------------------------------
The `device model <https://docs.internetofthings.ibmcloud.com/reference/device_model.html>`__ describes the metadata and management characteristics of a device or a gateway. The device database in the IBM Watson Internet of Things Platform is the master source of device information. Applications and managed devices are able to send updates to the database such as a location or the progress of a firmware update. Once these updates are received by the IBM Watson Internet of Things Platform, the device database is updated, making the information available to applications.

The device model in the WIoTP client library is represented as DeviceData and to create a DeviceData one needs to create the following objects,

* DeviceInfo (Optional)
* DeviceLocation (Optional, required only if the device wants to be notified about the location set by the application through Watson IoT Platform API)
* DeviceFirmware (Optional)
* DeviceMetadata (optional)

The following code snippet shows how to create the object DeviceInfo along with DeviceMetadata with sample data:

.. code:: java

     DeviceInfo deviceInfo = new DeviceInfo.Builder().
				serialNumber("10087").
				manufacturer("IBM").
				model("7865").
				deviceClass("A").
				description("My RasPi Device").
				fwVersion("1.0.0").
				hwVersion("1.0").
				descriptiveLocation("EGL C").
				build();
	
     /**
       * Create a DeviceMetadata object 
      **/
     JsonObject data = new JsonObject();
     data.addProperty("customField", "customValue");
     DeviceMetadata metadata = new DeviceMetadata(data);

The following code snippet shows how to create the DeviceData object with the above created DeviceInfo and DeviceMetadata objects:

.. code:: java

	DeviceData deviceData = new DeviceData.Builder().
				 deviceInfo(deviceInfo).
				 metadata(metadata).
				 build();

Each gateway and attached devices must have its own DeviceData to represent itself in the Platform. In the case of gateway, the DeviceData will be passed to the library as part of constructing the ManagedGateway instance, and in the case of attached device, the DeviceData will be passed as part of the sendDeviceManageRequest(). 

----

Construct ManagedGateway
-------------------------------------------------------------------------------
ManagedGateway - A gateway class that connects the gateway as managed gateway to IBM Watson Internet of Things Platform and enables the gateway to perform one or more Device Management operations for itself and attached devices. Also the ManagedGateway instance can be used to do normal gateway operations like publishing gateway events, attached device events and listening for commands from application.

ManagedGateway exposes 2 different constructors to support different user patterns, 

**Constructor One**

Constructs a ManagedGateway instance by accepting the DeviceData and the following properties,

* Organization-ID - Your organization ID.
* Gateway-Type - The type of your gateway device.
* Gateway-ID - The ID of your gateway device.
* Authentication-Method - Method of authentication (The only value currently supported is "token"). 
* Authentication-Token - API key token
* clean-session - true or false (required only if you want to connect the Gateway in durable subscription. By default the clean-session is set to true).
* Port - Specify the port to connect to, supported ports are 8883 and 443. (default port is 8883). 
* WebSocket - true or false (default is false, required if you want to connect the device using websockets).
* MaxInflightMessages - Sets the maximum number of inflight messages for the connection (default value is 100).
* Automatic-Reconnect - true or false (default: false). When set, the library will automatically attempt to reconnect to the Watson IoT Platform while the client is in disconnected state.
* Disconnected-Buffer-Size - The maximum number of messages that will be stored in memory while the client is disconnected. Default: 5000.

**Note:** One must set clean-session to false to connect the Gateway in durable subscription. Refer to `Subscription Buffers and Clean Session <https://docs.internetofthings.ibmcloud.com/reference/mqtt/index.html#/subscription-buffers-and-clean-session#subscription-buffers-and-clean-session>`__ for more information about the clean session.


All these properties are required to interact with the IBM Watson Internet of Things Platform. 

The following code shows how to create a ManagedGateway instance:

.. code:: java

	Properties options = new Properties();
	options.setProperty("Organization-ID", "uguhsp");
	options.setProperty("Gateway-Type", "iotsample-arduino");
	options.setProperty("Gateway-ID", "00aabbccde03");
	options.setProperty("Authentication-Method", "token");
	options.setProperty("Authentication-Token", "AUTH TOKEN FOR DEVICE");
	
	ManagedGateway ManagedGateway = new ManagedGateway(options, deviceData);

**Constructor Two**

Construct a ManagedGateway instance by accepting the DeviceData and the MqttClient instance. This constructor requires the DeviceData to be created with additional device attributes like Device Type and Device Id as follows:

.. code:: java
	
	// Code that constructs the MqttClient (either Synchronous or Asynchronous MqttClient)
	.....
	
	// Code that constructs the DeviceData
	DeviceData deviceData = new DeviceData.Builder().
				 typeId("Gateway-Type").
				 deviceId("Gateway-ID").
				 deviceInfo(deviceInfo).
				 metadata(metadata).
				 build();
	
	....
	ManagedGateway ManagedGateway = new ManagedGateway(mqttClient, deviceData);
	
Note this constructor helps the custom device users to create a ManagedGateway instance with the already created and connected MqttClient instance to take advantage of device management operations. But we recommend the users to use the library for all the device functionalities.

----

Manage request - gateway
-------------------------------------------------------

The gateway can invoke sendGatewayManageRequest() method to participate in device management activities. The manage request will initiate a connect request internally if the device is not connected to the IBM Watson Internet of Things Platform already:

.. code:: java

	managedGateway.sendGatewayManageRequest(0, true, true);
	
As shown, this method accepts following 3 parameters,

* *lifetime* The length of time in seconds within which the gateway must send another **Manage** request in order to avoid being reverted to an unmanaged device and marked as dormant. If set to 0, the managed gateway will not become dormant. When set, the minimum supported setting is 3600 (1 hour).
* *supportFirmwareActions* Tells whether the gateway supports firmware actions or not. The gateway must add a firmware handler to handle the firmware requests.
* *supportDeviceActions* Tells whether the gateway supports Device actions or not. The gateway must add a Device action handler to handle the reboot and factory reset requests.

Manage request - attached devices
--------------------------------------

The gateway can invoke sendDeviceManageRequest() method to make the attached devices participate in the device management activities. 

.. code:: java

	managedGateway.sendDeviceManageRequest(typeId, deviceId, lifetime, true, true);

As shown, this method accepts the details of the attached device apart from the lifetime and device/firmware support parameters. The gateway can also use the overloaded sendDeviceManageRequest() method to specify the DeviceData for the attached device.

Refer to the `documentation <https://docs.internetofthings.ibmcloud.com/devices/device_mgmt/index.html#/manage-device#manage-device>`__ for more information about the manage operation.

----

Unmanage request - gateway
-----------------------------------------------------

A gateway can invoke sendGatewayUnmanageRequet() method when it no longer needs to be managed. The IBM Watson Internet of Things Platform will no longer send new device management requests for this gateway and all device management requests from the gateway (only for the gateway and not for the attached devices) will be rejected other than a **Manage** request.

.. code:: java

	managedGateway.sendGatewayUnmanageRequet();
{'fraction_non_alphanumeric': 0.09100075623897151, 'fraction_numerical': 0.004537433829089992, 'mean_word_length': 3.968937875751503, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7540492', 'n_tokens_mistral': 4627, 'n_tokens_neox': 4276, 'n_words': 2433}