part of the preparation works for Ina-city Hackerthon

Dependencies:   Grove_temperature mbed-http

Fork of Mbed-to-cybozu-kintone_post_sample by Junichi Katsu

main.cpp

Committer:
MACRUM
Date:
2018-08-24
Revision:
2:687ce876e4ee
Parent:
1:6c0383514e5b

File content as of revision 2:687ce876e4ee:

#include "mbed.h"
#include <sstream>
#include "easy-connect.h"
#include "https_request.h"
#include "ssl_ca_pem.h"
#include "Grove_temperature.h"

#if !defined(TARGET_WIO_3G)
#error Selected target is not supported.
#endif

// For your API Token, refer to "API token" in your application setting page
// Please DO NOT FORGET to assign "add records" to your key.
const char API_TOKEN[] = "api-key";

// Your domain name can be seen in the usage explanation with curl.
const char URL[] = "https://{domain}.cybozu.com/k/v1/record.json";

// app_id, application id, can be checked with your application's URL
// e.g. https://{domain}.cybozu.com/k/3/ -> app_id is 3
int app_id = 3;

// on-board resources
Serial pc(USBTX, USBRX, 115200);
DigitalOut GrovePower(PB_10, 1);

// Grove sensors
// Temperature sensor
Grove_temperature tempSensor(A4);

bool post_kintone(NetworkInterface* nif, const char *url, int app_id_, char* field_code, float value)
{
    HttpsRequest* post_req = new HttpsRequest(nif, SSL_CA_PEM, HTTP_POST, url);
    post_req->set_header("X-Cybozu-API-Token", API_TOKEN);
    post_req->set_header("Content-Type", "application/json");

    std::stringstream ss_body;

    ss_body << "{\"app\": " << app_id_ << ", \"record\": {\"" << field_code << "\": {\"value\": \"" << value << "\"}}}\n";

    string body = ss_body.str();
    pc.printf("body:%s\n",body.c_str());

    HttpResponse* post_res = post_req->send(body.c_str(), body.length());
    pc.printf("res:%s\n",post_res->get_body_as_string().c_str());

    if(post_res->get_status_code() == 200) {
        delete post_req;
        return true;
    }

    delete post_req;
    return false;
}

// main() runs in its own thread in the OS
int main()
{

    NetworkInterface* network = NULL;
    network = easy_connect(true);    // If true, prints out connection details.

    if (!network) {
        pc.printf("\n----- Network Error -----\n");
        return -1;
    }

    pc.printf("\n----- Network Connected -----\n");
    wait(2.0);

    while(1) {

        float currentTemp = tempSensor.getTemperature();

        bool ret = post_kintone(network, URL, app_id, "temp", currentTemp);
        pc.printf("\n----- HTTPS POST response [%s]-----\n",ret== true ? "OK" : "NG");

        wait(10.0);
    }
}