This offer is only addressed to commercial customers including freelancers and entrepreneurs. All prices exclude all taxes.
Subscribe Find out first about new and important news
  • Share via email
  • Subscribe to blog alert

Connecting a simple device to the Bosch IoT Suite

What you will learn to do

Learn how to create a ESP8266 based device prototype and connect it to Bosch IoT Things via MQTT and Bosch IoT Hub. This tutorial will take your approximately 3 hours after installing all necessary software.

What you will need

Prepare the following hardware and software

What you need to do

You will have to

Building your hardware device

Before working on the hardware make sure to unplug it from any power source. In the example setup below we use a NodeMCU v2 and a 400 point breadboard. Feel free to replace them with any other ESP8266 based device and a fitting breadboard size.

Connect your illuminance sensor to the device as pictured below:

Connection schema for hardware setup.

This image was created with Fritzing and is licensed under Creative Commons Attribution-ShareALike 3.0 Unported. See http://creativecommons.org/licenses/by-sa/3.0/ for the full description.


Booking and configuring the Bosch IoT Suite for Asset Communication package

In this section, you will book the necessary services, configure a namespace for your things (digital twins) and create and configure a technical OAuth2.0 client to ease access to the Bosch IoT Suite’s APIs.

  1. Go to Bosch IoT Suite and create a Bosch IoT Suite account, if not already done.

    In the process you will create or reuse an existing Bosch ID. This is Bosch’s unified user ID including Single-Sign-On functionality. You can use it for many Bosch applications.

  2. Book the Bosch IoT Suite for Asset Communication package by clicking on New Subscription and following the subscription wizard.

    It includes:

    • Bosch IoT Hub service instance
    • Bosch IoT Things service instance
    • both already fully pre-configured to integrate with each other
    • the unified Device Provisioning API for simplified device registration

    This tutorial will refer to it as Asset Communication package.
    Provisioning your service should only take a few moments

  3. Configure your unique Bosch IoT Things namespace by following these steps:
    1. Click on Dashboard next to your Asset Communication package subscription to open the Things UI.
    2. A new tab will open up and after the automatic login you will be able to click on the Namespace tab.
    3. Register a new globally unique namespace. Use java package notation, e.g. your.things.namespace .

      The namespace is used as a unique prefix for all your thing IDs to make the thing Ids globally unique.

    Screenshot of Things UI while creating a new namespace.

  4. Create an OAuth2.0 client with full access to Bosch IoT Things and Bosch IoT Hub by following these steps:
    1. Go back to the Bosch IoT Suite Portal.
    2. Click on the My Account icon on the upper right and select OAuth2.0 Clients.
    3. Click on New OAuth2.0 Client.
    4. Give this client a name, e.g., Asset Communication Client and select both the Hub and Things full access scopes from your Asset Communication package.
    5. Click the Create button.

      You can use this OAuth2.0 client in your application to authenticate it with many of the Bosch IoT Suite APIs as a technical client.

      In this tutorial you will mainly use a so called Test Token of this client to authenticate against all HTTP REST APIs. Please note that the Test Token is only valid for a few minutes each time you generate one.

  5. It takes a few moments to register you new OAuth2.0 client. Click the Refresh button to check wether its done.
  6. To generate a Test Token, click on the Use button next to your OAuth2.0 client:Screenshot of the OAuth2.0 client list

As a result, you should now have:

  • created a Bosch IoT Suite account
  • booked an instance of the Asset Communication package
  • created a unique Bosch IoT Things namespace
  • obtained an OAuth2.0 Test Token

Registering your device with the Bosch IoT Suite

You can now register your device with the Asset Communication package at the Device Provisioning API.
The numbers in the image refer to the following steps to be performed.

Screenshot showing the steps to provision a device

  1. Create your OAuth2.0 Test Token as described above and add it to the request by clicking on Authorize on the top right.
  2. Use the POST method on the provisioning resource.
  3. Click the Try it out button.
  4. Add your service instance id from your subscription credential details.
  5. Click the Edit button below the sample JSON payload.
  6. Edit the payload using the following template and replace everything in <pointy brackets>
    {
        "id": "<your.Things.namespace>:<your-device-id-4711>",
        "hub": {
            "device": {
                "enabled": true
            },
            "credentials": {
                "auth-id": "<your-device-id-4711>",
                "type": "hashed-password",
                "secrets": [
                    {
                    "password": "<your-device-password>"
                    }
                ]
            }
        },
        "things": {
            "thing": {
                "attributes": {
                    "manufacturer": "<Your awesome company>"
                }
            }
        }
    }
  7. Hit Execute to run your API call and register your device.
    You should get a response with the code HTTP 201 Created and a payload reflecting the device you just registered. Remember your device password!

    If you get a HTTP 401 response your Test Token is has probably reached its validity time of a few minutes. Generate a new token by clicking on Use on your OAuth2.0 client list

Generating the boilerplate code for your firmware

In the next step, you will generate a lot of the Bosch IoT Suite related boilerplate code using a Vorto Code Generator.

Vorto is an open source Eclipse IoT Community project, that aims to support standardization in the Internet of Things by creating a language, a repository and a number of code generators for device descriptions.

  1. Go to https://vorto.eclipse.org and search for:
    SimpleIlluminence
  2. Select the SimpleIlluminance information model with the com.bosch.iotacademy.demo namespace.
  3. Select the Bosch IoT Suite plugin from the list of Official Plugins on the right, select the Arduino (ESP8266) option and hit Generate Code. This will start a download of a Arduino project file.
    Visualization for click through Arduino code generation
  4. Extract and open the resulting download in your Arduino IDE.
  5. In your Arduino IDE do the following:
    1. Import the pubsubclient library using the Arduino library manager.
    2. Go to pubsubclient.h header file and change the MQTT_MAX_PACKET_SIZE to 1024.
      1. On Windows and Mac you can ususally find the file in the folder %USERPROFILE%/Documents/Arduino/libraries/PubSubClient/src/.
      2. On Linux it might be in the folder /home/<username>/Sketchbook/libraries/PubSubClient/src/.
    3. Connect your prototyping board to your laptop via USB.
    4. Make the following settings in your Arduino IDE:
      1. Under Tools -> Board select your ESP8266 prototyping board. (e.g. NodeMCU 1.0). If you can’t select any EP8266 based board you have not installed the ESP8266 Core for Arduino.
      2. Again in Tools -> Port select the port your board has registered with. Refer to Troubleshooting.
      3. (Optional but recommended) change the upload speed to the highest setting.

Configuring the firmware code for your prototype device

Configure your device firmware in the first 50 lines with the following details (replace everything in <pointy brackets>)

  • From Asset Communication subscription credentials:
    tenantId: "<your Bosch IoT Hub's tenant id, looks like "txxxxxxxxxxxxxxxxxxxx">"
    hono_endpoint: "mqtt.bosch-iot-hub.com"

  • The SHA-1 server fingerprint of the Bosch IoT Hub MQTT adapter.
    mqttServerFingerprint: "A0 DB E1 EA 2A 53 70 25 85 69 18 96 A3 41 2E 54 F5 96 DB 2B"
  • From your device provisioning request:
    deviceId: "<your.namespace>:<your-device-id-4711>"
    authId:  "<your.namespace>_<your-device-id-4711>"
    device_password: "<your-device-secret>"
    
    ditto_topic: "<your.namespace>/<your-device-id-4711>"
  • Your WiFi details go here:
    ssid: "<ENTER YOUR WIFI SSID>"
    password: "<ENTER YOUR WIFI PASSWORD>"

Adapting the firmware to send real data

Arduino sketches have two main functions:

  • setup() is run by the framework once on startup, after bootloading is complete.
  • loop() will be run repeatedly as soon as setup is done, with small interruptions for system tasks.
  1. In setup() you will need to initialize the illuminance sensors initial and default values. Add at the end of setup():
    setup() {
    
        ...
    
        /* minimum measured value since last reboot */
        infoModel.illuminance.setminMeasuredValue(1024);
        /* maximum measured value since last reboot */
        infoModel.illuminance.setmaxMeasuredValue(0);
        /* default values for analog GPIO A0*/
        infoModel.illuminance.setminRangeValue(0);
        infoModel.illuminance.setmaxRangeValue(1024);
        /* unscientific but accurate unit description */
        infoModel.illuminance.setsensorUnits("out of 1024 parts");
    }
    
  2. In loop() you will need to read the current illuminance sensor reading, set the illuminance message payload accordingly and publish the data. Replace the loop() function with:
    void loop() {    
        /* Check if connection to MQTT broker is still good */
        if (!mqttClient.connected()) {
            /* Reconnect if not */
            reconnect();
        }
    
        /* Event handling of the MQTT client */
        mqttClient.loop();
    
        /* Publish the telemetry data periodically */
        long now = millis();
        if (now - lastMqttMsg > MQTT_DATA_PERIOD) {
            lastMqttMsg = now;
    
            /* Read the values from input pin */
            int illuminanceValue = analogRead(A0);
            delay(3); //walk-around a bug in NodeMCU
    
            /* current value */
            infoModel.illuminance.setsensorValue(illuminanceValue);
    
            /* minimum value measured since last reboot */ 
            if (illuminanceValue<infoModel.illuminance.getminMeasuredValue()) {
                infoModel.illuminance.setminMeasuredValue(illuminanceValue);
            };
    
            /* maximum value measured since last reboot */
            if (illuminanceValue>infoModel.illuminance.getmaxMeasuredValue()) {
                infoModel.illuminance.setmaxMeasuredValue(illuminanceValue);
            };
    
            /* publish data to MQTT endpoint */
            publishIlluminance();
        }
    }
  3. Compile and upload the firmware to your prototyping device.
  4. Open the serial monitor to check for debug information. If you get unreadable output change the baud rate of the serial monitor to 115200

Screenshot of serial monitor settings

Checking your work

On your serial monitor you should see output like this:

Connecting to WiFi 
........................
WiFi connected
IP address: 123.123.123.123
MAC address: XX:XX:XX:XX:XX:XX
Device ID: com.bosch.iotacademy.demo:my-device-id-4711
Successfully established secure connection to broker
Successfully verified server certificate
Succesfully connected to MQTT Broker
Publishing Payload for illuminance: {"topic":"com.bosch.iotacademy.demo/my-device-id-4711/things/twin/commands/modify","headers":{"response-required": false},"path":"/features/illuminance","value": { "properties": {"status": {"SensorValue": {"currentMeasured": 723.00,"minMeasured": 723.00,"maxMeasured": 723.00,}},"configuration": {}}}} to topic: telemetry/txxxxxxxxxxxxxxxxxxxxxxxxx_hub/com.bosch.iotacademy.demo:my-device-id-4711
...

Check your updated digital twin in the Bosch IoT Things API.
For this, create a new Test Token, if the previous one is expired (every a few minutes) by clicking on Use on your OAuth2.0 client list.
The numbers in the image refer to the following steps to be performed.

Screenshot showing the steps to get a thing by thing Id

  1. Add your Test Token to the request by clicking on Authorize on the top right and pasting it in the bearer Auth form.
  2. Use the GET method on the Things resource.
  3. Click the Try it out button.
  4. Add your thing ID like <your.namespace>:<your-device-id-4711> to the thingId field.
  5. Hit Execute to run your API call. You should get a response with the code HTTP 200 OK and a payload reflecting your thing with the updated values for your sensors:
    {
        "thingId": "com.bosch.iotacademy.demo:my-device-id-4711",
        "policyId": "com.bosch.iotacademy.demo:my-device-id-4711",
        "attributes": {
            "manufacturer": "your awesome company Inc."
        }
        "features" : {
            "illuminance": {
                "properties": {
                    "status": {
                        "sensorValue": 913,
                        "minMeasuredValue": 589,
                        "maxMeasuredValue": 1024,
                        "minRangeValue": 0,
                        "maxRangeValue": 1024,
                        "sensorUnits": "out of 1024 parts"
                    },
                "configuration": {}
                }
            }
        }
    }

Troubleshooting

If your Arduino IDE is behind a (corporate) proxy

  • If you can’t download the list of additional boards, you might need to setup your proxy in the Arduino IDE. Go to File -> Preferences -> Network and setup your proxy accordingly.
  • If now you can find ESP8266 board plugin, but downloading doesn’t work and gives you an SSL error, you might be behind a TSL terminating proxy. You will need to add your proxy’s SSL certificate to your Arduino IDE’s shipped Java truststore, or simply replace the truststore with your systems Java truststore.To do that replace the cacerts file in
    <path_to_arduino_ide>/java/lib/security/cacerts

    with

    <path_to_java_home>/lib/security/cacerts

If your device is behind a proxy

This is currently not supported by the ESP8266 Core libraries. Your device needs to be connected through a proxy-free environment.

How to find the right serial port

Arduino IDE doesn’t discover the correct port for the ESP8266 based boards automatically. You need to set it using the Tools -> Port menu. To find what to set it to check the descriptions below:

Windows:

  • Find the COM port number in the Windows Device Manager
  • Screenshot showing the windows device manager with USB COM port numbers
  • If your prototyping board shows up with a yellow exclamation mark you might need to install the driver for it manually. You can find the driver for the NodeMCU on their website

Serial monitor displays “Secure connection failed, restart Device”

Make sure you have installed version 2.4.1 of the ESP8266 Core in Tools -> Board ->Boards Manager

Screenshot of Arduino IDE Boards Manager with ESP8266 Core version 2.4.1 installed

Serial monitor displays “Verification failed, restart Device”

Make sure you are using the correct SHA-1 fingerprint and version 2.4.1 of the ESP8266 Core

Cookie Information

This website uses cookies for reasons of functionality, comfort, and statistics. If you consent to this use of cookies, please click ”Ok“. If you like to disable the cookies for webtracking, please click here. For more information see our Privacy Policy