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.

85 lines
1.8 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. mqttSend(MQTT_TOPIC_UARTIN, receivedChars); // publish: UART -> mqtt bus
  33. newData = false;
  34. }
  35. }
  36. #if MQTT_SUPPORT
  37. void _UARTtoMQTTMqttCallback(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 = mqttTopicKey((char *) topic);
  44. bool isUARTOut = t.equals(MQTT_TOPIC_UARTOUT);
  45. if (isUARTOut) {
  46. Serial.print(payload);
  47. Serial.println();
  48. }
  49. }
  50. }
  51. #endif
  52. // -----------------------------------------------------------------------------
  53. // SETUP & LOOP
  54. // -----------------------------------------------------------------------------
  55. void UARTtoMQTTSetup() {
  56. #if MQTT_SUPPORT
  57. mqttRegister(_UARTtoMQTTMqttCallback);
  58. #endif
  59. // Register oop
  60. espurnaRegisterLoop(UARTtoMQTTLoop);
  61. }
  62. void UARTtoMQTTLoop() {
  63. _recvWithEndMarker();
  64. _sendNewData();
  65. }
  66. #endif