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.

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