mqtt.ino 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // MQTT callback
  2. void mqttCallback(char* topic, byte* payload, unsigned int length) {
  3. //Serial.print("Message arrived [");
  4. //Serial.print(topic);
  5. //Serial.println("] ");
  6. /*for (int i = 0; i < length; i++) {
  7. Serial.print((char)payload[i]);
  8. }
  9. Serial.println();*/
  10. if (strcmp(topic, mqtt_topic_in) == 0) { //if topic = mqtt_topic_in
  11. for (int i = 0; i < length; i++) {
  12. cmdPayload[i] = (char)payload[i];
  13. }
  14. cmdPayload[length + 1] = '\0';
  15. Serial.print("cmdPayload:");
  16. Serial.println(cmdPayload);
  17. cmdInQueue = true;
  18. }//if topic = mqtt_topic_in
  19. if ( useDomoticz ) {
  20. if (strcmp(topic, DOMOTICZ_OUT_TOPIC) == 0) { //if topic = DOMOTICZ_OUT_TOPIC
  21. if ( !domoticzOutParserBusy ) {
  22. for (int i = 0; i < length; i++) {
  23. domoticzOutPayload[i] = (char)payload[i];
  24. }
  25. domoticzOutPayload[length + 1] = '\0';
  26. domoticzOutParseData = true; // parse domoticz data in the next loop()
  27. }
  28. }
  29. }
  30. }//mqttCallback
  31. boolean mqttReconnect() {
  32. // Create a random MQTT client ID
  33. String mqttClientId = "ESP8266Client-";
  34. mqttClientId += String(random(0xffff), HEX);
  35. if (mqttclient.connect(mqttClientId.c_str())) {
  36. Serial.println("MQTT connected");
  37. // Once connected, publish an announcement...
  38. mqttclient.publish(mqtt_topic_out, "connected");
  39. // ... and resubscribe
  40. mqttclient.subscribe(mqtt_topic_in);
  41. mqttclient.subscribe(domoticz_out_topic);
  42. }
  43. return mqttclient.connected();
  44. } //mqttReconnect
  45. void mqttClientInit() {
  46. mqttclient.setServer(mqtt_server, mqtt_port);
  47. mqttclient.setCallback(mqttCallback);
  48. mqttLastReconnectAttempt = 0;
  49. }
  50. void mqttHandleConnection() {
  51. if ( WiFi.status() == WL_CONNECTED ) {
  52. // MQTT reconnect if not connected (nonblocking)
  53. if (!mqttclient.connected()) {
  54. long now = millis();
  55. if (now - mqttLastReconnectAttempt > 5000) {
  56. mqttLastReconnectAttempt = now;
  57. if (mqttReconnect()) { // Attempt to reconnect
  58. mqttLastReconnectAttempt = 0;
  59. }
  60. }
  61. } else { // Client connected
  62. mqttclient.loop();
  63. }//else
  64. }
  65. }