Overview

Skill Level: Beginner

Beginner

Introduction The Internet of Things (IoT) is radically changing the way businesses operate by unlocking hidden value in unconnected machines. Connectivity is critical in generating intelligence, but not all devices connect directly to the internet as they may use different kinds of radio technology to transmit data. Essentially the Gateway acts as a bridge between […]

Step-by-step

  1. Introduction

     

    The Internet of Things (IoT) is radically changing the way businesses operate by unlocking hidden value in unconnected machines. Connectivity is critical in generating intelligence, but not all devices connect directly to the internet as they may use different kinds of radio technology to transmit data. Essentially the Gateway acts as a bridge between the IoT devices and the Internet beyond. i.e. Simple devices (in terms of processing, memory, and communication cost) connect to a Gateway over Zigbee or another low-power radio network, Gateway then store and parse the information and then send them over to cloud servers for processing and analytics.

     

    IBM Watson IoT Platform and Gateway support

    The IBM Watson Internet of Things Platform is a fully managed, cloud-hosted service that makes it simple to derive value from Internet of Things (IoT) devices. When combined with the IBM Bluemix platform, Watson IoT Platform provides simple, but powerful application access to IoT devices and data. You can rapidly compose analytics applications, visualization dashboards, and mobile IoT apps. Create IoT applications that feed insights to your backend enterprise applications.

     

    Gateways are a specialized class of devices in Watson IoT Platform which serve as access points to the Watson IoT Platform for other devices. Gateway devices have additional permission when compared to regular devices and can perform the following functions:

    • Register new devices to Watson IoT Platform
    • Send and receive its own sensor data like a directly connected device,
    • Send and receive data on behalf of the devices connected to it
    • Run a device management agent, so that it can be managed, also manage the devices connected to it

    Refer to the documentation for more information about the Gateway support in Watson IoT Platform.

     

  2. What is demonstrated in this recipe?

    The Gateway support is demonstrated in this recipe by connecting the Arduino Uno to Raspberry Pi where the Raspberry Pi act as a Gateway and publishes events/receives commands on behalf of Arduino Uno to IBM Watson IoT Platform.

    Don’t have hardware?

    If you do not have Raspberry Pi and Arduino UNO, dont worry, you can still follow the recipe to connect your device as a gateway and serve as access points to the Watson IoT Platform for other devices. In this case, you can use your Windows or Linux server as the gateway instead of Raspberry Pi. Also, the sample has a simulator in place of Arduino UNO that will act as an attached device.

    Jump to the section “Register your Gateway in IBM Watson IoT Platform“, in case if you don’t have the hardware as the following sections explain about the hardware connectivity and serial communication between the Raspberry Pi and Arduino UNO.

    Configuration with hardware

    The following configuration is used in this recipe to demonstrate the gateway support,

    The Arduino Uno will read the signal from PIR sensor along with the internal temperature sensor every moment and send these readings to Raspberry Pi, upon receiving the sensor readings, Raspberry Pi Gateway will publish the same to Watson IoT Platform through MQTT. A sample application (running outside of Raspberry Pi and Arduino Uno), written in Java, will process these sensor readings by subscribing to IBM Watson IoT Platform. And when the application observes a movement detection, it will send a command back to Arduino through the Watson IoT Platform and Raspberry Pi Gateway to blink the LED. The same is illustrated in the below diagram,

    Also, the sample application allows one to blink the LED for a specified number of times by sending the command at any moment. For example, one can send a command to blink the LED for 10 times regardless of whether the movement is detected by the PIR sensor or not.

    If you do not have PIR sensor and LED, don’t worry, you can still follow the recipe to see how the Gateway (Raspberry Pi) sends the internal temperature of the Arduino Uno to Watson IoT Platform and receive commands on behalf of Arduino Uno. You can still observe the blink near PIN 13 when the sample application sends a command to blink the LED.

    Following samples are used in the recipe to demonstrate the Gateway support,

    1. Device sample – to be run on Arduino Uno, written in C, that sends/receives data to/from the Raspberry Pi Gateway. Also controls the sensor.
    2. Gateway sample – to be run on Raspberry Pi, written in Java, that connects the Raspberry Pi and Arduino Uno to IBM Watson IoT Platform.
    3. Application sample – to be run on a server environment (Windows platform in this case), written in Java that processes the Arduino Uno events and sends the LED blink command back to Arduino Uno through Watson IoT Platform.

    these samples are explained in detail in the below sections.

  3. Connect PIR sensor and LED to Arduino

    Connect PIR (movement) Sensor and LED actuator to the Arduino UNO.

    Connect PIR sensor

    The PIR sensor acts as a digital output so all we need to do is, listen for the pin to flip high (detected) or low (not detected). The PIR sensor has 3 pins, namely, +, -, and output.

    Connect + to 5v, – to ground and output to any available digital PIN using the jumper wires and breadboard as shown in the below diagram. In this example we connect the output to PIN 2.

    Connect LED

    The LED actuator has 2 pins, namely, ground and power. Connect ground to ground, power to PIN 13 and place the 330 ohm resister in between the ground as shown in the diagram below,

    At this step we have successfully connected the PIR (movement) Sensor and LED actuator to the Arduino UNO.

  4. Program Arduino Uno

    Connect Arduino Uno to your computer using the micro USB cable and upload the sketch to perform one or more operations.

    In order to program Arduino Uno we need to download and setup the Arduino IDE. Go through this tutorial for setting up the Arduino Software (IDE) on your computer.

    In this section, we will show the sketch code to read/write data from/to the sensors attached to Arduino Uno individually and then upload the entire code to Arduino Uno.

    Sketch to read PIR sensor value

    void setup() {
    Serial.begin(9600);
    pinMode(2,INPUT); // PIR sensor reading
    }

    void loop() {
    char val[10];
    int buttonState = digitalRead(2);
    itoa(buttonState, val, 10);
    Serial.println(val);
    }

    As shown, the sketch reads the signal coming in from the PIR sensor on PIN 2 and writes the same into the serial port so that the Raspberry Pi can consume the same. Upload this sketch code to Arduino Uno to view the PIR readings on the Serial Monitor of Arduino IDE. Try to block the PIR sensor to change the readings from 0 to 1.

    Sketch to read internal temperature sensor

    Most new AVR chips used in the Arduino have an internal temperature sensor. This is helpful to demonstrate the Gateway support for people who don’t have the PIR sensor. The following sketch code can be used to read the temperature sensor value,

    void setup() {
    Serial.begin(9600);
    }

    void loop() {
    char val[10];
    dtostrf(getTemp(),1,2, val);
    Serial.println(val);
    }

    /*
    This function is reproduced as is from Arduino site => http://playground.arduino.cc/Main/InternalTemperatureSensor
    */
    double getTemp(void) {
    unsigned int wADC;
    double t;
    ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3));
    ADCSRA |= _BV(ADEN); // enable the ADC
    delay(20); // wait for voltages to become stable.
    ADCSRA |= _BV(ADSC); // Start the ADC
    // Detect end-of-conversion
    while (bit_is_set(ADCSRA,ADSC));
    // Reading register "ADCW" takes care of how to read ADCL and ADCH.
    wADC = ADCW;
    // The offset of 324.31 could be wrong. It is just an indication.
    t = (wADC - 324.31 ) / 1.22;
    // The returned temperature is in degrees Celcius.
    return (t);
    }

    Again upload this sketch to Arduino to view the temperature on the Serial Monitor of Arduino IDE.

    Sketch to blink LED

    As shown below, the sketch powers the LED by writing on PIN 13 when it receives a non-zero value from Raspberry Pi.

    void setup() {
    Serial.begin(9600);
    pinMode(13,OUTPUT); // LED actuator
    }

    void loop() {
    if (Serial.available()) {
    int value = Serial.parseInt();
    blink(value);
    }
    }

    // code to blink the LED for n times
    void blink(int n){
    for (int i = 0; i < n; i++) {
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);
    }
    }

    As shown in the sketch, the Arduino reads the blink command from the serial port and toggles the PIN 13 from HIGH to LOW to blink the LED for the specified number of times.

    Upload the combined Sketch

    The complete sketch code that combines all 3 operations is available here. Upload this code into Arduino Uno using the IDE and observe that the Arduino Uno sends the PIR and temperature readings in the following format that is expected by Raspberry Pi Gateway,

    <event name> <comma separated sensor readings>

    for example, status temp:35.22,pir:0.

    In this step, we have seen how to read PIR sensor, read internal temperature and blink LED through the sketch code. Then uploaded the combined Sketch code to Arduino Uno.

  5. Connect Arduino Uno to Raspberry Pi

    Connect Arduino Uno to Raspberry Pi using the USB cable.

    There are many ways of connecting the Raspberry Pi and Arduino, such as using the GPIO and Serial pins and using I2C. But connecting through the USB cable is one of the easiest way to get them talking, because hardware that required is minimal: all you will need is a micro USB cable that comes with the Arduino.

    Ideally the Arduino Uno connects to Raspberry pi using the port “/dev/ttyACM0”. However the port might change at times, to find the exact port, run the following command in Raspberry Pi without the Arduino Uno plugged in:

     ls /dev/tty*

    Now plug in your Arduio Uno and run the command again. If a new name appears, then this is the name of your port. If the port is different from /dev/ttyACM0, make a note of it, we need to pass the same while running the Gateway sample.

    In this step, we have successfully connected Arduino to Raspberry Pi Using the micro USB cable.

  6. Program Raspberry Pi to do Serial Communication

    Program Raspberry Pi to write/read data to/from the Arduino Uno using the RXTX library.

    In the previous section we saw how Arduino writes and reads the data to or from the serial port. In this section we will see how to use the Java RXTX library for serial communication with Raspberry Pi Gateway to read/write the data from/to Arduino Uno. In order to use the RXTX library, we need to install the library on Raspberry Pi using the following command:

    sudo apt-get install librxtx-java

    Observe that the following files are installed,

    • /usr/lib/jni/librxtxSerial.so
    • /usr/share/java/RXTXcomm.jar

    At high level, the sample does the following to read and write data from Arduino Uno using the the RXTX library.

    Initialize the Port

    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
    // Enumerate system ports and try connecting to Arduino over each
    while (portEnum.hasMoreElements()) {
    CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
    if (currPortId.getName().equals(PORT_NAME)) {
    portId = currPortId;
    break;
    }
    }

    As shown, the sample iterates through all of the system ports looking for a match for the Arduino Uno, and then attempts to connect to it.

    Connect to Serial Port

    The sample then connects to the port, configures the communication parameters, like the bit rate, timeout and etc.. as shown below,

    // open serial port, and use class name for the appName.
    serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000);
    // set port parameters
    serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

    // open the streams
    input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
    output = new BufferedWriter(new OutputStreamWriter(serialPort.getOutputStream()));

    Also, opens the input and output streams to read and write data to/from the Arduino Uno.

    Read data from Arduino Uno

    The sample then adds an event listener to receive events from the Arduino, and informs the library to call back when there’s data available

    // add event listeners
    serialPort.addEventListener(this);
    serialPort.notifyOnDataAvailable(true);

    // A sample event listener,
    public synchronized void serialEvent(SerialPortEvent oEvent) {
    String line = null;
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
    try {
    line = input.readLine();
    System.out.println(line);
    } catch (Exception e) {
    System.err.println(e.toString());
    }
    }
    // Ignore all the other eventTypes, but you should consider the other ones.
    }

    As shown in the code the RXTX library calls the serialEvent() method when the data is available to read from the serial port. This is where the Raspberry Pi gets the sensor readings (the PIR movement sensor and the internal temperature) from Arduino. One can add a logic to process the data, convert it to the form expected by IBM Watson IoT Platform and send it to Watson IoT Platform. The sample code has the logic to do the same. (this will be explained in the later section of this recipe)

    Write the command to Arduino Uno

    In order to send data to Arduino Uno (blink LED), the sample uses the output stream that we opened earlier and writes the data as shown below,

    this.output.write("<number of times to blink LED>");

    Things to note down

    On Raspberry Pi, the RXTX library places its lock in the folder /var/lock. If this doesn’t exist, communication will not work, although you won’t receive any obvious errors as to why. To create this directory if missing, open the terminal application and create the lock directory as the root user or equivalent:

    sudo mkdir /var/lock

    In this step we have seen how Raspberry Pi reads/writes data to or from the Arduino Uno using the RXTX library.

  7. Register your Gateway in IBM Watson IoT Platform

    In order to demonstrate the Gateway support, we need to setup the Watson IoT Platform organization and register the Gateway in it. This section shows how you can setup the same.

    Carry out the steps present in this recipe to register your Gateway in IBM Watson Internet of Things Platform.

    At this step, we have successfully created the Watson IoT platform service and registered the Gateway in it.

  8. Program Gateway to Connect to Watson IoT Platform

    Program your Gateway to connect to Watson IoT Platform.

    In the previous sections we saw how Arduino and Raspberry Pi communicates using the serial port. In this section, we will see how to connect and interact the Gateway to IBM Watson IoT Platform. The Gateway sample used in this recipe is written using the Java Client Library for IBM Watson IoT Platform that simplifies the interactions with the IBM IoT Platform.

    At high level, the sample does the following to interact with Watson IoT Platform.

    Construct GatewayClient instance

    The Gateway sample uses the com.ibm.iotf.client.gateway.GatewayClient class from the IoTF Java Client Library that simplifies the Gateway interactions with IBM Watson IoT Platform. The createGatewayClient() method in the Gateway sample creates a GatewayClient instance by passing the required properties as shown below,

    Properties options = new Properties();

    options.setProperty("org", "<Your Organization ID>");
    options.setProperty("type", "<The Gateway Device Type>");
    options.setProperty("id", "The Gateway Device ID");
    options.setProperty("auth-method", "token");
    options.setProperty("auth-token", "API token");

    gwClient = new GatewayClient(options);

    Connect this Gateway to IBM Watson IoT Platform

    The next step is to connect the Gateway to the Watson IoT Platform by calling the connect function.

    gwClient.connect();

    After the successful connection to the Watson IoT Platform, the Gateway can perform the following operations,

    • Publish events for itself and on behalf of devices connected behind the Gateway
    • Subscribe to commands for itself and on behalf of devices behind the Gateway

    Register Arduino Uno to IBM Watson IoT Platform

    There are different ways to register the Arduino Uno device (which is connected to Raspberry Pi Gateway) to IBM Watson IoT Platform,

    • Auto registration: The device gets added automatically in IBM Watson IoT Platform when Gateway publishes any event/subscribes to any commands for the Arduino Uno device.
    • API: The Watson IoT Platform API can be used to register the Arduino Uno device to the Watson IoT Platform.

    This recipe adds the device using the IBM Watson IoT Platform API,

    Subscribe to Application Commands for Arduino Uno

    The Gateway can subscribe to commands directed at the Gateway itself and to any device connected via the gateway. When the GatewayClient connects, it automatically subscribes to any commands for this Gateway. But to subscribe to any commands for the devices connected via the Gateway, we need to use one of the overloaded subscribeToDeviceCommands() method,

    To receive and process the Arduino Uno commands, the Gateway sample does the following,

    • Adds a command callback method
    • Subscribes to commands for Arduino Uno
    GatewayCommandCallback callback = new GatewayCommandCallback();
    gwClient.setCommandCallback(callback);
    gwClient.subscribeToDeviceCommands(DEVICE_TYPE, ARDUINO_DEVICE_ID);

    Once the Command callback is added to the GatewayClient, the processCommand() method is invoked when it receives any command for Arduino Uno from Watson IoT Platform. The Gateway CommandCallback defines a BlockingQueue to store and process the commands (in separate thread) for smooth handling of MQTT publish message as shown below,

    public class GatewayCommandCallback implements CommandCallback, Runnable {
    // A queue to hold & process the commands
    private BlockingQueue<Command> queue = new LinkedBlockingQueue<Command>();

    public void processCommand(Command cmd) {
    queue.put(cmd);
    }

    public void run() {
    while(true) {
    Command cmd = queue.take();
    JsonObject payloadJson = JSON_PARSER.parse(cmd.getPayload()).getAsJsonObject();
    payloadJson = payloadJson.get("d").getAsJsonObject();
    int value = payloadJson.get(LED_DATAPOINT_NAME).getAsInt();
    arduinoInterface.sendCommand(value);
    }
    }
    }

    Publish Arduino Uno Events to Watson IoT Platform

    Events are the mechanism by which devices and gateways publish data to the Watson IoT Platform, The sample uses one of the overloaded publishDeviceEvent() methods to publish the PIR and internal temperature readings to Watson IoT platform.

    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
    line = input.readLine(); // sensor readings from Arduino Uno

    String[] tokens = line.split(" ");

    String eventName = tokens[0];
    JsonElement event = new JsonParser().parse("{" + tokens[1] + "}");
    boolean status = this.gwClient.publishDeviceEvent(this.deviceType, this.deviceId, eventName, event);
    }

    As shown, the Gateway sample, prepares the sensor readings in JSON format and sends them to Watson IoT Platform.

    Publish Gateway Events to Watson IoT Platform

    While Raspberry Pi Gateway publishes events on behalf of the Arduino, the Raspberry Pi Gateway can publish its own events as well. The sample publishes a blink event every second, that has the CPU and memory utilization of this sample Gateway process.

     JsonObject event = new JsonObject();
    event.addProperty("name", SystemObject.getName());
    try {
    event.addProperty("cpu", obj.getProcessCpuLoad());
    } catch (Exception e) {
    e.printStackTrace();
    }
    event.addProperty("mem", obj.getMemoryUsed());
    gwClient.publishGWEvent("blink", event, 2);

     

    Refer to the Gateway section of the programming guide to know more about the list of operations that can be performed by the Gateway using the Java Client Library.

    In this step we have seen how to connect Gateway and its devices to Watson IoT Platform, publish events and subscribe to commands.

  9. Start Gateway Sample

    Connect your Gateway to Watson IoT Platform.

    1. Connect to your Gateway using SSH.
    2. Setup the Raspbian environment with Maven and Git, by installing them as follows:
      sudo apt-get update
      sudo apt-get install maven

      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
    3. Build the Gateway Sample from Github:
      1. Clone the gateway-samples project using git clone as follows:
         git clone https://github.com/ibm-messaging/gateway-samples.git
      2. Navigate to the gateway-samples project:
         cd gateway-samplesjavagateway-samples
      3. Run the maven build as follows:
         mvn clean package

        Please refer to the README on IoT Gateway Samples Github repository for details

    4. As we plan to register the attached device (in this case Arduino Uno or the simulator) via the IBM Watson IoT Platform API, we need the Organization’s API Key and Token. This can be achieved by carrying out steps present in this section – Generate API Key in Watson IoT Platform. Note down API Key and Authentication Token. We need these to register the Arduino Uno device in Watson IoT Platform and attach to Raspberry Pi gateway.
    5. Modify the gateway.properties file, present under target/classes directory structure, and enter the Gateway device registration details that you noted in the section Register your Gateway in IBM Watson IoT Platform “. Also, enter the API-Key and Token that you noted in Step 4, listed above.
      ## Gateway Registration detail
      Organization-ID = <Your Organization ID>
      Gateway-Type = <Your Gateway Device Type>
      Gateway-ID = <Your Gateway Device ID>
      Authentication-Method = token
      Authentication-Token = <Your Gateway Token>

      ## There are 2 ways to register the attached device to WIoTP. Manual or Automatic
      Registration-Mode = Manual

      ## Mandatory Organization API-Key and Token to create the device type
      API-Key = <Your Organization API-Key>
      API-Token = <Your Organization Token>

      Port = <Specify the port in which Arduino Uno connects to Raspberry Pi. Required only if the port is not /dev/ttyACM0>

      (Note: specify the port if Arduino Uno is not connected through port /dev/ttyACM0. Refer to section “Connect Arduino Uno to Raspberry Pi” to find the port in which Arduino Uno is connected to Raspberry Pi. But, its not required if you are running in simulator mode. I.e, you dont have the hardware)

    6. If required, set the library path where RxTx library is installed,
      export MAVEN_OPTS=-Djava.library.path=/usr/lib/jni 

      (Note that the /usr/lib/jni is the directory where the RxTX library is present. Not required if you are running in simulator mode)

    7. Go back to the root directory (Where you have the pom.xml file located), and run the Gateway sample using the following command:
       mvn exec:java -Dexec.mainClass="com.ibm.iotf.sample.client.gateway.SampleRasPiGateway"
    8. Observe that the Gateway connects to IBM Watson IoT Platform using the client ID of the form g:orgId:typeId:deviceId. The first character ‘g’ says that we are a gateway.
    9. Go to the Watson IoT Platform dashboard(Refresh if needed) and observe that Arduino Uno device is registered automatically with ID “Arduino01“. The device ID “Arduino01” is hardcoded in the sample code, and it gets added via the Watson IoT Platform API. This is the real power of Gateway and Watson IoT Platform, one can easily onboard the devices behind the Gateway without pre-registering it in Watson IoT Platform.
    10. Click on the Gateway01 row to view the events that are published by the Gateway itself,
    11. The individual sensor values can be observed by moving the page to Sensor Information section as shown below,
    12. As shown above, the CPU and Memory utilization of the Gateway process is sent as an event by the Gateway. Note that the Gateway can publish its own events as well.
    13. Scroll down further to view the attached devices for this Gateway, in this case we must see Arduino01 as the attached device,
    14. Click Arduino01 to observe the events from the Arduino Uno device,
    15. The individual sensor values can be observed by moving the page to Sensor Information section as shown below,
    16. As shown, the PIR and internal temperature values are sent by the Gateway on behalf of the attached device (Arduino Uno). Now block the PIR movement sensor and see the value changing from 0 to 1.

    In this section, we have successfully connected the Gateway and Arduino Uno to Watson IoT Platform. Also observed various sensor readings.

  10. Program Application

    Program an application to parse the sensor event and send blink command.

    So far we have seen how to send the sensor readings to Watson IoT Platform, in this step, we will see how to program an application to parse these readings and send a command back to blink the LED that is attached to Arduino Uno.

    At high level, the sample does the following to interact with Watson IoT Platform.

    Connect Application to IBM Watson IoT Platform

    The Application Sample uses the com.ibm.iotf.client.app.ApplicationClient class from the IoTF Java Client Library that simplifies the application interactions with IBM Watson IoT Platform. The createApplicationClient() method in the application sample creates an ApplicationClient instance and connects the application to IBM Watson IoT Platform by passing the required properties as shown below,

    Properties options = new Properties();

    options.setProperty(org, <Your organization ID>);
    options.put("id", "<The unique ID of your application within your organization>");
    options.setProperty(auth-method, apikey);
    options.put("API-Key", "<YOUR API KEY>");
    options.put("Authentication-Token", "<YOUR TOKEN>");

    myAppClient= new ApplicationClient(options);

    Connect Application to IBM Watson IoT Platform

    The next step is to connect the Application to the Watson IoT Platform by calling the connect() function.

    myAppClient.connect();

    After the successful connection to the Watson IoT Platform, the application can perform the following operations, like subscribing to device events, subscribing to device status, publishing device events and commands.

    Subscribe to Arduino Uno Events

    To receive and process the Arduino Uno events, the sample application does the following,

    • Adds an event callback method
    • Subscribes to Arduino Uno device Events

    The subscribeToEvents() method in the application sample adds a Event callback handler and subscribes to events from the Arduino Uno device as shown below,

     MyEventCallback r = new MyEventCallback(this);
    myAppClient.setEventCallback(r);
    myAppClient.subscribeToDeviceEvents(DEVICE_TYPE, ARDUINO_DEVICE_ID);

    The callback method processEvent() is invoked by the ApplicationClient when it receives any event for Arduino Uno from Watson IoT Platform. The Event Callback class defines a BlockingQueue to store and process the events (in separate thread) for smooth handling of MQTT publish message as shown below,

    class MyEventCallback implements Runnable, EventCallback {
    private BlockingQueue<Event> queue = new LinkedBlockingQueue<Event>();

    public void processEvent(Event event) {
    queue.put(event);
    }

    public void run() {
    while(true) {
    Event event = queue.take();
    String payload = event.getPayload();
    JsonObject payloadJson = JSON_PARSER.parse(payload).getAsJsonObject();
    JsonObject content = payloadJson.get("d").getAsJsonObject();
    int value = content.get(PIR_DATAPOINT_NAME).getAsInt();
    if(value != 0)
    app.sendBlinkCommand(value);
    }
    }
    }

    Send blink Command to Arduino Uno

    The sample application sends a blink command to Arduino Uno,

    • Whenever it receives a positive value in the PIR sensor reading (when movement is detected)
    • And whenever the user wants it
    JsonObject cmd = new JsonObject();
    cmd.addProperty(LED_DATAPOINT_NAME, value);
    myAppClient.publishCommand(DEVICE_TYPE, ARDUINO_DEVICE_ID, COMMAND_NAME, cmd, 2);

    As shown in the above code, the application sends the blink command to the Arduino Uno and the same will be received by the Raspberry Pi Gateway as the Gateway sample running on Raspberry Pi subscribes to all the commands for the Arduino Uno device (Explained in section “Program Gateway to Connect to Watson IoT Platform”).

    Refer to the application section of the programming guide to know more about the list of operations that can be performed by the application using the Java Client Library.

    In this step, we seen seen how to create a sample java application to connect to Watson IoT platform, read device events and send command back to the device.

  11. Start Application Sample

    Start the command-line application sample written in Java that will send the LED blink command.

    Generate API Key and Token of Watson IoT Platform

    In order to connect application(s) to IBM Watson IoT Platform, you must generate the API key and token. This can be achieved by carrying out steps present in this section – Generate API Key in Watson IoT Platform.

    Note down the Key and Token, We need these to connect the application to Watson IoT Platform.

    Start the application sample

    1. Continue to use the Gateway Sample build, we built in the earlier section Start Gateway Sample “, using Maven.
    2. Modify the application.properties file, located under target/classes, by entering your Organization ID, API Key and Authentication Token of the application as follows:

      id = <Unique application id>
      Organization-ID = <Your Organization ID>
      Authentication-Method = apikey
      API-Key = <Your Organization's API Key>
      Authentication-Token = <Your Organization's Token>
      Device-Type = iotsample-deviceType
      Device-ID = Arduino01

      (Note 1: The “id” accepts a value which has to be a ‘Unique application id‘. Any Random number will do, to get started)
      (Note 2: the Device-Type should be iotsample-deviceType and Device-ID must be Arduino01 if you have not modified the Gateway sample to register the Arduino Uno in different id)

    3. Run the application sample by specifying the following command:
      mvn exec:java -Dexec.mainClass="com.ibm.iotf.sample.client.application.SampleApplication"
    4. Observe that the application connects to IBM Watson IoT Platform and prints the following message in the console, “Enter any valid number anytime to turn the LED blink”
    5. Enter a number, say 10 in the console and observe that the LED attached to Arduino Uno blinks for 10 times. If you don’t have LED attached, you can still observe the blink near PIN13.
    6. Block the PIR movement sensor now and observe that the LED blinks for sometime.

    In this section, we have successfully sent the blink command to Arduino Uno using a sample Java Application.

  12. Conclusion

    In this recipe we demonstrated the Gateway support using the Java Client Library for IBM Watson 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 Gateway development in IBM Watson IoT Platform.

  13. Where to go from here?

     

    1. Go through Gateway Device Management recipe to connect your gateway as managed Gateway and manage one or more attached devices using the IBM Watson IoT Platform DM protocol.
    2. Go through the Node-RED recipe to receive your Gateway and attached device events to Node-RED application.
    3. Go through list of Analytical and Cognitive recipes to analyze IoT events published to Watson IoT Platform.

3 comments on"Connect your Device as Gateway to Watson IoT Platform"

  1. But I wonder if it’s possible to connect through DNS?

  2. Ravinder544 July 05, 2017

    i have followed all the steps in the receipe.
    But at step 11 when i execute SampleApplication, it ask for “Enter any valid number anytime to turn the LED blink” and when i give a integer value it shows output but LED light does not blink.
    Please Help me out

Join The Discussion