Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <WiFi.h>
#include "Esp32MQTTClient.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
const char* ssid = ""; //nazaw wifi
const char* password = ""; //hasło
Adafruit_BME280 bme;
/*String containing Hostname, Device Id & Device Key in the format: */
/* "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>" */
/* "HostName=<host_name>;DeviceId=<device_id>;SharedAccessSignature=<device_sas_token>" */
static const char* connectionString = ""; // conection string
static bool hasIoTHub = false;
void setup() {
Serial.begin(115200);
Serial.println("Starting connecting WiFi.");
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
if (!Esp32MQTTClient_Init((const uint8_t*)connectionString))
{
hasIoTHub = false;
Serial.println("Initializing IoT hub failed.");
return;
}
hasIoTHub = true;
}
void loop() {
Serial.println("start sending events.");
if (hasIoTHub)
{
char buff[128];
bool status = bme.begin(0x76);
if (!status)
{
Serial.println("Could not find a valid BME280 sensor, check wiring!");
}
bme.setSampling(Adafruit_BME280::MODE_FORCED,
Adafruit_BME280::SAMPLING_X16, // temperature
Adafruit_BME280::SAMPLING_X16, // pressure
Adafruit_BME280::SAMPLING_X16, // humidity
Adafruit_BME280::FILTER_X16);
bme.takeForcedMeasurement();
float temperature = bme.readTemperature();
// bme.readPressure() / 100.0F;
// bme.readHumidity();
snprintf(buff, 128, "{\"Temperature\": %f }" ,temperature);
EVENT_INSTANCE* message = Esp32MQTTClient_Message_Generate(buff );
if (Esp32MQTTClient_SendEventInstance(message))
{
Serial.println(buff);
Serial.println("Sending data succeed");
}
else
{
Serial.println("Failure...");
}
delay(60 * 1000); // czas uśpienia
}
}
EVENT_INSTANCE *Esp32MQTTClient_Message_Generate(const char *eventString )
{
EVENT_TYPE type = MESSAGE;
if (eventString == NULL)
{
return NULL;
}
EVENT_INSTANCE *event = (EVENT_INSTANCE *)malloc(sizeof(EVENT_INSTANCE));
event->type = type;
if (type == MESSAGE)
{
event->messageHandle = IoTHubMessage_CreateFromString(eventString);
(void)IoTHubMessage_SetContentTypeSystemProperty(event->messageHandle, "application%2fjson");
(void)IoTHubMessage_SetContentEncodingSystemProperty(event->messageHandle, "utf-8");
if (event->messageHandle == NULL)
{
LogError("iotHubMessageHandle is NULL!");
free(event);
return NULL;
}
}
else if (type == STATE)
{
event->stateString = eventString;
}
return event;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.