No Description
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

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