Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <WiFi.h>
- #include <PubSubClient.h>
- WiFiClient espClient;
- PubSubClient client(espClient);
- // Create an object of the class Bsec
- //Bsec iaqSensor;
- #define BUILTIN_LED 4
- #define SSID "xxxxxx"
- #define PWD "xxxxxx"
- #define mqtt_user "user"
- #define mqtt_pwd "password"
- // env variable
- String temperature;
- String humidity;
- String pressure;
- String CO2;
- String gasResistance;
- bool can_sleep = false;
- void WiFiStationGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
- Serial.print("WiFi connected. IP: ");
- Serial.println(WiFi.localIP());
- // Connect to MQTT broker (with timeout)
- bool connected = connectToBroker();
- unsigned long timeout = millis();
- while ( !connected ) {
- delay(1000);
- connected = connectToBroker();
- if(millis() - timeout > 5000){
- connected = false;
- break;
- }
- }
- // Publish data
- if(connected) {
- publishData();
- // Once connected at least one time, eSP32 can sleep
- can_sleep = true;
- }
- }
- bool connectToBroker(){
- Serial.print("Attempting MQTT connection...");
- // Create a random client ID
- String clientId = "ESP8266Client-";
- clientId += String(random(0xffff), HEX);
- // Attempt to connect
- if (client.connect(clientId.c_str(), mqtt_user, mqtt_pwd)) {
- Serial.println("connected");
- return true;
- }
- else {
- // Error on connection (host unreachable)
- Serial.print("failed, rc=");
- Serial.print(client.state());
- delay(100);
- }
- return false;
- }
- void publishData(){
- #define MSG_BUFFER_SIZE (50)
- char msg[MSG_BUFFER_SIZE];
- static int value = 0;
- snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", ++value);
- Serial.print("Publish message: ");
- Serial.println(msg);
- temperature = 25.6 + random(5);
- humidity = 45 + random(10);
- Serial.println("Umidità:"+(String)temperature);
- Serial.println("Temperatura:"+(String)humidity);
- client.publish("esp32/humidity", humidity.c_str());
- client.publish("esp32/temperature", temperature.c_str());
- //wait a little before sleep, so data can be sent to broker
- delay(200);
- }
- void setup() {
- Serial.begin(115200);
- Serial.print("Connecting to ");
- Serial.println(SSID);
- WiFi.onEvent(WiFiStationGotIP, SYSTEM_EVENT_STA_GOT_IP);
- WiFi.begin(SSID, PWD);
- // Test on local LAN mosquitto broker
- IPAddress ip;
- ip.fromString("192.168.2.81");
- client.setServer(ip, 1883);
- }
- void loop() {
- if(can_sleep){
- // ESP32 wakes up every 30 seconds
- esp_sleep_enable_timer_wakeup(10000000);
- Serial.println("Going to deep-sleep now");
- Serial.flush();
- esp_deep_sleep_start();
- while (WiFi.status() != WL_CONNECTED) {;}
- }
- }
Add Comment
Please, Sign In to add comment