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.

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