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.

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