LightSensorExample file needed
응답
17. 9. 22 오전 2:43

Hi does anyone have a the LightSensorExample project file that you guys can upload somewhere. I have tried downloading all the versions but can’t find it however i need it for my project. 

 

If you have the file please upload it and sens the link here or write out the code here. Thanks

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 22 오전 10:08 as a reply to Darren Tan.

https://xdk.bosch-connectivity.com/documents/37728/286250/XDK_Guide_Sensor.pdf

 

Also you have example "Sending sensor data over USB". There are code files for each sensor inside XDK

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 22 오후 1:29 as a reply to Zoran Roncevic.

Hello Darren,

I am not exactly sure what you refer to, when you say LightSensorExample, but I can give you code samples for initializing and reading the sensor here.

#include "XdkSensorHandle.h"

void init (void){
    Retcode_T lightSensorInitReturnValue = RETCODE_FAILURE;
    Retcode_T returnBrightnessValue = RETCODE_FAILURE;
    Retcode_T returnIntegrationTimeValue = RETCODE_FAILURE;
    lightSensorInitReturnValue = LightSensor_init(
            xdkLightSensor_MAX44009_Handle);
    if (RETCODE_OK != lightSensorInitReturnValue) {
        // do something
    }
    returnBrightnessValue = LightSensor_setBrightness(
            xdkLightSensor_MAX44009_Handle, LIGHTSENSOR_NORMAL_BRIGHTNESS);
    if (RETCODE_OK != returnBrightnessValue) {
        // do something
    }
    returnIntegrationTimeValue = LightSensor_setIntegrationTime(
            xdkLightSensor_MAX44009_Handle, LIGHTSENSOR_200MS);
    if (RETCODE_OK != returnIntegrationTimeValue) {
        // do something
    }
}

void read (void) {
  Retcode_T returnValue = RETCODE_FAILURE;
  returnValue = LightSensor_init(xdkLightSensor_MAX44009_Handle);
  if ( RETCODE_OK != returnValue) {
    // do something
  }
  uint32_t milliLuxData = UINT32_C(0);
  /* read ambient light sensor */
  returnValue = LightSensor_readLuxData(xdkLightSensor_MAX44009_Handle,
      &milliLuxData);
  if (RETCODE_OK == returnValue) {
    printf("Light sensor data obtained in milli lux: %d \n\r",
        (unsigned int) milliLuxData);
  }
}

Before you read data, you have to use init() to initialize the LightSensor. The function read() only prints the data to the console, but does nothing more than that with the data. If you require more information on the subject of sensors, please refer to the Sensor Guide, as Zoran already mentioned, or the First Steps Guide here.

Please tell me if this was helpful and do not hesitate to ask further questions.

Kind regards,
Franjo

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 28 오전 11:46 as a reply to Franjo Stjepandic.
/**
 * This software is copyrighted by Bosch Connected Devices and Solutions GmbH, 2016.
 * The use of this software is subject to the XDK SDK EULA
 */

/* module includes ********************************************************** */

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

/* additional interface header files */
#include <FreeRTOS.h>
#include <timers.h>

#include "PAL_initialize_ih.h"
#include "PAL_socketMonitor_ih.h"
#include "BCDS_WlanConnect.h"
#include "BCDS_NetworkConfig.h"
#include <Serval_HttpClient.h>
#include <Serval_Network.h>

/* own header files */
#include "HttpExampleClient.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 */

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

/* local functions ********************************************************** */
/* The description is in the header file. */



static retcode_t wlanConnect(void)
{
    NCI_ipSettings_t myIpSettings;
    char ipAddress[PAL_IP_ADDRESS_SIZE] = {0};
    Ip_Address_T* IpaddressHex = Ip_getMyIpAddr();
    WLI_connectSSID_t connectSSID;
    WLI_connectPassPhrase_t connectPassPhrase;

    if(WLI_SUCCESS != WLI_init())
    {
        return(RC_PLATFORM_ERROR);
    }

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

    connectSSID = (WLI_connectSSID_t) WLAN_CONNECT_WPA_SSID;
    connectPassPhrase = (WLI_connectPassPhrase_t) WLAN_CONNECT_WPA_PASS;

    if (WLI_SUCCESS == WLI_connectWPA(connectSSID, connectPassPhrase, NULL))
    {
        NCI_getIpSettings(&myIpSettings);
        *IpaddressHex = Basics_htonl(myIpSettings.ipV4);
        (void)Ip_convertAddrToString(IpaddressHex,(char *)&ipAddress);
        printf("Connected to WPA network successfully \r\n ");
        printf(" Ip address of the device %s \r\n ",ipAddress);
        return(RC_OK);
    }
    else
    {
        return(RC_PLATFORM_ERROR);
    }

}

/* The description is in the configuration header file. */
static retcode_t callbackOnSent(Callable_T *callfunc, retcode_t status)
{
    (void) callfunc;

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

/* The description is in the configuration header file. */
static retcode_t httpClientResponseCallback(HttpSession_T *httpSession ,
        Msg_T *msg_ptr, retcode_t status)
{
    (void) httpSession;
    retcode_t rc = status;

    if (status != RC_OK)
    {
        /* Error occurred in downloading the page */
    }
    else if (msg_ptr == NULL)
    {
        rc = RC_HTTP_PARSER_INVALID_CONTENT_TYPE;
    }
    else
    {
        if (HttpMsg_getStatusCode(msg_ptr)!= Http_StatusCode_OK)
        {
        	rc = RC_HTTP_INVALID_RESPONSE;
        }
        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 length %d \r\n", content_ptr, len);
            }
        }
    }

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

/* global functions ********************************************************** */

/**
 * @brief initialize the sensors
 *
 * @return NONE
 */

void init (void){
    Retcode_T lightSensorInitReturnValue = RETCODE_FAILURE;
    Retcode_T returnBrightnessValue = RETCODE_FAILURE;
    Retcode_T returnIntegrationTimeValue = RETCODE_FAILURE;
    lightSensorInitReturnValue = LightSensor_init(
            xdkLightSensor_MAX44009_Handle);
    if (RETCODE_OK != lightSensorInitReturnValue) {
        // do something
    }
    returnBrightnessValue = LightSensor_setBrightness(
            xdkLightSensor_MAX44009_Handle, LIGHTSENSOR_NORMAL_BRIGHTNESS);
    if (RETCODE_OK != returnBrightnessValue) {
        // do something
    }
    returnIntegrationTimeValue = LightSensor_setIntegrationTime(
            xdkLightSensor_MAX44009_Handle, LIGHTSENSOR_200MS);
    if (RETCODE_OK != returnIntegrationTimeValue) {
        // do something
    }
}

void read (void) {
  Retcode_T returnValue = RETCODE_FAILURE;
  returnValue = LightSensor_init(xdkLightSensor_MAX44009_Handle);
  if ( RETCODE_OK != returnValue) {
    // do something
  }
  uint32_t milliLuxData = UINT32_C(0);
  /* read ambient light sensor */
  returnValue = LightSensor_readLuxData(xdkLightSensor_MAX44009_Handle,
      &milliLuxData);
  if (RETCODE_OK == returnValue) {
    printf("Light sensor data obtained in milli lux: %d \n\r",
        (unsigned int) milliLuxData);
  }
}

void connectServer(xTimerHandle xTimer)
{
    (void) (xTimer);

    retcode_t rc = RC_OK;
    Msg_T* msg_ptr;
    Ip_Port_T destPort = (Ip_Port_T) DEST_PORT_NUMBER;
    static Callable_T SentCallable;
    const char url_ptr[100];
    int n = sprintf(url_ptr,"/update?key=WI5HXGBDB0TOWCSR&field1=%.2f&field2=%.2f", milliLuxData, milliLuxData);

    Callable_assign(&SentCallable, &callbackOnSent);

    rc = HttpClient_initRequest(&destAddr, Ip_convertIntToPort(destPort), &msg_ptr);

    if (rc != RC_OK || msg_ptr == NULL)
    {
       printf("Failed HttpClient_initRequest\r\n " );
       return;
    }

    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;
    }
}

/* The description is in the interface header file. */
extern 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 = CONNECT_TIME_INTERVAL;

        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);
        }
        connectTimerHandle = xTimerCreate(
                (const char * const ) "connectServer", Ticks,
                TIMER_AUTORELOAD_ON, NULL, connectServer);

        if (connectTimerHandle != NULL)
        {
            if(xTimerStart(connectTimerHandle, TIMERBLOCKTIME)!=pdTRUE)
            {
                assert(0);
            }

        }
    }
}

/* The description is in the interface header file. */
extern void deinit(void)
{
    /*do nothing*/
}

/**
 * @brief This is a template function where the user can write his custom application.
 *
 */
void appInitSystem(xTimerHandle xTimer)
{
    (void) (xTimer);
    /*Call the RHC init API */
    init();
}
/** ************************************************************************* */

This is the code after combining it, i'm getting errors and i'm sure this is wrong. Please help and advise on how it should be done.

The errors im getting are:

C:/XDK-Workbench/SDK/xdk110/Apps/HttpExampleClient/source/HttpExampleClient.c:145:13: error: 'xdkLightSensor_MAX44009_Handle' undeclared (first use in this function)
C:/XDK-Workbench/SDK/xdk110/Apps/HttpExampleClient/source/HttpExampleClient.c:150:45: error: 'LIGHTSENSOR_NORMAL_BRIGHTNESS' undeclared (first use in this function)
C:/XDK-Workbench/SDK/xdk110/Apps/HttpExampleClient/source/HttpExampleClient.c:155:45: error: 'LIGHTSENSOR_200MS' undeclared (first use in this function)
C:/XDK-Workbench/SDK/xdk110/Apps/HttpExampleClient/source/HttpExampleClient.c:163:34: error: 'xdkLightSensor_MAX44009_Handle' undeclared (first use in this function)
C:/XDK-Workbench/SDK/xdk110/Apps/HttpExampleClient/source/HttpExampleClient.c:186:85: error: 'milliLuxData' undeclared (first use in this function)
C:/XDK-Workbench/SDK/xdk110/Apps/HttpExampleClient/source/HttpExampleClient.c:216:13: error: redefinition of 'init'

 

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 28 오전 11:49 as a reply to Darren Tan.
I realise i forgot to add
#include "XdkSensorHandle.h"

But after adding that i still get errors like these:

C:/XDK-Workbench/SDK/xdk110/Apps/HttpExampleClient/source/HttpExampleClient.c:187:85: error: 'milliLuxData' undeclared (first use in this function)
C:/XDK-Workbench/SDK/xdk110/Apps/HttpExampleClient/source/HttpExampleClient.c:217:13: error: redefinition of 'init'

 

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 28 오후 3:04 as a reply to Darren Tan.

Hello Darren,

I took a look at your implementation and can guide you to a solution.

Regarding the issue of the redefinition of the function init(): You are using two init() functions in your code. I posted one of them to initialize the light sensor and the other one is the already existing from the HttpExampleClient you are using. To solve the issue, I recommend renaming one of the functions, or combining the implementation from both functions into one init() function.

Regarding your second issue, the variable milliLuxData is only declared as a local variable in the function read(). But you are using the same variable in the function connectServer() without declaration. That's the reason why the error stating that the variable is undeclared appears.

To solve the issue, you could declare the variable as a global variable, outside of the function read(). In this case, both functions connectServer() and read() would have access to the content of the variable milliLuxData. Alternatively, you could reimplement the signature of the function read() to return the value of the variable milliLuxData. Then this function call could be used to deliver the value of milliLuxData to be inserted in the URL of the GET request.

Besides that, as I analyzed your code, I noticed that you are using the XDK-Workbench 1.5.2. I would recommend using the latest XDK-Workbench version 3.0.1, since solutions for other issues may only be applicable in later versions of the XDK-Workbench.

Please let me know if that was helpful and do not hesitate to ask if you have further questions.

Kind regards,
Franjo

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 29 오전 2:51 as a reply to Franjo Stjepandic.

This is my current code, it compiles fine, however  i still get 0 as a data from the sensor.

/*
* Licensee agrees that the example code provided to Licensee has been developed and released by Bosch solely as an example to be used as a potential reference for Licensee�s application development. 
* Fitness and suitability of the example code for any use within Licensee�s applications need to be verified by Licensee on its own authority by taking appropriate state of the art actions and measures (e.g. by means of quality assurance measures).
* Licensee shall be responsible for conducting the development of its applications as well as integration of parts of the example code into such applications, taking into account the state of the art of technology and any statutory regulations and provisions applicable for such applications. Compliance with the functional system requirements and testing there of (including validation of information/data security aspects and functional safety) and release shall be solely incumbent upon Licensee. 
* For the avoidance of doubt, Licensee shall be responsible and fully liable for the applications and any distribution of such applications into the market.
* 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are 
* met:
* 
*     (1) Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer. 
* 
*     (2) Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in
*     the documentation and/or other materials provided with the
*     distribution.  
*     
*     (3)The name of the author may not be used to
*     endorse or promote products derived from this software without
*     specific prior written permission.
* 
*  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 
*  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
*  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
*  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
*  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
*  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
*  POSSIBILITY OF SUCH DAMAGE.
*/
/*----------------------------------------------------------------------------*/

/**
* @ingroup APPS_LIST
*
* @defgroup HTTP_EXAMPLE_CLIENT HttpExampleClient
* @{
*
* @brief Demo application for communicating with the HTTP to GET and POST content on the Server and demonstrate the use of custom headers.
*
* @details This example shows how to use the network stack to perform an HTTP Client Request.
*
* The example connects to the server <a href="http://www.posttestserver.com">www.posttestserver.com</a> and establishes a connection to the server.
*
* To view your posts, browse to the year, month, day, time and directory name XDK:
* <a href="http://posttestserver.com/data/">http://posttestserver.com/data/</a> This means all posts are visible to everybody so don't test with secure credentials.
* There you can see your custem heders as well.
*
* You need to add your WLAN-Credatials in \ref HttpExampleClient.h\n
* When running the program keep the USB plugged in to the PC. You can see in the consol output of the XDK-Workbench the content of the GET request.
*
* @file HttpExampleClient.c
**/

/* module includes ********************************************************** */

/* 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

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

/* 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 "XdkSensorHandle.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 */
uint32_t milliLuxData = UINT32_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;
    case 1:
        n = strlen(myheader2);
        rc = TcpMsg_copyContentAtomic(omsh_ptr, myheader2, n);
        if (rc != RC_OK)
            return rc;
        omsh_ptr->position = 2;
    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;
    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 ********************************************************** */


void Sensorinit (void){
    Retcode_T lightSensorInitReturnValue = RETCODE_FAILURE;
    Retcode_T returnBrightnessValue = RETCODE_FAILURE;
    Retcode_T returnIntegrationTimeValue = RETCODE_FAILURE;
    lightSensorInitReturnValue = LightSensor_init(
            xdkLightSensor_MAX44009_Handle);
    if (RETCODE_OK != lightSensorInitReturnValue) {
        // do something
    }
    returnBrightnessValue = LightSensor_setBrightness(
            xdkLightSensor_MAX44009_Handle, LIGHTSENSOR_NORMAL_BRIGHTNESS);
    if (RETCODE_OK != returnBrightnessValue) {
        // do something
    }
    returnIntegrationTimeValue = LightSensor_setIntegrationTime(
            xdkLightSensor_MAX44009_Handle, LIGHTSENSOR_200MS);
    if (RETCODE_OK != returnIntegrationTimeValue) {
        // do something
    }
}

void Sensorread (void) {
  Retcode_T returnValue = RETCODE_FAILURE;
  returnValue = LightSensor_init(xdkLightSensor_MAX44009_Handle);
  if ( RETCODE_OK != returnValue) {
    // do something
  }
  //uint32_t milliLuxData = UINT32_C(0);
  /* read ambient light sensor */
  returnValue = LightSensor_readLuxData(xdkLightSensor_MAX44009_Handle,
      &milliLuxData);
  if (RETCODE_OK == returnValue) {
    printf("Light sensor data obtained in milli lux: %d \n\r",
        (unsigned int) milliLuxData);
  }
}
/**
 * @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;
    Ip_Port_T destPort = (Ip_Port_T) DEST_PORT_NUMBER;
    static Callable_T SentCallable;
    const char url_ptr[100];
    int n = sprintf(url_ptr,"/update?key=WI5HXGBDB0TOWCSR&field1=%.2f&field2=%.2f", milliLuxData, milliLuxData);
    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 = CONNECT_TIME_INTERVAL;

        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);
    }
    AppCmdProcessor = (CmdProcessor_T *) CmdProcessorHandle;
    BCDS_UNUSED(param2);
    /*Call the RHC init API */
    Init();

}
/**@} */

 

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 29 오전 3:27 as a reply to Darren Tan.
Also, do i have to call the method Sensorinit and Sensorread inside PrintWebpageContent?
0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 29 오전 3:37 as a reply to Darren Tan.
If yes, could you show me how to do it? As i do not understand how method calling works.
0 (0 투표)
RE: LightSensorExample file needed
응답
17. 9. 29 오후 4:34 as a reply to Darren Tan.

Hello Darren,

I analyzed your code. The content of the variable milliLuxData is indeed zero because you do not call the function Sensorread() to update the value of the variable.
The function Sensorinit() isn't called anywhere either.

If I may explain it in more detail. For your application, you need to call functions, which initialize certain modules as the sensors, the Wi-Fi or HTTP itself only once. It is recommended to do that in the function appInitSystem(), which is the first function that is called within the entire application. This is why you should add the line Sensorinit() inside the function appInitSystem().

Regarding your suggestion about the function Sensorread(), you are correct, you should insert a call of the function Sensorread() in PrintWebpageContent(), before the variable milliLuxData is called.

Besides that, most of the issues you are facing are due to missing basic C knowledge, I would kindly recommend going through a C tutorial to get familiar with the language.

Additionally, I would recommend going through the XDK guides First Steps and FreeRTOS to get familiar about how applications on the XDK should be programmed to work properly. As mentioned before, there is also a guide for sensors. You can find all the guides here.

Please let me know if that was helpful and do not hesitate to ask if you have further questions.

Kind regards,
Franjo

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 10. 2 오전 11:04 as a reply to Franjo Stjepandic.

Hi, sorry for the trouble yet again. I've got it to work as how you explained it, however the data is being shown on the console only, it does not seem to be showing in thingspeak, it keeps updating 0, the workbench keeps saying that this line has unused variable as well.

"int n = sprintf(url_ptr,"/update?key=WI5HXGBDB0TOWCSR&field1=%.2f&field2=%.2f", milliLuxData, milliLuxData);"

 

/*
* Licensee agrees that the example code provided to Licensee has been developed and released by Bosch solely as an example to be used as a potential reference for Licensee�s application development. 
* Fitness and suitability of the example code for any use within Licensee�s applications need to be verified by Licensee on its own authority by taking appropriate state of the art actions and measures (e.g. by means of quality assurance measures).
* Licensee shall be responsible for conducting the development of its applications as well as integration of parts of the example code into such applications, taking into account the state of the art of technology and any statutory regulations and provisions applicable for such applications. Compliance with the functional system requirements and testing there of (including validation of information/data security aspects and functional safety) and release shall be solely incumbent upon Licensee. 
* For the avoidance of doubt, Licensee shall be responsible and fully liable for the applications and any distribution of such applications into the market.
* 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are 
* met:
* 
*     (1) Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer. 
* 
*     (2) Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in
*     the documentation and/or other materials provided with the
*     distribution.  
*     
*     (3)The name of the author may not be used to
*     endorse or promote products derived from this software without
*     specific prior written permission.
* 
*  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 
*  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
*  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
*  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
*  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
*  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
*  POSSIBILITY OF SUCH DAMAGE.
*/
/*----------------------------------------------------------------------------*/

/**
* @ingroup APPS_LIST
*
* @defgroup HTTP_EXAMPLE_CLIENT HttpExampleClient
* @{
*
* @brief Demo application for communicating with the HTTP to GET and POST content on the Server and demonstrate the use of custom headers.
*
* @details This example shows how to use the network stack to perform an HTTP Client Request.
*
* The example connects to the server <a href="http://www.posttestserver.com">www.posttestserver.com</a> and establishes a connection to the server.
*
* To view your posts, browse to the year, month, day, time and directory name XDK:
* <a href="http://posttestserver.com/data/">http://posttestserver.com/data/</a> This means all posts are visible to everybody so don't test with secure credentials.
* There you can see your custem heders as well.
*
* You need to add your WLAN-Credatials in \ref HttpExampleClient.h\n
* When running the program keep the USB plugged in to the PC. You can see in the consol output of the XDK-Workbench the content of the GET request.
*
* @file HttpExampleClient.c
**/

/* module includes ********************************************************** */

/* 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

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

/* 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 "XdkSensorHandle.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 */
static uint32_t milliLuxData = UINT32_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;
    case 1:
        n = strlen(myheader2);
        rc = TcpMsg_copyContentAtomic(omsh_ptr, myheader2, n);
        if (rc != RC_OK)
            return rc;
        omsh_ptr->position = 2;
    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;
    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 ********************************************************** */

void Sensorinit (void){
    Retcode_T lightSensorInitReturnValue = RETCODE_FAILURE;
    Retcode_T returnBrightnessValue = RETCODE_FAILURE;
    Retcode_T returnIntegrationTimeValue = RETCODE_FAILURE;
    lightSensorInitReturnValue = LightSensor_init(
            xdkLightSensor_MAX44009_Handle);
    if (RETCODE_OK != lightSensorInitReturnValue) {
        // do something
    }
    returnBrightnessValue = LightSensor_setBrightness(
            xdkLightSensor_MAX44009_Handle, LIGHTSENSOR_NORMAL_BRIGHTNESS);
    if (RETCODE_OK != returnBrightnessValue) {
        // do something
    }
    returnIntegrationTimeValue = LightSensor_setIntegrationTime(
            xdkLightSensor_MAX44009_Handle, LIGHTSENSOR_200MS);
    if (RETCODE_OK != returnIntegrationTimeValue) {
        // do something
    }
}

void Sensorread (void) {
  Retcode_T returnValue = RETCODE_FAILURE;
  returnValue = LightSensor_init(xdkLightSensor_MAX44009_Handle);
  if ( RETCODE_OK != returnValue) {
	  // do something
  }
  uint32_t milliLuxData = UINT32_C(0);
  /* read ambient light sensor */
  returnValue = LightSensor_readLuxData(xdkLightSensor_MAX44009_Handle,
      &milliLuxData);
  if (RETCODE_OK == returnValue) {
    printf("Light sensor data obtained in milli lux: %d \n\r",
        (unsigned int) milliLuxData);
  }
}


/**
 * @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)
{
	Sensorread();
    BCDS_UNUSED(param1);
    BCDS_UNUSED(param2);
    retcode_t rc = RC_OK;
    Msg_T* msg_ptr;
    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=WI5HXGBDB0TOWCSR&field1=%.2f&field2=%.2f", milliLuxData, milliLuxData);
    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 = CONNECT_TIME_INTERVAL;

        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)
{
	Sensorinit();
    if (CmdProcessorHandle == NULL)
    {
        printf("Command processor handle is null \n\r");
        assert(false);
    }
    AppCmdProcessor = (CmdProcessor_T *) CmdProcessorHandle;
    BCDS_UNUSED(param2);
    /*Call the RHC init API */
    Init();

}
/**@} */

 

 

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 10. 4 오전 11:45 as a reply to Darren Tan.

Hello Darren,

I am glad to hear that you were able to make your application work. Your new issue can have multiple reasons. One could be indeed related to your XDK application, the other to the thingspeak platform itself.

The values in the url_ptr are set to zero, because you have two declarations of milliLuxData in your project. The first is global, which is appropriate for this use. The problem is the second one in Sensorread(). You declare uint32_t milliLuxData = UINT32_C(0); locally inside the function, which is why the local milliLuxData is updated, but the global one is not. To make this work, simply remove the declaration of milliLuxData inside Sensorread().

Additionally, in the line sprintf(url_ptr,"/update?key=WI5HXGBDB0TOWCSR&field1=%.2f&field2=%.2f", milliLuxData, milliLuxData); the variable milliLuxData is of type unsigned integer 32-bit. But the format identifiers you use are for float / double. If you require the values to be used with the unit lux and not millilux, you can wrap the variable like this:

((float) milliLuxData/1000)

This converts the variable to float, and then divides it by 1000.

Regarding your unused variable, you store the return value of the sprintf() function in the variable n, but your application does no further processing with the variable and that's the reason why the variable is marked as unused.

Please let me know, if that was helpful and do not hesitate to ask if you have further questions.

Kind regards,
Franjo

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 10. 5 오후 7:12 as a reply to Franjo Stjepandic.

This is my current code, however i have a issue where i get this constantly. 

INFO | XDK DEVICE 1: GET Response Content 448 
INFO | XDK DEVICE 1: Page content 3 Bytes Download Completed 
INFO | XDK DEVICE 1: error occurred in connecting server 

 

I've been looking around and trying to modify the code but still unable to find a fix, however i was able to send data constantly and not get the error in the old HttpExampleClient code, however that code does not work with the new 3.0.1 workbench.

 

/*
* Licensee agrees that the example code provided to Licensee has been developed and released by Bosch solely as an example to be used as a potential reference for Licensee�s application development. 
* Fitness and suitability of the example code for any use within Licensee�s applications need to be verified by Licensee on its own authority by taking appropriate state of the art actions and measures (e.g. by means of quality assurance measures).
* Licensee shall be responsible for conducting the development of its applications as well as integration of parts of the example code into such applications, taking into account the state of the art of technology and any statutory regulations and provisions applicable for such applications. Compliance with the functional system requirements and testing there of (including validation of information/data security aspects and functional safety) and release shall be solely incumbent upon Licensee. 
* For the avoidance of doubt, Licensee shall be responsible and fully liable for the applications and any distribution of such applications into the market.
* 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are 
* met:
* 
*     (1) Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer. 
* 
*     (2) Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in
*     the documentation and/or other materials provided with the
*     distribution.  
*     
*     (3)The name of the author may not be used to
*     endorse or promote products derived from this software without
*     specific prior written permission.
* 
*  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 
*  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
*  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
*  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
*  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
*  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
*  POSSIBILITY OF SUCH DAMAGE.
*/
/*----------------------------------------------------------------------------*/

/**
* @ingroup APPS_LIST
*
* @defgroup HTTP_EXAMPLE_CLIENT HttpExampleClient
* @{
*
* @brief Demo application for communicating with the HTTP to GET and POST content on the Server and demonstrate the use of custom headers.
*
* @details This example shows how to use the network stack to perform an HTTP Client Request.
*
* The example connects to the server <a href="http://www.posttestserver.com">www.posttestserver.com</a> and establishes a connection to the server.
*
* To view your posts, browse to the year, month, day, time and directory name XDK:
* <a href="http://posttestserver.com/data/">http://posttestserver.com/data/</a> This means all posts are visible to everybody so don't test with secure credentials.
* There you can see your custem heders as well.
*
* You need to add your WLAN-Credatials in \ref HttpExampleClient.h\n
* When running the program keep the USB plugged in to the PC. You can see in the consol output of the XDK-Workbench the content of the GET request.
*
* @file HttpExampleClient.c
**/

/* module includes ********************************************************** */

/* 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

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

/* 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 "BCDS_LightSensor.h"
#include "XdkSensorHandle.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 */
uint32_t milliLuxData = UINT32_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;
    case 1:
        n = strlen(myheader2);
        rc = TcpMsg_copyContentAtomic(omsh_ptr, myheader2, n);
        if (rc != RC_OK)
            return rc;
        omsh_ptr->position = 2;
    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;
    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 initLightSensor(void)
{
	Retcode_T returnValue = RETCODE_FAILURE;
	returnValue = LightSensor_init(xdkLightSensor_MAX44009_Handle);
	if(RETCODE_OK != returnValue)
	{
		printf("Light Sensor initialization Failed\n\r");
	}
}

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

	//uint32_t milliLuxData = UINT32_C(0);
	Retcode_T returnValue = RETCODE_FAILURE;

	returnValue = LightSensor_readLuxData(xdkLightSensor_MAX44009_Handle,
			&milliLuxData);

	if(RETCODE_OK == returnValue)
	{
		//printf("Light sensor data obtained in milli lux: %d \n\r",(unsigned int) milliLuxData);
	}
}

/**
 * @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;
    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 */
    //printf("(After)Light sensor data obtained in milli lux: %d \n\r",(unsigned int) milliLuxData);           //debugging issue
    printf("Sending data to Thingspeak\r\n");
    int n = sprintf(url_ptr,"/update?key=WI5HXGBDB0TOWCSR&field1=%d",(unsigned int) milliLuxData/1000);
    printf("Data sent\r\n");
    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 = CONNECT_TIME_INTERVAL;

        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(1000);
    uint32_t timerAutoReloadOn = pdTRUE;

    xTimerHandle LightSensorHandle= NULL;

    initLightSensor();

    LightSensorHandle = xTimerCreate((const char *) "readLightSensor", OneSecondDelay, timerAutoReloadOn, NULL, readLightSensor);

    xTimerStart(LightSensorHandle,timerBlockTime);

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

}
/**@} */

 

0 (0 투표)
RE: LightSensorExample file needed
응답
17. 10. 6 오전 9:06 as a reply to Darren Tan.
Bascially i need the code to loop the part where it sends data, now, it only sends data once and stops.
0 (0 투표)
RE: LightSensorExample file needed
응답
17. 10. 6 오후 1:11 as a reply to Darren Tan.

Hello Darren,

The lines in your console appear because the HttpExampleClient example in XDK-Workbench 3.0.1 differ from the HttpExampleClient of the XDK-Workbench 2.0.1. The Example from 3.0.1 sends an additional POST request after a successful GET Request instead of only sending periodic GET requests as was the case in the example from 2.0.1.

That's the reason, why there is a log in the console saying error occurred in connecting server after the GET request was successfully sent. Additionally, the timer responsible for sending GET requests is stopped.

To solve it, you only need to remove all implementation code in the function HttpClientResponseCallback() from line 386 to line 399.

Furthermore, the HttpExampleClient has some things which you do not need, such as seralizing custom headers. I recommend removing source code which you do not need or use. (But be aware that errors might appear if you don't remove code properly)

Please let me know if that was helpful and do not hesitate to ask if you have further questions.

Kind regards,
Franjo

0 (0 투표)