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.

86 lines
2.0 KiB

6 years ago
6 years ago
  1. #ifdef UART_MQTT_SUPPORT
  2. // -----------------------------------------------------------------------------
  3. // GLOBALS TO THE MODULE
  4. // -----------------------------------------------------------------------------
  5. const byte numChars = 100;
  6. char receivedChars[numChars]; // an array to store the received data
  7. boolean newData = false;
  8. void _recvWithEndMarker() {
  9. static byte ndx = 0;
  10. char endMarker = '\n';
  11. char rc;
  12. while (Serial.available() > 0 && newData == false) {
  13. rc = Serial.read();
  14. if (rc != endMarker) {
  15. receivedChars[ndx] = rc;
  16. ndx++;
  17. if (ndx >= numChars) {
  18. ndx = numChars - 1;
  19. }
  20. }
  21. else {
  22. receivedChars[ndx] = '\0'; // terminate the string
  23. ndx = 0;
  24. newData = true;
  25. }
  26. }
  27. }
  28. void _uartSendUART_MQTT() {
  29. if (newData == true && MQTT_SUPPORT) {
  30. DEBUG_MSG_P(PSTR("[UART_MQTT] Send data over MQTT: %s\n"), receivedChars);
  31. mqttSend(MQTT_TOPIC_UARTIN, receivedChars); // publish: UART -> mqtt bus
  32. newData = false;
  33. }
  34. }
  35. void _uartSendMQTT_UART(const char * message) {
  36. DEBUG_MSG_P(PSTR("[UART_MQTT] Send data over UART: %s\n"), message);
  37. Serial.print(message);
  38. Serial.println();
  39. }
  40. #if MQTT_SUPPORT
  41. void _UART_MQTTMqttCallback(unsigned int type, const char * topic, const char * payload) {
  42. if (type == MQTT_CONNECT_EVENT) {
  43. mqttSubscribe(MQTT_TOPIC_UARTOUT);
  44. }
  45. if (type == MQTT_MESSAGE_EVENT) {
  46. // Match topic
  47. String t = mqttTopicKey((char *) topic);
  48. bool isUARTOut = t.equals(MQTT_TOPIC_UARTOUT);
  49. if (isUARTOut) {
  50. _uartSendMQTT_UART(payload);
  51. }
  52. }
  53. }
  54. #endif
  55. // -----------------------------------------------------------------------------
  56. // SETUP & LOOP
  57. // -----------------------------------------------------------------------------
  58. void uart_mqttSetup() {
  59. #if MQTT_SUPPORT
  60. mqttRegister(_UART_MQTTMqttCallback);
  61. #endif
  62. // Register oop
  63. espurnaRegisterLoop(UART_MQTTLoop);
  64. }
  65. void UART_MQTTLoop() {
  66. _recvWithEndMarker();
  67. _uartSendUART_MQTT();
  68. }
  69. #endif