#define LED 2
#include <WiFi.h>
#include <Arduino.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 4 // 设置获取数据的引脚
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);  
// 对应DHT的版本,选择一个取消注释

//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,22);
IPAddress subnet(255,255,255,0);

const char *ssid = "ESP32_AP_TEST";
const char *password = "12345678";

// 凯撒密码加密函数
String caesarEncrypt(String plaintext, int shift) {
    String ciphertext = "";
    for (int i = 0; i < plaintext.length(); i++) {
        char c = plaintext.charAt(i);
        if (isalpha(c)) {
            char encryptedChar = (c - 'a' + shift) % 26 + 'a';
            ciphertext += encryptedChar;
        } else {
            ciphertext += c;
        }
    }
    return ciphertext;
}

void setup() {
    Serial.begin(115200);
   dht.begin();        
  Serial.println();
  
  WiFi.mode(WIFI_AP); //设置工作在AP模式

  WiFi.softAPConfig(local_IP, gateway, subnet); //设置AP地址
  while(!WiFi.softAP(ssid, password)){}; //启动AP
  Serial.println("AP启动成功");

  Serial.print("IP address: ");
  Serial.println(WiFi.softAPIP()); // 打印IP地址

  WiFi.softAPsetHostname("myHostName"); //设置主机名
  Serial.print("HostName: ");
  Serial.println(WiFi.softAPgetHostname()); //打印主机名

  Serial.print("mac Address: ");
  Serial.println(WiFi.softAPmacAddress()); //打印mac地址
}

void loop() {
    String plaintext = "Hello ESP32";
    int shift = 3;
    String encryptedText = caesarEncrypt(plaintext, shift);
    Serial.println("加密后: " + encryptedText);
   
     delay(1000);
  Serial.println(WiFi.softAPgetStationNum()); //打印客户端连接数
   delay(2000); // 暂停2秒,读取数据官方说明需要250毫秒
   float h = dht.readHumidity();          //读取湿度
   float t = dht.readTemperature();       //读取摄氏度
   float f = dht.readTemperature(true);   //读取华氏度
   if (isnan(h) || isnan(t) || isnan(f)) {    //如果读取错误
      Serial.println("读取传感器失败");         //读取失败提示
      return;
   }
   float hif = dht.computeHeatIndex(f, h);  //计算华氏度的热指数
   float hic = dht.computeHeatIndex(t, h, false); //计算摄氏度的热指数
 
   Serial.print ("湿度: ");
   Serial.print (h);
   Serial.print ("% | ");
   Serial.print ("摄氏度: ");
   Serial.print (t);
   Serial.print ("*C | 华氏度:");
   Serial.print (f);
   Serial.print ("*F ");
   Serial.print (" | 摄氏热指数: ");
   Serial.print (hic);
   Serial.print ("*C  | 华氏热指数");
   Serial.print (hif);
   Serial.println ("*F");

}