Controle d'une LED au travers de Home Assistant
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.

86 lines
1.7 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. #include <Arduino.h>
  2. #include "mqttled.h"
  3. #include <ESP8266WiFi.h>
  4. #include <PubSubClient.h>
  5. // WIFI
  6. WiFiClient espClient;
  7. // MQTT
  8. char message_buff[100];
  9. PubSubClient client(espClient);
  10. void setup() {
  11. Serial.begin(SERIAL_SPEED);
  12. Serial.println("\nresetting");
  13. // WIFI
  14. setupWifi();
  15. // MQTT
  16. client.setServer(MQTT_SERVER, MQTT_PORT);
  17. client.setCallback(callbackMQTT);
  18. testConnectMQTT();
  19. pinMode(LED_PIN, OUTPUT);
  20. }
  21. // WIFI
  22. void setupWifi() {
  23. Serial.print("Connexion a ");
  24. Serial.print(WIFI_SSID);
  25. WiFi.mode(WIFI_STA);
  26. WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  27. while (WiFi.status() != WL_CONNECTED) {
  28. delay(500);
  29. Serial.print(".");
  30. }
  31. Serial.println(" OK");
  32. Serial.print("IP : ");
  33. Serial.println(WiFi.localIP());
  34. }
  35. // MQTT
  36. void testConnectMQTT() {
  37. while (!client.connected()) {
  38. Serial.print("Connexion au serveur MQTT... ");
  39. if (client.connect("ESP8266Client", MQTT_USER, MQTT_PASS)) {
  40. Serial.print("OK\nSubscribe");
  41. client.subscribe("homeassistant/switch1");
  42. Serial.println(" OK");
  43. } else {
  44. Serial.print("KO, erreur : ");
  45. Serial.print(client.state());
  46. Serial.println(", on attend 5 secondes avant de recommencer");
  47. delay(5000);
  48. }
  49. }
  50. }
  51. void callbackMQTT(char* topic, byte* payload, unsigned int length) {
  52. String stopic = String(topic);
  53. unsigned int i = 0;
  54. for(i = 0; i < length; i++) {
  55. message_buff[i] = payload[i];
  56. }
  57. message_buff[i] = '\0';
  58. String msgString = String(message_buff);
  59. Serial.print("Received [" + stopic + "] : ");
  60. Serial.println(msgString);
  61. if (msgString == "ON") {
  62. digitalWrite(LED_PIN, HIGH);
  63. } else {
  64. digitalWrite(LED_PIN, LOW);
  65. }
  66. }
  67. void loop() {
  68. testConnectMQTT();
  69. client.loop();
  70. }