Overview

Skill Level: Intermediate

Intermediate

Introduction The device management feature enhances theIBM Watson IoT Platform service with new capabilities for managing devices. This recipe provides a sample agent implementation that demonstrates the following device management capabilities on a Raspberry Pi.ManageFirmware UpdateDevice RebootLocation UpdateDiagnostic updateUnmanageRefer to the documentation for detailed information about IBM Watson IoT Platform device management capabilities to create […]

Ingredients

Software Requirements

  • IBM Bluemix account
  • Java7 or later
  • Maven
  • Git

Hardware Requirements

  • Raspberry Pi Model B, with 8 GB SD card

Step-by-step

  1. Introduction

    The device management feature enhances theIBM Watson IoT Platform service with new capabilities for managing devices. This recipe provides a sample agent implementation that demonstrates the following device management capabilities on a Raspberry Pi.

    • Manage
    • Firmware Update
    • Device Reboot
    • Location Update
    • Diagnostic update
    • Unmanage

    Refer to the documentation for detailed information about IBM Watson IoT Platform device management capabilities to create your own management agent. 

    The sample code for this recipe is written using the Java Client Library for IBM Watson IoT Platform and connects the device as manage device to Watson IoT in the first step such that this device can participate in Device Management(DM) activities. The sample performs one or more Device Management activities based on the user input and helps you to build a DM agent that runs on the device.

  2. Prepare

    Get your device ready


    (Following steps are required to demonstrate the Firmware Update process)

    1. Connect to your Raspberry Pi device using SSH.
    2. Setup the Raspbian environment with Maven and Git if not installed already, by installing them as follows,
      sudo apt-get update
      sudo apt-get install maven
    3. Git is present in the latest Raspbian OS and hence the users need not install it again. However, if the users have an older version of Raspbian and do not see Git being part of it, then, make use of the following command to install the Git automatically using:
      sudo apt-get install git-all 
    4. Download the Raspberry Pi Watson IoT Platform connector debian package from the github:

      https://github.com/ibm-messaging/iot-raspberrypi/releases/download/1.0.2/iot_1.0-1_armhf.deb
    5. Install the package with command:
      sudo dpkg -i iot_1.0-1_armhf.deb

      (later this recipe demonstrates how to upgrade this service through Firmware Update functionality)

    6. Find the MAC address of your Raspberry Pi by running the following service command:

      service iot getdeviceid 
    7. Enter your MAC address here to visualize your data:
       

  3. Register your Device In Watson IoT Platform

    In order to demonstrate the device management capabilities, we need to setup the IBM Watson IoT Platform organization and register the Raspberry Pi device in it. This section shows how you can setup the same. 

    Carry out the steps present in this recipe to register your Raspberry Pi device in IBM Watson IoT Platform. devicecredentials5

    At this step, we have successfully created the IoT service and registered the Raspberry Pi device in it.

  4. Start Agent

     Start the Device Management Agent 

    In order to become a managed device, your device will require a device management agent. A management agent is a collection of logic installed on a device which allows it to connect to the Watson Internet of Things service as a managed device. The management agent understands the device management commands used in the device management messaging protocol.

    1. Get back to the SSH session and Clone the iot-device-samples project using git clone as follows,

      git clone https://github.com/ibm-messaging/iot-device-samples.git
    2. Navigate to the device-management-sample project,
      cd iot-device-samplesjavadevice-management-sample
    3. Run the maven build as follows,
      mvn clean package 

      (Please refer to the README on iot-device-samples Github repository for details)

    4. Modify the DMDeviceSample.properties file present under target/classes directory structure by entering your device information and registration details like Organization ID, Device Type, Device ID, Authentication Method and Authentication Token.
      ## connectivity parameters
      Organization-ID = <Your Organization ID>
      Device-Type = <Your Device Type>
      Device-ID = <Your Device ID>
      Authentication-Method = token
      Authentication-Token = <Your Device Token>
    5. Run the Device Management sample agent by specifying the following command:
      mvn exec:java -Dexec.mainClass="com.ibm.iotf.sample.devicemgmt.device.SampleRasPiDMAgent"
    6. Observe that the device connects to IBM Watson IoT Platform and lists down various device management operations that the sample agent can perform:
      manage [lifetime in seconds] :: Request to make the device as Managed device in IoTF
      unmanage :: Request to make the device unmanaged
      firmware :: Adds a Firmware Handler that listens for the firmware requests from IoTF
      reboot :: Adds a Device action Handler that listens for reboot request from IoTF
      location :: Starts a task that updates a random location at every 30 seconds
      errorcode :: Starts a task that appends/clears a simulated ErrorCode at every 30 seconds
      log :: Starts a task that appends/clears a simulated Log message at every 30 seconds
      quit :: quit this sample agent
  5. Manage

     Become a managed device

     Type “manage” with an optional lifetime parameter (in seconds) in the SSH session to become a managed device:

    1. manage 3600
    2. Observe the following message in the console:
      Device is connected as Managed device now !!

      (This means that the device is connected to IBM Watson IoT Platform as managed device and can participate in Device Management activities. Refer to the following link for more information about the manage request)

    3. Note: If a lifetime parameter is specified, the agent must send another manage request before the lifetime expires, otherwise the device will be marked as dormant. So in this case, agent sends another manage request before 1 hour (3600 seconds).
  6. Firmware Update

    Update Raspberry Pi IBM IoT Connector service with a new version 

    • To participate in Firmware Actions, the device needs to set supports.firmwareActions field to true, add a firmware handler and resend the manage request. Type “firmware” in the console to trigger the sample code to do the same:
      firmware
    • Observe that the agent sends a manage request with supports.firmwareActions field set to true and adds a firmware handler which listens to the Firmware requests from IBM Watson IoT Platform. Refer to this link for detailed information about the firmware update process.
    • The firmware update process is segregated in 2 distinct actions, namely, Firmware Download and Firmware Update. Let us initiate the actions one by one by carrying out the following steps.

    Start Firmware Download action:

    There are different ways to initiate the firmware download action, in this sub section, we will show how to initiate the firmware download action using the IoT Platform dashboard. (Alternatively one can use the Watson IoT Platform API to initiate the action as well. Refer to the documentation for more information about the JSON message to be used).

    Initiate Firmware Download, via IBM Watson IoT Platform Dashboard, by doing following activities,

    • Launch IBM Watson IoT Platform dashboard
    • Click on DEVICES tab (see below)
    • Click on Action tab (see below)
    • Click on Initiate Action button present in the bottom of the page as shown below,
    • Select the Download Firmware Action and click next
    • Select the appropriate Device Type and click next
    • Select your device and click next
    • Specify the Firmware-URI as follows (see below diagram) and click Initiate button:
      https://github.com/ibm-messaging/iot-raspberrypi/releases/download/1.0.2.1/iot_1.0-2_armhf.deb
    • Specify the Firmware verifier as follows and other values are optional:
      a1f46487f7b5637c85ae712ecb1d33f7

      (This is the MD5 checksum value of debian package iot_1.0-2_armhf.deb. The sample agent code verifies the downloaded image against this checksum and reports the error if any)

    • This step initiates a firmware download process wherein the agent starts downloading the package iot_1.0-2_armhf.deb from the mentioned URI and reports the Firmware Download status to IBM Watson IoT Platform regularly.

     Start Firmware Update Action:

    As similar to Firmware download action, The Firmware update action can be initiated using either the IBM Watson IoT Platform dashboard or the Watson IoT Platform API. In this section we will show how to initiate the Firmware update using the dashboard.

    • Select the Update Firmware Action and click next
    • Select the appropriate Device Type and click next
    • Select your device and click next
    • Just click the Initiate button, no need to enter any firmware details:
    • The Firmware Handler in the agent starts updating the debian package iot_1.0-2_armhf.deb and reports the progress to IBM Watson IoT Platform
      regularly through mgmt.firmware object.
    • Once the Firmware Update is done, Enter your MAC address here to visualize the data from the updated service.
    • Observe that a new datapoint “memoryusage” gets reported to the IBM Watson IoT Platform Quickstart.
    • Repeat the steps from 4 to 8 to install/update any other debian package on the Raspberry Pi.
  7. Device Reboot

    Initiate Device Reboot action 

    • To participate in Device Actions like Reboot and factory Reset, the device needs to set supports.deviceActions field to true, add a device action handler and resend the manage request. Type “reboot” in the console to trigger the sample code to do the same:
      reboot
    • The agent registers a device action handler to the library code that gets invoked when there is a device action request from the IBM Watson IoT Platform. Refer to this link for more information about the device action.

    Start Reboot action using IBM Watson IoT Platform dashboard

    There are different ways to initiate the reboot action, In this sub section, we will show how to initiate the reboot action using the IBM Watson IoT Platform dashboard.

    Initiate the Device Reboot action via IBM Watson IoT Platform dashboard by performing the following activities,

    • Launch IBM Watson IoT Platform dashboard
    • Click on DEVICES tab
    • Click on Action tab
    • Click on Initiate Action button present in the bottom of the page as shown below,
    • Select the Reboot Action and click next
    • Select the appropriate Device Type and click next
    • Select your Device and click Initiate

    Start Reboot action using IBM Watson IoT Platform API – Alternate approach

    Alternatively one can use the Watson IoT Platform API to initiate the reboot action as well. In this sub section, we will show how to initiate the reboot action using the Watson IoT Platform API.

    Initiate the Device Reboot action via ReST API by doing the following activities,

    • Generate API Key (If not generated already) to secure the communication to IBM Watson IoT Platform by carrying out the steps mentioned in this section – Generate API Key in Watson IoT Platform. Note down “API Key” and “Authentication Token” and use them to authenticate while performing the ReST operation
    • Send the following JSON message at the specified URI using the generated API Key and Authentication Token,
      • ReST URI:
        https://<Organization ID>.internetofthings.ibmcloud.com/api/v0002/mgmt/requests

        (Modify the URI with your Organization ID)

      • JSON Message:
        {
        "action": "device/reboot",
        "devices": [
        {
        "typeId": "<Device Type>",
        "deviceId": "<Device ID>"
        }
        ]}

        (Modify the message with your Device Type and Device ID)

    • Observe that the Raspberry Pi device reboots. In order to complete the reboot action, the device needs to connect again and send a manage() request. So, once your device is up, run the sample again and send a manage request.
  8. Location update

     Update the location of the device to IBM Watson IoT Platform

    1. Type “location” in the console to update the device location information to IBM Watson IoT Platform:
      location
    2. Observe that the agent sends a location update message for every 30 seconds. Refer to this link for more information about updating the device location.
    3. The modified location could be retrieved using the Watson IoT Platform API, Issue GET on the following ReST URI with the API Key and Authentication Token that you retrieved earlier, and select the header as Accept: application/json
      https://<Organization ID>.internetofthings.ibmcloud.com/api/v0002/device/types/<Device Type>/devices/<Device ID>/location

      (Modify the URI with your Organization ID, Device Type and Device ID)

  9. Diagnostics: Error Code

    Append/clear Error Code

     Type “errorcode” in the console to generate simulated device Error Codes:

    1. errorcode
    2. Observe that the agent adds an Error Code for every 30 seconds. And clears the Error Codes at every 25th iteration. Refer to the documentation link for more information about updating the Error Code.
    3. The Error Codes can be viewed in IBM Watson IoT Platform Dashboard, Go to the following section to view the same,
      • Launch IBM Watson IoT Platform dashboard
      • Click on DEVICES tab
      • Click on Diagnose tab
      • Click on the corresponding Device
      • Scroll down to view the Error Codes

  10. Diagnostics: Log

     Append/clear Log Information to IBM Watson IoT Platform 

    1. Type “log” in the console to generate simulated device Log messages:
       log

      (Note that these are device local Log messages and does not provide diagnostic information relating to the device connection to the IBM Watson IoT Platform)

    2. Observe that the agent adds a Log message for every 30 seconds and clears the Log messages at every 25th iteration. Refer to the documentation for more information about adding the Log message to IBM Watson IoT Platform.
    3. The Log messages can be viewed in IBM Watson IoT Platform Dashboard, Go to the following section to view the same,
      • Launch IBM Watson IoT Platform dashboard
      • Click on DEVICES tab
      • Click on Diagnose tab
      • Click on the corresponding Device
      • Scroll down to view the Diagnostics Logs

  11. Unmanage

    Leave from Managed state

    1. Type “unmanage” to remove device from management activities:
      unmanage
    2. The device becomes an unmanaged device and can not participate in management activities, but it can continue to publish device events and subscribe to application commands.
    3. The Watson Internet of Things will no longer send new device management requests to this device and device management requests from this device will be rejected other than a Manage device request. Refer to the documentation for more information about the unmanage operation.
  12. Conclusion

    In this recipe, we demonstrated the device management support using the Java Client Library for IBM Watson IoT Platform IoT Platform. Developers can look at the code made available in the Github repository to understand whats happening under the hood. Developers can consider this recipe as a template for any device management agent development in IBM Watson IoT Platform.

  13. Where to go from here?

    1.  Go through IBM Watson IoT Real-Time Insights recipe that enables one to perform analytics on real-time data from the IoT devices and gain diagnostic insights. Though the recipe is written to analyze the vehicle data, the same can be used as a template to derive insights from any IoT data.
    2. Go through the Node-RED recipe to receive your device events to Node-RED application.
    3. Go through Connect Raspberry Pi as Gateway to Watson IoT Platform recipe that helps one to connect the Gateway and devices behind it to IBM Watson IoT Platform and publish/receive messages on behalf of these devices to/from Watson IoT Platform.
    4. Browse through various tutorials available in developerWorks Recipes to know how to connect specific devices to IBM Watson IoT Platform, visualize the events originating from these devices, control, process and analyze these device events using applications.
    5. Browse through various IBM Watson IoT Programming guides to develop your own Device, Gateway or Application code There are several client libraries available for use with the Watson Internet of Things Platform. The client libraries are designed to allow users to interact with their Devices, Gateways and Applications using their preferred language, and to simplify this interaction as much as possible.

10 Comments on "Connect Raspberry Pi as Managed Device to IBM Watson IoT Platform"

  1. I followed the above and built the agent fine. It starts up, but then fails to connect.It just continues to try with the following:

    INFO: main: Connecting to ssl://oze3mh.messaging.internetofthings.ibmcloud.com:8883 (attemp#1)

    I have updated the property file with my correct device information (which was created when i registered it using the iot service) and if I start/stop the iot service that connects fine too so I know the configuration is good and connectivity is not an issue.

    One the IotF app on my Bluemix, I get the following error:

    “Token Auth failed (device does not exist)”

    Which does not make sense as I am using the correct configuration info and I have duplicated by running “service iot getdeviceid”
    Any ideas?

    • YMDH_sathish_Palaniappan September 18, 2015

      Copying the answer by Ben in the Developer Works forum,

      Good day,

      I looked at the logs for your organization and I noticed the error message is:

      Token auth failed (Device does not exist): ClientID=’d:oze3mh:type:id ‘

      (type and id have been replaced in the above for privacy/security reasons)

      Notice the space at the end of the client ID but before the close quote?

      Your device is registered without the space.

      It’s possible you have a trailing space in your config file. If not, I think your configuration file might be somewhat broken – double check that the line endings are properly encoded for the Pi’s Operating System.

      Can you double-check your device registration and config file?

      -Ben

  2. YMDH_sathish_Palaniappan September 18, 2015

    Copying the answer by Ben in the Developer Works forum,

    Good day,

    I looked at the logs for your organization and I noticed the error message is:

    Token auth failed (Device does not exist): ClientID=’d:oze3mh:type:id ‘

    (type and id have been replaced in the above for privacy/security reasons)

    Notice the space at the end of the client ID but before the close quote?

    Your device is registered without the space.

    It’s possible you have a trailing space in your config file. If not, I think your configuration file might be somewhat broken – double check that the line endings are properly encoded for the Pi’s Operating System.

    Can you double-check your device registration and config file?

    -Ben

  3. 1. Is it possible to make my Texas Instruments cc3200 LaunchPad a managed device as described in This recipe ?
    2. Should I get the device management agent, described above, installed on my cc3200 launchpad ?
    3. The following link https://docs.internetofthings.ibmcloud.com/nodejs/node-js_applications.html describes NodeJS Client Library. Is there future intention for device management commands to be added to this client API ?

  4. Thank you for the detailed answer, @YMDH_sathish_Palaniappan

  5. Hi,
    I have follow the instructions and when I came to this command:
    java -cp com.ibm.iotf.client-0.0.3.jar:com.ibm.iotf.samples-0.0.3.jar:lib/* com.ibm.iotf.sample.devicemgmt.device.SampleRasPiDMAgent

    I got this error:
    Exception in thread “main” java.lang.UnsupportedClassVersionError: com/ibm/iotf/ sample/devicemgmt/device/SampleRasPiDMAgent : Unsupported major.minor version 51 .0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:643)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14 2)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
    Could not find the main class: com.ibm.iotf.sample.devicemgmt.device.SampleRasPi DMAgent. Program will exit.

    What can the problem be ?

    • Recipes@IoTF November 23, 2015

      Your java version is not compatible with the library. As mentioned in the requirement section, please try using Java7 and later. We recommend to use JDK8. Let me know if you still face any issues.

      • Thank you very much! I thought I had installed it, but raspberry pi for somehow preferred version 6.

        But now I got another problem:

        Starting sample DM agent…
        Trying to look for the default properties file :: DMDeviceSample.properties
        Found one in – /home/pi/DMDeviceSample.properties
        {Device-ID=XXXX, Device-Type=XXXX, Organization-ID=play, Authentication-Method=token, Authentication-Token=XXX}
        Org ID = play
        Client ID = XXXXXXX
        Client Username = use-token-auth
        Client Password =XXXXXXX
        Nov 23, 2015 5:00:45 PM com.ibm.iotf.client.AbstractClient connect
        INFO: main: Connecting to ssl://play.messaging.internetofthings.ibmcloud.com:8883 (attempt #1)…
        Nov 23, 2015 5:00:57 PM com.ibm.iotf.client.AbstractClient connect
        INFO: main: Connecting to ssl://play.messaging.internetofthings.ibmcloud.com:8883 (attempt #2)…
        Nov 23, 2015 5:01:08 PM com.ibm.iotf.client.AbstractClient connect
        INFO: main: Connecting to ssl://play.messaging.internetofthings.ibmcloud.com:8883 (attempt #3)…
        Nov 23, 2015 5:01:19 PM com.ibm.iotf.client.AbstractClient connect
        INFO: main: Connecting to ssl://play.messaging.internetofthings.ibmcloud.com:8883 (attempt #4)…
        Connect already in progress (32110)
        at org.eclipse.paho.client.mqttv3.MqttAsyncClient.connect(MqttAsyncClient.java:470)
        at org.eclipse.paho.client.mqttv3.MqttAsyncClient.connect(MqttAsyncClient.java:457)
        at com.ibm.iotf.client.AbstractClient.connect(Unknown Source)
        at com.ibm.iotf.client.device.DeviceClient.connect(Unknown Source)
        at com.ibm.iotf.devicemgmt.device.ManagedDevice.connect(Unknown Source)
        at com.ibm.iotf.sample.devicemgmt.device.SampleRasPiDMAgent.connect(Unknown Source)
        at com.ibm.iotf.sample.devicemgmt.device.SampleRasPiDMAgent.main(Unknown Source)
        Nov 23, 2015 5:01:20 PM com.ibm.iotf.client.AbstractClient connect
        INFO: main: Connecting to ssl://play.messaging.internetofthings.ibmcloud.com:8883 (attempt #5)…
        Nov 23, 2015 5:01:30 PM com.ibm.iotf.client.AbstractClient waitBeforeNextConnectAttempt
        INFO: main: 5 consecutive failed attempts to connect. Retry delay set to 10000ms

        • Recipes@IoTF November 24, 2015

          Looks like there is an issue with your device credentials or connection parameters. Are you sure the device is already registered in your organization “play” and the credentials are correct? Can you please email me the following details?

          1. Organization ID
          2. Device Type
          3. Device ID
          4. Authentication Token
          5. API key and API Token of the organization

          Please email the details to iosuppor@in.ibm.com. We are very happy to help you out. Thanks !

Join The Discussion