CoAP example application for mbed OS 5. I refer F411-mbed-os-example-simpleHTTPClient code

Dependencies:   DHT

Fork of coap-example by sandbox

source/main.cpp

Committer:
fbdp1202
Date:
2018-01-02
Revision:
1:cca24408264b
Parent:
0:0681e205d0e9

File content as of revision 1:cca24408264b:

#include <string.h>
#include "mbed.h"
#include "easy-connect.h"
#include "TCPSocket.h"
#include "DHT.h"

DHT sensor(D7,DHT22);

#define SERVER_IP "192.168.0.6"
#define SERVER_PORT 50000

Serial pc(USBTX, USBRX);

int main(){
    int error = 0;
    pc.baud(115200);
    pc.printf("\r\n Simple HTTP example over ESP8266\r\n\r\n");

    pc.printf("\r\nConnecting...\r\n");
    NetworkInterface *network = easy_connect(true);
    while(!network){
        pc.printf("Error: Cannot connect to the network\r\n");
        wait(1);
        network = easy_connect(true);
    }
    
    pc.printf("Success\r\n\r\n");
    pc.printf("MAC: %s\r\n", network->get_mac_address());
    pc.printf("IP: %s\r\n", network->get_ip_address());
    pc.printf("Netmask: %s\r\n", network->get_netmask());
    pc.printf("Gateway: %s\r\n", network->get_gateway());
    pc.printf("RSSI: %d\r\n\r\n", wifi.get_rssi());

    pc.printf("\r\nDone\r\n");

    TCPSocket socket;

    socket.open(network);
    socket.connect(SERVER_IP, SERVER_PORT);

    pc.printf("Sending request to %s : %d ...\r\n", SERVER_IP, SERVER_PORT);

    float c = 0, h = 0;
    int scount, rcount;
    while(1){
        char rbuffer[64];
        rcount = socket.recv(rbuffer, sizeof rbuffer);
//        pc.printf("%s\r\n", rbuffer);
        if(!strcmp(rbuffer, "GET /DHT22\r\n")){
            pc.printf("Command Request")
            scount = socket.send("OK!", sizeof("OK!"));
            error = sensor.readData();
            if (error == 0) {
                c   = sensor.ReadTemperature(CELCIUS);
                h   = sensor.ReadHumidity();
            }
            else if(error == 6){
                printf("CheckSum Error.\r\n");
            }
            char sbuffer[64];
            sprintf(sbuffer, "{temp: \"%.1f\", humid: \"%.1f\"}\n", c, h);
            scount = socket.send(sbuffer, sizeof(sbuffer));
            pc.printf(sbuffer);
        }
        else{
            pc.printf("Unknown request\r\n");
            scount = socket.send("Unknown request\r\n", sizeof("Unknown request\r\n"));
        }
    }
}