Connecting Salesforce To Renesas IoT Sandbox

This tutorial uses the Renesas S3A7 IoT Fast Prototyping Kit with the Renesas IoT Sandbox powered by the Medium One Cloud to connect to your Salesforce.com platform. This tutorial extends the current Smart Garage Monitoring Guide by integrating it with Salesforce.com. When a case is created in Salesforce, a ticket is sent to Renesas IoT Sandbox. Device data is gathered and posted back to the Salesforce’s case automatically.

In this tutorial, you will understand how data is transferred between the Renesas IoT Sandbox powered by Medium One cloud, and Salesforce.com platform. You will create a ‘case’ in the salesforce environment and view this event via datastream in Renesas IoT Sandbox. Additionally, you will use the attached S3A7 kit to collect board data such as device name, it’s IP address, temperature and humidity, and populate this information in the salesforce.com case’s comment field.

Prerequisites:

  • Smart Garage Monitoring Guide tutorial
  • The hardware from Smart Garage Monitoring Guide tutorial:
    • AMS sensor attached to J18 port
    • Bosch sensor attached to J5 port on S3-A7 kit
  • IMPORTANT: You will need the activation email containing the credentials (device’s API key and API password) from your Smart Garage Monitoring Guide tutorial

 

Step 1: Log into your Smart Garage project on Renesas IoT Sandbox

This tutorial builds on the Smart Garage Monitoring Guide tutorial.  You’ll need to complete the Smart Garage Monitoring Guide tutorial, and only then continue with this tutorial.  

You can start a new Smart Garage Monitoring Guide Tutorial here to redo, or review as a refresher. Make sure your board is powered.

Important: You will need your original welcome email with your credentials from your Smart Garage tutorial; specifically, your device’s API key, and  API password. A sample welcome email is shown below:

Note: After finishing the Smart Garage Monitoring Guide tutorial, your board’s display should look similar to the following picture:

 

Step 2: Create a Salesforce.com free developer account

Sign up for a free developer salesforce account at: https://developer.salesforce.com/signup

Enter all required data and click “Sign me up” to create account.

Note: You will receive a welcome ‘Your Developer Edition Login Information’ email from salesforcedevs.com stating your user name and asking you to set your password. Follow through these instructions.

Once you have created your developer account, you will need to configure your account to connect it to the Renesas IoT Sandbox environment; this is shown in the following step.

 

Step 3: Setup and Configure Salesforce.com

Enable Apex Permissions in Salesforce

a.  Salesforce Viewing Mode (Lightning or Classic)

If you see a salesforce page similar to the following, you are in the new Salesforce Lightning Experience mode. Switch to Salesforce Classic mode by selecting the person icon in the upper right and then click on Switch to Salesforce Classic.

If you are already in Salesforce Classic mode, go to (b).

 

 

You will be switched to Classic Mode and see the following view.  Click on “Setup” in the top righthand corner.

 

 

b.  System Administrator Mode

Setup will open up the Administer page.  Look for System Administrator under Recent Items and click on it.

 

If you don’t find it, go to “Administer” -> “Manage Users” -> “Profile” in the sidebar.

 

Under Profiles, you should find System Administrator.  Click on it.

 

 

The ‘System Administrator’ profile page will appear as shown below.

 

Now scroll down and check that the Author Apex permission is enabled.

 

Add Renesas IoT Sandbox to Approved Sites

Click on “Setup” in the upper righthand corner on Salesforce.com.  Go to the quick find box on the left-hand side, type in “remote.” Under “Security Settings”, click on “Remote Site Settings.”

 

You will see the Remote Site page.  To add Renesas Sandbox as a new remote site, click on New Remote Site.

 

 

Add remote site URL to “https://api-renesas-na-sandbox.mediumone.com

Click Save.

Create Apex Classes

From the Salesforce Developer Force Homepage you should see your name next to the Setup button on the top right hand corner. Click on your name, then click on Developer Console underneath it.

 

A new window should open. Click on File → New → Apex Class. Name the class “M1”.

Replace the existing code by copying and pasting the following into the window, replacing <DEVICE_PASSWORD> with the API basic user’s password, <API_KEY> with your API key from the email described in Step 1.

public class M1 {
    private static String user_id='device';
    private static String password='<DEVICE_PASSWORD>';
    private static String api_key ='<API_KEY>';

    @future(callout=true)
    public static void send_data(String event){
        String url = 'https://api-renesas-na-sandbox.mediumone.com/v2/login/?no_cookies';
        Http h = new Http();
        HttpRequest req = new HttpRequest();     
        JSONGenerator gen = JSON.createGenerator(false);
        gen.writeStartObject();
        gen.writeStringField('login_id', user_id);
        gen.writeStringField('password', password);
        gen.writeStringField('api_key', api_key);
        String body = gen.getAsString();

        req.setBody(body);
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Accept', 'application/json');
        req.setEndpoint(url);
        req.setMethod('POST');
        HTTPResponse res = h.send(req);
        send_event_helper(event,res.getBody().removeStart('"').removeEnd('"'));
    }

            private static void send_event_helper(String val, String token){      
                        String url = 'https://api-renesas-na-sandbox.mediumone.com/v2/events/salesforce?token=' + token;
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        String body = '{"event_data":' + val + '}';
        req.setBody(body);
        req.setHeader('Content-Type', 'application/json');
        req.setEndpoint(url);
        req.setMethod('POST');
        HTTPResponse res = http.send(req);
        Integer status_code = res.getStatusCode();
        System.assertEquals(200, status_code);
     }
}

Go to File→ Save.

Now, you need to create the trigger. Go to File→ new → Apex Trigger.

Name the class “m1_trigger”. Choose the sObject to be ‘Case’ and Submit.

Copy and paste the following into the window:

trigger m1_trigger on Case (after insert, after update, after undelete) {
    for(Case c: Trigger.new){
        String event = JSON.serialize(c);
        M1.send_data(event);
    }
}

 

Click File ->Save.

You may now close the Force.com Developer Console window.

Now, whenever you create a new case, it will send case details to your Medium One account.

You have successfully created your test classes, and can deploy your code to production. For information on moving code from sandbox to production, click here.

Notes:

This APEX code snippet sends salesforce.com under the datastream called ‘salesforce’. If you would like to connect your production salesforce.com account (non developer), you’ll need to create APEX test code.  Refer to the Appendix A: for sample test code.

 

Step 4: Link Salesforce.com to Renesas IoT Sandbox

In Renesas IoT Sandbox, go to “Setup”  -> “External APIs.” Click “Add New Service Key”.

 

Select ‘salesforce’ from the drop down menu; then click “Save and Activate”.

If this is your first time logging to Salesforce account, you will need to allow access for Salesforce. Click ‘Allow”.

Lastly, a window will open up saying ‘Authentication successful. You may close this page.’

Now, you can post to and edit cases from M1 workflows.

Create salesforce stream on your Renesas IoT Sandbox project

In Salesforce.com, the created APEX code snippet sends salesforce.com under the datastream called ‘salesforce’. Now, we need to create and link this ‘salesforce’ datastream in Renesas IoT environment.

In Renesas IoT Sandbox,  go to “Config” -> “Data Streams”, then click on 

In Create New Data Stream, enter a new stream’s name to be ‘salesforce’; then click “Save Data Stream”.

 

Now, the ‘salesforce’ datastream is linked to collect all events between saleforce.com and Renesas IoT Sandbox.

Check Point

You can quickly check that your new environment is generated correctly by creating a case, and seeing its data stream created in Renesas Iot Sandbox environment.

In home page of Salesforce.com, click on “+” and then on “Cases”.

 

Create a new case by clicking on “New“.

 

Fill all required information (Account Name, Status, Case Origin, Subject, and Description) to “New Case” ; then click “Save”.

 

Note: If this is a new ‘Account Name’ that is not linked in your account profiles, you will quickly need to create it by clicking on magnifying glass, then on “New’ and entering all necessary info to the Account page; then click “Save”

 

By clicking “Save” on Creating a new case, we created a new event, which was sent to Renesas IoT Sandbox. Now, we can easily check if we have received this event by opening the DataViewer and checking the content of ‘salesforce’ datastream.

In Renesas IoT Sandbox, go to “Data Viewer” -> “Data Streams”. Click “View” on newly created ‘salesforce’ datastream.

 

If the creation of case in saleforce.com was successful, you will see the following log file in the data stream viewer:

 

You can expand the device’s log file from this event by clicking on ‘+’ sign:

NOTE: If no event appears, don’t continue and go back and make sure you follow all steps correctly.

 

Step 5: Sample Temperature and Humidity Data

In order to send a meaningful data to Salesforce, for the purpose of this tutorial, we will add a temperature and humidity monitoring workflows.

In this step, you will be creating a workflow that samples the temperature and humidity sensor data on the screen.  Make sure the sensor is attached to the board. Note, in this step, the data is still encoded and we will decode it in subsequent steps.

Create a new workflow and name it “Temperature and Humidity Sampling”. Drag the “raw” touched tag and the “raw” connected tag into the workflow. Select “Scheduler” from the Tags & Triggers menu and drag the Custom trigger into the workflow.

 

Double click on the Custom trigger and check the box next to “All Users” before clicking Save. Leave Minutely Interval to 10 (default).

Finally, drag a Base Python module into the workflow. Increase the number of inputs of Base Python’s module to three (in1, in2 and in3) and connect as shown in the following figure:

This workflow will trigger when one of these 3 things happen:

  • Once per minute
  • Connect event is received
  • Touched event is received

Once the Base Python is connected with its inputs, replace the script with the following code:

'''
This workflow requests the temperature and humidity from the board.
Last Updated: Sept 15, 2016
Author: Medium One
'''

import cloud_driver_ams
cloud_driver_ams.request_ams_temperature_humidity(3, 'temp_and_humidity', 's3a7')

Then click the “Save and Activate” button to finish setting up the workflow.

 

Step 6: Process Temperature and Humidity Data

In this step, we will take the raw temperature and raw humidity data that our previous workflow produced and process it to display it on the board.

Create a new workflow and name it “Temperature and Humidity Processing”. You will create the following workflow.

 

Drag the rawtemp_and_humidity” tag into the workflow. Drag a Base Python module into the workflow, connect it to the temp_and_humidity tag. Drag the “Processed Stream – Single” output onto the workflow and connect its “in1” to the Base Python module’s “out1”.

Double click the Processed Stream and make sure the “processed” stream is selected (should be by default).  Don’t change any other values.  Note: this workflow creates a new  processed temp_and_humidity event with each encoded raw temp_and_humidity event. Then click “Save” to finish setting up the workflow.

Replace the Base Python script with the following code:

'''
This workflow decodes the temperature and humidity from the sensor.
Last Updated: Sept 15, 2016
Author: Medium One
'''
import MQTT
import cloud_driver_ams
t,h = cloud_driver_ams.decode_ams_temperature_humidity(IONode.get_input('in1')['event_data']['value'])
out = {}
out['temperature'] = t
out['humidity'] = h

# set output to input
if out:
 IONode.set_output('out1', out)

# print to display
MQTT.publish_event_to_client('s3a7', 'D{};{}'.format(16, "Humidity: "+str(out['humidity'])), 'latin1')
MQTT.publish_event_to_client('s3a7', 'D{};{}'.format(17, "Temperature: "+str(out['temperature'])), 'latin1')

 

Then click “Save and Activate”.

 

CHECK POINT

Touch the screen again. Two lines that says:“Humidity: [number]  Temperature: [number]” should appear. The display with added Humidity and Temperature is shown below.

NOTE:  If this doesn’t appear, don’t continue. Go back and check all of your steps.

Congrats, you just printed humidity and temperature sensor values on the screen.

 

Step 7: Create a Salesforce workflow

In this section we will create a workflow that will trigger when a salesforce.com case is created.  This workflow will gather sensor data and transmit that data back to the salesforce.com case.

Create a new workflow and name it “Salesforce”; then add salesforce tag Id” and raw tag ip_address”.

 

Now, configure both, “salesforce” Id tag and “raw” ip_address tags.

Click on “salesforce” Id tag, and make sure Trigger is selected. Then click “Save”.

 

Similarly, click on “raw” ip_address tag, and make sure Trigger is not selected, since we only want to trigger this workflow when a new Salesforce case is created. Then click “Save”.

 

Click on Base Python, and replace the existing script with the following code:

import Salesforce
import MQTT
import Analytics
import Filter

salesforce_id = IONode.get_input('in1')['event_data']['value']
salesforce_update = "Device Information from Renesas IoT Sandbox:\n"

# get ip address
salesforce_update += "IP Address: "+IONode.get_input('in2')['event_data']['value']+"\n"

# get air quality
events = Analytics.events('processed', Filter.string_tag('processed.air_quality'), None, 1)
if len(events) > 0:
    salesforce_update += "Air Quality: "+str(events[0]['event_data']['air_quality'])+"ppm @ "+events[0]['observed_at']+"\n"

# get temperature & humidity
events = Analytics.events('processed', Filter.string_tag('processed.temperature'), None, 1)
if len(events) > 0:
    salesforce_update += "Temperature: "+str(events[0]['event_data']['temperature'])+"C @ "+events[0]['observed_at']+"\n"
    salesforce_update += "Humidity: "+str(events[0]['event_data']['humidity'])+"% @ "+events[0]['observed_at']+"\n"

log(salesforce_update)
Salesforce.comment_case(salesforce_id,salesforce_update)

Then click “Save and Activate”.

 

Check point

Now, let’s create a new salesforce case and test the created workflows.

In this tutorial, we created a new case with Subject: Device not working in salesforce.com.

 

Once we click on “Save”, this case was created. Click on Feed tab and you will see acknowledgement of the case creation. You can read the comment that the case was created.

 

Refresh the salesforce page and see the event on salesforce.com. In the section ‘All Updates for this case’, you can view sent data from Renesas IoT Sandbox regarding the connected board.

In this tutorial, we sent IP address, Air Quality, Temperature, and Humidity.

Congratulations! You just connected salesforce.com to the Renesas IoT Sandbox and populated a new case with useful information regarding your connected device.

WHAT’S NEXT?

You have connected Renesas IoT Sandbox with your Salesforce.com account! The rest is up to your imagination!

 

Appendix A: Add Apex Test classes

Salesforce requires that for deployment to Production organizations, at least 75% of the Apex code must be covered by test cases. If you plan on moving off of a Developer organization, you must add the following test interfaces and tests.

The reason for creating these test classes is that you may not have a real HTTP callout in a test, so you must create mock HTTP Callout responses to demonstrate how the data should respond given the input.

In Force.com Developer Console, click on File→ New -> Apex Class, and name the class “TestM1SucessfulSendEvent.” Copy and paste the following code in, replacing <YOUR_ENVIRONMENT> with the URL you placed in Remote Site Settings in step 3.

 

@isTest

global class TestM1SucessfulSendEvent implements HttpCalloutMock  {

global HTTPResponse respond(HTTPRequest req) {

System.assertEquals('<YOUR_ENVIRONMENT> /v2/events/salesforce?token=token', req.getEndpoint());

System.assertEquals('POST', req.getMethod());

HttpResponse res = new HttpResponse();

res.setStatusCode(200);

return res;

}

}

 

Click Save.  Click File→ New -> Apex Class, and name the class “TestM1SucessfulLogin.” Copy and paste the following:

 

@isTest

global class TestM1SucessfulLogin implements HttpCalloutMock {

global HTTPResponse respond(HTTPRequest req) {

System.assertEquals('<YOUR_ENVIRONMENT>/v2/login/?no_cookies', req.getEndpoint());

System.assertEquals('POST', req.getMethod());

HttpResponse res = new HttpResponse();

res.setStatusCode(200);

return res;

}

}

 

Click Save.

Create the last class and name it “M1Test.” Paste the following:

 

@isTest

public class M1Test {

@isTest static void testSuccessfulEvent() {

M1.login_mock = new TestM1SucessfulLogin();

M1.event_mock = new TestM1SucessfulSendEvent();

M1.send_data('{"test":"test"}');

}

 

@isTest static void testSuccessfulCaseCreation() {

M1.login_mock = new TestM1SucessfulLogin();

M1.event_mock = new TestM1SucessfulSendEvent();

Case new_case = new Case();

insert new_case;

}

}

 

Now you have successfully created your test classes, and can deploy your code to production. For information on moving code from sandbox to production, click here.