Upload data to Thingspeak
응답
19. 5. 6 오후 1:50

Good day, may I have some suggestion on this code? I cant compile. I am using workbench 3.6.0Thank you

/* own header files */
#include "XDKAppInfo.h"

#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_HTTP_EXAMPLE_CLIENT
#define WLAN_CONNECT_WPA_SSID "kent"
#define WLAN_CONNECT_WPA_PASS "kentlee0429"

/* system header files */
#include <stdio.h>

/* additional interface header files */
#include "BCDS_WlanConnect.h"
#include "BCDS_NetworkConfig.h"
#include "BCDS_CmdProcessor.h"
#include <Serval_HttpClient.h>
#include <Serval_Network.h>
#include "PAL_socketMonitor_ih.h"
#include "PAL_initialize_ih.h"
#include "FreeRTOS.h"
#include "XdkSensorHandle.h"
#include "timers.h"

/* constant definitions ***************************************************** */

/* local variables ********************************************************** */

/* global variables ********************************************************* */
static xTimerHandle connectTimerHandle; /**< variable to store timer handle*/
Ip_Address_T destAddr = UINT32_C(0);/*< variable to store the Ip address of the server */
static uint32_t intialOffset = UINT32_C(0); /* < variable to store the offset, the first byte to be received */
static uint32_t noOfBytesRecv = UINT32_C(512); /*< variable to store the number of bytes to receive */
char const *urlPtrReq = "/post.php?dump&html&dir=XDK"; /* URL string for the http website to post the payload*/
uint8_t payload[] = "XDK Testing"; /* payload to add to a request */
Accelerometer_XyzData_T aData = { INT32_C(0), INT32_C(0), INT32_C(0) };

/*Application Command Processor Instance */
CmdProcessor_T *AppCmdProcessor;

/* inline functions ********************************************************* */

/* local functions ********************************************************** */

/**
 * @brief This API is called when the HTTP page
 *      Connecting to a WLAN Access point.
 *       This function connects to the required AP (SSID_NAME).
 *       The function will return once we are connected and have acquired IP address
 *   @warning
 *      If the WLAN connection fails or we don't acquire an IP address, We will be stuck in this function forever.
 *      Check whether the callback "SimpleLinkWlanEventHandler" or "SimpleLinkNetAppEventHandler" hits once the
 *      sl_WlanConnect() API called, if not check for proper GPIO pin interrupt configuration or for any other issue
 *
 * @retval     RC_OK       IP address returned successfully
 *
 * @retval     RC_PLATFORM_ERROR         Error occurred in fetching the ip address
 *
 */
static retcode_t WlanConnect(void)
{
    NetworkConfig_IpSettings_T myIpSettings;
    char ipAddress[PAL_IP_ADDRESS_SIZE] = { 0 };
    Ip_Address_T* IpaddressHex = Ip_getMyIpAddr();
    WlanConnect_SSID_T connectSSID;
    WlanConnect_PassPhrase_T connectPassPhrase;
    Retcode_T ReturnValue = (Retcode_T) RETCODE_FAILURE;
    int32_t Result = INT32_C(-1);

    if (RETCODE_OK != WlanConnect_Init())
    {
        return (RC_PLATFORM_ERROR);
    }

    printf("Connecting to %s \r\n ", WLAN_CONNECT_WPA_SSID);

    connectSSID = (WlanConnect_SSID_T) WLAN_CONNECT_WPA_SSID;
    connectPassPhrase = (WlanConnect_PassPhrase_T) WLAN_CONNECT_WPA_PASS;
    ReturnValue = NetworkConfig_SetIpDhcp(NULL);
    if (RETCODE_OK != ReturnValue)
    {
        printf("Error in setting IP to DHCP \r\n");
        return (RC_PLATFORM_ERROR);
    }
    if (RETCODE_OK == WlanConnect_WPA(connectSSID, connectPassPhrase, NULL))
    {
        ReturnValue = NetworkConfig_GetIpSettings(&myIpSettings);
        if (RETCODE_OK == ReturnValue)
        {
            *IpaddressHex = Basics_htonl(myIpSettings.ipV4);
            Result = Ip_convertAddrToString(IpaddressHex, ipAddress);
            if (Result < 0)
            {
                printf("Couldn't convert the IP address to string format \r\n ");
                return (RC_PLATFORM_ERROR);
            }
            printf("Connected to WPA network successfully \r\n ");
            printf(" Ip address of the device %s \r\n ", ipAddress);
            return (RC_OK);
        }
        else
        {
            printf("Error in getting IP settings \r\n");
            return (RC_PLATFORM_ERROR);
        }
    }
    else
    {
        return (RC_PLATFORM_ERROR);
    }

}


/**
 * @brief This API is called after the HTTP connects with the server to get the Content.
 *
 * @param[in]: callfunc
 *               The structure storing the pointer to the message handler
 * @param[in]: retcode_t
 *               The return code of the HTTP connect
 * @retval: retcode_t
 *               The return code of the callback Function
 */
static retcode_t CallbackOnSent(Callable_T *callfunc, retcode_t status)
{
    BCDS_UNUSED(callfunc);

    if (status != RC_OK)
    {
        //printf("error occurred in connecting server \r\n");
    }
    return (RC_OK);
}

/**
 * @brief This API is called after the HTTP connects with the server to post the Content.
 *
 * @param[in]: callfunc
 *               The structure storing the pointer to the message handler
 * @param[in]: retcode_t
 *               The return code of the HTTP connect
 * @retval: retcode_t
 *               The return code of the callback Function
 */
static retcode_t CallbackOnRecv(Callable_T *callfunc, retcode_t status)
{
    BCDS_UNUSED(callfunc);

    if (status != RC_OK)
    {
        //printf("error occurred in connecting server \r\n");
    }
    else
    {
        printf("Post Request Sent \r\n");
    }
    return (RC_OK);
}

/**
 * @brief API responsible to pass the payload to the requested URL
 *
 * @param[in] omsh_ptr This data structure is used hold the buffer and information needed by the serializer.
 *
 */
static retcode_t httpPayloadSerializer(
        OutMsgSerializationHandover_T *omsh_ptr)
{
    retcode_t rc = RC_OK;
    memcpy(omsh_ptr->buf_ptr, payload, strlen((char*) payload));
    omsh_ptr->len = strlen((char*) payload);

    return rc;
}


/**
 * @brief API responsible to internal headers have been serialized but before the header-terminating token
 *
 * @param[in] omsh_ptr This data structure is used hold the buffer and information needed by the serializer.
 *
 */
static retcode_t serializeMyHeaders(OutMsgSerializationHandover_T *omsh_ptr)
{
    retcode_t rc;
    omsh_ptr->len = 0;
    int n;
    static const char* myheader1 = "MyHeader: XDK\r\n";
    static const char* myheader2 = "MyOtherHeader: TestPurpose\r\n";

    switch (omsh_ptr->position)
    {
    case 0:
        n = strlen(myheader1);
        rc = TcpMsg_copyStaticContent(omsh_ptr, myheader1, n);
        if (rc != RC_OK)
            return rc;
        omsh_ptr->position = 1;
  break;
    case 1:
        n = strlen(myheader2);
        rc = TcpMsg_copyContentAtomic(omsh_ptr, myheader2, n);
        if (rc != RC_OK)
            return rc;
        omsh_ptr->position = 2;
  break;
    default:
        return RC_OK;
        break;
    }
}

/**
 * @brief API responsible to Post Data on html page.
 *
 * @param[in] Not used.
 *
 *
 * @param[in] Not used.
 */
static void PostContentOnWebpage(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);
    retcode_t rc = RC_OK;
    Msg_T* msg_ptr;
 int DEST_PORT_NUMBER;
    Ip_Port_T destPort = (Ip_Port_T) DEST_PORT_NUMBER;
    static Callable_T RecvCallable;
    Callable_T * Callable_pointer;
    Callable_pointer = Callable_assign(&RecvCallable, CallbackOnRecv);
    if (Callable_pointer == NULL)
    {
        printf("Failed Callable_assign\r\n ");
        return;
    }
    rc = HttpClient_initRequest(&destAddr, Ip_convertIntToPort(destPort), &msg_ptr);

    if (rc != RC_OK || msg_ptr == NULL)
    {
        //printf("Failed HttpClient_initRequest \r\n ");
        return;
    }
    HttpMsg_serializeCustomHeaders(msg_ptr, serializeMyHeaders);
    HttpMsg_setReqMethod(msg_ptr, Http_Method_Post);

    rc = HttpMsg_setReqUrl(msg_ptr, urlPtrReq);
    if (rc != RC_OK)
    {
        printf("Failed to fill message \r\n ");
        return;
    }

    /* set content type and payload */
    HttpMsg_setContentType(msg_ptr, Http_ContentType_Text_Plain);

    rc = Msg_prependPartFactory(msg_ptr, &httpPayloadSerializer);
    if (RC_OK == rc)
    {
        rc = HttpClient_pushRequest(msg_ptr, &RecvCallable,
        NULL);
        if (rc != RC_OK)
        {
            printf("Failed HttpClient_pushRequest \r\n  ");
            return;
        }
    }
    if (rc != RC_OK)
    {
        printf("Failed to Fill the payload on payloadSerializer \r\n  ");
        return;
    }
}

/**
 * @brief This API is called after downloading the HTTP page from the server
 *
 * @param[in]: HttpSession_T
 *               The pointer holding the details of the http session
 * @param[in]: Msg_T
 *               The structure storing the pointer to the message handler
 * @param[in]: retcode_t
 *               The return code of the HTTP page download
 *
 * @retval: retcode_t
 *               The return code of the HTTP connect
 *
 */
static retcode_t HttpClientResponseCallback(HttpSession_T *httpSession,
        Msg_T *msg_ptr, retcode_t status)
{
    BCDS_UNUSED(httpSession);
    retcode_t rc = status;
    uint32_t pageContentSize; /* total length of the content at the server */
    bool flag = false; /* flag to set to true if this is the last piece of the message */
    Retcode_T returnValue = RETCODE_OK;
    if (rc != RC_OK)
    {
        /* Error occurred in downloading the page */
        printf("error occurred in downloading HTML \r\n");
    }
    else if (msg_ptr == NULL)
    {
        rc = RC_HTTP_PARSER_INVALID_CONTENT_TYPE;
    }
    else
    {
        rc = HttpMsg_getRange(msg_ptr, UINT32_C(0), &pageContentSize, &flag);
        if (rc != RC_OK)
        {
            printf("Failed to Get Range \r\n ");
        }
        else
        {
            if (HttpMsg_getContentType(msg_ptr) != Http_ContentType_Text_Html)
            {
                rc = RC_HTTP_INVALID_RESPONSE;
            }
            else
            {
                char const *content_ptr = "";
                unsigned int len = UINT32_C(0);
                HttpMsg_getContent(msg_ptr, &content_ptr, &len);
                printf("GET Response Content %s \r\n", content_ptr);
                intialOffset += (len);
                /* Clear the Content Buffer */
                memset(content_ptr, UINT32_C(0), len);
                /* check if this is the last piece of the message. This parameter will also be true if the message is not fragmented.*/
/*                if (flag == true)
                {
                    printf("Page content %lu Bytes Download Completed \r\n", pageContentSize);
                    if (xTimerStop(connectTimerHandle, 0) != pdTRUE)
                    {
                        assert(false);
                    }
                    /* En-queuing to application command processor to post the content on Http page */
/*                    returnValue = CmdProcessor_enqueue(AppCmdProcessor, PostContentOnWebpage, NULL, UINT32_C(0));
                    if (RETCODE_OK != returnValue)
                    {
                        printf("En-queuing to application command processor failed \r\n");
                    }
                } */
            }
        }
    }

    if (rc != RC_OK)
    {
        printf("error occurred in downloading HTML \r\n");
    }
    return (rc);
}
/* global functions ********************************************************** */

static void initSensor(void)
{
 Retcode_T returnValue = RETCODE_FAILURE;
 returnValue = Accelerometer_init(xdkAccelerometers_BMA280_Handle);
 if(RETCODE_OK != returnValue)
 {
  printf("BMA280 Accelerometer initialization Failed\n\r");
 }
}

static void readAccelerometer(xTimerHandle xTimer)
{
 (void) xTimer;

 Retcode_T returnValue = RETCODE_FAILURE;


 returnValue = Accelerometer_readXyzGValue(xdkAccelerometers_BMA280_Handle,&aData);

 if(RETCODE_OK == returnValue)
 {
  printf("BMA280 Acceleration Data - M/S2 %f m/s2 %f m/s2 %f m/s2\n\r",
   (float) bma280.xAxisData, (float) bma280.yAxisData, (float) bma280.zAxisData);
 }
}

/**
 * @brief API responsible to read html page content of the client and print it on the console.
 *
 * @param[in] Not used.
 *
 *
 * @param[in] Not used.
 */


static void PrintWebpageContent(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);
    retcode_t rc = RC_OK;
    Msg_T* msg_ptr;
 int DEST_PORT_NUMBER;
    Ip_Port_T destPort = (Ip_Port_T) DEST_PORT_NUMBER;
    static Callable_T SentCallable;
    const char url_ptr[100]; /* URL string for the http website */
    int n = sprintf(url_ptr,"/update?key=H2XL7UF32O1T2V3Y&field1=%d");
    Callable_T * Callable_pointer;
    Callable_pointer = Callable_assign(&SentCallable, CallbackOnSent);#
    if (Callable_pointer == NULL)
    {
        printf("Failed Callable_assign\r\n ");
        return;
    }
    rc = HttpClient_initRequest(&destAddr, Ip_convertIntToPort(destPort), &msg_ptr);

    if (rc != RC_OK || msg_ptr == NULL)
    {
        //printf("Failed HttpClient_initRequest \r\n ");
        return;
    }
    HttpMsg_setRange(msg_ptr, intialOffset, noOfBytesRecv);
    HttpMsg_setReqMethod(msg_ptr, Http_Method_Get);
    rc = HttpMsg_setReqUrl(msg_ptr, url_ptr);
    if (rc != RC_OK)
    {
        printf("Failed to fill message \r\n ");
        return;
    }

    rc = HttpClient_pushRequest(msg_ptr, &SentCallable,
            HttpClientResponseCallback);
    if (rc != RC_OK)
    {
        printf("Failed HttpClient_pushRequest \r\n  ");
        return;
    }
}

/**
 * @brief This API triggers periodically and initiate PrintWebpageContent to download the web page content.
 *
 * @param[in]: xTimer
 *               The timer handle of the function
 *
 */
static void ConnectServer(xTimerHandle xTimer)
{
    BCDS_UNUSED(xTimer);
    Retcode_T returnValue = RETCODE_OK;

    returnValue = CmdProcessor_enqueue(AppCmdProcessor, PrintWebpageContent, NULL, UINT32_C(0));
    if (RETCODE_OK != returnValue)
    {
        printf("En-queuing to application command processor failed \r\n");
    }
}

/* The description is in the interface header file. */
static void Init(void)
{
    retcode_t rc = RC_OK;

    rc = WlanConnect();
    if (RC_OK != rc)
    {
        printf("Network init/connection failed %i \r\n", rc);
        return;
    }

    rc = PAL_initialize();
    if (RC_OK != rc)
    {
        printf("PAL and network initialize %i \r\n", rc);
        return;
    }

    PAL_socketMonitorInit();

    /* start client */
    rc = HttpClient_initialize();
    if (rc != RC_OK)
    {
        printf("Failed to initialize http client \r\n ");
        return;
    }

    if (RC_OK != PAL_getIpaddress((uint8_t*) "api.thingspeak.com", &destAddr))
    {
        return;
    }

    else
    {
        uint32_t Ticks = 2000;

/*        if (Ticks != UINT32_MAX) /* Validated for portMAX_DELAY to assist the task to wait Infinitely (without timing out) */
/*        {
            Ticks /= portTICK_RATE_MS;
        }
        if (UINT32_C(0) == Ticks) /* ticks cannot be 0 in FreeRTOS timer. So ticks is assigned to 1 */
/*        {
            Ticks = UINT32_C(1);
        }
        /* Timer to Get Content from the connected server */
        connectTimerHandle = xTimerCreate((const char * const ) "ConnectServer", Ticks,TIMER_AUTORELOAD_ON, NULL, ConnectServer);
        if (connectTimerHandle != NULL)
        {
            if (xTimerStart(connectTimerHandle, TIMERBLOCKTIME) != pdTRUE)
            {
                assert(false);
            }
            else
            {
                printf("Started the timer successfully \r\n ");
            }

        }
    }
}

/**
 * @brief This is a template function where the user can write his custom application.
 *
 */
void appInitSystem(void * CmdProcessorHandle, uint32_t param2)
{
    if (CmdProcessorHandle == NULL)
    {
        printf("Command processor handle is null \n\r");
        assert(false);
    }
    uint32_t timerBlockTime = UINT32_MAX;
    uint32_t OneSecondDelay = UINT32_C(2000);
    uint32_t timerAutoReloadOn = pdTRUE;

    xTimerHandle SensorHandle= NULL;

    initSensor();

    SensorHandle = xTimerCreate((const char *) "readAccelerometer", OneSecondDelay, timerAutoReloadOn, NULL, readAccelerometer);

    xTimerStart(SensorHandle,timerBlockTime);

    AppCmdProcessor = (CmdProcessor_T *) CmdProcessorHandle;
    BCDS_UNUSED(param2);
    /*Call the RHC init API */
    Init();

}
/**@} */

0 (0 투표)
RE: Upload data to Thingspeak
응답
19. 5. 7 오전 4:47 as a reply to l Kent.

Hi Kent

/* own header files */
#include "XDKAppInfo.h"

#undef BCDS_MODULE_ID  /* Module ID define before including Basics package*/
#define BCDS_MODULE_ID XDK_APP_MODULE_ID_HTTP_EXAMPLE_CLIENT
#define WLAN_CONNECT_WPA_SSID "kent"
#define WLAN_CONNECT_WPA_PASS "kentlee0429"

/* system header files */
#include <stdio.h>

/* additional interface header files */
#include "BCDS_WlanConnect.h"
#include "BCDS_NetworkConfig.h"
#include "BCDS_CmdProcessor.h"
#include <Serval_HttpClient.h>
#include <Serval_Network.h>
#include "PAL_socketMonitor_ih.h"
#include "PAL_initialize_ih.h"
#include "FreeRTOS.h"
#include "XdkSensorHandle.h"
#include "timers.h"

/* constant definitions ***************************************************** */

/* local variables ********************************************************** */

/* global variables ********************************************************* */
static xTimerHandle connectTimerHandle; /**< variable to store timer handle*/
Ip_Address_T destAddr = UINT32_C(0);/*< variable to store the Ip address of the server */
static uint32_t intialOffset = UINT32_C(0); /* < variable to store the offset, the first byte to be received */
static uint32_t noOfBytesRecv = UINT32_C(512); /*< variable to store the number of bytes to receive */
char const *urlPtrReq = "/post.php?dump&html&dir=XDK"; /* URL string for the http website to post the payload*/
uint8_t payload[] = "XDK Testing"; /* payload to add to a request */
Accelerometer_XyzData_T aData = { INT32_C(0), INT32_C(0), INT32_C(0) };
#define TIMER_AUTORELOAD_ON                 UINT8_C(1)  /**< Auto reload of timer is disabled*/
#define TIMERBLOCKTIME                      UINT32_MAX     /**< Macro used to define blocktime of a timer*/
/*Application Command Processor Instance */
CmdProcessor_T *AppCmdProcessor;

/* inline functions ********************************************************* */

/* local functions ********************************************************** */

/**
 * @brief This API is called when the HTTP page
 *      Connecting to a WLAN Access point.
 *       This function connects to the required AP (SSID_NAME).
 *       The function will return once we are connected and have acquired IP address
 *   @warning
 *      If the WLAN connection fails or we don't acquire an IP address, We will be stuck in this function forever.
 *      Check whether the callback "SimpleLinkWlanEventHandler" or "SimpleLinkNetAppEventHandler" hits once the
 *      sl_WlanConnect() API called, if not check for proper GPIO pin interrupt configuration or for any other issue
 *
 * @retval     RC_OK       IP address returned successfully
 *
 * @retval     RC_PLATFORM_ERROR         Error occurred in fetching the ip address
 *
 */
static retcode_t WlanConnect(void)
{
    NetworkConfig_IpSettings_T myIpSettings;
    char ipAddress[PAL_IP_ADDRESS_SIZE] = { 0 };
    Ip_Address_T* IpaddressHex = Ip_getMyIpAddr();
    WlanConnect_SSID_T connectSSID;
    WlanConnect_PassPhrase_T connectPassPhrase;
    Retcode_T ReturnValue = (Retcode_T) RETCODE_FAILURE;
    int32_t Result = INT32_C(-1);

    if (RETCODE_OK != WlanConnect_Init())
    {
        return (RC_PLATFORM_ERROR);
    }

    printf("Connecting to %s \r\n ", WLAN_CONNECT_WPA_SSID);

    connectSSID = (WlanConnect_SSID_T) WLAN_CONNECT_WPA_SSID;
    connectPassPhrase = (WlanConnect_PassPhrase_T) WLAN_CONNECT_WPA_PASS;
    ReturnValue = NetworkConfig_SetIpDhcp(NULL);
    if (RETCODE_OK != ReturnValue)
    {
        printf("Error in setting IP to DHCP \r\n");
        return (RC_PLATFORM_ERROR);
    }
    if (RETCODE_OK == WlanConnect_WPA(connectSSID, connectPassPhrase, NULL))
    {
        ReturnValue = NetworkConfig_GetIpSettings(&myIpSettings);
        if (RETCODE_OK == ReturnValue)
        {
            *IpaddressHex = Basics_htonl(myIpSettings.ipV4);
            Result = Ip_convertAddrToString(IpaddressHex, ipAddress);
            if (Result < 0)
            {
                printf("Couldn't convert the IP address to string format \r\n ");
                return (RC_PLATFORM_ERROR);
            }
            printf("Connected to WPA network successfully \r\n ");
            printf(" Ip address of the device %s \r\n ", ipAddress);
            return (RC_OK);
        }
        else
        {
            printf("Error in getting IP settings \r\n");
            return (RC_PLATFORM_ERROR);
        }
    }
    else
    {
        return (RC_PLATFORM_ERROR);
    }

}


/**
 * @brief This API is called after the HTTP connects with the server to get the Content.
 *
 * @param[in]: callfunc
 *               The structure storing the pointer to the message handler
 * @param[in]: retcode_t
 *               The return code of the HTTP connect
 * @retval: retcode_t
 *               The return code of the callback Function
 */
static retcode_t CallbackOnSent(Callable_T *callfunc, retcode_t status)
{
    BCDS_UNUSED(callfunc);

    if (status != RC_OK)
    {
        //printf("error occurred in connecting server \r\n");
    }
    return (RC_OK);
}

/**
 * @brief This API is called after the HTTP connects with the server to post the Content.
 *
 * @param[in]: callfunc
 *               The structure storing the pointer to the message handler
 * @param[in]: retcode_t
 *               The return code of the HTTP connect
 * @retval: retcode_t
 *               The return code of the callback Function
 */
static retcode_t CallbackOnRecv(Callable_T *callfunc, retcode_t status)
{
    BCDS_UNUSED(callfunc);

    if (status != RC_OK)
    {
        //printf("error occurred in connecting server \r\n");
    }
    else
    {
        printf("Post Request Sent \r\n");
    }
    return (RC_OK);
}

/**
 * @brief API responsible to pass the payload to the requested URL
 *
 * @param[in] omsh_ptr This data structure is used hold the buffer and information needed by the serializer.
 *
 */
static retcode_t httpPayloadSerializer(
        OutMsgSerializationHandover_T *omsh_ptr)
{
    retcode_t rc = RC_OK;
    memcpy(omsh_ptr->buf_ptr, payload, strlen((char*) payload));
    omsh_ptr->len = strlen((char*) payload);

    return rc;
}


/**
 * @brief API responsible to internal headers have been serialized but before the header-terminating token
 *
 * @param[in] omsh_ptr This data structure is used hold the buffer and information needed by the serializer.
 *
 */
static retcode_t serializeMyHeaders(OutMsgSerializationHandover_T *omsh_ptr)
{
    retcode_t rc;
    omsh_ptr->len = 0;
    int n;
    static const char* myheader1 = "MyHeader: XDK\r\n";
    static const char* myheader2 = "MyOtherHeader: TestPurpose\r\n";

    switch (omsh_ptr->position)
    {
    case 0:
        n = strlen(myheader1);
        rc = TcpMsg_copyStaticContent(omsh_ptr, myheader1, n);
        if (rc != RC_OK)
            return rc;
        omsh_ptr->position = 1;
  break;
    case 1:
        n = strlen(myheader2);
        rc = TcpMsg_copyContentAtomic(omsh_ptr, myheader2, n);
        if (rc != RC_OK)
            return rc;
        omsh_ptr->position = 2;
  break;
    default:
        return RC_OK;
        break;
    }
}

/**
 * @brief API responsible to Post Data on html page.
 *
 * @param[in] Not used.
 *
 *
 * @param[in] Not used.
 */
static void PostContentOnWebpage(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);
    retcode_t rc = RC_OK;
    Msg_T* msg_ptr;
 int DEST_PORT_NUMBER;
    Ip_Port_T destPort = (Ip_Port_T) DEST_PORT_NUMBER;
    static Callable_T RecvCallable;
    Callable_T * Callable_pointer;
    Callable_pointer = Callable_assign(&RecvCallable, CallbackOnRecv);
    if (Callable_pointer == NULL)
    {
        printf("Failed Callable_assign\r\n ");
        return;
    }
    rc = HttpClient_initRequest(&destAddr, Ip_convertIntToPort(destPort), &msg_ptr);

    if (rc != RC_OK || msg_ptr == NULL)
    {
        //printf("Failed HttpClient_initRequest \r\n ");
        return;
    }
    HttpMsg_serializeCustomHeaders(msg_ptr, serializeMyHeaders);
    HttpMsg_setReqMethod(msg_ptr, Http_Method_Post);

    rc = HttpMsg_setReqUrl(msg_ptr, urlPtrReq);
    if (rc != RC_OK)
    {
        printf("Failed to fill message \r\n ");
        return;
    }

    /* set content type and payload */
    HttpMsg_setContentType(msg_ptr, Http_ContentType_Text_Plain);

    rc = Msg_prependPartFactory(msg_ptr, &httpPayloadSerializer);
    if (RC_OK == rc)
    {
        rc = HttpClient_pushRequest(msg_ptr, &RecvCallable,
        NULL);
        if (rc != RC_OK)
        {
            printf("Failed HttpClient_pushRequest \r\n  ");
            return;
        }
    }
    if (rc != RC_OK)
    {
        printf("Failed to Fill the payload on payloadSerializer \r\n  ");
        return;
    }
}

/**
 * @brief This API is called after downloading the HTTP page from the server
 *
 * @param[in]: HttpSession_T
 *               The pointer holding the details of the http session
 * @param[in]: Msg_T
 *               The structure storing the pointer to the message handler
 * @param[in]: retcode_t
 *               The return code of the HTTP page download
 *
 * @retval: retcode_t
 *               The return code of the HTTP connect
 *
 */
static retcode_t HttpClientResponseCallback(HttpSession_T *httpSession,
        Msg_T *msg_ptr, retcode_t status)
{
    BCDS_UNUSED(httpSession);
    retcode_t rc = status;
    uint32_t pageContentSize; /* total length of the content at the server */
    bool flag = false; /* flag to set to true if this is the last piece of the message */
    Retcode_T returnValue = RETCODE_OK;
    if (rc != RC_OK)
    {
        /* Error occurred in downloading the page */
        printf("error occurred in downloading HTML \r\n");
    }
    else if (msg_ptr == NULL)
    {
        rc = RC_HTTP_PARSER_INVALID_CONTENT_TYPE;
    }
    else
    {
        rc = HttpMsg_getRange(msg_ptr, UINT32_C(0), &pageContentSize, &flag);
        if (rc != RC_OK)
        {
            printf("Failed to Get Range \r\n ");
        }
        else
        {
            if (HttpMsg_getContentType(msg_ptr) != Http_ContentType_Text_Html)
            {
                rc = RC_HTTP_INVALID_RESPONSE;
            }
            else
            {
                char const *content_ptr = "";
                unsigned int len = UINT32_C(0);
                HttpMsg_getContent(msg_ptr, &content_ptr, &len);
                printf("GET Response Content %s \r\n", content_ptr);
                intialOffset += (len);
                /* Clear the Content Buffer */
                memset(content_ptr, UINT32_C(0), len);
                /* check if this is the last piece of the message. This parameter will also be true if the message is not fragmented.*/                if (flag == true)
                {
                    printf("Page content %lu Bytes Download Completed \r\n", pageContentSize);
                    if (xTimerStop(connectTimerHandle, 0) != pdTRUE)
                    {
                        assert(false);
                    }
                    /* En-queuing to application command processor to post the content on Http page */
                   returnValue = CmdProcessor_enqueue(AppCmdProcessor, PostContentOnWebpage, NULL, UINT32_C(0));
                    if (RETCODE_OK != returnValue)
                    {
                        printf("En-queuing to application command processor failed \r\n");
                    }
                }
            }
        }
    }

    if (rc != RC_OK)
    {
        printf("error occurred in downloading HTML \r\n");
    }
    return (rc);
}
/* global functions ********************************************************** */

static void initSensor(void)
{
 Retcode_T returnValue = RETCODE_FAILURE;
 returnValue = Accelerometer_init(xdkAccelerometers_BMA280_Handle);
 if(RETCODE_OK != returnValue)
 {
  printf("BMA280 Accelerometer initialization Failed\n\r");
 }
}

static void readAccelerometer(xTimerHandle xTimer)
{
 (void) xTimer;

 Retcode_T returnValue = RETCODE_FAILURE;

 Accelerometer_XyzData_T bma280 = { INT16_C(0), INT16_C(0), INT16_C(0) };

 returnValue = Accelerometer_readXyzGValue(xdkAccelerometers_BMA280_Handle,&aData);

 if(RETCODE_OK == returnValue)
 {
  printf("BMA280 Acceleration Data - M/S2 %f m/s2 %f m/s2 %f m/s2\n\r",
   (float) bma280.xAxisData, (float) bma280.yAxisData, (float) bma280.zAxisData);
 }
}

/**
 * @brief API responsible to read html page content of the client and print it on the console.
 *
 * @param[in] Not used.
 *
 *
 * @param[in] Not used.
 */


static void PrintWebpageContent(void * param1, uint32_t param2)
{
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);
    retcode_t rc = RC_OK;
    Msg_T* msg_ptr;
 int DEST_PORT_NUMBER;
    Ip_Port_T destPort = (Ip_Port_T) DEST_PORT_NUMBER;
    static Callable_T SentCallable;
    const char url_ptr[100]; /* URL string for the http website */
    int n = sprintf(url_ptr,"/update?key=H2XL7UF32O1T2V3Y&field1=%d");
    Callable_T * Callable_pointer;
    Callable_pointer = Callable_assign(&SentCallable, CallbackOnSent);
    if (Callable_pointer == NULL)
    {
        printf("Failed Callable_assign\r\n ");
        return;
    }
    rc = HttpClient_initRequest(&destAddr, Ip_convertIntToPort(destPort), &msg_ptr);

    if (rc != RC_OK || msg_ptr == NULL)
    {
        //printf("Failed HttpClient_initRequest \r\n ");
        return;
    }
    HttpMsg_setRange(msg_ptr, intialOffset, noOfBytesRecv);
    HttpMsg_setReqMethod(msg_ptr, Http_Method_Get);
    rc = HttpMsg_setReqUrl(msg_ptr, url_ptr);
    if (rc != RC_OK)
    {
        printf("Failed to fill message \r\n ");
        return;
    }

    rc = HttpClient_pushRequest(msg_ptr, &SentCallable,
            HttpClientResponseCallback);
    if (rc != RC_OK)
    {
        printf("Failed HttpClient_pushRequest \r\n  ");
        return;
    }
}

/**
 * @brief This API triggers periodically and initiate PrintWebpageContent to download the web page content.
 *
 * @param[in]: xTimer
 *               The timer handle of the function
 *
 */
static void ConnectServer(xTimerHandle xTimer)
{
    BCDS_UNUSED(xTimer);
    Retcode_T returnValue = RETCODE_OK;

    returnValue = CmdProcessor_enqueue(AppCmdProcessor, PrintWebpageContent, NULL, UINT32_C(0));
    if (RETCODE_OK != returnValue)
    {
        printf("En-queuing to application command processor failed \r\n");
    }
}

/* The description is in the interface header file. */
static void Init(void)
{
    retcode_t rc = RC_OK;

    rc = WlanConnect();
    if (RC_OK != rc)
    {
        printf("Network init/connection failed %i \r\n", rc);
        return;
    }

    rc = PAL_initialize();
    if (RC_OK != rc)
    {
        printf("PAL and network initialize %i \r\n", rc);
        return;
    }

    PAL_socketMonitorInit();

    /* start client */
    rc = HttpClient_initialize();
    if (rc != RC_OK)
    {
        printf("Failed to initialize http client \r\n ");
        return;
    }

    if (RC_OK != PAL_getIpaddress((uint8_t*) "api.thingspeak.com", &destAddr))
    {
        return;
    }

    else
    {
        uint32_t Ticks = 2000;

        if (Ticks != UINT32_MAX) /* Validated for portMAX_DELAY to assist the task to wait Infinitely (without timing out) */
        {
            Ticks /= portTICK_RATE_MS;
        }
        if (UINT32_C(0) == Ticks) /* ticks cannot be 0 in FreeRTOS timer. So ticks is assigned to 1 */
        {
            Ticks = UINT32_C(1);
        }
        /* Timer to Get Content from the connected server */
        connectTimerHandle = xTimerCreate((const char * const ) "ConnectServer", Ticks,TIMER_AUTORELOAD_ON, NULL, ConnectServer);
        if (connectTimerHandle != NULL)
        {
            if (xTimerStart(connectTimerHandle, TIMERBLOCKTIME) != pdTRUE)
            {
                assert(false);
            }
            else
            {
                printf("Started the timer successfully \r\n ");
            }

        }
    }
}

/**
 * @brief This is a template function where the user can write his custom application.
 *
 */
void appInitSystem(void * CmdProcessorHandle, uint32_t param2)
{
    if (CmdProcessorHandle == NULL)
    {
        printf("Command processor handle is null \n\r");
        assert(false);
    }
    uint32_t timerBlockTime = UINT32_MAX;
    uint32_t OneSecondDelay = UINT32_C(2000);
    uint32_t timerAutoReloadOn = pdTRUE;

    xTimerHandle SensorHandle= NULL;

    initSensor();

    SensorHandle = xTimerCreate((const char *) "readAccelerometer", OneSecondDelay, timerAutoReloadOn, NULL, readAccelerometer);

    xTimerStart(SensorHandle,timerBlockTime);

    AppCmdProcessor = (CmdProcessor_T *) CmdProcessorHandle;
    BCDS_UNUSED(param2);
    /*Call the RHC init API */
    Init();

}
/**@} */

Tha above code is compilable.

Please check.

The following corrections i have made:

1. Defining the macro

#define TIMER_AUTORELOAD_ON                 UINT8_C(1)  /**< Auto reload of timer is disabled*/
#define TIMERBLOCKTIME                      UINT32_MAX     /**< Macro used to define blocktime of a timer*/

2. Declaring the variable bma280 in readAccelerometer() api

3. Commenting of the code was not proper.

Thanks

Priyashi

 

0 (0 투표)
RE: Upload data to Thingspeak
응답
19. 5. 7 오전 8:40 as a reply to Priyashi Yadav.
Good day Priyashi Yadav , should I flash the code in XdkApplicationTemplate AppController.h? I keep getting error when I try to run this code.
0 (0 투표)
RE: Upload data to Thingspeak
응답
19. 5. 7 오전 9:17 as a reply to l Kent.

Hi Kent

You can paste the given code in AppController.c file and replace appInitSystem() with AppController_Init().

clean and compile.

If you still face any errors attach the scrrenshot of the error to help you better.

Thanks

Priyashi

0 (0 투표)
RE: Upload data to Thingspeak
응답
19. 5. 7 오전 10:38 as a reply to Priyashi Yadav.
Good day, the code is running well. However, I could only show the data in the console. Could you please guide me to send the data to thingspeak platform? Thank you very much  
0 (0 투표)
RE: Upload data to Thingspeak
응답
19. 5. 8 오전 4:48 as a reply to l Kent.

Hi Kent

https://xdk.bosch-connectivity.com/community/-/message_boards/message/476685

Refer the above post.

Thanks

Priyashi

0 (0 투표)