logging.c: simple logging implementation
[heater.git] / firmware / logging.c
1 #ifdef USE_LOGGING
2
3 #include <avr/io.h>
4 #include <avr/eeprom.h>
5 #include <util/atomic.h>
6
7 #include "logging.h"
8
9 static unsigned char buffer_ee[LOG_EE_BUF_SIZE] EEMEM;
10 static unsigned char buffer_ram[LOG_RAM_BUF_SIZE];
11
12 static unsigned char buffer_ram_ptr, buffer_ee_ptr;
13 static unsigned char log_enabled = 0;
14
15 static void inline log_init_common()
16 {
17         log_enabled = 1;
18         buffer_ram_ptr = 0;
19         buffer_ee_ptr = 0;
20 }
21
22 #ifdef LOG_RATELIMIT_BOOTCOUNT
23 static unsigned char reboot_count EEMEM;
24
25 void log_init()
26 {
27         unsigned char r_count;
28
29         r_count = eeprom_read_byte(&reboot_count);
30         r_count >>= 4;
31
32         if (r_count < LOG_RATELIMIT_BOOTCOUNT) {
33                 r_count++;
34                 eeprom_write_byte(&reboot_count,
35                         (r_count << 4) | (MCUSR & 0xF));
36                 log_init_common();
37         }
38 }
39 #else
40 void log_init() { log_init_common(); }
41 #endif
42
43 void log_byte(unsigned char byte)
44 {
45         if (!log_enabled)
46                 return;
47
48         ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
49                 buffer_ram[buffer_ram_ptr++] = byte;
50
51                 if (buffer_ram_ptr >= LOG_RAM_BUF_SIZE)
52                         log_flush();
53         }
54 }
55
56 void log_word(uint16_t word)
57 {
58         if (!log_enabled)
59                 return;
60
61         ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
62                 log_byte(word & 0xFF);
63                 log_byte(word >> 8);
64         }
65 }
66
67 void log_flush()
68 {
69         unsigned char i;
70
71         if (!log_enabled)
72                 return;
73
74         ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
75                 for (i = 0; i < buffer_ram_ptr; i++) {
76                         eeprom_write_byte(&buffer_ee[buffer_ee_ptr++],
77                                 buffer_ram[i]);
78
79                         if (buffer_ee_ptr >= LOG_EE_BUF_SIZE) {
80                                 log_enabled = 0;
81                                 return;
82                         }
83                 }
84                 buffer_ram_ptr = 0;
85         }
86 }
87
88 #endif
89