Code clean-up

Dependencies:   Grove_temperature mbed-http

Fork of Wio_3G_HTTP-POST-example by Atsushi Tomizawa

main.cpp

Committer:
atomichan
Date:
2018-08-23
Revision:
1:6c0383514e5b
Parent:
0:b3812b1c103d
Child:
2:687ce876e4ee

File content as of revision 1:6c0383514e5b:

#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

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

#define D20 (PB_4)

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


// 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-token";
// 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;

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();

    printf("body:%s\r\n",body.c_str());
    
    HttpResponse* post_res = post_req->send(body.c_str(), body.length());
    
    printf("res:%s\r\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() {
    pc.printf("Greetings from Ina-city Hackerthon on 25-26 of August\n");
    
    NetworkInterface* network = NULL;

    pc.printf("\r\n----- Start -----\r\n");
    
    network = easy_connect(true);    // If true, prints out connection details.
    if (!network) {
        pc.printf("\r\n----- Network Error -----\r\n");
        return -1;
    }

    pc.printf("\r\n----- Network Connected -----\r\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\r",ret== true ? "OK" : "NG");
        
        wait(10.0);
    }
}