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.

71 lines
1.6 KiB

  1. #include <WiFi.h>
  2. #include <PubSubClient.h>
  3. const char* ssid = "Familia 2.4G";
  4. const char* password = "rr20072015";
  5. const char* mqttServer = "192.168.1.17";
  6. const int mqttPort = 1883;
  7. const char* mqttUser = "";
  8. const char* mqttPassword = "";
  9. WiFiClient espClient;
  10. PubSubClient client(espClient);
  11. void OnMqttReceived(char *topic, byte *payload, unsigned int length)
  12. {
  13. Serial.print("Received on ");
  14. Serial.print(topic);
  15. Serial.print(": ");
  16. String content = "";
  17. for (size_t i = 0; i < length; i++)
  18. {
  19. content.concat((char)payload[i]);
  20. }
  21. Serial.print(content);
  22. Serial.println();
  23. }
  24. void setup()
  25. { Serial.begin(115200);
  26. WiFi.begin(ssid, password);
  27. Serial.println("...................................");
  28. Serial.print("Connecting to WiFi.");
  29. while (WiFi.status() != WL_CONNECTED)
  30. { delay(500);
  31. Serial.print(".") ;
  32. }
  33. Serial.println("Connected to the WiFi network");
  34. client.setServer(mqttServer, mqttPort);
  35. while (!client.connected())
  36. { Serial.println("Connecting to MQTT...");
  37. if (client.connect("prueba", mqttUser, mqttPassword ))
  38. {Serial.println("connected");
  39. client.subscribe("prueba/xd");
  40. client.setCallback(OnMqttReceived);
  41. }
  42. else
  43. { Serial.print("failed with state ");
  44. Serial.print(client.state());
  45. delay(2000);
  46. }
  47. }
  48. }
  49. void loop()
  50. { client.loop();
  51. char str[16];
  52. if(Serial.read()>0)
  53. {
  54. sprintf(str, "%u", random(100));
  55. client.publish("prueba/xd", str);
  56. Serial.println(str);
  57. delay(100);
  58. }
  59. }