You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.8 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. // Summer School 2022
  2. // ESP32 test code for MQTT protocol using
  3. // a free MQTT broker by emqx
  4. // Gerardo Marx
  5. #include <WiFi.h>
  6. #include <PubSubClient.h>
  7. // WiFi configuration
  8. const char *ssid = "Haus2.4G"; // WiFi name
  9. const char *password = "7476Haus#CB2040$"; // WiFi password
  10. WiFiClient espClient;
  11. // mqtt brocker:
  12. const char *mqttBrocker = "broker.emqx.io";
  13. const char *topic = "esp32/test";
  14. const char *mqttUsername = "emqx";
  15. const char *mqttPassword = "public";
  16. const int mqttPort = 1883;
  17. PubSubClient client(espClient);
  18. void setup(){
  19. //serial communication
  20. Serial.begin(115200);
  21. WiFi.begin(ssid, password);
  22. while(WiFi.status() != WL_CONNECTED){
  23. delay(500);
  24. Serial.print("Connecting to ");
  25. Serial.println(ssid);
  26. }
  27. Serial.println("Connection done.");
  28. //connecting to a mqtt brocker:
  29. client.setServer(mqttBrocker, mqttPort);
  30. client.setCallback(callback);
  31. while(!client.connected()){
  32. String clientID = "esp32-gmarx-";
  33. clientID += String(WiFi.macAddress());
  34. Serial.printf("The %s tries to connect to mqtt borcker...\n",clientID.c_str());
  35. if(client.connect(clientID.c_str(), mqttUsername, mqttPassword)){
  36. Serial.println("mqtt brocker connected");
  37. }
  38. else {
  39. Serial.print("mqtt connection failed");
  40. Serial.println(client.state());
  41. delay(2000);
  42. }
  43. }
  44. //once connected publish and suscribe:
  45. client.publish(topic, "Hi EMQX broker I'm a ESP32 :)");
  46. client.subscribe(topic);
  47. }
  48. void loop(){
  49. client.loop();
  50. }
  51. void callback(char *topic, byte *payload, unsigned int length){
  52. Serial.print("Message recived in topic: ");
  53. Serial.println(topic);
  54. Serial.print("The message is: ");
  55. for(int i=0;i<length; i++){
  56. Serial.print((char) payload[i]);
  57. }
  58. Serial.println();
  59. Serial.println("-+-+-+End+-+-+-+");
  60. }