Example node for Yodiwo's Plegma API

Dependencies:   EthernetInterface FXOS8700Q HTTPClient HTTPD MQTTS SDFileSystem YodiwoPlegma mbed-rpc mbed-rtos mbed wolfSSL

pairing_http_handler.cpp

Committer:
mitsarionas
Date:
2015-09-04
Revision:
2:b7489c070d1f
Child:
5:1ef168357347

File content as of revision 2:b7489c070d1f:

#include "EthernetInterface.h"
#include "HTTPD.h"
#include "string.h"
#include "pairing_backend.h"
#include "pairing_http_handler.h"

HTTPD *httpd;
pairing_context pairing_state;
onPaired_callback pairing_done_cb;
EthernetInterface *interface;
void pairing_handler (int id);

int start_pairing_http_server(EthernetInterface *eth, int port, onPaired_callback onPaired)
{
    pairing_done_cb = onPaired;
    interface = eth;
    httpd = new HTTPD;
//    httpd->attach("/cgi-bin/", &callback_cgi);
//    httpd->attach("/ws/", &callback_ws);
    httpd->attach("/pairing/", &pairing_handler);
    httpd->attach("/", "/sd/www/");
    return httpd->start(port);
}

void pairing_handler (int id)
{
    int i, n;
    int ret;
    char buf[256];
    char backUrl[100];
    
    if (!strcmp(httpd->getFilename(id), "startpairing")) {
        printf("starting pairing...\n");
        pairing_context_init_from_config(&pairing_state, pairing_done_cb);
        pairing_get_tokens(&pairing_state);
        
        int idx = 0;
        i = 0;
        sprintf(backUrl, "http://%s", interface->getIPAddress());
        char *uri = httpd->getUri(id);
        printf("1st url part: %s\n",backUrl);
        while (uri[i] != '\0') {
            if (uri[i] == '/') {
                idx = i;
            }
            i++;
        }
        strncat(backUrl, uri, idx + 1);
        printf("more of url: %s\n", backUrl);
        char *redirect = get_server_phase2_url(&pairing_state, backUrl);
        printf("redirect url: %s\n", redirect);
        if (redirect) {
            httpd->redirect(id, 302, redirect, NULL, 0, NULL);
//            free(redirect);
            return;
        }

    } else if (!strcmp(httpd->getFilename(id), "next")) {
        ret = pairing_get_keys(&pairing_state);
        pairing_done_cb(pairing_state.nodeKey, pairing_state.secretKey);
        sprintf(buf, "OK\r\nnodeKey: %s\r\nsecretKey: %s\r\n", pairing_state.nodeKey, pairing_state.secretKey);
        httpd->send(id, buf, strlen(buf), "Content-Type: text/plain\r\n");
    } else {
        httpd->httpdError(id, 404);
    }
    strcpy(buf, httpd->getFilename(id));
    strcat(buf, "\r\n");
    strcat(buf, httpd->getQueryString(id));
    strcat(buf, "\r\n");
    n = strlen(buf);
 
    i = httpd->receive(id, &buf[n], sizeof(buf) - n);
    if (i < 0) return;
    i += n;
    buf[i] = 0;
 
    printf("CGI %d %s\r\n", id, buf);
//    httpd->send(id, buf, i, "Content-Type: text/plain\r\n");
}