]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/logging.c
schematics: bug fixes
[bike-lights.git] / firmware / logging.c
1 #ifdef USE_LOGGING
2
3 #include <avr/io.h>
4 #include <avr/eeprom.h>
5
6 #include "lights.h"
7
8 #define LOG_BUFFER 128
9 static unsigned char log_buffer_ee[LOG_BUFFER] EEMEM;
10 static unsigned char log_buffer_count;
11 static unsigned char log_buffer[LOG_BUFFER];
12 static unsigned char log_state EEMEM;
13 /* Upper 4 bits are reset count, lower 4 bits are reset reason from MCUSR */
14 static unsigned char reboot_count EEMEM = 0;
15 static unsigned char can_write_eeprom = 0;
16 static uint16_t flushed_end;
17
18 void log_set_state(unsigned char val)
19 {
20         if (can_write_eeprom)
21                 eeprom_write_byte(&log_state, val);
22 }
23
24 void init_log()
25 {
26         unsigned char r_count;
27
28         r_count = eeprom_read_byte(&reboot_count);
29         r_count >>= 4;
30
31         if (r_count < 5) {
32                 r_count++;
33                 eeprom_write_byte(&reboot_count,
34                         (r_count << 4) | (MCUSR & 0xF));
35                 MCUSR = 0;
36                 can_write_eeprom = 1;
37         } else {
38                 //eeprom_write_byte(&log_state, 0xFF);
39                 can_write_eeprom = 0;
40         }
41
42         log_set_state(1);
43         log_buffer_count = 0;
44         flushed_end = 0;
45 }
46
47 void log_byte(unsigned char byte) {
48         if (log_buffer_count >= LOG_BUFFER)
49                 return;
50         
51         // eeprom_write_word(&log_buffer[log_buffer_count], word);
52         log_buffer[log_buffer_count++] = byte;
53
54         if (log_buffer_count == LOG_BUFFER)
55                 log_flush();
56 }
57
58 void log_word(uint16_t word) {
59         log_byte(word & 0xFF);
60         log_byte(word >> 8);
61 }
62
63 void log_flush() {
64         unsigned char i;
65
66         if (!can_write_eeprom)
67                 return;
68
69         for (i=flushed_end; i < log_buffer_count; i++) {
70                 eeprom_write_byte(&log_buffer_ee[i],
71                         log_buffer[i]);
72         }
73
74         flushed_end = i;
75
76         if (flushed_end == LOG_BUFFER)
77                 log_set_state(0x42);
78 }
79
80 #endif
81