serial.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include "freertos/FreeRTOS.h"
  4. #include "freertos/task.h"
  5. #include "freertos/queue.h"
  6. #include "freertos/task.h"
  7. #include "esp_log.h"
  8. #include "serial.h"
  9. #include "uart.h"
  10. //#include "supervision.h"
  11. //#include "http_client.h"
  12. #include "wifi.h"
  13. #ifdef SERIAL_ENABLED
  14. // Global defines
  15. int serialRxCounter = 0;
  16. void serialRxTask(void *pvParameters)
  17. {
  18. const bool LOG_PRINT=false;
  19. int mode = -1; // Force a reset
  20. int reset = 1;
  21. unsigned char value[200];
  22. unsigned char *valP;
  23. ESP_LOGI("SERIAL", "serialRxTask starting. Core:%d\n",xPortGetCoreID());
  24. while(1)
  25. {
  26. while( serialAvailable() ) {
  27. const unsigned char c = serialRead();
  28. //printf("%c",c);
  29. if( mode == 0 && c == '{' ) {
  30. if(LOG_PRINT) printf("Rx start ");
  31. mode = 1;
  32. }
  33. else if( mode == 1 ) {
  34. if( c == '}' ) { // Check for end of value
  35. *(valP) = '\0';
  36. reset = 1;
  37. if(LOG_PRINT) printf("\nData:%s\n",value);
  38. char type[10];
  39. char id[21];
  40. char data[10];
  41. const int no = sscanf((const char *)value,"%9[^,],%20[^,],%9s",type,id,data);
  42. if(LOG_PRINT) printf("No:%d\n",no);
  43. if( no == 3 ) {
  44. if(LOG_PRINT) printf("-%s- -%s- -%s-\n",type,id,data);
  45. if( strcmp(type,"VPP") == 0 ) {
  46. int vpp = 0;
  47. const int no = sscanf(data,"%d",&vpp);
  48. if( no == 1 ) {
  49. ESP_LOGI("SERIAL", "VPP: %d",vpp);
  50. #ifdef MQTT_ENABLED
  51. sendMQTTMessage("/sensors/energy/waterHeater", data);
  52. #endif
  53. }
  54. }
  55. else if( strcmp(type,"OWT") == 0 ) {
  56. float t = 0.0f;
  57. const int no = sscanf(data,"%f",&t);
  58. if( no == 1 ) {
  59. char js[50];
  60. sprintf(js,"{\"id\":\"%s\",\"temp\":%s}",id,data);
  61. ESP_LOGI("SERIAL", "%s",js);
  62. #ifdef MQTT_ENABLED
  63. sendMQTTMessage("/sensors/energy/owTempSensor", js);
  64. #endif
  65. }
  66. }
  67. }
  68. else {
  69. ESP_LOGE("SERIAL", "ERROR 2");
  70. }
  71. }
  72. else if( c < ',' || c > 'Z') {
  73. ESP_LOGE("SERIAL", "ERROR 3");
  74. reset = 1;
  75. }
  76. else {
  77. *(valP++) = c;
  78. }
  79. }
  80. if( reset == 1 ) {
  81. serialRxCounter++;
  82. valP = value;
  83. value[0]='\0';
  84. mode = 0;
  85. reset = 0;
  86. }
  87. }
  88. vTaskDelay(100 / portTICK_PERIOD_MS);
  89. }
  90. vTaskDelete(NULL);
  91. }
  92. void initSerial() {
  93. initUart();
  94. xTaskCreate(serialRxTask, "Serial_RX_Task", 10000, NULL, 10, NULL);
  95. }
  96. #endif