I got a Wemos D1 mini pro that I've got connected to a humidity/temp sensor. The next step is to upload the data online, and in the first step, I got a auth() function that I'm trying to figure out.
I got the api to work fine in Postman, but when I try to make the same call from the Wemos, I just get -1 as a httpCode, and no reponse.
Can you see what's wrong in the code? I guess it got to do with how I should write the body perhaps.. Btw, I store all the credentials in a "credentials.h" file and the variables are of String data type.
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include "ArduinoJson.h"
#include "credentials.h"
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#define DHTPIN 2
#define DHTTYPE DHT21
DHT_Unified dht(DHTPIN, DHTTYPE);
int delayMS = 3000;
String requestBody;
void setup() {
Serial.begin(115200);
// Initialize device.
dht.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password); //WiFi connection
while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
delay(500);
Serial.println("Waiting for connection");
}
auth();
}
void loop() {
// Get temperature event and print its value.
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println(F("Error reading temperature!"));
}
else {
Serial.print(F("Temperature: "));
Serial.print(event.temperature);
Serial.println(F("°C"));
}
// Get humidity event and print its value.
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println(F("Error reading humidity!"));
}
else {
Serial.print(F("Humidity: "));
Serial.print(event.relative_humidity);
Serial.println(F("%"));
}
// Delay between measurements.
delay(delayMS);
}
void auth() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
HTTPClient http; //Declare object of class HTTPClient
http.begin("login.salesforce.com/services/oauth2/token"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
requestBody = "grant_type=password&client_id=" + consumerKey + "&client_secret=" + consumerSecret + "&username=" + userUsername + "&password=" + userPassword + "&format=urlencoded";
int httpCode = http.POST(requestBody); //Send the request
String payload = http.getString(); //Get the response payload
Serial.print(F("httpCode: "));
Serial.println(httpCode); //Print HTTP return code
Serial.print(F("payload: "));
Serial.println(payload); //Print request response payload
if (httpCode == 200) {
Serial.println("Connected to Salesforce!");
} else {
Serial.println("Failed to connect to Salesforce...");
}
http.end(); //Close connection
} else {
Serial.println("Error in WiFi connection");
}
}