#include <WiFi.h>
#include <PubSubClient.h>

WiFiClient wificlient;
String wifiSsid = "webserver";
String wifiPasswd = "www.nobiggie.cn";

const char* mqtt_server = "wulian.nobiggie.cn";
const char* mqtt_username="aaaaaaa";
const char* mqtt_password="abcdefg";
const char* sub="wifi/card01";
const char* pub="wifi/app01";
PubSubClient client(wificlient);

void setup(void) {
  Serial.begin(115200);
  WiFi.begin(wifiSsid .c_str(), wifiPasswd .c_str());
  WiFi.mode(WIFI_STA);

  int ii = 0;
  while (ii < 20 && WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    ii++;
  }
  Serial.println("wifi ok");
  client.setServer(mqtt_server, 1883);
  client.setCallback(mqttCallback);
}

void loop(void) {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  if (Serial.available()) {
    String receivedString = Serial.readStringUntil('\n');
    client.publish("wifi/app01", receivedString.c_str());
  }
}

void mqttCallback(char* topic, byte* payload, unsigned int length) {
  String str;
  for (int i = 0; i < length; i++) {
    str += (char)payload[i];
  }
  str="收到消息:"+str;
  client.publish(pub,str.c_str());
}

void reconnect() {
  while (!client.connected()) {
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);

    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {  // 无认证时留空
      Serial.println("MQTT 连接成功");
      client.subscribe(sub);
    } else {
      Serial.print("连接失败, rc=");
      Serial.print(client.state());
      delay(5000);
    }
  }
}