Brak opisu
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.

log.c 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * log.c
  3. */
  4. #include <stdarg.h>
  5. #include <stdio.h>
  6. #include "pico/stdlib.h"
  7. #include "config.h"
  8. #include "usb_cdc.h"
  9. #include "log.h"
  10. char log_buff[4096];
  11. size_t head = 0, tail = 0;
  12. bool full = false;
  13. static void add_to_log(const char *buff, int len) {
  14. for (int i = 0; i < len; i++) {
  15. log_buff[head] = buff[i];
  16. if (full && (++tail == sizeof(log_buff))) {
  17. tail = 0;
  18. }
  19. if (++(head) == sizeof(log_buff)) {
  20. head = 0;
  21. }
  22. full = (head == tail);
  23. }
  24. }
  25. void log_dump_to_usb(void) {
  26. if (head == tail) {
  27. return;
  28. }
  29. char buff[32];
  30. int l = snprintf(buff, sizeof(buff), "\r\n\r\nbuffered log output:\r\n");
  31. if ((l > 0) && (l <= sizeof(buff))) {
  32. usb_cdc_write(buff, l);
  33. }
  34. if (head > tail) {
  35. usb_cdc_write(log_buff + tail, head - tail);
  36. } else {
  37. usb_cdc_write(log_buff + tail, sizeof(log_buff) - tail);
  38. usb_cdc_write(log_buff, head);
  39. }
  40. l = snprintf(buff, sizeof(buff), "\r\n\r\nlive log:\r\n");
  41. if ((l > 0) && (l <= sizeof(buff))) {
  42. usb_cdc_write(buff, l);
  43. }
  44. }
  45. static int format_debug_log(char *buff, size_t len, const char *format, va_list args) {
  46. int l = vsnprintf(buff, len, format, args);
  47. if (l < 0) {
  48. // encoding error
  49. l = snprintf(buff, len, "%s: encoding error\r\n", __func__);
  50. } else if (l >= len) {
  51. // not enough space for string
  52. l = snprintf(buff, len, "%s: message too long (%d)\r\n", __func__, l);
  53. }
  54. return l;
  55. }
  56. void debug_log(bool log, const char* format, ...) {
  57. static char line_buff[256];
  58. va_list args;
  59. va_start(args, format);
  60. int l = format_debug_log(line_buff, sizeof(line_buff), format, args);
  61. va_end(args);
  62. if ((l > 0) && (l <= sizeof(line_buff))) {
  63. usb_cdc_write(line_buff, l);
  64. if (log) {
  65. add_to_log(line_buff, l);
  66. }
  67. }
  68. }