#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define BUF_SIZE 200
// Cloud server address
String server="https://bipfunctionns2024.azurewebsites.net/api/Message";
// Authorization key
const char *api_key = "aoEsjdhJ53sdhJsae934JYDFg-adga4802ygf==";
// WiFi login
const char* SSID = "Wokwi-GUEST";
const char* PASS = "";
void send_message(String& json) {
// Sends a JSON object to the BIP API.
// It must be formatted as a message:
/*
JSON message example:
{
"sender": "djordje",
"recipient": "martin",
"messageText": "Hello Martin"
}
*/
HTTPClient http;
Serial.println(server);
http.begin(server);
http.addHeader("x-functions-key", api_key, true, true);
Serial.print("[HTTPS] POST...\n");
Serial.println(json.c_str());
// start connection and send HTTP request
int httpCode = http.POST(json.c_str());
// httpCode will be negative on error
if(httpCode > 0) {
// HTTP request has been sent and the server response header has been received
Serial.printf("[HTTPS] POST... code: %d\n", httpCode);
if(httpCode == HTTP_CODE_OK) {
Serial.println("POST was successful. This is the response:");
String response = http.getString();
Serial.println(response);
} else {
Serial.println("POST failed. This is the response:");
String response = http.getString();
Serial.println(response);
}
} else {
Serial.printf("[HTTPS] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
void setup() {
Serial.begin(115200);
Serial.println("Sending a string message to BIP API");
WiFi.begin(SSID, PASS, 6);
while (WiFi.status() != WL_CONNECTED) { // Wait for connection
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.print("Connected to the WiFi AP. My address is: ");
Serial.println(WiFi.localIP());
// send an example message
send_test_message();
}
void loop() {
// put your main code here, to run repeatedly:
delay(1000); // this speeds up the simulation
}
void send_test_message() {
// Creates and sends a test message to BIP API
StaticJsonDocument<BUF_SIZE> doc;
doc["sender"] = "POST-example";
doc["recipient"] = "all";
doc["messageText"] = "This is a test message";
String jsonstring;
size_t n = serializeJson(doc, jsonstring);
send_message(jsonstring);
}