power output calculation
[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
37                 MCUSR = 0;
38
39                 log_init_common();
40         }
41 }
42 #else
43 void log_init() { log_init_common(); }
44 #endif
45
46 void log_byte(unsigned char byte)
47 {
48         if (!log_enabled)
49                 return;
50
51         ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
52                 buffer_ram[buffer_ram_ptr++] = byte;
53
54                 if (buffer_ram_ptr >= LOG_RAM_BUF_SIZE)
55                         log_flush();
56         }
57 }
58
59 void log_word(uint16_t word)
60 {
61         if (!log_enabled)
62                 return;
63
64         ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
65                 log_byte(word & 0xFF);
66                 log_byte(word >> 8);
67         }
68 }
69
70 void log_flush()
71 {
72         unsigned char i;
73
74         if (!log_enabled)
75                 return;
76
77         ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
78                 for (i = 0; i < buffer_ram_ptr; i++) {
79                         eeprom_write_byte(&buffer_ee[buffer_ee_ptr++],
80                                 buffer_ram[i]);
81
82                         if (buffer_ee_ptr >= LOG_EE_BUF_SIZE) {
83                                 log_enabled = 0;
84                                 return;
85                         }
86                 }
87                 buffer_ram_ptr = 0;
88         }
89 }
90
91 #endif
92