syslog.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #pragma GCC diagnostic error "-Wall"
  2. #pragma GCC diagnostic error "-Wextra"
  3. #include "common_config.h"
  4. #if defined(SYSLOG_ENABLE) && !defined(BT6702_SERVICE)
  5. #include "common_config.h"
  6. #include "syslog.h"
  7. #include "settings_api.h"
  8. #include "tcpip.h"
  9. #include "udp.h"
  10. #include "rtc.h"
  11. #include "netconf.h"
  12. #include <assert.h>
  13. static struct udp_pcb *upcb;
  14. // TODO either lock the buffers against race conditions or raise the task stack sizes, or lower the memory consumption
  15. static char packet[256];
  16. static char msg[200];
  17. void openlog(void)
  18. {
  19. upcb = udp_new();
  20. udp_bind(upcb, IP_ADDR_ANY, 0);
  21. }
  22. static void timestamp_rfc3339(char *ts)
  23. {
  24. TM_RTC_t data;
  25. uint16_t sys_year;
  26. TM_RTC_GetDateTime(&data, TM_RTC_Format_BIN);
  27. sys_year = 2000 + data.year;
  28. uint32_t subseconds = (1024 - data.subseconds) * 999999 / 1024;
  29. // TODO timezone?
  30. sprintf(ts, "%04i-%02i-%02iT%02i:%02i:%02i.%06luZ", sys_year, data.month, data.date, data.hours, data.minutes, data.seconds, subseconds);
  31. }
  32. void syslog(uint8_t severity, char *fmt, ...)
  33. {
  34. //char msg[200]; // arbitrary length; "Any transport receiver MUST be able to accept messages of up to and including 480 octets in length."
  35. va_list va;
  36. va_start(va, fmt);
  37. vsnprintf(msg, sizeof(msg), fmt, va);
  38. syslog_str(severity, msg);
  39. va_end(va);
  40. }
  41. void syslog_str(uint8_t severity, char *msg)
  42. {
  43. if (!sSettings.sSyslog.enabled) {
  44. return;
  45. }
  46. const uint8_t facility = 1;
  47. assert(severity < 8);
  48. uint8_t priority = facility * 8 + severity;
  49. #define SYSLOG_VERSION "1" // as defined in RFC5424
  50. #define BOM "\xef\xbb\xbf"
  51. struct pbuf* psend;
  52. // TODO to reduce memory consumption one can use a scatter-gather I/O instead of packet[]
  53. //char packet[256]; // arbitrary length; "Any transport receiver MUST be able to accept messages of up to and including 480 octets in length."
  54. static char timestamp[30];
  55. timestamp_rfc3339(timestamp);
  56. unsigned len = snprintf(packet, sizeof(packet), "<%u>" SYSLOG_VERSION " %s %s " HW_REV "_" VERSION " - - - " BOM "%s", priority, timestamp, ipaddr_ntoa(&xnetif.ip_addr), msg);
  57. //psend = pbuf_alloc(PBUF_RAW, sizeof(packet), PBUF_REF);
  58. psend = pbuf_alloc(PBUF_RAW, len, PBUF_REF);
  59. psend->payload = packet;
  60. //psend->len = len;
  61. udp_sendto(upcb, psend, &sSettings.sSyslog.server_ip, sSettings.sSyslog.server_port);
  62. pbuf_free(psend);
  63. }
  64. #endif // defined(HARDWARE_BT6711) && !defined(BT6702_SERVICE)