Advertisement
jenspauwels

Untitled

Nov 22nd, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. const char* ssid = "Wifi_Boven";
  5. const char* password = "A8F192685F2A";
  6. const char* mqtt_server = "192.168.1.112";
  7.  
  8. WiFiClient espClient;
  9. PubSubClient client(espClient);
  10.  
  11. void setup_wifi() {
  12. delay(10);
  13. Serial.println("Connecting");
  14. WiFi.begin(ssid, password);
  15.  
  16. while (WiFi.status() != WL_CONNECTED) {
  17. delay(500);
  18. Serial.print(".");
  19. }
  20. randomSeed(micros());
  21. }
  22.  
  23.  
  24. String getString(byte* payload, unsigned int length) {
  25. String tmp = "";
  26. for (int i = 0; i < length; i++) tmp += (char)payload[i];
  27. return tmp;
  28. }
  29.  
  30. void handleLed(int led,byte* payload, unsigned int length) {
  31. unsigned long time = millis();
  32. String status = getString(payload, length);
  33. if(status == "true") digitalWrite(led, HIGH);
  34. else digitalWrite(led, LOW);
  35. delay(500);
  36. }
  37.  
  38. void callback(char* topic, byte* payload, unsigned int length) {
  39. Serial.println("executed");
  40. if (strcmp(topic, "ledStatus") == 0) handleLed(BUILTIN_LED, payload, length);
  41. else if (strcmp(topic, "redLed") == 0) handleLed(2, payload, length);
  42. else if (strcmp(topic, "greenLed") == 0) handleLed(4, payload, length);
  43. else if (strcmp(topic, "orangeLed") == 0) handleLed(5, payload, length);
  44. }
  45.  
  46. void reconnect() {
  47. // Loop until we're reconnected
  48. while (!client.connected()) {
  49. Serial.println("Attempting MQTT connection...");
  50. // Create a random client ID
  51. String clientId = "ESP8266Client-";
  52. clientId += String(random(0xffff), HEX);
  53. // Attempt to connect
  54. if (client.connect(clientId.c_str())) {
  55. client.subscribe("orangeLed");
  56. client.subscribe("redLed");
  57. client.subscribe("greenLed");
  58. client.subscribe("ledStatus");
  59. }
  60. else {
  61. Serial.print("failed, rc=");
  62. Serial.print(client.state());
  63. Serial.println(" try again in 5 seconds");
  64. // Wait 5 seconds before retrying
  65. delay(5000);
  66. }
  67. }
  68. }
  69.  
  70. void setup() {
  71. pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
  72. pinMode(2, OUTPUT);
  73. pinMode(4, OUTPUT);
  74. pinMode(5, OUTPUT);
  75. Serial.begin(115200);
  76. setup_wifi();
  77. client.setServer(mqtt_server, 1883);
  78. client.setCallback(callback);
  79. }
  80.  
  81. void loop() {
  82. if (!client.connected()) reconnect();
  83. client.loop();
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement