ESP-WROOM-02 HTTP/POSTする

IMG_20150922_120127

 

昨日作ったボードで一旦 POSTしてみます。

電源はお馴染みのftdi(3.3v)ケーブルでいれます。

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>


void postData(String ip_addr, int port,String sid, float value );

//=== WiFi ===
const char* ssid = "wifi ssid";
const char* password = "wifi password";

//=== SENSOR ===
const String API_KEY = "uuid";
const String SID = "this sensor id";
const char* server= "server ip addr";
const int port = 8000;

void setup() {

  pinMode(16, OUTPUT);

  Serial.begin(115200);
  delay(100);
  
  Serial.println("");
  Serial.println("Start");
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  delay(3000);
}

int cnt=0;

void loop() {

  if (WiFi.status() != WL_CONNECTED) {
  
    delay(3000);
    Serial.print(".");
 
  }else{
    
    Serial.println("");
    Serial.println("WiFi connected");
    
    postData(server, port, SID, cnt);
    cnt++;
    delay(60000);
  }
}

void postData(String ip_addr, int port,String sid, float value ) {

  WiFiClient client;
  
  if (client.connect(ip_addr.c_str(), port) ) {
  
    Serial.println("connected.");
    
    String param = "sid=" + sid + "&value=" + value + "&api_key=" + API_KEY;

    String data = "POST /api/data/add/ HTTP/1.1\r\n";
    data += "Host: " + ip_addr + "\r\n";
    data += "User-Agent: ESP-WROOM-002\r\n";
    data += "Connection: close\r\n";
    data += "Content-Type: application/x-www-form-urlencoded;\r\n";
    data += "Content-Length: " + String(param.length()) + "\r\n";
    data += "\r\n";
    data += param;

    Serial.println(data);

    client.print(data.c_str());
  
  } else {
    Serial.println("Connection failed");
    client.stop();
  }
}

 

Leave a Reply