Fork of the espurna firmware for `mhsw` switches
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.

111 lines
2.4 KiB

  1. /*
  2. UART_MQTT MODULE
  3. Copyright (C) 2018 by Albert Weterings
  4. Adapted by Xose Pérez <xose dot perez at gmail dot com>
  5. */
  6. #include "uartmqtt.h"
  7. #if UART_MQTT_SUPPORT
  8. #include "mqtt.h"
  9. char _uartmqttBuffer[UART_MQTT_BUFFER_SIZE];
  10. bool _uartmqttNewData = false;
  11. #if UART_MQTT_USE_SOFT
  12. #include <SoftwareSerial.h>
  13. SoftwareSerial _uart_mqtt_serial(UART_MQTT_RX_PIN, UART_MQTT_TX_PIN, false, UART_MQTT_BUFFER_SIZE);
  14. #define UART_MQTT_PORT _uart_mqtt_serial
  15. #else
  16. #define UART_MQTT_PORT UART_MQTT_HW_PORT
  17. #endif
  18. // -----------------------------------------------------------------------------
  19. // Private
  20. // -----------------------------------------------------------------------------
  21. void _uartmqttReceiveUART() {
  22. static unsigned char ndx = 0;
  23. while (UART_MQTT_PORT.available() > 0 && _uartmqttNewData == false) {
  24. char rc = UART_MQTT_PORT.read();
  25. if (rc != UART_MQTT_TERMINATION) {
  26. _uartmqttBuffer[ndx] = rc;
  27. if (ndx < UART_MQTT_BUFFER_SIZE - 1) ndx++;
  28. } else {
  29. _uartmqttBuffer[ndx] = '\0';
  30. _uartmqttNewData = true;
  31. ndx = 0;
  32. }
  33. }
  34. }
  35. void _uartmqttSendMQTT() {
  36. if (_uartmqttNewData == true && MQTT_SUPPORT) {
  37. DEBUG_MSG_P(PSTR("[UART_MQTT] Send data over MQTT: %s\n"), _uartmqttBuffer);
  38. mqttSend(MQTT_TOPIC_UARTIN, _uartmqttBuffer);
  39. _uartmqttNewData = false;
  40. }
  41. }
  42. void _uartmqttSendUART(const char * message) {
  43. DEBUG_MSG_P(PSTR("[UART_MQTT] Send data over UART: %s\n"), message);
  44. UART_MQTT_PORT.println(message);
  45. }
  46. void _uartmqttMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  47. if (type == MQTT_CONNECT_EVENT) {
  48. mqttSubscribe(MQTT_TOPIC_UARTOUT);
  49. }
  50. if (type == MQTT_MESSAGE_EVENT) {
  51. // Match topic
  52. String t = mqttMagnitude((char *) topic);
  53. if (t.equals(MQTT_TOPIC_UARTOUT)) {
  54. _uartmqttSendUART(payload);
  55. }
  56. }
  57. }
  58. // -----------------------------------------------------------------------------
  59. // SETUP & LOOP
  60. // -----------------------------------------------------------------------------
  61. void _uartmqttLoop() {
  62. _uartmqttReceiveUART();
  63. _uartmqttSendMQTT();
  64. }
  65. void uartmqttSetup() {
  66. // Init port
  67. UART_MQTT_PORT.begin(UART_MQTT_BAUDRATE);
  68. // Register MQTT callbackj
  69. mqttRegister(_uartmqttMQTTCallback);
  70. // Register loop
  71. espurnaRegisterLoop(_uartmqttLoop);
  72. }
  73. #endif // UART_MQTT_SUPPORT