syslog.c 2.2 KB

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