Sample code that showcases how to use IBMIoTF client library to connect the mbed LPC1768 or FRDM-K64F devices to the IBM Internet of Things Cloud service.

Dependencies:   C12832 IBMIoTF LM75B MMA7660

src/Main.cpp

Committer:
lokeshhk
Date:
2017-05-31
Revision:
5:48b6090e0df1
Parent:
4:a416fef97faa

File content as of revision 5:48b6090e0df1:

/*******************************************************************************
 * Copyright (c) 2015 IBM Corp.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Sathisumar Palaniappan - initial implementation
 *    Lokesh K Haralakatta - Port to support mbed os 5
 *******************************************************************************/

 // change this to 1 to output messages to LCD
 #define USE_LCD 0

#if USE_LCD
 #include "C12832.h"
 #include "Arial12x12.h"
 #define logMessage lcd.cls();lcd.locate(0,0);lcd.printf
 #define lcdFont lcd.set_font((unsigned char*) Arial12x12);
#else
 #define logMessage printf
 #define lcdFont
#endif

#include "stdio.h"
#include "mbed.h"
#include "LM75B.h"
#include "MMA7660.h"
#include "DeviceClient.h"
#include "Command.h"

#if defined(TARGET_UBLOX_C027)
#warning "Compiling for mbed C027"
#include "C027.h"
#elif defined(TARGET_LPC1768)
#warning "Compiling for mbed LPC1768"
#include "LPC1768.h"
#elif defined(TARGET_K64F)
#warning "Compiling for mbed K64F"
#include "K64F.h"
#endif

//LED
DigitalOut led1(LED1);

char *joystickPos;
void joystickThread(void const *args);
void processCommand(IoTF::Command &cmd);

int blink_interval = 0;
int main()
{
    //Set LCD font if USE_LCD == 1
    lcdFont

    // K64F: turn off the main board LED
    led2 = LED2_OFF;

    //Start thread to read data from joystick
    Thread jThd(joystickThread);
    joystickPos = "CENTRE";


    // Set IoT Foundation connection parameters
    char *organization = "quickstart";     // For a registered connection, replace with your org
    char *deviceType = "qsType";        // For a registered connection, replace with your device type
    char *deviceId = "qsDevice";                  // For a registered connection, replace with your device id
    char *method = "token";               // Not required to change as IBM IoTF expects only "token" for now
    char *token = "password";             // For a registered connection, replace with your auth-token

    // Create DeviceClient
    IoTF::DeviceClient *client = new IoTF::DeviceClient(organization, deviceType, deviceId);
    
    if(client->connect()){
        //Subscribe to device commands with CMD Callback to process the received command
        client->setCommandCallback(processCommand);

    // Create buffer to hold the event
    char buf[250];
    int count = 0;
    sprintf(buf,"{\"d\":{\"myName\":\"IoT mbed\"}}");

    while(1) {
        if (++count == 100) {
            logMessage("\r\n");

            //Construct an event message with desired datapoints
            sprintf(buf,
            "{\"d\":{\"myName\":\"IoT mbed\",\"accelX\":%0.4f,\"accelY\":%0.4f,\"accelZ\":%0.4f,\"temp\":%0.4f,\"joystick\":\"%s\",\"potentiometer1\":%0.4f,\"potentiometer2\":%0.4f}}",
            MMA.x(), MMA.y(), MMA.z(), sensor.temp(), joystickPos, ain1.read(), ain2.read());

            //Message is converted from datapoints into json format and then published
            bool status = client->publishEvent("blink", buf);

            logMessage("Publish status = %s\r\n",status?"true":"false");

            if(status == false) {
                // Check if connection is lost and retry
                int re_count = 0;
                while(!client->isConnected()) {
                    logMessage("Reconnecting... %d\r\n", re_count++);
                    client->reConnect();
                    wait(5.0);
                }
            }
            count = 0;
        }
        if (blink_interval == 0)
            led2 = LED2_OFF;
        else if (count % blink_interval == 0)
            led2 = !led2;

        client->yield(10);  // allow the MQTT client to receive messages
    }

       if(client->isConnected()){
           logMessage("Disconnecting the client from server...\r\n");
           client->disconnect();
        }
        else
           logMessage("Client already disconnected from server...\r\n");
    }
    else{
        logMessage("Client could not connect to server...\r\n");
    }

    delete client;
    logMessage("!!! Done !!!\r\n");
    return 0;
}

void processCommand(IoTF::Command &cmd)
{
    LOG("Command received name: %s, payload: %s\n", cmd.getCommand(), cmd.getPayload());

    if (strcmp(cmd.getCommand(), "blink") == 0) {
        char *payload = cmd.getPayload();
        char* pos = strchr(payload, '}');

        if (pos != NULL) {
            *pos = '\0';
            char* ratepos = strstr(payload, "rate");
            if(ratepos == NULL) {
                return;
            }
            if ((pos = strchr(ratepos, ':')) != NULL)
            {
                int blink_rate = atoi(pos + 1);
                blink_interval = (blink_rate <= 0) ? 0 : (blink_rate > 50 ? 1 : 50/blink_rate);
            }
        }
    } else {
        WARN("Unsupported command: %s\n", cmd.getCommand());
    }
    logMessage("blink interval = %d\n", blink_interval);
    wait(1.0);
}

void joystickThread(void const *args) {
    while (1) {
        if (Down)
            joystickPos = "DOWN";
        else if (Left)
            joystickPos = "LEFT";
        else if (Click)
            joystickPos = "CLICK";
        else if (Up)
            joystickPos = "UP";
        else if (Right)
            joystickPos = "RIGHT";
        else
            joystickPos = "CENTRE";
    }
}