2741555f29e417a61a88c1003f8b540f910b3fcf
[fw/altos] / src / drivers / ao_log_fat.c
1 /*
2  * Copyright © 2013 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "ao.h"
19 #include "ao_log.h"
20 #include "ao_fat.h"
21
22 static uint8_t  log_year, log_month, log_day;
23 static uint8_t  log_open;
24 static uint8_t  log_mutex;
25
26 static void
27 ao_log_open(void)
28 {
29         char    name[12];
30         int8_t  status;
31
32         sprintf(name,"%04d%02d%02dLOG", 2000 + log_year, log_month, log_day);
33         status = ao_fat_open(name, AO_FAT_OPEN_WRITE);
34         switch (status) {
35         case AO_FAT_SUCCESS:
36                 ao_fat_seek(0, AO_FAT_SEEK_END);
37                 log_open = 1;
38                 break;
39         case -AO_FAT_ENOENT:
40                 status = ao_fat_creat(name);
41                 if (status == AO_FAT_SUCCESS)
42                         log_open = 1;
43                 break;
44         } 
45 }
46
47 static void
48 ao_log_close(void)
49 {
50         log_open = 0;
51         ao_fat_close();
52 }
53
54 uint8_t
55 ao_log_full(void)
56 {
57         return ao_fat_full();
58 }
59
60 uint8_t
61 ao_log_mega(struct ao_log_mega *log)
62 {
63         uint8_t wrote = 0;
64         ao_mutex_get(&log_mutex);
65         if (log->type == AO_LOG_GPS_TIME) {
66                 if (log_open &&
67                     (log_year != log->u.gps.year ||
68                      log_month != log->u.gps.month ||
69                      log_day != log->u.gps.day)) {
70                         ao_log_close();
71                 }
72                 if (!log_open) {
73                         log_year = log->u.gps.year;
74                         log_month = log->u.gps.month;
75                         log_day = log->u.gps.day;
76                         ao_log_open();
77                 }
78         }
79         if (log_open) {
80                 wrote = ao_fat_write(log, sizeof (*log)) == AO_FAT_SUCCESS;
81                 ao_fat_sync();
82         }
83         ao_mutex_put(&log_mutex);
84         return wrote;
85 }