/**
 * @file    main.cpp
 * @brief   Vins Netra 2 client
 * @author  Vinay Shrivastava
 * @version 1.0
 * @see
 *
 * Copyright (c) 2016
 * 
 * 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 <string>
#include <sstream>
#include <vector>
#include "security.h"
#include "mbed.h"
#include "rtos.h"
#include "resources.h"


// Network interaction must be performed outside of interrupt context
Semaphore updates(0);
volatile bool registered = false;
volatile bool clicked = false;
volatile bool update_trigger = false;
osThreadId mainThread;

void unregister() {
    registered = false;
    updates.release();
}

void button_clicked() {
    clicked = true;
    updates.release();
}

void trigger_update(){
	update_trigger = true;
}	

// debug printf function
void trace_printer(const char* str) {
    printf("%s\r\n", str);
}

// Entry point to the program
int main() {

    unsigned int seed;
    size_t len;

#ifdef MBEDTLS_ENTROPY_HARDWARE_ALT
    // Used to randomize source port
    mbedtls_hardware_poll(NULL, (unsigned char *) &seed, sizeof seed, &len);

#elif defined MBEDTLS_TEST_NULL_ENTROPY

#warning "mbedTLS security feature is disabled. Connection will not be secure !! Implement proper hardware entropy for your selected hardware."
    // Used to randomize source port
    mbedtls_null_entropy_poll( NULL,(unsigned char *) &seed, sizeof seed, &len);

#else

#error "This hardware does not have entropy, endpoint will not register to Connector.\
You need to enable NULL ENTROPY for your application, but if this configuration change is made then no security is offered by mbed TLS.\
Add MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES and MBEDTLS_TEST_NULL_ENTROPY in mbed_app.json macros to register your endpoint."

#endif

    srand(seed);
    red_led = 1;
    blue_led = 1;
    //status_ticker.attach_us(blinky, 250000);
    // Keep track of the main thread
    mainThread = osThreadGetId();

    // Sets the console baud-rate
    output.baud(115200);

    output.printf("\r\nStarting mbed Client example in ");
#if defined (MESH) || (MBED_CONF_LWIP_IPV6_ENABLED==true)
    output.printf("IPv6 mode\r\n");
#else
    output.printf("IPv4 mode\r\n");
#endif

    mbed_trace_init();
    mbed_trace_print_function_set(trace_printer);

    NetworkInterface *network_interface = 0;
    int connect_success = -1;
#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI
    output.printf("\n\rConnecting to WiFi...\r\n");
    connect_success = wifi.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
    network_interface = &wifi;
#elif MBED_CONF_APP_NETWORK_INTERFACE == ETHERNET
    output.printf("\n\rConnecting to ethernet...\r\n");
    connect_success = eth.connect();
    network_interface = &eth;
#endif
#ifdef MESH
    output.printf("\n\rConnecting to Mesh...\r\n");
    mesh.initialize(&rf_phy);
    connect_success = mesh.connect();
    network_interface = &mesh;
#endif
    if(connect_success == 0) {
    output.printf("\n\rConnected to Network successfully\r\n");
    } else {
        output.printf("\n\rConnection to Network Failed %d! Exiting application....\r\n", connect_success);
        return 0;
    }
    const char *ip_addr = network_interface->get_ip_address();
    if (ip_addr) {
        output.printf("IP address %s\r\n", ip_addr);
    } else {
        output.printf("No IP address\r\n");
    }

    // create resources
    ButtonResource button_resource;
    LedResource led_resource;
    BigPayloadResource big_payload_resource;
	GnssCustomResource gnss_resource;
	AccelResource accel_resource;
	
	// enable accelerometer
	accel.enable();	
	output.printf("Initializied accelerometer\r\n");
	
	// Set gps UART baud rate
	gps.baud(115200);
	
    // Check GNSS UART connectivity
    if(gps.readable()) output.printf("GNSS UART interface connected. \n");
    else output.printf("WARNING: GNSS UART interface not connected or powered ON. \n");	

#ifdef TARGET_K64F
    // On press of SW3 button on K64F board, example application
    // will call unregister API towards mbed Device Connector
    //unreg_button.fall(&mbed_client,&MbedClient::test_unregister);
    unreg_button.fall(&unregister);

    // Observation Button (SW2) press will send update of endpoint resource values to connector
    obs_button.fall(&button_clicked);
#endif

    // Send update of endpoint resource values to connector every # seconds periodically
    timer.attach(&trigger_update, 0.5);

    // Create endpoint interface to manage register and unregister
    mbed_client.create_interface(MBED_SERVER_ADDRESS, network_interface);

    // Create Objects of varying types, see simpleclient.h for more details on implementation.
    M2MSecurity* register_object = mbed_client.create_register_object(); // server object specifying connector info
    M2MDevice*   device_object   = mbed_client.create_device_object();   // device resources object

    // Create list of Objects to register
    M2MObjectList object_list;

    // Add objects to list
    object_list.push_back(device_object);
	object_list.push_back(accel_resource.get_object());	     
	object_list.push_back(gnss_resource.get_object());	
   
    //object_list.push_back(button_resource.get_object());
    //object_list.push_back(led_resource.get_object());
    //object_list.push_back(big_payload_resource.get_object());

    // Set endpoint registration object
    mbed_client.set_register_object(register_object);

    // Register with mbed Device Connector
    mbed_client.test_register(register_object, object_list);
    registered = true;
    updates.wait(5000);

    while (true) {
        updates.wait(2000);
        if(registered) {
            if(!clicked && !update_trigger) {
                mbed_client.test_update_register();
            }
        }else {
            break;
        }
        if(clicked) {
           clicked = false;
            button_resource.handle_button_click();
        }
		if(update_trigger)
		{
			update_trigger = false;
			// Call resource refresh functions 
			// gnss_resource
			accel_resource.handle_accel_update();
			if(gps.readable()) gnss_resource.handle_gnss_update();
		}
    }

    mbed_client.test_unregister();
	timer.detach();
    //status_ticker.detach();
}
