Last active
May 27, 2023 03:39
-
-
Save alloyking/7a39a153632c914e227b942a52624dee to your computer and use it in GitHub Desktop.
WIFI, https, post JSON, DHT11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <DHT.h> | |
#include <WiFiClientSecure.h> | |
#include <ArduinoJson.h> | |
// DHT22 sensor configuration | |
#define DHT_PIN 4 | |
#define DHT_TYPE DHT11 | |
DHT dht(DHT_PIN, DHT_TYPE); | |
// Wi-Fi credentials | |
const char* ssid = "SSID"; | |
const char* password = "XXXXXXXXX"; | |
// Server configuration | |
const char* host = "mywebsite.com"; | |
const int httpsPort = 443; | |
unsigned long lastRequestTime = 0; | |
const unsigned long requestInterval = 5000; // Interval between requests in milliseconds | |
// Add these variables to hold client_id and client_secret | |
const char* clientID = "client_id"; | |
const char* clientSecret = "secret"; | |
String bearerToken; | |
void setup() { | |
Serial.begin(115200); | |
// Connect to Wi-Fi | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(1000); | |
Serial.println("Connecting to WiFi..."); | |
} | |
Serial.println("Connected to WiFi"); | |
// Print the IP address | |
Serial.print("IP address: "); | |
Serial.println(WiFi.localIP()); | |
// Initialize the DHT sensor | |
dht.begin(); | |
Serial.println("DHT started"); | |
// Get the bearer token | |
bearerToken = getBearerToken(); | |
} | |
void loop() { | |
// Check if it's time to make the HTTP request | |
unsigned long currentTime = millis(); | |
if (currentTime - lastRequestTime >= requestInterval) { | |
lastRequestTime = currentTime; | |
makeHttpPostRequest(); | |
} | |
// Other code in the loop | |
// ... | |
} | |
void setInterval(unsigned long interval, void (*callback)()) { | |
static unsigned long lastExecution = 0; | |
if (millis() - lastExecution >= interval) { | |
lastExecution = millis(); | |
(*callback)(); | |
} | |
} | |
String getBearerToken() { | |
Serial.println("getBearerToken called"); | |
// Create a WiFiClientSecure object | |
WiFiClientSecure client; | |
// Set the CA certificate (optional) | |
// Uncomment the line below if you have a custom CA certificate | |
// client.setCACert(/* Your CA certificate */); | |
client.setInsecure(); | |
// Connect to the server | |
if (!client.connect(host, httpsPort)) { | |
Serial.println("Connection failed"); | |
return ""; | |
} | |
// Create the request payload | |
String payload = "client_id=" + String(clientID) + "&client_secret=" + String(clientSecret) + "&grant_type=client_credentials"; | |
// Send the HTTP POST request | |
client.println("POST /oauth/token HTTP/1.1"); | |
client.println("Host: mywebsite.com"); | |
client.println("Content-Type: application/x-www-form-urlencoded"); | |
client.print("Content-Length: "); | |
client.println(payload.length()); | |
client.println(); | |
client.println(payload); | |
// Read the response from the server | |
String response; | |
bool inBody = false; | |
size_t contentLength = 0; | |
while (client.connected()) { | |
String line = client.readStringUntil('\n'); | |
if (!inBody && line == "\r") { | |
inBody = true; | |
} else if (inBody) { | |
if (contentLength == 0) { | |
// Parse chunk size | |
contentLength = strtol(line.c_str(), NULL, 16); | |
} else { | |
// Append chunk to response | |
response += line; | |
contentLength -= line.length(); | |
} | |
if (contentLength == 0) { | |
// End of chunk | |
break; | |
} | |
} | |
} | |
// Print the response | |
Serial.println("Server Response:"); | |
Serial.println(response); | |
// Disconnect from the server | |
client.stop(); | |
// Extract the bearer token from the response | |
int tokenStartIndex = response.indexOf("\"access_token\":\"") + 16; | |
int tokenEndIndex = response.indexOf("\"", tokenStartIndex); | |
if (tokenStartIndex == -1 || tokenEndIndex == -1) { | |
Serial.println("Bearer token not found in response"); | |
return ""; | |
} | |
String token = response.substring(tokenStartIndex, tokenEndIndex); | |
return token; | |
} | |
void makeHttpPostRequest() { | |
Serial.println("makeHttpPostRequest called"); | |
// Create a WiFiClientSecure object | |
WiFiClientSecure client; | |
// Set the CA certificate (optional) | |
// Uncomment the line below if you have a custom CA certificate | |
// client.setCACert(/* Your CA certificate */); | |
client.setInsecure(); | |
// Connect to the server | |
if (!client.connect(host, httpsPort)) { | |
Serial.println("Connection failed"); | |
return; | |
} | |
// Read the temperature from the DHT sensor | |
float temperature = dht.readTemperature(); | |
float humidity = dht.readHumidity(); | |
// Create the JSON payload | |
DynamicJsonDocument payloadJson(256); | |
JsonObject payloadObj = payloadJson.to<JsonObject>(); | |
payloadObj["temperature"] = temperature; | |
payloadObj["humidity"] = humidity; | |
// Serialize the JSON object to a string | |
String payload; | |
serializeJson(payloadObj, payload); | |
// Create the payload array | |
DynamicJsonDocument requestJson(256); | |
JsonObject requestObj = requestJson.to<JsonObject>(); | |
requestObj["payload"] = payload; | |
// Serialize the request array to a string | |
String requestPayload; | |
serializeJson(requestObj, requestPayload); | |
// array ( | |
// 'payload' => '{"temperature":-9.040000000000006,"humidity":"26.7"}', | |
// ) | |
// Send the HTTPS POST request with the Bearer token | |
client.println("POST /api/store HTTP/1.1"); | |
client.println("Host: website.com"); | |
client.println("Connection: close"); | |
client.println("Content-Type: application/json"); | |
client.print("Content-Length: "); | |
client.println(requestPayload.length()); | |
client.println("Authorization: Bearer " + bearerToken); | |
client.println(); | |
client.println(requestPayload); | |
// Read the response from the server | |
Serial.println("Response from server:"); | |
while (client.connected()) { | |
// String line = client.readStringUntil('\n'); | |
// Serial.println(line); | |
} | |
// Disconnect from the server | |
client.stop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment