mbed Sensor node for Instrumented Booth over ETH.

Dependencies:   EthernetInterface-1 MaxbotixDriver Presence HTU21D_TEMP_HUMID_SENSOR_SAMPLE Resources SHARPIR mbed-rtos mbed-src WDT_K64F nsdl_lib

Fork of Trenton_Switch_LPC1768_ETH by Demo Team

main.cpp

Committer:
erigow01
Date:
2014-03-25
Revision:
15:59f4cee0da79
Parent:
14:5f84f9ae168e
Child:
16:3fb612af0dc5

File content as of revision 15:59f4cee0da79:

/* mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "mbed.h"
#include "cc3000.h"
#include "main.h"
#include "rtos.h"
#include "LPD8806.h"
// NanoService includes
#include "Endpoint.h"
#include "UDPSocket.h"
#include "sn_nsdl.h"
#include "sn_coap_header.h"
#include "sn_coap_protocol.h"
#include "sn_nsdl_lib.h"
#include "sn_grs.h"
#include <stdint.h>

#define STRINGIFY(x) #x
#define TO_STRING(x) STRINGIFY(x)

using namespace mbed_cc3000;

tUserFS user_info;

/* cc3000 module declaration specific for user's board. Check also init() */
#if (MY_BOARD == WIGO)
cc3000 wifi(PTA16, PTA13, PTD0, SPI(PTD2, PTD3, PTC5));
Serial pc(USBTX, USBRX);
#elif (MY_BOARD == WIFI_DIPCORTEX)
cc3000 wifi(p28, p27, p30, SPI(p21, p14, p37));
Serial pc(UART_TX, UART_RX);
#elif (MY_BOARD == MBED_BOARD_EXAMPLE)
cc3000 wifi(p9, p10, p8, SPI(p5, p6, p7));
Serial pc(USBTX, USBRX);
#else

#endif

#ifndef CC3000_UNENCRYPTED_SMART_CONFIG
  const uint8_t smartconfigkey[] = {0x73,0x6d,0x61,0x72,0x74,0x63,0x6f,0x6e,0x66,0x69,0x67,0x41,0x45,0x53,0x31,0x36};
#else
  const uint8_t smartconfigkey = 0;
#endif

// NSP configuration
/* Change this IP address to that of your NanoService Platform installation */
Endpoint nsp;
UDPSocket server;
static const char* NSP_ADDRESS = "10.2.131.119"; /* demo NSP, web interface at http://nanoservice-demo.mbed.org*/ 
static const int NSP_PORT = 5683;
char endpoint_name[] = {"umbrella"};
uint8_t ep_type[] = {"mbed_kl25z"};
uint8_t lifetime_ptr[] = {"86400"};

typedef uint8_t (*sn_grs_dyn_res_callback_t)(sn_coap_hdr_s *, sn_nsdl_addr_s *, sn_proto_info_s *);

//LED Config
//Number of RGB LEDs in strand:
int nLEDs=80;
int datapin=1;
int clockpin=2;
LPD8806 strip = LPD8806(nLEDs,datapin,clockpin);


/**
 *  \brief Print cc3000 information
 *  \param none
 *  \return none
 */
void print_cc3000_info() {
    uint8_t myMAC[8];

    printf("MAC address + cc3000 info \r\n");
    wifi.get_user_file_info((uint8_t *)&user_info, sizeof(user_info));
    wifi.get_mac_address(myMAC);
    printf(" MAC address %02x:%02x:%02x:%02x:%02x:%02x \r\n \r\n", myMAC[0], myMAC[1], myMAC[2], myMAC[3], myMAC[4], myMAC[5]);

    printf(" FTC        %i \r\n",user_info.FTC);
    printf(" PP_version %i.%i \r\n",user_info.PP_version[0], user_info.PP_version[1]);
    printf(" SERV_PACK  %i.%i \r\n",user_info.SERV_PACK[0], user_info.SERV_PACK[1]);
    printf(" DRV_VER    %i.%i.%i \r\n",user_info.DRV_VER[0], user_info.DRV_VER[1], user_info.DRV_VER[2]);
    printf(" FW_VER     %i.%i.%i \r\n",user_info.FW_VER[0], user_info.FW_VER[1], user_info.FW_VER[2]);
}

/**
 *  \brief Connect to SSID with a timeout
 *  \param ssid     Name of SSID
 *  \param key      Password
 *  \param sec_mode Security mode
 *  \return none
 */
void connect_to_ssid(char *ssid, char *key, unsigned char sec_mode) {
    printf("Connecting to SSID: %s. Timeout is 10s. \r\n",ssid);
    if (wifi.connect_to_AP((uint8_t *)ssid, (uint8_t *)key, sec_mode) == true) {
        printf(" Connected. \r\n");
    } else {
        printf(" Connection timed-out (error). Please restart. \r\n");
        while(1);
  }
}

/**
 *  \brief Connect to SSID without security
 *  \param ssid Name of SSID
 *  \return none
 */
void connect_to_ssid(char *ssid) {
    wifi.connect_open((uint8_t *)ssid);
}

/**
 *  \brief First time configuration
 *  \param none
 *  \return none
 */
void do_FTC(void) {
    printf("Running First Time Configuration \r\n");
    wifi.start_smart_config(smartconfigkey);
    while (wifi.is_dhcp_configured() == false) {
         wait_ms(500);
         printf("Waiting for dhcp to be set. \r\n");
    }
    user_info.FTC = 1;
    wifi.set_user_file_info((uint8_t *)&user_info, sizeof(user_info));
    wifi._wlan.stop();
    printf("FTC finished. \r\n");
}

/**
 *  \brief Start smart config
 *  \param none
 *  \return none
 */
void start_smart_config() {
    wifi.start_smart_config(smartconfigkey);
}

// ****************************************************************************
// NSP initialization

static void nsp_connect()
{
    
    printf("EP Name: %s", endpoint_name);
    printf("NSP Location: coap://%s:%d\n", NSP_ADDRESS, NSP_PORT);
    
    // Bind the port
    //cellular->bind(EP_PORT);
    server.init();
    server.bind(NSP_PORT);
    nsp.set_address(NSP_ADDRESS, NSP_PORT);

    printf("UDP connection to NSP successful.\r\n");  
}

extern "C" void *nsdl_alloc(uint16_t size)
{
    return malloc(size);
}

extern "C" void nsdl_free(void* ptr_to_free)
{
    free(ptr_to_free);
}

static uint8_t tx_cb(sn_nsdl_capab_e protocol, uint8_t *data_ptr, uint16_t data_len, sn_nsdl_addr_s *address_ptr)
{
/*    
    int buffer_len = data_len+2;
    printf("TX callback! Sending %d bytes\r\n", buffer_len);
    char buffer[buffer_len];
    buffer[0] = data_len >> 8;
    buffer[1] = data_len & 0xFF;
    memcpy(buffer+2, data_ptr, data_len);
  */  
    //if(cellular->write((char*)buffer, (int)buffer_len, 1000) != buffer_len)
    if(server.sendTo(nsp, (char*)data_ptr, (int)data_len) != data_len)
        printf("Sending failed\r\n");
        
    
    return 1;
    
}

static uint8_t rx_cb(sn_coap_hdr_s *coap_packet_ptr, sn_nsdl_addr_s *address_ptr)
{
    printf("RX callback!\r\n");
    return 0;
}

void nsdl_create_static_resource(sn_nsdl_resource_info_s *resource_structure, uint16_t pt_len, uint8_t *pt, uint16_t rpp_len, uint8_t *rpp_ptr, uint8_t *rsc, uint16_t rsc_len)
{
    resource_structure->access = SN_GRS_GET_ALLOWED;
    resource_structure->mode = SN_GRS_STATIC;
    resource_structure->pathlen = pt_len;
    resource_structure->path = pt;
    resource_structure->resource_parameters_ptr->resource_type_len = rpp_len;
    resource_structure->resource_parameters_ptr->resource_type_ptr = rpp_ptr;
    resource_structure->resource = rsc;
    resource_structure->resourcelen = rsc_len;
    sn_nsdl_create_resource(resource_structure);
}

void nsdl_create_dynamic_resource(sn_nsdl_resource_info_s *resource_structure, uint16_t pt_len, uint8_t *pt, uint16_t rpp_len, uint8_t *rpp_ptr, uint8_t is_observable, sn_grs_dyn_res_callback_t callback_ptr, int access_right)
{
    resource_structure->access = (sn_grs_resource_acl_e)access_right;
    resource_structure->resource = 0;
    resource_structure->resourcelen = 0;
    resource_structure->sn_grs_dyn_res_callback = callback_ptr;
    resource_structure->mode = SN_GRS_DYNAMIC;
    resource_structure->pathlen = pt_len;
    resource_structure->path = pt;
    resource_structure->resource_parameters_ptr->resource_type_len = rpp_len;
    resource_structure->resource_parameters_ptr->resource_type_ptr = rpp_ptr;
    resource_structure->resource_parameters_ptr->observable = is_observable;
    sn_nsdl_create_resource(resource_structure);
}

sn_nsdl_ep_parameters_s* nsdl_init_register_endpoint(sn_nsdl_ep_parameters_s *endpoint_structure, uint8_t* name, uint8_t* typename_ptr, uint8_t *lifetime_ptr)
{
    if (NULL == endpoint_structure)
    {   
        endpoint_structure = (sn_nsdl_ep_parameters_s*)nsdl_alloc(sizeof(sn_nsdl_ep_parameters_s));
    }
    if (endpoint_structure)
    {
        memset(endpoint_structure, 0, sizeof(sn_nsdl_ep_parameters_s));
        endpoint_structure->endpoint_name_ptr = name;
        endpoint_structure->endpoint_name_len = strlen((char*)name);
        endpoint_structure->type_ptr = typename_ptr;
        endpoint_structure->type_len =  strlen((char*)typename_ptr);
        endpoint_structure->lifetime_ptr = lifetime_ptr;
        endpoint_structure->lifetime_len =  strlen((char*)lifetime_ptr);
    }
    return endpoint_structure;
}

void nsdl_clean_register_endpoint(sn_nsdl_ep_parameters_s **endpoint_structure)
{
    if (*endpoint_structure)
    {
        nsdl_free(*endpoint_structure);
        *endpoint_structure = NULL;
    }
}

void nsdl_init()
{
    uint8_t nsp_addr[4];
    sn_nsdl_mem_s memory_cbs;
    memory_cbs.sn_nsdl_alloc = &nsdl_alloc;
    memory_cbs.sn_nsdl_free = &nsdl_free;
    if(sn_nsdl_init(&tx_cb, &rx_cb, &memory_cbs) == -1) {
        printf("libNsdl init failed\r\n");
    } else {
        printf("libNsdl init done\r\n");
    }
    /* Set nsp address for library */
    set_NSP_address(nsp_addr, 5683, SN_NSDL_ADDRESS_TYPE_IPV4);
}

static int create_resources()
{
    sn_nsdl_resource_info_s *resource_ptr = NULL;
    sn_nsdl_ep_parameters_s *endpoint_ptr = NULL;
    
    printf("Creating resources\r\n");

    /* Create resources */
    resource_ptr = (sn_nsdl_resource_info_s*)nsdl_alloc(sizeof(sn_nsdl_resource_info_s));
    if(!resource_ptr)
        return 0;
    memset(resource_ptr, 0, sizeof(sn_nsdl_resource_info_s));

    resource_ptr->resource_parameters_ptr = (sn_nsdl_resource_parameters_s*)nsdl_alloc(sizeof(sn_nsdl_resource_parameters_s));
    if(!resource_ptr->resource_parameters_ptr)
    {
        nsdl_free(resource_ptr);
        return 0;
    }
    memset(resource_ptr->resource_parameters_ptr, 0, sizeof(sn_nsdl_resource_parameters_s));

    // Static resources
    nsdl_create_static_resource(resource_ptr, sizeof("3/0/1")-1, (uint8_t*) "3/0/1", 0, 0,  (uint8_t*) "KL25Z Umbrella Stand", sizeof("KL25Z Umbrella Stand")-1);

    // Dynamic resources
    // create_light_resource(resource_ptr);
    // create_gps_resource(resource_ptr);

    /* Register with NSP */
    endpoint_ptr = nsdl_init_register_endpoint(endpoint_ptr, (uint8_t*)endpoint_name, ep_type, lifetime_ptr);
    if(sn_nsdl_register_endpoint(endpoint_ptr) != 0) {
        printf("NSP registering failed\r\n");
    } else {
        printf("NSP registering OK\r\n");
    }
    nsdl_clean_register_endpoint(&endpoint_ptr);

    nsdl_free(resource_ptr->resource_parameters_ptr);
    nsdl_free(resource_ptr);
    return 1;
}

void nsp_register()
{
    sn_nsdl_ep_parameters_s *endpoint_ptr = NULL;

    endpoint_ptr = nsdl_init_register_endpoint(endpoint_ptr, (uint8_t*)endpoint_name, ep_type, lifetime_ptr);
    if(sn_nsdl_register_endpoint(endpoint_ptr) != 0) {
        printf("NSP re-registration failed\r\n");
    } else {
        printf("NSP re-registration OK\r\n");
    }
    nsdl_clean_register_endpoint(&endpoint_ptr);
}

void socket_event_loop()
{
    sn_nsdl_addr_s received_packet_address;
    uint8_t received_address[4];
    char buffer[2048];
    int n;
    Endpoint from;

    memset(&received_packet_address, 0, sizeof(sn_nsdl_addr_s));
    received_packet_address.addr_ptr = received_address; 

    printf("Starting socket read loop...\r\n");
    while(1)
    {
        //n = cellular->read(buffer, sizeof(buffer), 1000);
        n = server.receiveFrom(from, buffer, sizeof(buffer));
        printf("Received %d bytes", n);
        if (n < 0)
        {
            printf("Socket error\r\n");
        }
        else
        {   
            uint16_t len = 0;
            if (n > 2) {
                len = 256 * buffer[0] + buffer[1]; 
                printf("CoAP length header = %d bytes\r\n", len);
                sn_nsdl_process_coap((uint8_t*)buffer+2, len, &received_packet_address);
            }
        } 
    }

}

/************************************************************************************
Use Color Fill to fill strips from bottom up in a 6 strip alternating configuration.
c           The colour
delay       Time between each pixel activation
numStrips   Number of sub-strips
direction   <0 implies top down, >0 bottom up, 0 all at once. Assumes first pixel is top.
alternating 0 implies first pixel of each strip is top, otherwise alternates top/bottom/top etc.
*************************************************************************************/
void colorFillAlternatingSubStrips(uint32_t c, uint8_t delay, uint8_t numSubStrips, uint8_t alternating, int8_t direction) {
    
    int i,j;
    int pixelsPerStrip = strip.numPixels() / numSubStrips;

    //set each pixel sequentially:
    for (i=0; i < pixelsPerStrip; i++) {
        for(j = 0; j < numSubStrips; j++) {
            if(!alternating || j % 2 == 0) {
                // Even strip
                if(direction <= 0) {
                    //Down
                    strip.setPixelColor(j*pixelsPerStrip + i, c);
                } else if (direction > 0) {
                    //Up
                    strip.setPixelColor((j+1)*pixelsPerStrip - 1 - i, c);
                }
            } else {
                // Odd Strip
                if(direction < 0) {
                    //Down
                    strip.setPixelColor((j+1)*pixelsPerStrip - 1 - i, c);
                } else if (direction >= 0) {
                    //Up
                    strip.setPixelColor(j*pixelsPerStrip + i, c);
                }
            }
        }
        if(direction != 0) {
            strip.show();
            wait_ms(delay);
        }
    }
    if(direction == 0) {
        strip.show();
        wait_ms(delay);
    }
}

void doNotificationIteration() {
    colorFillAlternatingSubStrips(strip.Color(0,127,0), 100, 6, 1, 1);
    wait_ms (3000);
    colorFillAlternatingSubStrips(strip.Color(0,0,0), 100, 6, 1, 1);
    wait_ms (1000);
}


/**
 *  \brief Simple socket demo
 *  \param none
 *  \return int
 */
int main() {
    init(); /* board dependent init */
    pc.baud(115200);

    wifi.start(0);
    printf("cc3000 simple socket demo. \r\n");
    print_cc3000_info();

    printf("Attempting SSID Connection. \r\n");

    wifi._wlan.ioctl_set_connection_policy(0, 0, 0);
#ifndef CC3000_TINY_DRIVER
    connect_to_ssid(SSID, AP_KEY, AP_SECURITY);
#else
    connect_to_ssid(SSID);
#endif

    printf("DHCP request \r\n");
    while (wifi.is_dhcp_configured() == false) {
         wait_ms(500);
         printf("  Waiting for dhcp to be set. \r\n");
    }

    tNetappIpconfigRetArgs ipinfo2;
    wifi.get_ip_config(&ipinfo2); // data is returned in the ipinfo2 structure
    printf("DHCP assigned IP Address = %d.%d.%d.%d \r\n", ipinfo2.aucIP[3], ipinfo2.aucIP[2], ipinfo2.aucIP[1], ipinfo2.aucIP[0]);

    // Bind the socket and configure NSP settings
    nsp_connect();
 
    // Initalize NanoService library
    nsdl_init();

    // Create resources & register with NSP
    create_resources(); 
     
    // Start socket listening loop
    socket_event_loop();

}