Skip to content

Instantly share code, notes, and snippets.

@hiroki-uchida
Last active August 6, 2023 19:39
Show Gist options
  • Save hiroki-uchida/90da6cbd5f85aae4d92003df023d6687 to your computer and use it in GitHub Desktop.
Save hiroki-uchida/90da6cbd5f85aae4d92003df023d6687 to your computer and use it in GitHub Desktop.
ESP32
lib_deps =
	bblanchon/ArduinoJson@^6.21.2
	256dpi/MQTT@^2.5.1

mqtt_handler.h

#ifndef MQTT_HANDLER_H
#define MQTT_HANDLER_H

#include <Arduino.h>
#include <WiFiClientSecure.h>
#include <MQTTClient.h>
#include <ArduinoJson.h>

extern WiFiClientSecure net;
extern MQTTClient client;

extern unsigned int pubCount;
extern unsigned long loopCount;
extern TaskHandle_t MQTT_CLIENT_LOOP_TASK;

extern void mqttClientLoopTask(void * parameter);

extern void messageHandler(String &topic, String &payload);

extern void setup_aws_iot();

extern void publishReport();

#endif // MQTT_HANDLER_H

mqtt_handler.cpp

#include "secret.h"
#include "mqtt_handler.h"
#include "action_handler.h"

WiFiClientSecure net = WiFiClientSecure();
MQTTClient client = MQTTClient(256);

unsigned int pubCount = 0;
unsigned long loopCount = 0;

TaskHandle_t MQTT_CLIENT_LOOP_TASK;

void mqttClientLoopTask(void * parameter) {
  for(;;) {
    client.loop();
    delay(10);
  }
}

// サブスクライブしているトピックを受信したときの割り込みハンドラ
// {
//   "version":68,
//   "timestamp":1688200328,
//   "state": {
//     "power_status":"on"
//   },
//   "metadata": {
//     "power_status": {
//       "timestamp": 1688200328
//     }
//   }
// }
int count = 0;
void messageHandler(String &topic, String &payload) {
  count++;
  Serial.println("count: " + String(count));
  Serial.println("topic: " + topic);
  Serial.println("payload: " + payload);

  // AWS IoT Shadow
  StaticJsonDocument<200> doc;
  deserializeJson(doc, payload);

  if (doc["name"] == "manual_open") {
    Serial.println("manual_open");
    action_manual_open();
  } else if (doc["name"] == "manual_close") {
    Serial.println("manual_close");
    action_manual_close();
  } else if (doc["name"] == "manual_loop_start") {
    Serial.println("manual_loop_start");
    action_manual_loop_start();
  } else if (doc["name"] == "manual_loop_stop") {
    Serial.println("manual_loop_stop");
    action_manual_loop_stop();
  }
}

// AWS IoT Core接続機能の初期化処理
void setup_aws_iot(){
  // AWS IoT Coreに接続
  net.setCACert(AWS_CERT_CA);
  net.setCertificate(AWS_CERT_CRT);
  net.setPrivateKey(AWS_CERT_PRIVATE);
  client.begin(
    AWS_IOT_ENDPOINT,
    8883,
    net
  );

  // サブスクライブしているトピックを受信したときの割り込みハンドラを指定
  client.onMessage(messageHandler);

  // AWS IoT Coreに接続待ち
  Serial.println("Connecting to AWS IOT");
  while (!client.connect(THING_NAME)) {
    delay(100);
  }

  if(!client.connected()){
    Serial.println("AWS IoT Timeout!");
    return;
  }

  // サブスクライブ開始
  client.subscribe(AWS_IOT_SUBSCRIBE_JOB_TOPIC);

  Serial.println("AWS IoT Connected!");

  xTaskCreate(
      mqttClientLoopTask,       /* Task function. */
      "MQTT_CLIENT_LOOP_TASK",    /* name of task. */
      10000,           /* Stack size of task */
      NULL,            /* parameter of the task */
      1,               /* priority of the task */
      &MQTT_CLIENT_LOOP_TASK);         /* Task handle to keep track of created task */
  vTaskResume(MQTT_CLIENT_LOOP_TASK);
}

// // パブリッシュする
// // {
// // 	"state": {
// // 		"reported": {
// // 			"power_status": statuses.power_status,
// // 		}
// // 	}
// // }
// void publishReport(){
//   StaticJsonDocument<200> doc;
//   doc["state"]["reported"]["power_status"] = statuses.power_status;

//   char jsonBuffer[512];
//   serializeJson(doc, jsonBuffer);
//   client.publish(AWS_IOT_PUBLISH_TOPIC, jsonBuffer);
//   Serial.println("publishReport");
// }
; PlatformIO Project Configuration File
;
;   Build options: build flags, source filter
;   Upload options: custom upload port, speed and extra flags
;   Library options: dependencies, extra library storages
;   Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps = adafruit/Adafruit SSD1306@^2.5.7
monitor_speed = 115200
#include <Adafruit_SSD1306.h>

// GND: GND
// VCC: 3V3
// SCL: G22
// SDA: G21

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET 4
#define SCREEN_ADDRESS 0x3C

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
  Serial.begin(115200);
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }

  // display.display();

  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("Booting...");
  display.display();
  delay(1000);
}

int i = 0;
void loop() {
  display.clearDisplay();
  display.setTextSize(1);

  display.setCursor(0, 0);
  display.println("CO2: 1000ppm");

  display.setCursor(0, 10);
  display.println("Temperature: 25.0C");

  display.setCursor(0, 20);
  display.println("Humidity: 50%");
  display.display();

  display.setCursor(0, 40);
  display.println("Count: " + String(i++));
  display.display();

  delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment