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.

90 lines
2.0 KiB

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